jimsh0.c 615 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472
  1. /* This is single source file, bootstrap version of Jim Tcl. See http://jim.tcl.tk/ */
  2. #define JIM_COMPAT
  3. #define JIM_ANSIC
  4. #define JIM_REGEXP
  5. #define HAVE_NO_AUTOCONF
  6. #define JIM_TINY
  7. #define _JIMAUTOCONF_H
  8. #define TCL_LIBRARY "."
  9. #define jim_ext_bootstrap
  10. #define jim_ext_aio
  11. #define jim_ext_readdir
  12. #define jim_ext_regexp
  13. #define jim_ext_file
  14. #define jim_ext_glob
  15. #define jim_ext_exec
  16. #define jim_ext_clock
  17. #define jim_ext_array
  18. #define jim_ext_stdlib
  19. #define jim_ext_tclcompat
  20. #if defined(_MSC_VER)
  21. #define TCL_PLATFORM_OS "windows"
  22. #define TCL_PLATFORM_PLATFORM "windows"
  23. #define TCL_PLATFORM_PATH_SEPARATOR ";"
  24. #define HAVE_MKDIR_ONE_ARG
  25. #define HAVE_SYSTEM
  26. #elif defined(__MINGW32__)
  27. #define TCL_PLATFORM_OS "mingw"
  28. #define TCL_PLATFORM_PLATFORM "windows"
  29. #define TCL_PLATFORM_PATH_SEPARATOR ";"
  30. #define HAVE_MKDIR_ONE_ARG
  31. #define HAVE_SYSTEM
  32. #define HAVE_SYS_TIME_H
  33. #define HAVE_DIRENT_H
  34. #define HAVE_UNISTD_H
  35. #define HAVE_UMASK
  36. #include <sys/stat.h>
  37. #ifndef S_IRWXG
  38. #define S_IRWXG 0
  39. #endif
  40. #ifndef S_IRWXO
  41. #define S_IRWXO 0
  42. #endif
  43. #else
  44. #define TCL_PLATFORM_OS "unknown"
  45. #define TCL_PLATFORM_PLATFORM "unix"
  46. #define TCL_PLATFORM_PATH_SEPARATOR ":"
  47. #ifdef _MINIX
  48. #define vfork fork
  49. #define _POSIX_SOURCE
  50. #else
  51. #define _GNU_SOURCE
  52. #endif
  53. #define HAVE_FORK
  54. #define HAVE_WAITPID
  55. #define HAVE_ISATTY
  56. #define HAVE_MKSTEMP
  57. #define HAVE_LINK
  58. #define HAVE_SYS_TIME_H
  59. #define HAVE_DIRENT_H
  60. #define HAVE_UNISTD_H
  61. #define HAVE_UMASK
  62. #define HAVE_PIPE
  63. #define _FILE_OFFSET_BITS 64
  64. #endif
  65. #define JIM_VERSION 84
  66. #ifndef JIM_WIN32COMPAT_H
  67. #define JIM_WIN32COMPAT_H
  68. #ifdef __cplusplus
  69. extern "C" {
  70. #endif
  71. #if defined(_WIN32) || defined(WIN32)
  72. #define HAVE_DLOPEN
  73. void *dlopen(const char *path, int mode);
  74. int dlclose(void *handle);
  75. void *dlsym(void *handle, const char *symbol);
  76. char *dlerror(void);
  77. #if defined(__MINGW32__)
  78. #define JIM_SPRINTF_DOUBLE_NEEDS_FIX
  79. #endif
  80. #ifdef _MSC_VER
  81. #if _MSC_VER >= 1000
  82. #pragma warning(disable:4146)
  83. #endif
  84. #include <limits.h>
  85. #define jim_wide _int64
  86. #ifndef HAVE_LONG_LONG
  87. #define HAVE_LONG_LONG
  88. #endif
  89. #ifndef LLONG_MAX
  90. #define LLONG_MAX 9223372036854775807I64
  91. #endif
  92. #ifndef LLONG_MIN
  93. #define LLONG_MIN (-LLONG_MAX - 1I64)
  94. #endif
  95. #define JIM_WIDE_MIN LLONG_MIN
  96. #define JIM_WIDE_MAX LLONG_MAX
  97. #define JIM_WIDE_MODIFIER "I64d"
  98. #define strcasecmp _stricmp
  99. #define strtoull _strtoui64
  100. #include <io.h>
  101. #include <winsock.h>
  102. int gettimeofday(struct timeval *tv, void *unused);
  103. #define HAVE_OPENDIR
  104. struct dirent {
  105. char *d_name;
  106. };
  107. typedef struct DIR {
  108. long handle;
  109. struct _finddata_t info;
  110. struct dirent result;
  111. char *name;
  112. } DIR;
  113. DIR *opendir(const char *name);
  114. int closedir(DIR *dir);
  115. struct dirent *readdir(DIR *dir);
  116. #endif
  117. #endif
  118. #ifdef __cplusplus
  119. }
  120. #endif
  121. #endif
  122. #ifndef UTF8_UTIL_H
  123. #define UTF8_UTIL_H
  124. #ifdef __cplusplus
  125. extern "C" {
  126. #endif
  127. #define MAX_UTF8_LEN 4
  128. int utf8_fromunicode(char *p, unsigned uc);
  129. #ifndef JIM_UTF8
  130. #include <ctype.h>
  131. #define utf8_strlen(S, B) ((B) < 0 ? (int)strlen(S) : (B))
  132. #define utf8_strwidth(S, B) utf8_strlen((S), (B))
  133. #define utf8_tounicode(S, CP) (*(CP) = (unsigned char)*(S), 1)
  134. #define utf8_getchars(CP, C) (*(CP) = (C), 1)
  135. #define utf8_upper(C) toupper(C)
  136. #define utf8_title(C) toupper(C)
  137. #define utf8_lower(C) tolower(C)
  138. #define utf8_index(C, I) (I)
  139. #define utf8_charlen(C) 1
  140. #define utf8_prev_len(S, L) 1
  141. #define utf8_width(C) 1
  142. #else
  143. #endif
  144. #ifdef __cplusplus
  145. }
  146. #endif
  147. #endif
  148. #ifndef __JIM__H
  149. #define __JIM__H
  150. #ifdef __cplusplus
  151. extern "C" {
  152. #endif
  153. #include <time.h>
  154. #include <limits.h>
  155. #include <stdlib.h>
  156. #include <stdarg.h>
  157. #ifndef HAVE_NO_AUTOCONF
  158. #endif
  159. #ifndef jim_wide
  160. # ifdef HAVE_LONG_LONG
  161. # define jim_wide long long
  162. # ifndef LLONG_MAX
  163. # define LLONG_MAX 9223372036854775807LL
  164. # endif
  165. # ifndef LLONG_MIN
  166. # define LLONG_MIN (-LLONG_MAX - 1LL)
  167. # endif
  168. # define JIM_WIDE_MIN LLONG_MIN
  169. # define JIM_WIDE_MAX LLONG_MAX
  170. # else
  171. # define jim_wide long
  172. # define JIM_WIDE_MIN LONG_MIN
  173. # define JIM_WIDE_MAX LONG_MAX
  174. # endif
  175. # ifdef HAVE_LONG_LONG
  176. # define JIM_WIDE_MODIFIER "lld"
  177. # else
  178. # define JIM_WIDE_MODIFIER "ld"
  179. # define strtoull strtoul
  180. # endif
  181. #endif
  182. #define UCHAR(c) ((unsigned char)(c))
  183. #define JIM_ABI_VERSION 101
  184. #define JIM_OK 0
  185. #define JIM_ERR 1
  186. #define JIM_RETURN 2
  187. #define JIM_BREAK 3
  188. #define JIM_CONTINUE 4
  189. #define JIM_SIGNAL 5
  190. #define JIM_EXIT 6
  191. #define JIM_EVAL 7
  192. #define JIM_MAX_CALLFRAME_DEPTH 1000
  193. #define JIM_MAX_EVAL_DEPTH 2000
  194. #define JIM_PRIV_FLAG_SHIFT 20
  195. #define JIM_NONE 0
  196. #define JIM_ERRMSG 1
  197. #define JIM_ENUM_ABBREV 2
  198. #define JIM_UNSHARED 4
  199. #define JIM_MUSTEXIST 8
  200. #define JIM_NORESULT 16
  201. #define JIM_SUBST_NOVAR 1
  202. #define JIM_SUBST_NOCMD 2
  203. #define JIM_SUBST_NOESC 4
  204. #define JIM_SUBST_FLAG 128
  205. #define JIM_CASESENS 0
  206. #define JIM_NOCASE 1
  207. #define JIM_OPT_END 2
  208. #define JIM_PATH_LEN 1024
  209. #define JIM_NOTUSED(V) ((void) V)
  210. #define JIM_LIBPATH "auto_path"
  211. #define JIM_INTERACTIVE "tcl_interactive"
  212. typedef struct Jim_Stack {
  213. int len;
  214. int maxlen;
  215. void **vector;
  216. } Jim_Stack;
  217. typedef struct Jim_HashEntry {
  218. void *key;
  219. union {
  220. void *val;
  221. int intval;
  222. } u;
  223. struct Jim_HashEntry *next;
  224. } Jim_HashEntry;
  225. typedef struct Jim_HashTableType {
  226. unsigned int (*hashFunction)(const void *key);
  227. void *(*keyDup)(void *privdata, const void *key);
  228. void *(*valDup)(void *privdata, const void *obj);
  229. int (*keyCompare)(void *privdata, const void *key1, const void *key2);
  230. void (*keyDestructor)(void *privdata, void *key);
  231. void (*valDestructor)(void *privdata, void *obj);
  232. } Jim_HashTableType;
  233. typedef struct Jim_HashTable {
  234. Jim_HashEntry **table;
  235. const Jim_HashTableType *type;
  236. void *privdata;
  237. unsigned int size;
  238. unsigned int sizemask;
  239. unsigned int used;
  240. unsigned int collisions;
  241. unsigned int uniq;
  242. } Jim_HashTable;
  243. typedef struct Jim_HashTableIterator {
  244. Jim_HashTable *ht;
  245. Jim_HashEntry *entry, *nextEntry;
  246. int index;
  247. } Jim_HashTableIterator;
  248. #define JIM_HT_INITIAL_SIZE 16
  249. #define Jim_FreeEntryVal(ht, entry) \
  250. if ((ht)->type->valDestructor) \
  251. (ht)->type->valDestructor((ht)->privdata, (entry)->u.val)
  252. #define Jim_SetHashVal(ht, entry, _val_) do { \
  253. if ((ht)->type->valDup) \
  254. (entry)->u.val = (ht)->type->valDup((ht)->privdata, (_val_)); \
  255. else \
  256. (entry)->u.val = (_val_); \
  257. } while(0)
  258. #define Jim_SetHashIntVal(ht, entry, _val_) (entry)->u.intval = (_val_)
  259. #define Jim_FreeEntryKey(ht, entry) \
  260. if ((ht)->type->keyDestructor) \
  261. (ht)->type->keyDestructor((ht)->privdata, (entry)->key)
  262. #define Jim_SetHashKey(ht, entry, _key_) do { \
  263. if ((ht)->type->keyDup) \
  264. (entry)->key = (ht)->type->keyDup((ht)->privdata, (_key_)); \
  265. else \
  266. (entry)->key = (void *)(_key_); \
  267. } while(0)
  268. #define Jim_CompareHashKeys(ht, key1, key2) \
  269. (((ht)->type->keyCompare) ? \
  270. (ht)->type->keyCompare((ht)->privdata, (key1), (key2)) : \
  271. (key1) == (key2))
  272. #define Jim_HashKey(ht, key) ((ht)->type->hashFunction(key) + (ht)->uniq)
  273. #define Jim_GetHashEntryKey(he) ((he)->key)
  274. #define Jim_GetHashEntryVal(he) ((he)->u.val)
  275. #define Jim_GetHashEntryIntVal(he) ((he)->u.intval)
  276. #define Jim_GetHashTableCollisions(ht) ((ht)->collisions)
  277. #define Jim_GetHashTableSize(ht) ((ht)->size)
  278. #define Jim_GetHashTableUsed(ht) ((ht)->used)
  279. typedef struct Jim_Obj {
  280. char *bytes;
  281. const struct Jim_ObjType *typePtr;
  282. int refCount;
  283. int length;
  284. union {
  285. jim_wide wideValue;
  286. int intValue;
  287. double doubleValue;
  288. void *ptr;
  289. struct {
  290. void *ptr1;
  291. void *ptr2;
  292. } twoPtrValue;
  293. struct {
  294. void *ptr;
  295. int int1;
  296. int int2;
  297. } ptrIntValue;
  298. struct {
  299. struct Jim_VarVal *vv;
  300. unsigned long callFrameId;
  301. int global;
  302. } varValue;
  303. struct {
  304. struct Jim_Obj *nsObj;
  305. struct Jim_Cmd *cmdPtr;
  306. unsigned long procEpoch;
  307. } cmdValue;
  308. struct {
  309. struct Jim_Obj **ele;
  310. int len;
  311. int maxLen;
  312. } listValue;
  313. struct Jim_Dict *dictValue;
  314. struct {
  315. int maxLength;
  316. int charLength;
  317. } strValue;
  318. struct {
  319. unsigned long id;
  320. struct Jim_Reference *refPtr;
  321. } refValue;
  322. struct {
  323. struct Jim_Obj *fileNameObj;
  324. int lineNumber;
  325. } sourceValue;
  326. struct {
  327. struct Jim_Obj *varNameObjPtr;
  328. struct Jim_Obj *indexObjPtr;
  329. } dictSubstValue;
  330. struct {
  331. int line;
  332. int argc;
  333. } scriptLineValue;
  334. } internalRep;
  335. struct Jim_Obj *prevObjPtr;
  336. struct Jim_Obj *nextObjPtr;
  337. } Jim_Obj;
  338. #define Jim_IncrRefCount(objPtr) \
  339. ++(objPtr)->refCount
  340. #define Jim_DecrRefCount(interp, objPtr) \
  341. if (--(objPtr)->refCount <= 0) Jim_FreeObj(interp, objPtr)
  342. #define Jim_IsShared(objPtr) \
  343. ((objPtr)->refCount > 1)
  344. #define Jim_FreeNewObj Jim_FreeObj
  345. #define Jim_FreeIntRep(i,o) \
  346. if ((o)->typePtr && (o)->typePtr->freeIntRepProc) \
  347. (o)->typePtr->freeIntRepProc(i, o)
  348. #define Jim_GetIntRepPtr(o) (o)->internalRep.ptr
  349. #define Jim_SetIntRepPtr(o, p) \
  350. (o)->internalRep.ptr = (p)
  351. struct Jim_Interp;
  352. typedef void (Jim_FreeInternalRepProc)(struct Jim_Interp *interp,
  353. struct Jim_Obj *objPtr);
  354. typedef void (Jim_DupInternalRepProc)(struct Jim_Interp *interp,
  355. struct Jim_Obj *srcPtr, Jim_Obj *dupPtr);
  356. typedef void (Jim_UpdateStringProc)(struct Jim_Obj *objPtr);
  357. typedef struct Jim_ObjType {
  358. const char *name;
  359. Jim_FreeInternalRepProc *freeIntRepProc;
  360. Jim_DupInternalRepProc *dupIntRepProc;
  361. Jim_UpdateStringProc *updateStringProc;
  362. int flags;
  363. } Jim_ObjType;
  364. #define JIM_TYPE_NONE 0
  365. #define JIM_TYPE_REFERENCES 1
  366. typedef struct Jim_CallFrame {
  367. unsigned long id;
  368. int level;
  369. struct Jim_HashTable vars;
  370. struct Jim_HashTable *staticVars;
  371. struct Jim_CallFrame *parent;
  372. Jim_Obj *const *argv;
  373. int argc;
  374. Jim_Obj *procArgsObjPtr;
  375. Jim_Obj *procBodyObjPtr;
  376. struct Jim_CallFrame *next;
  377. Jim_Obj *nsObj;
  378. Jim_Obj *unused_fileNameObj;
  379. int unused_line;
  380. Jim_Stack *localCommands;
  381. struct Jim_Obj *tailcallObj;
  382. struct Jim_Cmd *tailcallCmd;
  383. } Jim_CallFrame;
  384. typedef struct Jim_EvalFrame {
  385. Jim_CallFrame *framePtr;
  386. int level;
  387. int procLevel;
  388. struct Jim_Cmd *cmd;
  389. struct Jim_EvalFrame *parent;
  390. Jim_Obj *const *argv;
  391. int argc;
  392. Jim_Obj *scriptObj;
  393. } Jim_EvalFrame;
  394. typedef struct Jim_VarVal {
  395. Jim_Obj *objPtr;
  396. struct Jim_CallFrame *linkFramePtr;
  397. int refCount;
  398. } Jim_VarVal;
  399. typedef int Jim_CmdProc(struct Jim_Interp *interp, int argc,
  400. Jim_Obj *const *argv);
  401. typedef void Jim_DelCmdProc(struct Jim_Interp *interp, void *privData);
  402. typedef struct Jim_Dict {
  403. struct JimDictHashEntry {
  404. int offset;
  405. unsigned hash;
  406. } *ht;
  407. unsigned int size;
  408. unsigned int sizemask;
  409. unsigned int uniq;
  410. Jim_Obj **table;
  411. int len;
  412. int maxLen;
  413. unsigned int dummy;
  414. } Jim_Dict;
  415. typedef struct Jim_Cmd {
  416. int inUse;
  417. int isproc;
  418. struct Jim_Cmd *prevCmd;
  419. Jim_Obj *cmdNameObj;
  420. union {
  421. struct {
  422. Jim_CmdProc *cmdProc;
  423. Jim_DelCmdProc *delProc;
  424. void *privData;
  425. } native;
  426. struct {
  427. Jim_Obj *argListObjPtr;
  428. Jim_Obj *bodyObjPtr;
  429. Jim_HashTable *staticVars;
  430. int argListLen;
  431. int reqArity;
  432. int optArity;
  433. int argsPos;
  434. int upcall;
  435. struct Jim_ProcArg {
  436. Jim_Obj *nameObjPtr;
  437. Jim_Obj *defaultObjPtr;
  438. } *arglist;
  439. Jim_Obj *nsObj;
  440. } proc;
  441. } u;
  442. } Jim_Cmd;
  443. typedef struct Jim_PrngState {
  444. unsigned char sbox[256];
  445. unsigned int i, j;
  446. } Jim_PrngState;
  447. typedef struct Jim_Interp {
  448. Jim_Obj *result;
  449. int unused_errorLine;
  450. Jim_Obj *currentFilenameObj;
  451. int break_level;
  452. int maxCallFrameDepth;
  453. int maxEvalDepth;
  454. int evalDepth;
  455. int returnCode;
  456. int returnLevel;
  457. int exitCode;
  458. long id;
  459. int signal_level;
  460. jim_wide sigmask;
  461. int (*signal_set_result)(struct Jim_Interp *interp, jim_wide sigmask);
  462. Jim_CallFrame *framePtr;
  463. Jim_CallFrame *topFramePtr;
  464. struct Jim_HashTable commands;
  465. unsigned long procEpoch; /* Incremented every time the result
  466. of procedures names lookup caching
  467. may no longer be valid. */
  468. unsigned long callFrameEpoch; /* Incremented every time a new
  469. callframe is created. This id is used for the
  470. 'ID' field contained in the Jim_CallFrame
  471. structure. */
  472. int local;
  473. int quitting;
  474. int safeexpr;
  475. Jim_Obj *liveList;
  476. Jim_Obj *freeList;
  477. Jim_Obj *unused_currentScriptObj;
  478. Jim_EvalFrame topEvalFrame;
  479. Jim_EvalFrame *evalFrame;
  480. int procLevel;
  481. Jim_Obj * const *unused_argv;
  482. Jim_Obj *nullScriptObj;
  483. Jim_Obj *emptyObj;
  484. Jim_Obj *trueObj;
  485. Jim_Obj *falseObj;
  486. unsigned long referenceNextId;
  487. struct Jim_HashTable references;
  488. unsigned long lastCollectId; /* reference max Id of the last GC
  489. execution. It's set to ~0 while the collection
  490. is running as sentinel to avoid to recursive
  491. calls via the [collect] command inside
  492. finalizers. */
  493. jim_wide lastCollectTime;
  494. Jim_Obj *stackTrace;
  495. Jim_Obj *errorProc;
  496. Jim_Obj *unknown;
  497. Jim_Obj *defer;
  498. Jim_Obj *traceCmdObj;
  499. int unknown_called;
  500. int errorFlag;
  501. void *cmdPrivData; /* Used to pass the private data pointer to
  502. a command. It is set to what the user specified
  503. via Jim_CreateCommand(). */
  504. Jim_Cmd *oldCmdCache;
  505. int oldCmdCacheSize;
  506. struct Jim_CallFrame *freeFramesList;
  507. struct Jim_HashTable assocData;
  508. Jim_PrngState *prngState;
  509. struct Jim_HashTable packages;
  510. Jim_Stack *loadHandles;
  511. } Jim_Interp;
  512. #define Jim_SetResultString(i,s,l) Jim_SetResult(i, Jim_NewStringObj(i,s,l))
  513. #define Jim_SetResultInt(i,intval) Jim_SetResult(i, Jim_NewIntObj(i,intval))
  514. #define Jim_SetResultBool(i,b) Jim_SetResultInt(i, b)
  515. #define Jim_SetEmptyResult(i) Jim_SetResult(i, (i)->emptyObj)
  516. #define Jim_GetResult(i) ((i)->result)
  517. #define Jim_CmdPrivData(i) ((i)->cmdPrivData)
  518. #define Jim_SetResult(i,o) do { \
  519. Jim_Obj *_resultObjPtr_ = (o); \
  520. Jim_IncrRefCount(_resultObjPtr_); \
  521. Jim_DecrRefCount(i,(i)->result); \
  522. (i)->result = _resultObjPtr_; \
  523. } while(0)
  524. #define Jim_GetId(i) (++(i)->id)
  525. #define JIM_REFERENCE_TAGLEN 7 /* The tag is fixed-length, because the reference
  526. string representation must be fixed length. */
  527. typedef struct Jim_Reference {
  528. Jim_Obj *objPtr;
  529. Jim_Obj *finalizerCmdNamePtr;
  530. char tag[JIM_REFERENCE_TAGLEN+1];
  531. } Jim_Reference;
  532. #define Jim_NewEmptyStringObj(i) Jim_NewStringObj(i, "", 0)
  533. #define Jim_FreeHashTableIterator(iter) Jim_Free(iter)
  534. #define JIM_EXPORT extern
  535. JIM_EXPORT void *(*Jim_Allocator)(void *ptr, size_t size);
  536. #define Jim_Free(P) Jim_Allocator((P), 0)
  537. #define Jim_Realloc(P, S) Jim_Allocator((P), (S))
  538. #define Jim_Alloc(S) Jim_Allocator(NULL, (S))
  539. JIM_EXPORT char * Jim_StrDup (const char *s);
  540. JIM_EXPORT char *Jim_StrDupLen(const char *s, int l);
  541. JIM_EXPORT char **Jim_GetEnviron(void);
  542. JIM_EXPORT void Jim_SetEnviron(char **env);
  543. JIM_EXPORT int Jim_MakeTempFile(Jim_Interp *interp, const char *filename_template, int unlink_file);
  544. #ifndef CLOCK_REALTIME
  545. # define CLOCK_REALTIME 0
  546. #endif
  547. #ifndef CLOCK_MONOTONIC
  548. # define CLOCK_MONOTONIC 1
  549. #endif
  550. #ifndef CLOCK_MONOTONIC_RAW
  551. # define CLOCK_MONOTONIC_RAW CLOCK_MONOTONIC
  552. #endif
  553. JIM_EXPORT jim_wide Jim_GetTimeUsec(unsigned type);
  554. JIM_EXPORT int Jim_Eval(Jim_Interp *interp, const char *script);
  555. JIM_EXPORT int Jim_EvalSource(Jim_Interp *interp, const char *filename, int lineno, const char *script);
  556. #define Jim_Eval_Named(I, S, F, L) Jim_EvalSource((I), (F), (L), (S))
  557. JIM_EXPORT int Jim_EvalGlobal(Jim_Interp *interp, const char *script);
  558. JIM_EXPORT int Jim_EvalFile(Jim_Interp *interp, const char *filename);
  559. JIM_EXPORT int Jim_EvalFileGlobal(Jim_Interp *interp, const char *filename);
  560. JIM_EXPORT int Jim_EvalObj (Jim_Interp *interp, Jim_Obj *scriptObjPtr);
  561. JIM_EXPORT int Jim_EvalObjVector (Jim_Interp *interp, int objc,
  562. Jim_Obj *const *objv);
  563. JIM_EXPORT int Jim_EvalObjList(Jim_Interp *interp, Jim_Obj *listObj);
  564. JIM_EXPORT int Jim_EvalObjPrefix(Jim_Interp *interp, Jim_Obj *prefix,
  565. int objc, Jim_Obj *const *objv);
  566. #define Jim_EvalPrefix(i, p, oc, ov) Jim_EvalObjPrefix((i), Jim_NewStringObj((i), (p), -1), (oc), (ov))
  567. JIM_EXPORT int Jim_EvalNamespace(Jim_Interp *interp, Jim_Obj *scriptObj, Jim_Obj *nsObj);
  568. JIM_EXPORT int Jim_SubstObj (Jim_Interp *interp, Jim_Obj *substObjPtr,
  569. Jim_Obj **resObjPtrPtr, int flags);
  570. JIM_EXPORT Jim_Obj *Jim_GetSourceInfo(Jim_Interp *interp, Jim_Obj *objPtr,
  571. int *lineptr);
  572. JIM_EXPORT void Jim_SetSourceInfo(Jim_Interp *interp, Jim_Obj *objPtr,
  573. Jim_Obj *fileNameObj, int lineNumber);
  574. JIM_EXPORT void Jim_InitStack(Jim_Stack *stack);
  575. JIM_EXPORT void Jim_FreeStack(Jim_Stack *stack);
  576. JIM_EXPORT int Jim_StackLen(Jim_Stack *stack);
  577. JIM_EXPORT void Jim_StackPush(Jim_Stack *stack, void *element);
  578. JIM_EXPORT void * Jim_StackPop(Jim_Stack *stack);
  579. JIM_EXPORT void * Jim_StackPeek(Jim_Stack *stack);
  580. JIM_EXPORT void Jim_FreeStackElements(Jim_Stack *stack, void (*freeFunc)(void *ptr));
  581. JIM_EXPORT int Jim_InitHashTable (Jim_HashTable *ht,
  582. const Jim_HashTableType *type, void *privdata);
  583. JIM_EXPORT void Jim_ExpandHashTable (Jim_HashTable *ht,
  584. unsigned int size);
  585. JIM_EXPORT int Jim_AddHashEntry (Jim_HashTable *ht, const void *key,
  586. void *val);
  587. JIM_EXPORT int Jim_ReplaceHashEntry (Jim_HashTable *ht,
  588. const void *key, void *val);
  589. JIM_EXPORT int Jim_DeleteHashEntry (Jim_HashTable *ht,
  590. const void *key);
  591. JIM_EXPORT int Jim_FreeHashTable (Jim_HashTable *ht);
  592. JIM_EXPORT Jim_HashEntry * Jim_FindHashEntry (Jim_HashTable *ht,
  593. const void *key);
  594. JIM_EXPORT Jim_HashTableIterator *Jim_GetHashTableIterator
  595. (Jim_HashTable *ht);
  596. JIM_EXPORT Jim_HashEntry * Jim_NextHashEntry
  597. (Jim_HashTableIterator *iter);
  598. JIM_EXPORT Jim_Obj * Jim_NewObj (Jim_Interp *interp);
  599. JIM_EXPORT void Jim_FreeObj (Jim_Interp *interp, Jim_Obj *objPtr);
  600. JIM_EXPORT void Jim_InvalidateStringRep (Jim_Obj *objPtr);
  601. JIM_EXPORT Jim_Obj * Jim_DuplicateObj (Jim_Interp *interp,
  602. Jim_Obj *objPtr);
  603. JIM_EXPORT const char * Jim_GetString(Jim_Obj *objPtr,
  604. int *lenPtr);
  605. JIM_EXPORT const char *Jim_String(Jim_Obj *objPtr);
  606. JIM_EXPORT int Jim_Length(Jim_Obj *objPtr);
  607. JIM_EXPORT Jim_Obj * Jim_NewStringObj (Jim_Interp *interp,
  608. const char *s, int len);
  609. JIM_EXPORT Jim_Obj *Jim_NewStringObjUtf8(Jim_Interp *interp,
  610. const char *s, int charlen);
  611. JIM_EXPORT Jim_Obj * Jim_NewStringObjNoAlloc (Jim_Interp *interp,
  612. char *s, int len);
  613. JIM_EXPORT void Jim_AppendString (Jim_Interp *interp, Jim_Obj *objPtr,
  614. const char *str, int len);
  615. JIM_EXPORT void Jim_AppendObj (Jim_Interp *interp, Jim_Obj *objPtr,
  616. Jim_Obj *appendObjPtr);
  617. JIM_EXPORT void Jim_AppendStrings (Jim_Interp *interp,
  618. Jim_Obj *objPtr, ...);
  619. JIM_EXPORT int Jim_StringEqObj(Jim_Obj *aObjPtr, Jim_Obj *bObjPtr);
  620. JIM_EXPORT int Jim_StringMatchObj (Jim_Interp *interp, Jim_Obj *patternObjPtr,
  621. Jim_Obj *objPtr, int nocase);
  622. JIM_EXPORT Jim_Obj * Jim_StringRangeObj (Jim_Interp *interp,
  623. Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr,
  624. Jim_Obj *lastObjPtr);
  625. JIM_EXPORT Jim_Obj * Jim_FormatString (Jim_Interp *interp,
  626. Jim_Obj *fmtObjPtr, int objc, Jim_Obj *const *objv);
  627. JIM_EXPORT Jim_Obj * Jim_ScanString (Jim_Interp *interp, Jim_Obj *strObjPtr,
  628. Jim_Obj *fmtObjPtr, int flags);
  629. JIM_EXPORT int Jim_CompareStringImmediate (Jim_Interp *interp,
  630. Jim_Obj *objPtr, const char *str);
  631. JIM_EXPORT int Jim_StringCompareObj(Jim_Interp *interp, Jim_Obj *firstObjPtr,
  632. Jim_Obj *secondObjPtr, int nocase);
  633. JIM_EXPORT int Jim_Utf8Length(Jim_Interp *interp, Jim_Obj *objPtr);
  634. JIM_EXPORT Jim_Obj * Jim_NewReference (Jim_Interp *interp,
  635. Jim_Obj *objPtr, Jim_Obj *tagPtr, Jim_Obj *cmdNamePtr);
  636. JIM_EXPORT Jim_Reference * Jim_GetReference (Jim_Interp *interp,
  637. Jim_Obj *objPtr);
  638. JIM_EXPORT int Jim_SetFinalizer (Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *cmdNamePtr);
  639. JIM_EXPORT int Jim_GetFinalizer (Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj **cmdNamePtrPtr);
  640. JIM_EXPORT Jim_Interp * Jim_CreateInterp (void);
  641. JIM_EXPORT void Jim_FreeInterp (Jim_Interp *i);
  642. JIM_EXPORT int Jim_GetExitCode (Jim_Interp *interp);
  643. JIM_EXPORT const char *Jim_ReturnCode(int code);
  644. JIM_EXPORT void Jim_SetResultFormatted(Jim_Interp *interp, const char *format, ...);
  645. JIM_EXPORT void Jim_RegisterCoreCommands (Jim_Interp *interp);
  646. JIM_EXPORT int Jim_CreateCommand (Jim_Interp *interp,
  647. const char *cmdName, Jim_CmdProc *cmdProc, void *privData,
  648. Jim_DelCmdProc *delProc);
  649. JIM_EXPORT int Jim_DeleteCommand (Jim_Interp *interp,
  650. Jim_Obj *cmdNameObj);
  651. JIM_EXPORT int Jim_RenameCommand (Jim_Interp *interp,
  652. Jim_Obj *oldNameObj, Jim_Obj *newNameObj);
  653. JIM_EXPORT Jim_Cmd * Jim_GetCommand (Jim_Interp *interp,
  654. Jim_Obj *objPtr, int flags);
  655. JIM_EXPORT int Jim_SetVariable (Jim_Interp *interp,
  656. Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr);
  657. JIM_EXPORT int Jim_SetVariableStr (Jim_Interp *interp,
  658. const char *name, Jim_Obj *objPtr);
  659. JIM_EXPORT int Jim_SetGlobalVariableStr (Jim_Interp *interp,
  660. const char *name, Jim_Obj *objPtr);
  661. JIM_EXPORT int Jim_SetVariableStrWithStr (Jim_Interp *interp,
  662. const char *name, const char *val);
  663. JIM_EXPORT int Jim_SetVariableLink (Jim_Interp *interp,
  664. Jim_Obj *nameObjPtr, Jim_Obj *targetNameObjPtr,
  665. Jim_CallFrame *targetCallFrame);
  666. JIM_EXPORT Jim_Obj * Jim_MakeGlobalNamespaceName(Jim_Interp *interp,
  667. Jim_Obj *nameObjPtr);
  668. JIM_EXPORT Jim_Obj * Jim_GetVariable (Jim_Interp *interp,
  669. Jim_Obj *nameObjPtr, int flags);
  670. JIM_EXPORT Jim_Obj * Jim_GetGlobalVariable (Jim_Interp *interp,
  671. Jim_Obj *nameObjPtr, int flags);
  672. JIM_EXPORT Jim_Obj * Jim_GetVariableStr (Jim_Interp *interp,
  673. const char *name, int flags);
  674. JIM_EXPORT Jim_Obj * Jim_GetGlobalVariableStr (Jim_Interp *interp,
  675. const char *name, int flags);
  676. JIM_EXPORT int Jim_UnsetVariable (Jim_Interp *interp,
  677. Jim_Obj *nameObjPtr, int flags);
  678. JIM_EXPORT Jim_CallFrame *Jim_GetCallFrameByLevel(Jim_Interp *interp,
  679. Jim_Obj *levelObjPtr);
  680. JIM_EXPORT int Jim_Collect (Jim_Interp *interp);
  681. JIM_EXPORT void Jim_CollectIfNeeded (Jim_Interp *interp);
  682. JIM_EXPORT int Jim_GetIndex (Jim_Interp *interp, Jim_Obj *objPtr,
  683. int *indexPtr);
  684. JIM_EXPORT Jim_Obj * Jim_NewListObj (Jim_Interp *interp,
  685. Jim_Obj *const *elements, int len);
  686. JIM_EXPORT void Jim_ListInsertElements (Jim_Interp *interp,
  687. Jim_Obj *listPtr, int listindex, int objc, Jim_Obj *const *objVec);
  688. JIM_EXPORT void Jim_ListAppendElement (Jim_Interp *interp,
  689. Jim_Obj *listPtr, Jim_Obj *objPtr);
  690. JIM_EXPORT void Jim_ListAppendList (Jim_Interp *interp,
  691. Jim_Obj *listPtr, Jim_Obj *appendListPtr);
  692. JIM_EXPORT int Jim_ListLength (Jim_Interp *interp, Jim_Obj *objPtr);
  693. JIM_EXPORT int Jim_ListIndex (Jim_Interp *interp, Jim_Obj *listPrt,
  694. int listindex, Jim_Obj **objPtrPtr, int seterr);
  695. JIM_EXPORT Jim_Obj *Jim_ListGetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx);
  696. JIM_EXPORT int Jim_SetListIndex (Jim_Interp *interp,
  697. Jim_Obj *varNamePtr, Jim_Obj *const *indexv, int indexc,
  698. Jim_Obj *newObjPtr);
  699. JIM_EXPORT Jim_Obj * Jim_ConcatObj (Jim_Interp *interp, int objc,
  700. Jim_Obj *const *objv);
  701. JIM_EXPORT Jim_Obj *Jim_ListJoin(Jim_Interp *interp,
  702. Jim_Obj *listObjPtr, const char *joinStr, int joinStrLen);
  703. JIM_EXPORT Jim_Obj * Jim_NewDictObj (Jim_Interp *interp,
  704. Jim_Obj *const *elements, int len);
  705. JIM_EXPORT int Jim_DictKey (Jim_Interp *interp, Jim_Obj *dictPtr,
  706. Jim_Obj *keyPtr, Jim_Obj **objPtrPtr, int flags);
  707. JIM_EXPORT int Jim_DictKeysVector (Jim_Interp *interp,
  708. Jim_Obj *dictPtr, Jim_Obj *const *keyv, int keyc,
  709. Jim_Obj **objPtrPtr, int flags);
  710. JIM_EXPORT int Jim_SetDictKeysVector (Jim_Interp *interp,
  711. Jim_Obj *varNamePtr, Jim_Obj *const *keyv, int keyc,
  712. Jim_Obj *newObjPtr, int flags);
  713. JIM_EXPORT Jim_Obj **Jim_DictPairs(Jim_Interp *interp,
  714. Jim_Obj *dictPtr, int *len);
  715. JIM_EXPORT int Jim_DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
  716. Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr);
  717. #define JIM_DICTMATCH_KEYS 0x0001
  718. #define JIM_DICTMATCH_VALUES 0x002
  719. JIM_EXPORT int Jim_DictMatchTypes(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *patternObj, int match_type, int return_types);
  720. JIM_EXPORT int Jim_DictSize(Jim_Interp *interp, Jim_Obj *objPtr);
  721. JIM_EXPORT int Jim_DictInfo(Jim_Interp *interp, Jim_Obj *objPtr);
  722. JIM_EXPORT Jim_Obj *Jim_DictMerge(Jim_Interp *interp, int objc, Jim_Obj *const *objv);
  723. JIM_EXPORT int Jim_GetReturnCode (Jim_Interp *interp, Jim_Obj *objPtr,
  724. int *intPtr);
  725. JIM_EXPORT int Jim_EvalExpression (Jim_Interp *interp,
  726. Jim_Obj *exprObjPtr);
  727. JIM_EXPORT int Jim_GetBoolFromExpr (Jim_Interp *interp,
  728. Jim_Obj *exprObjPtr, int *boolPtr);
  729. JIM_EXPORT int Jim_GetBoolean(Jim_Interp *interp, Jim_Obj *objPtr,
  730. int *booleanPtr);
  731. JIM_EXPORT int Jim_GetWide (Jim_Interp *interp, Jim_Obj *objPtr,
  732. jim_wide *widePtr);
  733. JIM_EXPORT int Jim_GetWideExpr(Jim_Interp *interp, Jim_Obj *objPtr,
  734. jim_wide *widePtr);
  735. JIM_EXPORT int Jim_GetLong (Jim_Interp *interp, Jim_Obj *objPtr,
  736. long *longPtr);
  737. #define Jim_NewWideObj Jim_NewIntObj
  738. JIM_EXPORT Jim_Obj * Jim_NewIntObj (Jim_Interp *interp,
  739. jim_wide wideValue);
  740. JIM_EXPORT int Jim_GetDouble(Jim_Interp *interp, Jim_Obj *objPtr,
  741. double *doublePtr);
  742. JIM_EXPORT void Jim_SetDouble(Jim_Interp *interp, Jim_Obj *objPtr,
  743. double doubleValue);
  744. JIM_EXPORT Jim_Obj * Jim_NewDoubleObj(Jim_Interp *interp, double doubleValue);
  745. JIM_EXPORT void Jim_WrongNumArgs (Jim_Interp *interp, int argc,
  746. Jim_Obj *const *argv, const char *msg);
  747. JIM_EXPORT int Jim_GetEnum (Jim_Interp *interp, Jim_Obj *objPtr,
  748. const char * const *tablePtr, int *indexPtr, const char *name, int flags);
  749. JIM_EXPORT int Jim_CheckShowCommands(Jim_Interp *interp, Jim_Obj *objPtr,
  750. const char *const *tablePtr);
  751. JIM_EXPORT int Jim_ScriptIsComplete(Jim_Interp *interp,
  752. Jim_Obj *scriptObj, char *stateCharPtr);
  753. JIM_EXPORT int Jim_FindByName(const char *name, const char * const array[], size_t len);
  754. typedef void (Jim_InterpDeleteProc)(Jim_Interp *interp, void *data);
  755. JIM_EXPORT void * Jim_GetAssocData(Jim_Interp *interp, const char *key);
  756. JIM_EXPORT int Jim_SetAssocData(Jim_Interp *interp, const char *key,
  757. Jim_InterpDeleteProc *delProc, void *data);
  758. JIM_EXPORT int Jim_DeleteAssocData(Jim_Interp *interp, const char *key);
  759. JIM_EXPORT int Jim_CheckAbiVersion(Jim_Interp *interp, int abi_version);
  760. JIM_EXPORT int Jim_PackageProvide (Jim_Interp *interp,
  761. const char *name, const char *ver, int flags);
  762. JIM_EXPORT int Jim_PackageRequire (Jim_Interp *interp,
  763. const char *name, int flags);
  764. #define Jim_PackageProvideCheck(INTERP, NAME) \
  765. if (Jim_CheckAbiVersion(INTERP, JIM_ABI_VERSION) == JIM_ERR || Jim_PackageProvide(INTERP, NAME, "1.0", JIM_ERRMSG)) \
  766. return JIM_ERR
  767. JIM_EXPORT void Jim_MakeErrorMessage (Jim_Interp *interp);
  768. JIM_EXPORT int Jim_InteractivePrompt (Jim_Interp *interp);
  769. JIM_EXPORT void Jim_HistoryLoad(const char *filename);
  770. JIM_EXPORT void Jim_HistorySave(const char *filename);
  771. JIM_EXPORT char *Jim_HistoryGetline(Jim_Interp *interp, const char *prompt);
  772. JIM_EXPORT void Jim_HistorySetCompletion(Jim_Interp *interp, Jim_Obj *completionCommandObj);
  773. JIM_EXPORT void Jim_HistorySetHints(Jim_Interp *interp, Jim_Obj *hintsCommandObj);
  774. JIM_EXPORT void Jim_HistoryAdd(const char *line);
  775. JIM_EXPORT void Jim_HistoryShow(void);
  776. JIM_EXPORT void Jim_HistorySetMaxLen(int length);
  777. JIM_EXPORT int Jim_HistoryGetMaxLen(void);
  778. JIM_EXPORT int Jim_InitStaticExtensions(Jim_Interp *interp);
  779. JIM_EXPORT int Jim_StringToWide(const char *str, jim_wide *widePtr, int base);
  780. JIM_EXPORT int Jim_IsBigEndian(void);
  781. #define Jim_CheckSignal(i) ((i)->signal_level && (i)->sigmask)
  782. JIM_EXPORT void Jim_SignalSetIgnored(jim_wide mask);
  783. JIM_EXPORT int Jim_LoadLibrary(Jim_Interp *interp, const char *pathName);
  784. JIM_EXPORT void Jim_FreeLoadHandles(Jim_Interp *interp);
  785. JIM_EXPORT int Jim_AioFilehandle(Jim_Interp *interp, Jim_Obj *command);
  786. JIM_EXPORT int Jim_IsDict(Jim_Obj *objPtr);
  787. JIM_EXPORT int Jim_IsList(Jim_Obj *objPtr);
  788. #ifdef __cplusplus
  789. }
  790. #endif
  791. #endif
  792. #ifndef JIM_SUBCMD_H
  793. #define JIM_SUBCMD_H
  794. #ifdef __cplusplus
  795. extern "C" {
  796. #endif
  797. #define JIM_MODFLAG_HIDDEN 0x0001
  798. #define JIM_MODFLAG_FULLARGV 0x0002
  799. typedef int jim_subcmd_function(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
  800. typedef struct {
  801. const char *cmd;
  802. const char *args;
  803. jim_subcmd_function *function;
  804. short minargs;
  805. short maxargs;
  806. unsigned short flags;
  807. } jim_subcmd_type;
  808. #define JIM_DEF_SUBCMD(name, args, minargs, maxargs) { name, args, NULL, minargs, maxargs }
  809. #define JIM_DEF_SUBCMD_HIDDEN(name, args, minargs, maxargs) { name, args, NULL, minargs, maxargs, JIM_MODFLAG_HIDDEN }
  810. const jim_subcmd_type *
  811. Jim_ParseSubCmd(Jim_Interp *interp, const jim_subcmd_type *command_table, int argc, Jim_Obj *const *argv);
  812. int Jim_SubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
  813. int Jim_CallSubCmd(Jim_Interp *interp, const jim_subcmd_type *ct, int argc, Jim_Obj *const *argv);
  814. void Jim_SubCmdArgError(Jim_Interp *interp, const jim_subcmd_type *ct, Jim_Obj *subcmd);
  815. #ifdef __cplusplus
  816. }
  817. #endif
  818. #endif
  819. #ifndef JIMREGEXP_H
  820. #define JIMREGEXP_H
  821. #ifdef __cplusplus
  822. extern "C" {
  823. #endif
  824. #include <stdlib.h>
  825. typedef struct {
  826. int rm_so;
  827. int rm_eo;
  828. } regmatch_t;
  829. typedef struct regexp {
  830. int re_nsub;
  831. int cflags;
  832. int err;
  833. int regstart;
  834. int reganch;
  835. int regmust;
  836. int regmlen;
  837. int *program;
  838. const char *regparse;
  839. int p;
  840. int proglen;
  841. int eflags;
  842. const char *start;
  843. const char *reginput;
  844. const char *regbol;
  845. regmatch_t *pmatch;
  846. int nmatch;
  847. } regexp;
  848. typedef regexp regex_t;
  849. #define REG_EXTENDED 0
  850. #define REG_NEWLINE 1
  851. #define REG_ICASE 2
  852. #define REG_NOTBOL 16
  853. enum {
  854. REG_NOERROR,
  855. REG_NOMATCH,
  856. REG_BADPAT,
  857. REG_ERR_NULL_ARGUMENT,
  858. REG_ERR_UNKNOWN,
  859. REG_ERR_TOO_BIG,
  860. REG_ERR_NOMEM,
  861. REG_ERR_TOO_MANY_PAREN,
  862. REG_ERR_UNMATCHED_PAREN,
  863. REG_ERR_UNMATCHED_BRACES,
  864. REG_ERR_BAD_COUNT,
  865. REG_ERR_JUNK_ON_END,
  866. REG_ERR_OPERAND_COULD_BE_EMPTY,
  867. REG_ERR_NESTED_COUNT,
  868. REG_ERR_INTERNAL,
  869. REG_ERR_COUNT_FOLLOWS_NOTHING,
  870. REG_ERR_INVALID_ESCAPE,
  871. REG_ERR_CORRUPTED,
  872. REG_ERR_NULL_CHAR,
  873. REG_ERR_UNMATCHED_BRACKET,
  874. REG_ERR_NUM
  875. };
  876. int jim_regcomp(regex_t *preg, const char *regex, int cflags);
  877. int jim_regexec(regex_t *preg, const char *string, size_t nmatch, regmatch_t pmatch[], int eflags);
  878. size_t jim_regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size);
  879. void jim_regfree(regex_t *preg);
  880. #ifdef __cplusplus
  881. }
  882. #endif
  883. #endif
  884. #ifndef JIM_SIGNAL_H
  885. #define JIM_SIGNAL_H
  886. #ifdef __cplusplus
  887. extern "C" {
  888. #endif
  889. const char *Jim_SignalId(int sig);
  890. #ifdef __cplusplus
  891. }
  892. #endif
  893. #endif
  894. #ifndef JIMIOCOMPAT_H
  895. #define JIMIOCOMPAT_H
  896. #include <stdio.h>
  897. #include <errno.h>
  898. #include <sys/stat.h>
  899. void Jim_SetResultErrno(Jim_Interp *interp, const char *msg);
  900. int Jim_OpenForWrite(const char *filename, int append);
  901. int Jim_OpenForRead(const char *filename);
  902. #if defined(__MINGW32__) || defined(_WIN32)
  903. #ifndef STRICT
  904. #define STRICT
  905. #endif
  906. #define WIN32_LEAN_AND_MEAN
  907. #include <windows.h>
  908. #include <fcntl.h>
  909. #include <io.h>
  910. #include <process.h>
  911. typedef HANDLE phandle_t;
  912. #define JIM_BAD_PHANDLE INVALID_HANDLE_VALUE
  913. #define WIFEXITED(STATUS) (((STATUS) & 0xff00) == 0)
  914. #define WEXITSTATUS(STATUS) ((STATUS) & 0x00ff)
  915. #define WIFSIGNALED(STATUS) (((STATUS) & 0xff00) != 0)
  916. #define WTERMSIG(STATUS) (((STATUS) >> 8) & 0xff)
  917. #define WNOHANG 1
  918. int Jim_Errno(void);
  919. long waitpid(phandle_t phandle, int *status, int nohang);
  920. phandle_t JimWaitPid(long processid, int *status, int nohang);
  921. long JimProcessPid(phandle_t phandle);
  922. #define HAVE_PIPE
  923. #define pipe(P) _pipe((P), 0, O_NOINHERIT)
  924. typedef struct __stat64 jim_stat_t;
  925. #define Jim_Stat _stat64
  926. #define Jim_FileStat _fstat64
  927. #define Jim_Lseek _lseeki64
  928. #define O_TEXT _O_TEXT
  929. #else
  930. #if defined(HAVE_STAT64)
  931. typedef struct stat64 jim_stat_t;
  932. #define Jim_Stat stat64
  933. #if defined(HAVE_FSTAT64)
  934. #define Jim_FileStat fstat64
  935. #endif
  936. #if defined(HAVE_LSTAT64)
  937. #define Jim_LinkStat lstat64
  938. #endif
  939. #else
  940. typedef struct stat jim_stat_t;
  941. #define Jim_Stat stat
  942. #if defined(HAVE_FSTAT)
  943. #define Jim_FileStat fstat
  944. #endif
  945. #if defined(HAVE_LSTAT)
  946. #define Jim_LinkStat lstat
  947. #endif
  948. #endif
  949. #if defined(HAVE_LSEEK64)
  950. #define Jim_Lseek lseek64
  951. #else
  952. #define Jim_Lseek lseek
  953. #endif
  954. #if defined(HAVE_UNISTD_H)
  955. #include <unistd.h>
  956. #include <fcntl.h>
  957. #include <sys/wait.h>
  958. typedef int phandle_t;
  959. #define Jim_Errno() errno
  960. #define JIM_BAD_PHANDLE -1
  961. #define JimProcessPid(PIDTYPE) (PIDTYPE)
  962. #define JimWaitPid waitpid
  963. #ifndef HAVE_EXECVPE
  964. #define execvpe(ARG0, ARGV, ENV) execvp(ARG0, ARGV)
  965. #endif
  966. #endif
  967. #ifndef O_TEXT
  968. #define O_TEXT 0
  969. #endif
  970. #endif
  971. int Jim_FileStoreStatData(Jim_Interp *interp, Jim_Obj *varName, const jim_stat_t *sb);
  972. #endif
  973. int Jim_bootstrapInit(Jim_Interp *interp)
  974. {
  975. if (Jim_PackageProvide(interp, "bootstrap", "1.0", JIM_ERRMSG))
  976. return JIM_ERR;
  977. return Jim_EvalSource(interp, "bootstrap.tcl", 1,
  978. "\n"
  979. "proc package {cmd args} {\n"
  980. " if {$cmd eq \"require\"} {\n"
  981. " foreach path $::auto_path {\n"
  982. " lassign $args pkg\n"
  983. " set pkgpath $path/$pkg.tcl\n"
  984. " if {$path eq \".\"} {\n"
  985. " set pkgpath $pkg.tcl\n"
  986. " }\n"
  987. " if {[file exists $pkgpath]} {\n"
  988. " tailcall uplevel #0 [list source $pkgpath]\n"
  989. " }\n"
  990. " }\n"
  991. " }\n"
  992. "}\n"
  993. "set tcl_platform(bootstrap) 1\n"
  994. );
  995. }
  996. int Jim_initjimshInit(Jim_Interp *interp)
  997. {
  998. if (Jim_PackageProvide(interp, "initjimsh", "1.0", JIM_ERRMSG))
  999. return JIM_ERR;
  1000. return Jim_EvalSource(interp, "initjimsh.tcl", 1,
  1001. "\n"
  1002. "\n"
  1003. "\n"
  1004. "proc _jimsh_init {} {\n"
  1005. " rename _jimsh_init {}\n"
  1006. " global jim::exe jim::argv0 tcl_interactive auto_path tcl_platform\n"
  1007. "\n"
  1008. "\n"
  1009. " if {[exists jim::argv0]} {\n"
  1010. " if {[string match \"*/*\" $jim::argv0]} {\n"
  1011. " set jim::exe [file join [pwd] $jim::argv0]\n"
  1012. " } else {\n"
  1013. " set jim::argv0 [file tail $jim::argv0]\n"
  1014. " set path [split [env PATH \"\"] $tcl_platform(pathSeparator)]\n"
  1015. " if {$tcl_platform(platform) eq \"windows\"} {\n"
  1016. "\n"
  1017. " set path [lmap p [list \"\" {*}$path] { string map {\\\\ /} $p }]\n"
  1018. " }\n"
  1019. " foreach p $path {\n"
  1020. " set exec [file join [pwd] $p $jim::argv0]\n"
  1021. " if {[file executable $exec]} {\n"
  1022. " set jim::exe $exec\n"
  1023. " break\n"
  1024. " }\n"
  1025. " }\n"
  1026. " }\n"
  1027. " }\n"
  1028. "\n"
  1029. "\n"
  1030. " lappend p {*}[split [env JIMLIB {}] $tcl_platform(pathSeparator)]\n"
  1031. " if {[exists jim::exe]} {\n"
  1032. " lappend p [file dirname $jim::exe]\n"
  1033. " }\n"
  1034. " lappend p {*}$auto_path\n"
  1035. " set auto_path $p\n"
  1036. "\n"
  1037. " if {$tcl_interactive && [env HOME {}] ne \"\"} {\n"
  1038. " foreach src {.jimrc jimrc.tcl} {\n"
  1039. " if {[file exists [env HOME]/$src]} {\n"
  1040. " uplevel #0 source [env HOME]/$src\n"
  1041. " break\n"
  1042. " }\n"
  1043. " }\n"
  1044. " }\n"
  1045. " return \"\"\n"
  1046. "}\n"
  1047. "\n"
  1048. "if {$tcl_platform(platform) eq \"windows\"} {\n"
  1049. " set jim::argv0 [string map {\\\\ /} $jim::argv0]\n"
  1050. "}\n"
  1051. "\n"
  1052. "\n"
  1053. "set tcl::autocomplete_commands {array clock debug dict file history info namespace package signal socket string tcl::prefix zlib}\n"
  1054. "\n"
  1055. "\n"
  1056. "\n"
  1057. "proc tcl::autocomplete {prefix} {\n"
  1058. " if {[set space [string first \" \" $prefix]] != -1} {\n"
  1059. " set cmd [string range $prefix 0 $space-1]\n"
  1060. " if {$cmd in $::tcl::autocomplete_commands || [info channel $cmd] ne \"\"} {\n"
  1061. " set arg [string range $prefix $space+1 end]\n"
  1062. "\n"
  1063. " return [lmap p [$cmd -commands] {\n"
  1064. " if {![string match \"${arg}*\" $p]} continue\n"
  1065. " function \"$cmd $p\"\n"
  1066. " }]\n"
  1067. " }\n"
  1068. " }\n"
  1069. "\n"
  1070. " if {[string match \"source *\" $prefix]} {\n"
  1071. " set path [string range $prefix 7 end]\n"
  1072. " return [lmap p [glob -nocomplain \"${path}*\"] {\n"
  1073. " function \"source $p\"\n"
  1074. " }]\n"
  1075. " }\n"
  1076. "\n"
  1077. " return [lmap p [lsort [info commands $prefix*]] {\n"
  1078. " if {[string match \"* *\" $p]} {\n"
  1079. " continue\n"
  1080. " }\n"
  1081. " function $p\n"
  1082. " }]\n"
  1083. "}\n"
  1084. "\n"
  1085. "\n"
  1086. "set tcl::stdhint_commands {array clock debug dict file history info namespace package signal string zlib}\n"
  1087. "\n"
  1088. "set tcl::stdhint_cols {\n"
  1089. " none {0}\n"
  1090. " black {30}\n"
  1091. " red {31}\n"
  1092. " green {32}\n"
  1093. " yellow {33}\n"
  1094. " blue {34}\n"
  1095. " purple {35}\n"
  1096. " cyan {36}\n"
  1097. " normal {37}\n"
  1098. " grey {30 1}\n"
  1099. " gray {30 1}\n"
  1100. " lred {31 1}\n"
  1101. " lgreen {32 1}\n"
  1102. " lyellow {33 1}\n"
  1103. " lblue {34 1}\n"
  1104. " lpurple {35 1}\n"
  1105. " lcyan {36 1}\n"
  1106. " white {37 1}\n"
  1107. "}\n"
  1108. "\n"
  1109. "\n"
  1110. "set tcl::stdhint_col $tcl::stdhint_cols(lcyan)\n"
  1111. "\n"
  1112. "\n"
  1113. "proc tcl::stdhint {string} {\n"
  1114. " set result \"\"\n"
  1115. " if {[llength $string] >= 2} {\n"
  1116. " lassign $string cmd arg\n"
  1117. " if {$cmd in $::tcl::stdhint_commands || [info channel $cmd] ne \"\"} {\n"
  1118. " catch {\n"
  1119. " set help [$cmd -help $arg]\n"
  1120. " if {[string match \"Usage: $cmd *\" $help]} {\n"
  1121. " set n [llength $string]\n"
  1122. " set subcmd [lindex $help $n]\n"
  1123. " incr n\n"
  1124. " set hint [join [lrange $help $n end]]\n"
  1125. " set prefix \"\"\n"
  1126. " if {![string match \"* \" $string]} {\n"
  1127. " if {$n == 3 && $subcmd ne $arg} {\n"
  1128. "\n"
  1129. " set prefix \"[string range $subcmd [string length $arg] end] \"\n"
  1130. " } else {\n"
  1131. " set prefix \" \"\n"
  1132. " }\n"
  1133. " }\n"
  1134. " set result [list $prefix$hint {*}$::tcl::stdhint_col]\n"
  1135. " }\n"
  1136. " }\n"
  1137. " }\n"
  1138. " }\n"
  1139. " return $result\n"
  1140. "}\n"
  1141. "\n"
  1142. "_jimsh_init\n"
  1143. );
  1144. }
  1145. int Jim_globInit(Jim_Interp *interp)
  1146. {
  1147. if (Jim_PackageProvide(interp, "glob", "1.0", JIM_ERRMSG))
  1148. return JIM_ERR;
  1149. return Jim_EvalSource(interp, "glob.tcl", 1,
  1150. "\n"
  1151. "\n"
  1152. "\n"
  1153. "\n"
  1154. "\n"
  1155. "\n"
  1156. "\n"
  1157. "package require readdir\n"
  1158. "\n"
  1159. "\n"
  1160. "proc glob.globdir {dir pattern} {\n"
  1161. " if {[file exists $dir/$pattern]} {\n"
  1162. "\n"
  1163. " return [list $pattern]\n"
  1164. " }\n"
  1165. "\n"
  1166. " set result {}\n"
  1167. " set files [readdir $dir]\n"
  1168. " lappend files . ..\n"
  1169. "\n"
  1170. " foreach name $files {\n"
  1171. " if {[string match $pattern $name]} {\n"
  1172. "\n"
  1173. " if {[string index $name 0] eq \".\" && [string index $pattern 0] ne \".\"} {\n"
  1174. " continue\n"
  1175. " }\n"
  1176. " lappend result $name\n"
  1177. " }\n"
  1178. " }\n"
  1179. "\n"
  1180. " return $result\n"
  1181. "}\n"
  1182. "\n"
  1183. "\n"
  1184. "\n"
  1185. "\n"
  1186. "proc glob.explode {pattern} {\n"
  1187. " set oldexp {}\n"
  1188. " set newexp {\"\"}\n"
  1189. "\n"
  1190. " while 1 {\n"
  1191. " set oldexp $newexp\n"
  1192. " set newexp {}\n"
  1193. " set ob [string first \\{ $pattern]\n"
  1194. " set cb [string first \\} $pattern]\n"
  1195. "\n"
  1196. " if {$ob < $cb && $ob != -1} {\n"
  1197. " set mid [string range $pattern 0 $ob-1]\n"
  1198. " set subexp [lassign [glob.explode [string range $pattern $ob+1 end]] pattern]\n"
  1199. " if {$pattern eq \"\"} {\n"
  1200. " error \"unmatched open brace in glob pattern\"\n"
  1201. " }\n"
  1202. " set pattern [string range $pattern 1 end]\n"
  1203. "\n"
  1204. " foreach subs $subexp {\n"
  1205. " foreach sub [split $subs ,] {\n"
  1206. " foreach old $oldexp {\n"
  1207. " lappend newexp $old$mid$sub\n"
  1208. " }\n"
  1209. " }\n"
  1210. " }\n"
  1211. " } elseif {$cb != -1} {\n"
  1212. " set suf [string range $pattern 0 $cb-1]\n"
  1213. " set rest [string range $pattern $cb end]\n"
  1214. " break\n"
  1215. " } else {\n"
  1216. " set suf $pattern\n"
  1217. " set rest \"\"\n"
  1218. " break\n"
  1219. " }\n"
  1220. " }\n"
  1221. "\n"
  1222. " foreach old $oldexp {\n"
  1223. " lappend newexp $old$suf\n"
  1224. " }\n"
  1225. " list $rest {*}$newexp\n"
  1226. "}\n"
  1227. "\n"
  1228. "\n"
  1229. "\n"
  1230. "proc glob.glob {base pattern} {\n"
  1231. " set dir [file dirname $pattern]\n"
  1232. " if {$pattern eq $dir || $pattern eq \"\"} {\n"
  1233. " return [list [file join $base $dir] $pattern]\n"
  1234. " } elseif {$pattern eq [file tail $pattern]} {\n"
  1235. " set dir \"\"\n"
  1236. " }\n"
  1237. "\n"
  1238. "\n"
  1239. " set dirlist [glob.glob $base $dir]\n"
  1240. " set pattern [file tail $pattern]\n"
  1241. "\n"
  1242. "\n"
  1243. " set result {}\n"
  1244. " foreach {realdir dir} $dirlist {\n"
  1245. " if {![file isdir $realdir]} {\n"
  1246. " continue\n"
  1247. " }\n"
  1248. " if {[string index $dir end] ne \"/\" && $dir ne \"\"} {\n"
  1249. " append dir /\n"
  1250. " }\n"
  1251. " foreach name [glob.globdir $realdir $pattern] {\n"
  1252. " lappend result [file join $realdir $name] $dir$name\n"
  1253. " }\n"
  1254. " }\n"
  1255. " return $result\n"
  1256. "}\n"
  1257. "\n"
  1258. "\n"
  1259. "\n"
  1260. "\n"
  1261. "\n"
  1262. "\n"
  1263. "\n"
  1264. "\n"
  1265. "\n"
  1266. "\n"
  1267. "\n"
  1268. "\n"
  1269. "proc glob {args} {\n"
  1270. " set nocomplain 0\n"
  1271. " set base \"\"\n"
  1272. " set tails 0\n"
  1273. "\n"
  1274. " set n 0\n"
  1275. " foreach arg $args {\n"
  1276. " if {[info exists param]} {\n"
  1277. " set $param $arg\n"
  1278. " unset param\n"
  1279. " incr n\n"
  1280. " continue\n"
  1281. " }\n"
  1282. " switch -glob -- $arg {\n"
  1283. " -d* {\n"
  1284. " set switch $arg\n"
  1285. " set param base\n"
  1286. " }\n"
  1287. " -n* {\n"
  1288. " set nocomplain 1\n"
  1289. " }\n"
  1290. " -ta* {\n"
  1291. " set tails 1\n"
  1292. " }\n"
  1293. " -- {\n"
  1294. " incr n\n"
  1295. " break\n"
  1296. " }\n"
  1297. " -* {\n"
  1298. " return -code error \"bad option \\\"$arg\\\": must be -directory, -nocomplain, -tails, or --\"\n"
  1299. " }\n"
  1300. " * {\n"
  1301. " break\n"
  1302. " }\n"
  1303. " }\n"
  1304. " incr n\n"
  1305. " }\n"
  1306. " if {[info exists param]} {\n"
  1307. " return -code error \"missing argument to \\\"$switch\\\"\"\n"
  1308. " }\n"
  1309. " if {[llength $args] <= $n} {\n"
  1310. " return -code error \"wrong # args: should be \\\"glob ?options? pattern ?pattern ...?\\\"\"\n"
  1311. " }\n"
  1312. "\n"
  1313. " set args [lrange $args $n end]\n"
  1314. "\n"
  1315. " set result {}\n"
  1316. " foreach pattern $args {\n"
  1317. " set escpattern [string map {\n"
  1318. " \\\\\\\\ \\x01 \\\\\\{ \\x02 \\\\\\} \\x03 \\\\, \\x04\n"
  1319. " } $pattern]\n"
  1320. " set patexps [lassign [glob.explode $escpattern] rest]\n"
  1321. " if {$rest ne \"\"} {\n"
  1322. " return -code error \"unmatched close brace in glob pattern\"\n"
  1323. " }\n"
  1324. " foreach patexp $patexps {\n"
  1325. " set patexp [string map {\n"
  1326. " \\x01 \\\\\\\\ \\x02 \\{ \\x03 \\} \\x04 ,\n"
  1327. " } $patexp]\n"
  1328. " foreach {realname name} [glob.glob $base $patexp] {\n"
  1329. " incr n\n"
  1330. " if {$tails} {\n"
  1331. " lappend result $name\n"
  1332. " } else {\n"
  1333. " lappend result [file join $base $name]\n"
  1334. " }\n"
  1335. " }\n"
  1336. " }\n"
  1337. " }\n"
  1338. "\n"
  1339. " if {!$nocomplain && [llength $result] == 0} {\n"
  1340. " set s $(([llength $args] > 1) ? \"s\" : \"\")\n"
  1341. " return -code error \"no files matched glob pattern$s \\\"[join $args]\\\"\"\n"
  1342. " }\n"
  1343. "\n"
  1344. " return $result\n"
  1345. "}\n"
  1346. );
  1347. }
  1348. int Jim_stdlibInit(Jim_Interp *interp)
  1349. {
  1350. if (Jim_PackageProvide(interp, "stdlib", "1.0", JIM_ERRMSG))
  1351. return JIM_ERR;
  1352. return Jim_EvalSource(interp, "stdlib.tcl", 1,
  1353. "\n"
  1354. "\n"
  1355. "if {![exists -command ref]} {\n"
  1356. "\n"
  1357. " proc ref {args} {{count 0}} {\n"
  1358. " format %08x [incr count]\n"
  1359. " }\n"
  1360. "}\n"
  1361. "\n"
  1362. "\n"
  1363. "proc lambda {arglist args} {\n"
  1364. " tailcall proc [ref {} function lambda.finalizer] $arglist {*}$args\n"
  1365. "}\n"
  1366. "\n"
  1367. "proc lambda.finalizer {name val} {\n"
  1368. " rename $name {}\n"
  1369. "}\n"
  1370. "\n"
  1371. "\n"
  1372. "proc curry {args} {\n"
  1373. " alias [ref {} function lambda.finalizer] {*}$args\n"
  1374. "}\n"
  1375. "\n"
  1376. "\n"
  1377. "\n"
  1378. "\n"
  1379. "\n"
  1380. "\n"
  1381. "\n"
  1382. "\n"
  1383. "\n"
  1384. "proc function {value} {\n"
  1385. " return $value\n"
  1386. "}\n"
  1387. "\n"
  1388. "\n"
  1389. "proc stackdump {stacktrace} {\n"
  1390. " set lines {}\n"
  1391. " lappend lines \"Traceback (most recent call last):\"\n"
  1392. " foreach {cmd l f p} [lreverse $stacktrace] {\n"
  1393. " set line {}\n"
  1394. " if {$f ne \"\"} {\n"
  1395. " append line \" File \\\"$f\\\", line $l\"\n"
  1396. " }\n"
  1397. " if {$p ne \"\"} {\n"
  1398. " append line \", in $p\"\n"
  1399. " }\n"
  1400. " if {$line ne \"\"} {\n"
  1401. " lappend lines $line\n"
  1402. " if {$cmd ne \"\"} {\n"
  1403. " set nl [string first \\n $cmd 1]\n"
  1404. " if {$nl >= 0} {\n"
  1405. " set cmd [string range $cmd 0 $nl-1]...\n"
  1406. " }\n"
  1407. " lappend lines \" $cmd\"\n"
  1408. " }\n"
  1409. " }\n"
  1410. " }\n"
  1411. " if {[llength $lines] > 1} {\n"
  1412. " return [join $lines \\n]\n"
  1413. " }\n"
  1414. "}\n"
  1415. "\n"
  1416. "\n"
  1417. "\n"
  1418. "proc defer {script} {\n"
  1419. " upvar jim::defer v\n"
  1420. " lappend v $script\n"
  1421. "}\n"
  1422. "\n"
  1423. "\n"
  1424. "\n"
  1425. "proc errorInfo {msg {stacktrace \"\"}} {\n"
  1426. " if {$stacktrace eq \"\"} {\n"
  1427. "\n"
  1428. " set stacktrace [info stacktrace]\n"
  1429. " }\n"
  1430. " lassign $stacktrace p f l cmd\n"
  1431. " if {$f ne \"\"} {\n"
  1432. " set result \"$f:$l: Error: \"\n"
  1433. " }\n"
  1434. " append result \"$msg\\n\"\n"
  1435. " append result [stackdump $stacktrace]\n"
  1436. "\n"
  1437. "\n"
  1438. " string trim $result\n"
  1439. "}\n"
  1440. "\n"
  1441. "\n"
  1442. "\n"
  1443. "proc {info nameofexecutable} {} {\n"
  1444. " if {[exists ::jim::exe]} {\n"
  1445. " return $::jim::exe\n"
  1446. " }\n"
  1447. "}\n"
  1448. "\n"
  1449. "\n"
  1450. "proc {dict update} {&varName args script} {\n"
  1451. " set keys {}\n"
  1452. " foreach {n v} $args {\n"
  1453. " upvar $v var_$v\n"
  1454. " if {[dict exists $varName $n]} {\n"
  1455. " set var_$v [dict get $varName $n]\n"
  1456. " }\n"
  1457. " }\n"
  1458. " catch {uplevel 1 $script} msg opts\n"
  1459. " if {[info exists varName]} {\n"
  1460. " foreach {n v} $args {\n"
  1461. " if {[info exists var_$v]} {\n"
  1462. " dict set varName $n [set var_$v]\n"
  1463. " } else {\n"
  1464. " dict unset varName $n\n"
  1465. " }\n"
  1466. " }\n"
  1467. " }\n"
  1468. " return {*}$opts $msg\n"
  1469. "}\n"
  1470. "\n"
  1471. "proc {dict replace} {dictionary {args {key value}}} {\n"
  1472. " if {[llength ${key value}] % 2} {\n"
  1473. " tailcall {dict replace}\n"
  1474. " }\n"
  1475. " tailcall dict merge $dictionary ${key value}\n"
  1476. "}\n"
  1477. "\n"
  1478. "\n"
  1479. "proc {dict lappend} {varName key {args value}} {\n"
  1480. " upvar $varName dict\n"
  1481. " if {[exists dict] && [dict exists $dict $key]} {\n"
  1482. " set list [dict get $dict $key]\n"
  1483. " }\n"
  1484. " lappend list {*}$value\n"
  1485. " dict set dict $key $list\n"
  1486. "}\n"
  1487. "\n"
  1488. "\n"
  1489. "proc {dict append} {varName key {args value}} {\n"
  1490. " upvar $varName dict\n"
  1491. " if {[exists dict] && [dict exists $dict $key]} {\n"
  1492. " set str [dict get $dict $key]\n"
  1493. " }\n"
  1494. " append str {*}$value\n"
  1495. " dict set dict $key $str\n"
  1496. "}\n"
  1497. "\n"
  1498. "\n"
  1499. "proc {dict incr} {varName key {increment 1}} {\n"
  1500. " upvar $varName dict\n"
  1501. " if {[exists dict] && [dict exists $dict $key]} {\n"
  1502. " set value [dict get $dict $key]\n"
  1503. " }\n"
  1504. " incr value $increment\n"
  1505. " dict set dict $key $value\n"
  1506. "}\n"
  1507. "\n"
  1508. "\n"
  1509. "proc {dict remove} {dictionary {args key}} {\n"
  1510. " foreach k $key {\n"
  1511. " dict unset dictionary $k\n"
  1512. " }\n"
  1513. " return $dictionary\n"
  1514. "}\n"
  1515. "\n"
  1516. "\n"
  1517. "proc {dict for} {vars dictionary script} {\n"
  1518. " if {[llength $vars] != 2} {\n"
  1519. " return -code error \"must have exactly two variable names\"\n"
  1520. " }\n"
  1521. " dict size $dictionary\n"
  1522. " tailcall foreach $vars $dictionary $script\n"
  1523. "}\n"
  1524. );
  1525. }
  1526. int Jim_tclcompatInit(Jim_Interp *interp)
  1527. {
  1528. if (Jim_PackageProvide(interp, "tclcompat", "1.0", JIM_ERRMSG))
  1529. return JIM_ERR;
  1530. return Jim_EvalSource(interp, "tclcompat.tcl", 1,
  1531. "\n"
  1532. "\n"
  1533. "\n"
  1534. "\n"
  1535. "\n"
  1536. "\n"
  1537. "\n"
  1538. "\n"
  1539. "set env [env]\n"
  1540. "\n"
  1541. "\n"
  1542. "if {[exists -command stdout]} {\n"
  1543. "\n"
  1544. " foreach p {gets flush close eof seek tell} {\n"
  1545. " proc $p {chan args} {p} {\n"
  1546. " tailcall $chan $p {*}$args\n"
  1547. " }\n"
  1548. " }\n"
  1549. " unset p\n"
  1550. "\n"
  1551. "\n"
  1552. "\n"
  1553. " proc puts {{-nonewline {}} {chan stdout} msg} {\n"
  1554. " if {${-nonewline} ni {-nonewline {}}} {\n"
  1555. " tailcall ${-nonewline} puts $msg\n"
  1556. " }\n"
  1557. " tailcall $chan puts {*}${-nonewline} $msg\n"
  1558. " }\n"
  1559. "\n"
  1560. "\n"
  1561. "\n"
  1562. "\n"
  1563. "\n"
  1564. " proc read {{-nonewline {}} chan} {\n"
  1565. " if {${-nonewline} ni {-nonewline {}}} {\n"
  1566. " tailcall ${-nonewline} read {*}${chan}\n"
  1567. " }\n"
  1568. " tailcall $chan read {*}${-nonewline}\n"
  1569. " }\n"
  1570. "\n"
  1571. " proc fconfigure {f args} {\n"
  1572. " foreach {n v} $args {\n"
  1573. " switch -glob -- $n {\n"
  1574. " -bl* {\n"
  1575. " $f ndelay $(!$v)\n"
  1576. " }\n"
  1577. " -bu* {\n"
  1578. " $f buffering $v\n"
  1579. " }\n"
  1580. " -tr* {\n"
  1581. "\n"
  1582. " }\n"
  1583. " default {\n"
  1584. " return -code error \"fconfigure: unknown option $n\"\n"
  1585. " }\n"
  1586. " }\n"
  1587. " }\n"
  1588. " }\n"
  1589. "}\n"
  1590. "\n"
  1591. "\n"
  1592. "proc fileevent {args} {\n"
  1593. " tailcall {*}$args\n"
  1594. "}\n"
  1595. "\n"
  1596. "\n"
  1597. "\n"
  1598. "proc parray {arrayname {pattern *} {puts puts}} {\n"
  1599. " upvar $arrayname a\n"
  1600. "\n"
  1601. " set max 0\n"
  1602. " foreach name [array names a $pattern]] {\n"
  1603. " if {[string length $name] > $max} {\n"
  1604. " set max [string length $name]\n"
  1605. " }\n"
  1606. " }\n"
  1607. " incr max [string length $arrayname]\n"
  1608. " incr max 2\n"
  1609. " foreach name [lsort [array names a $pattern]] {\n"
  1610. " $puts [format \"%-${max}s = %s\" $arrayname\\($name\\) $a($name)]\n"
  1611. " }\n"
  1612. "}\n"
  1613. "\n"
  1614. "\n"
  1615. "proc {file copy} {{force {}} source target} {\n"
  1616. " try {\n"
  1617. " if {$force ni {{} -force}} {\n"
  1618. " error \"bad option \\\"$force\\\": should be -force\"\n"
  1619. " }\n"
  1620. "\n"
  1621. " set in [open $source rb]\n"
  1622. "\n"
  1623. " if {[file exists $target]} {\n"
  1624. " if {$force eq \"\"} {\n"
  1625. " error \"error copying \\\"$source\\\" to \\\"$target\\\": file already exists\"\n"
  1626. " }\n"
  1627. "\n"
  1628. " if {$source eq $target} {\n"
  1629. " return\n"
  1630. " }\n"
  1631. "\n"
  1632. "\n"
  1633. " file stat $source ss\n"
  1634. " file stat $target ts\n"
  1635. " if {$ss(dev) == $ts(dev) && $ss(ino) == $ts(ino) && $ss(ino)} {\n"
  1636. " return\n"
  1637. " }\n"
  1638. " }\n"
  1639. " set out [open $target wb]\n"
  1640. " $in copyto $out\n"
  1641. " $out close\n"
  1642. " } on error {msg opts} {\n"
  1643. " incr opts(-level)\n"
  1644. " return {*}$opts $msg\n"
  1645. " } finally {\n"
  1646. " catch {$in close}\n"
  1647. " }\n"
  1648. "}\n"
  1649. "\n"
  1650. "\n"
  1651. "\n"
  1652. "proc popen {cmd {mode r}} {\n"
  1653. " lassign [pipe] r w\n"
  1654. " try {\n"
  1655. " if {[string match \"w*\" $mode]} {\n"
  1656. " lappend cmd <@$r &\n"
  1657. " set pids [exec {*}$cmd]\n"
  1658. " $r close\n"
  1659. " set f $w\n"
  1660. " } else {\n"
  1661. " lappend cmd >@$w &\n"
  1662. " set pids [exec {*}$cmd]\n"
  1663. " $w close\n"
  1664. " set f $r\n"
  1665. " }\n"
  1666. " lambda {cmd args} {f pids} {\n"
  1667. " if {$cmd eq \"pid\"} {\n"
  1668. " return $pids\n"
  1669. " }\n"
  1670. " if {$cmd eq \"close\"} {\n"
  1671. " $f close\n"
  1672. "\n"
  1673. " set retopts {}\n"
  1674. " foreach p $pids {\n"
  1675. " lassign [wait $p] status - rc\n"
  1676. " if {$status eq \"CHILDSTATUS\"} {\n"
  1677. " if {$rc == 0} {\n"
  1678. " continue\n"
  1679. " }\n"
  1680. " set msg \"child process exited abnormally\"\n"
  1681. " } else {\n"
  1682. " set msg \"child killed: received signal\"\n"
  1683. " }\n"
  1684. " set retopts [list -code error -errorcode [list $status $p $rc] $msg]\n"
  1685. " }\n"
  1686. " return {*}$retopts\n"
  1687. " }\n"
  1688. " tailcall $f $cmd {*}$args\n"
  1689. " }\n"
  1690. " } on error {error opts} {\n"
  1691. " $r close\n"
  1692. " $w close\n"
  1693. " error $error\n"
  1694. " }\n"
  1695. "}\n"
  1696. "\n"
  1697. "\n"
  1698. "local proc pid {{channelId {}}} {\n"
  1699. " if {$channelId eq \"\"} {\n"
  1700. " tailcall upcall pid\n"
  1701. " }\n"
  1702. " if {[catch {$channelId tell}]} {\n"
  1703. " return -code error \"can not find channel named \\\"$channelId\\\"\"\n"
  1704. " }\n"
  1705. " if {[catch {$channelId pid} pids]} {\n"
  1706. " return \"\"\n"
  1707. " }\n"
  1708. " return $pids\n"
  1709. "}\n"
  1710. "\n"
  1711. "\n"
  1712. "\n"
  1713. "proc throw {code {msg \"\"}} {\n"
  1714. " return -code $code $msg\n"
  1715. "}\n"
  1716. "\n"
  1717. "\n"
  1718. "proc {file delete force} {path} {\n"
  1719. " foreach e [readdir $path] {\n"
  1720. " file delete -force $path/$e\n"
  1721. " }\n"
  1722. " file delete $path\n"
  1723. "}\n"
  1724. );
  1725. }
  1726. #include <stdio.h>
  1727. #include <string.h>
  1728. #include <errno.h>
  1729. #include <fcntl.h>
  1730. #include <assert.h>
  1731. #ifdef HAVE_UNISTD_H
  1732. #include <unistd.h>
  1733. #include <sys/stat.h>
  1734. #endif
  1735. #ifdef HAVE_UTIL_H
  1736. #include <util.h>
  1737. #endif
  1738. #ifdef HAVE_PTY_H
  1739. #include <pty.h>
  1740. #endif
  1741. #if defined(HAVE_SYS_SOCKET_H) && defined(HAVE_SELECT) && defined(HAVE_NETINET_IN_H) && defined(HAVE_NETDB_H) && defined(HAVE_ARPA_INET_H)
  1742. #include <sys/socket.h>
  1743. #include <netinet/in.h>
  1744. #include <netinet/tcp.h>
  1745. #include <arpa/inet.h>
  1746. #include <netdb.h>
  1747. #ifdef HAVE_SYS_UN_H
  1748. #include <sys/un.h>
  1749. #endif
  1750. #define HAVE_SOCKETS
  1751. #elif defined (__MINGW32__)
  1752. #endif
  1753. #if defined(JIM_SSL)
  1754. #include <openssl/ssl.h>
  1755. #include <openssl/err.h>
  1756. #endif
  1757. #ifdef HAVE_TERMIOS_H
  1758. #endif
  1759. #define AIO_CMD_LEN 32
  1760. #define AIO_DEFAULT_RBUF_LEN 256
  1761. #define AIO_DEFAULT_WBUF_LIMIT (64 * 1024)
  1762. #define AIO_KEEPOPEN 1
  1763. #define AIO_NODELETE 2
  1764. #define AIO_EOF 4
  1765. #define AIO_WBUF_NONE 8
  1766. #define AIO_NONBLOCK 16
  1767. #define AIO_ONEREAD 32
  1768. enum wbuftype {
  1769. WBUF_OPT_NONE,
  1770. WBUF_OPT_LINE,
  1771. WBUF_OPT_FULL,
  1772. };
  1773. #if defined(JIM_IPV6)
  1774. #define IPV6 1
  1775. #else
  1776. #define IPV6 0
  1777. #ifndef PF_INET6
  1778. #define PF_INET6 0
  1779. #endif
  1780. #endif
  1781. #if defined(HAVE_SYS_UN_H) && defined(PF_UNIX)
  1782. #define UNIX_SOCKETS 1
  1783. #else
  1784. #define UNIX_SOCKETS 0
  1785. #endif
  1786. #ifndef MAXPATHLEN
  1787. #define MAXPATHLEN JIM_PATH_LEN
  1788. #endif
  1789. static int JimReadableTimeout(int fd, long ms)
  1790. {
  1791. #ifdef HAVE_SELECT
  1792. int retval;
  1793. struct timeval tv;
  1794. fd_set rfds;
  1795. FD_ZERO(&rfds);
  1796. FD_SET(fd, &rfds);
  1797. tv.tv_sec = ms / 1000;
  1798. tv.tv_usec = (ms % 1000) * 1000;
  1799. retval = select(fd + 1, &rfds, NULL, NULL, ms == 0 ? NULL : &tv);
  1800. if (retval > 0) {
  1801. return JIM_OK;
  1802. }
  1803. return JIM_ERR;
  1804. #else
  1805. return JIM_OK;
  1806. #endif
  1807. }
  1808. struct AioFile;
  1809. typedef struct {
  1810. int (*writer)(struct AioFile *af, const char *buf, int len);
  1811. int (*reader)(struct AioFile *af, char *buf, int len, int pending);
  1812. int (*error)(const struct AioFile *af);
  1813. const char *(*strerror)(struct AioFile *af);
  1814. int (*verify)(struct AioFile *af);
  1815. } JimAioFopsType;
  1816. typedef struct AioFile
  1817. {
  1818. Jim_Obj *filename;
  1819. int wbuft;
  1820. int flags;
  1821. long timeout;
  1822. int fd;
  1823. int addr_family;
  1824. void *ssl;
  1825. const JimAioFopsType *fops;
  1826. Jim_Obj *readbuf;
  1827. Jim_Obj *writebuf;
  1828. char *rbuf;
  1829. size_t rbuf_len;
  1830. size_t wbuf_limit;
  1831. } AioFile;
  1832. static void aio_consume(Jim_Obj *objPtr, int n);
  1833. static int stdio_writer(struct AioFile *af, const char *buf, int len)
  1834. {
  1835. int ret = write(af->fd, buf, len);
  1836. if (ret < 0 && errno == EPIPE) {
  1837. aio_consume(af->writebuf, Jim_Length(af->writebuf));
  1838. }
  1839. return ret;
  1840. }
  1841. static int stdio_reader(struct AioFile *af, char *buf, int len, int nb)
  1842. {
  1843. if (nb || af->timeout == 0 || JimReadableTimeout(af->fd, af->timeout) == JIM_OK) {
  1844. int ret;
  1845. errno = 0;
  1846. ret = read(af->fd, buf, len);
  1847. if (ret <= 0 && errno != EAGAIN && errno != EINTR) {
  1848. af->flags |= AIO_EOF;
  1849. }
  1850. return ret;
  1851. }
  1852. errno = ETIMEDOUT;
  1853. return -1;
  1854. }
  1855. static int stdio_error(const AioFile *af)
  1856. {
  1857. if (af->flags & AIO_EOF) {
  1858. return JIM_OK;
  1859. }
  1860. switch (errno) {
  1861. case EAGAIN:
  1862. case EINTR:
  1863. case ETIMEDOUT:
  1864. #ifdef ECONNRESET
  1865. case ECONNRESET:
  1866. #endif
  1867. #ifdef ECONNABORTED
  1868. case ECONNABORTED:
  1869. #endif
  1870. return JIM_OK;
  1871. default:
  1872. return JIM_ERR;
  1873. }
  1874. }
  1875. static const char *stdio_strerror(struct AioFile *af)
  1876. {
  1877. return strerror(errno);
  1878. }
  1879. static const JimAioFopsType stdio_fops = {
  1880. stdio_writer,
  1881. stdio_reader,
  1882. stdio_error,
  1883. stdio_strerror,
  1884. NULL,
  1885. };
  1886. static void aio_set_nonblocking(AioFile *af, int nb)
  1887. {
  1888. #ifdef O_NDELAY
  1889. int old = !!(af->flags & AIO_NONBLOCK);
  1890. if (old != nb) {
  1891. int fmode = fcntl(af->fd, F_GETFL);
  1892. if (nb) {
  1893. fmode |= O_NDELAY;
  1894. af->flags |= AIO_NONBLOCK;
  1895. }
  1896. else {
  1897. fmode &= ~O_NDELAY;
  1898. af->flags &= ~AIO_NONBLOCK;
  1899. }
  1900. (void)fcntl(af->fd, F_SETFL, fmode);
  1901. }
  1902. #endif
  1903. }
  1904. static int aio_start_nonblocking(AioFile *af)
  1905. {
  1906. int old = !!(af->flags & AIO_NONBLOCK);
  1907. if (af->timeout) {
  1908. aio_set_nonblocking(af, 1);
  1909. }
  1910. return old;
  1911. }
  1912. static int JimAioSubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
  1913. static AioFile *JimMakeChannel(Jim_Interp *interp, int fd, Jim_Obj *filename,
  1914. const char *hdlfmt, int family, int flags);
  1915. static const char *JimAioErrorString(AioFile *af)
  1916. {
  1917. if (af && af->fops)
  1918. return af->fops->strerror(af);
  1919. return strerror(errno);
  1920. }
  1921. static void JimAioSetError(Jim_Interp *interp, Jim_Obj *name)
  1922. {
  1923. AioFile *af = Jim_CmdPrivData(interp);
  1924. if (name) {
  1925. Jim_SetResultFormatted(interp, "%#s: %s", name, JimAioErrorString(af));
  1926. }
  1927. else {
  1928. Jim_SetResultString(interp, JimAioErrorString(af), -1);
  1929. }
  1930. }
  1931. static int aio_eof(AioFile *af)
  1932. {
  1933. return af->flags & AIO_EOF;
  1934. }
  1935. static int JimCheckStreamError(Jim_Interp *interp, AioFile *af)
  1936. {
  1937. int ret = 0;
  1938. if (!aio_eof(af)) {
  1939. ret = af->fops->error(af);
  1940. if (ret) {
  1941. JimAioSetError(interp, af->filename);
  1942. }
  1943. }
  1944. return ret;
  1945. }
  1946. static void aio_consume(Jim_Obj *objPtr, int n)
  1947. {
  1948. assert(objPtr->bytes);
  1949. assert(n <= objPtr->length);
  1950. memmove(objPtr->bytes, objPtr->bytes + n, objPtr->length - n + 1);
  1951. objPtr->length -= n;
  1952. }
  1953. static int aio_flush(Jim_Interp *interp, AioFile *af);
  1954. #ifdef jim_ext_eventloop
  1955. static int aio_autoflush(Jim_Interp *interp, void *clientData, int mask)
  1956. {
  1957. AioFile *af = clientData;
  1958. aio_flush(interp, af);
  1959. if (Jim_Length(af->writebuf) == 0) {
  1960. return -1;
  1961. }
  1962. return 0;
  1963. }
  1964. #endif
  1965. static int aio_flush(Jim_Interp *interp, AioFile *af)
  1966. {
  1967. int len;
  1968. const char *pt = Jim_GetString(af->writebuf, &len);
  1969. if (len) {
  1970. int ret = af->fops->writer(af, pt, len);
  1971. if (ret > 0) {
  1972. aio_consume(af->writebuf, ret);
  1973. }
  1974. if (ret < 0) {
  1975. return JimCheckStreamError(interp, af);
  1976. }
  1977. if (Jim_Length(af->writebuf)) {
  1978. #ifdef jim_ext_eventloop
  1979. void *handler = Jim_FindFileHandler(interp, af->fd, JIM_EVENT_WRITABLE);
  1980. if (handler == NULL) {
  1981. Jim_CreateFileHandler(interp, af->fd, JIM_EVENT_WRITABLE, aio_autoflush, af, NULL);
  1982. return JIM_OK;
  1983. }
  1984. else if (handler == af) {
  1985. return JIM_OK;
  1986. }
  1987. #endif
  1988. Jim_SetResultString(interp, "send buffer is full", -1);
  1989. return JIM_ERR;
  1990. }
  1991. }
  1992. return JIM_OK;
  1993. }
  1994. static int aio_read_len(Jim_Interp *interp, AioFile *af, unsigned flags, int neededLen)
  1995. {
  1996. if (!af->readbuf) {
  1997. af->readbuf = Jim_NewStringObj(interp, NULL, 0);
  1998. }
  1999. if (neededLen >= 0) {
  2000. neededLen -= Jim_Length(af->readbuf);
  2001. if (neededLen <= 0) {
  2002. return JIM_OK;
  2003. }
  2004. }
  2005. while (neededLen && !aio_eof(af)) {
  2006. int retval;
  2007. int readlen;
  2008. if (neededLen == -1) {
  2009. readlen = af->rbuf_len;
  2010. }
  2011. else {
  2012. readlen = (neededLen > af->rbuf_len ? af->rbuf_len : neededLen);
  2013. }
  2014. if (!af->rbuf) {
  2015. af->rbuf = Jim_Alloc(af->rbuf_len);
  2016. }
  2017. retval = af->fops->reader(af, af->rbuf, readlen, flags & AIO_NONBLOCK);
  2018. if (retval > 0) {
  2019. if (retval) {
  2020. Jim_AppendString(interp, af->readbuf, af->rbuf, retval);
  2021. }
  2022. if (neededLen != -1) {
  2023. neededLen -= retval;
  2024. }
  2025. if (flags & AIO_ONEREAD) {
  2026. return JIM_OK;
  2027. }
  2028. continue;
  2029. }
  2030. if ((flags & AIO_ONEREAD) || JimCheckStreamError(interp, af)) {
  2031. return JIM_ERR;
  2032. }
  2033. break;
  2034. }
  2035. return JIM_OK;
  2036. }
  2037. static Jim_Obj *aio_read_consume(Jim_Interp *interp, AioFile *af, int neededLen)
  2038. {
  2039. Jim_Obj *objPtr = NULL;
  2040. if (neededLen < 0 || af->readbuf == NULL || Jim_Length(af->readbuf) <= neededLen) {
  2041. objPtr = af->readbuf;
  2042. af->readbuf = NULL;
  2043. }
  2044. else if (af->readbuf) {
  2045. int len;
  2046. const char *pt = Jim_GetString(af->readbuf, &len);
  2047. objPtr = Jim_NewStringObj(interp, pt, neededLen);
  2048. aio_consume(af->readbuf, neededLen);
  2049. }
  2050. return objPtr;
  2051. }
  2052. static void JimAioDelProc(Jim_Interp *interp, void *privData)
  2053. {
  2054. AioFile *af = privData;
  2055. JIM_NOTUSED(interp);
  2056. aio_flush(interp, af);
  2057. Jim_DecrRefCount(interp, af->writebuf);
  2058. #if UNIX_SOCKETS
  2059. if (af->addr_family == PF_UNIX && (af->flags & AIO_NODELETE) == 0) {
  2060. Jim_Obj *filenameObj = aio_sockname(interp, af->fd);
  2061. if (filenameObj) {
  2062. if (Jim_Length(filenameObj)) {
  2063. remove(Jim_String(filenameObj));
  2064. }
  2065. Jim_FreeNewObj(interp, filenameObj);
  2066. }
  2067. }
  2068. #endif
  2069. Jim_DecrRefCount(interp, af->filename);
  2070. #ifdef jim_ext_eventloop
  2071. Jim_DeleteFileHandler(interp, af->fd, JIM_EVENT_READABLE | JIM_EVENT_WRITABLE | JIM_EVENT_EXCEPTION);
  2072. #endif
  2073. #if defined(JIM_SSL)
  2074. if (af->ssl != NULL) {
  2075. SSL_free(af->ssl);
  2076. }
  2077. #endif
  2078. if (!(af->flags & AIO_KEEPOPEN)) {
  2079. close(af->fd);
  2080. }
  2081. if (af->readbuf) {
  2082. Jim_FreeNewObj(interp, af->readbuf);
  2083. }
  2084. Jim_Free(af->rbuf);
  2085. Jim_Free(af);
  2086. }
  2087. static int aio_cmd_read(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2088. {
  2089. AioFile *af = Jim_CmdPrivData(interp);
  2090. int nonewline = 0;
  2091. jim_wide neededLen = -1;
  2092. static const char * const options[] = { "-pending", "-nonewline", NULL };
  2093. enum { OPT_PENDING, OPT_NONEWLINE };
  2094. int option;
  2095. int nb;
  2096. Jim_Obj *objPtr;
  2097. if (argc) {
  2098. if (*Jim_String(argv[0]) == '-') {
  2099. if (Jim_GetEnum(interp, argv[0], options, &option, NULL, JIM_ERRMSG) != JIM_OK) {
  2100. return JIM_ERR;
  2101. }
  2102. switch (option) {
  2103. case OPT_PENDING:
  2104. break;
  2105. case OPT_NONEWLINE:
  2106. nonewline++;
  2107. break;
  2108. }
  2109. }
  2110. else {
  2111. if (Jim_GetWide(interp, argv[0], &neededLen) != JIM_OK)
  2112. return JIM_ERR;
  2113. if (neededLen < 0) {
  2114. Jim_SetResultString(interp, "invalid parameter: negative len", -1);
  2115. return JIM_ERR;
  2116. }
  2117. }
  2118. argc--;
  2119. argv++;
  2120. }
  2121. if (argc) {
  2122. return -1;
  2123. }
  2124. nb = aio_start_nonblocking(af);
  2125. if (aio_read_len(interp, af, nb ? AIO_NONBLOCK : 0, neededLen) != JIM_OK) {
  2126. aio_set_nonblocking(af, nb);
  2127. return JIM_ERR;
  2128. }
  2129. objPtr = aio_read_consume(interp, af, neededLen);
  2130. aio_set_nonblocking(af, nb);
  2131. if (objPtr) {
  2132. if (nonewline) {
  2133. int len;
  2134. const char *s = Jim_GetString(objPtr, &len);
  2135. if (len > 0 && s[len - 1] == '\n') {
  2136. objPtr->length--;
  2137. objPtr->bytes[objPtr->length] = '\0';
  2138. }
  2139. }
  2140. Jim_SetResult(interp, objPtr);
  2141. }
  2142. else {
  2143. Jim_SetEmptyResult(interp);
  2144. }
  2145. return JIM_OK;
  2146. }
  2147. int Jim_AioFilehandle(Jim_Interp *interp, Jim_Obj *command)
  2148. {
  2149. Jim_Cmd *cmdPtr = Jim_GetCommand(interp, command, JIM_ERRMSG);
  2150. if (cmdPtr && !cmdPtr->isproc && cmdPtr->u.native.cmdProc == JimAioSubCmdProc) {
  2151. return ((AioFile *) cmdPtr->u.native.privData)->fd;
  2152. }
  2153. Jim_SetResultFormatted(interp, "Not a filehandle: \"%#s\"", command);
  2154. return -1;
  2155. }
  2156. static int aio_cmd_getfd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2157. {
  2158. AioFile *af = Jim_CmdPrivData(interp);
  2159. aio_flush(interp, af);
  2160. Jim_SetResultInt(interp, af->fd);
  2161. return JIM_OK;
  2162. }
  2163. static int aio_cmd_copy(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2164. {
  2165. AioFile *af = Jim_CmdPrivData(interp);
  2166. jim_wide count = 0;
  2167. jim_wide maxlen = JIM_WIDE_MAX;
  2168. int ok = 1;
  2169. Jim_Obj *objv[4];
  2170. if (argc == 2) {
  2171. if (Jim_GetWide(interp, argv[1], &maxlen) != JIM_OK) {
  2172. return JIM_ERR;
  2173. }
  2174. }
  2175. objv[0] = argv[0];
  2176. objv[1] = Jim_NewStringObj(interp, "flush", -1);
  2177. if (Jim_EvalObjVector(interp, 2, objv) != JIM_OK) {
  2178. Jim_SetResultFormatted(interp, "Not a filehandle: \"%#s\"", argv[0]);
  2179. return JIM_ERR;
  2180. }
  2181. objv[0] = argv[0];
  2182. objv[1] = Jim_NewStringObj(interp, "puts", -1);
  2183. objv[2] = Jim_NewStringObj(interp, "-nonewline", -1);
  2184. Jim_IncrRefCount(objv[1]);
  2185. Jim_IncrRefCount(objv[2]);
  2186. while (count < maxlen) {
  2187. jim_wide len = maxlen - count;
  2188. if (len > af->rbuf_len) {
  2189. len = af->rbuf_len;
  2190. }
  2191. if (aio_read_len(interp, af, 0, len) != JIM_OK) {
  2192. ok = 0;
  2193. break;
  2194. }
  2195. objv[3] = aio_read_consume(interp, af, len);
  2196. count += Jim_Length(objv[3]);
  2197. if (Jim_EvalObjVector(interp, 4, objv) != JIM_OK) {
  2198. ok = 0;
  2199. break;
  2200. }
  2201. if (aio_eof(af)) {
  2202. break;
  2203. }
  2204. if (count >= 16384 && af->rbuf_len < 65536) {
  2205. af->rbuf_len = 65536;
  2206. af->rbuf = Jim_Realloc(af->rbuf, af->rbuf_len);
  2207. }
  2208. }
  2209. Jim_DecrRefCount(interp, objv[1]);
  2210. Jim_DecrRefCount(interp, objv[2]);
  2211. if (!ok) {
  2212. return JIM_ERR;
  2213. }
  2214. Jim_SetResultInt(interp, count);
  2215. return JIM_OK;
  2216. }
  2217. static int aio_cmd_gets(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2218. {
  2219. AioFile *af = Jim_CmdPrivData(interp);
  2220. Jim_Obj *objPtr = NULL;
  2221. int len;
  2222. int nb;
  2223. unsigned flags = AIO_ONEREAD;
  2224. char *nl = NULL;
  2225. int offset = 0;
  2226. errno = 0;
  2227. nb = aio_start_nonblocking(af);
  2228. if (nb) {
  2229. flags |= AIO_NONBLOCK;
  2230. }
  2231. while (!aio_eof(af)) {
  2232. if (af->readbuf) {
  2233. const char *pt = Jim_GetString(af->readbuf, &len);
  2234. nl = memchr(pt + offset, '\n', len - offset);
  2235. if (nl) {
  2236. objPtr = Jim_NewStringObj(interp, pt, nl - pt);
  2237. aio_consume(af->readbuf, nl - pt + 1);
  2238. break;
  2239. }
  2240. offset = len;
  2241. }
  2242. if (aio_read_len(interp, af, flags, -1) != JIM_OK) {
  2243. break;
  2244. }
  2245. }
  2246. aio_set_nonblocking(af, nb);
  2247. if (!nl && aio_eof(af) && af->readbuf) {
  2248. objPtr = af->readbuf;
  2249. af->readbuf = NULL;
  2250. }
  2251. else if (!objPtr) {
  2252. objPtr = Jim_NewStringObj(interp, NULL, 0);
  2253. }
  2254. if (argc) {
  2255. if (Jim_SetVariable(interp, argv[0], objPtr) != JIM_OK) {
  2256. Jim_FreeNewObj(interp, objPtr);
  2257. return JIM_ERR;
  2258. }
  2259. len = Jim_Length(objPtr);
  2260. if (!nl && len == 0) {
  2261. len = -1;
  2262. }
  2263. Jim_SetResultInt(interp, len);
  2264. }
  2265. else {
  2266. Jim_SetResult(interp, objPtr);
  2267. }
  2268. return JIM_OK;
  2269. }
  2270. static int aio_cmd_puts(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2271. {
  2272. AioFile *af = Jim_CmdPrivData(interp);
  2273. int wlen;
  2274. const char *wdata;
  2275. Jim_Obj *strObj;
  2276. int wnow = 0;
  2277. int nl = 1;
  2278. if (argc == 2) {
  2279. if (!Jim_CompareStringImmediate(interp, argv[0], "-nonewline")) {
  2280. return -1;
  2281. }
  2282. strObj = argv[1];
  2283. nl = 0;
  2284. }
  2285. else {
  2286. strObj = argv[0];
  2287. }
  2288. #ifdef JIM_MAINTAINER
  2289. if (Jim_IsShared(af->writebuf)) {
  2290. Jim_DecrRefCount(interp, af->writebuf);
  2291. af->writebuf = Jim_DuplicateObj(interp, af->writebuf);
  2292. Jim_IncrRefCount(af->writebuf);
  2293. }
  2294. #endif
  2295. Jim_AppendObj(interp, af->writebuf, strObj);
  2296. if (nl) {
  2297. Jim_AppendString(interp, af->writebuf, "\n", 1);
  2298. }
  2299. wdata = Jim_GetString(af->writebuf, &wlen);
  2300. switch (af->wbuft) {
  2301. case WBUF_OPT_NONE:
  2302. wnow = 1;
  2303. break;
  2304. case WBUF_OPT_LINE:
  2305. if (nl || memchr(wdata, '\n', wlen) != NULL) {
  2306. wnow = 1;
  2307. }
  2308. break;
  2309. case WBUF_OPT_FULL:
  2310. if (wlen >= af->wbuf_limit) {
  2311. wnow = 1;
  2312. }
  2313. break;
  2314. }
  2315. if (wnow) {
  2316. return aio_flush(interp, af);
  2317. }
  2318. return JIM_OK;
  2319. }
  2320. static int aio_cmd_isatty(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2321. {
  2322. #ifdef HAVE_ISATTY
  2323. AioFile *af = Jim_CmdPrivData(interp);
  2324. Jim_SetResultInt(interp, isatty(af->fd));
  2325. #else
  2326. Jim_SetResultInt(interp, 0);
  2327. #endif
  2328. return JIM_OK;
  2329. }
  2330. static int aio_cmd_flush(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2331. {
  2332. AioFile *af = Jim_CmdPrivData(interp);
  2333. return aio_flush(interp, af);
  2334. }
  2335. static int aio_cmd_eof(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2336. {
  2337. AioFile *af = Jim_CmdPrivData(interp);
  2338. Jim_SetResultInt(interp, !!aio_eof(af));
  2339. return JIM_OK;
  2340. }
  2341. static int aio_cmd_close(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2342. {
  2343. AioFile *af = Jim_CmdPrivData(interp);
  2344. if (argc == 3) {
  2345. int option = -1;
  2346. #if defined(HAVE_SOCKETS)
  2347. static const char * const options[] = { "r", "w", "-nodelete", NULL };
  2348. enum { OPT_R, OPT_W, OPT_NODELETE };
  2349. if (Jim_GetEnum(interp, argv[2], options, &option, NULL, JIM_ERRMSG) != JIM_OK) {
  2350. return JIM_ERR;
  2351. }
  2352. #endif
  2353. switch (option) {
  2354. #if defined(HAVE_SHUTDOWN)
  2355. case OPT_R:
  2356. case OPT_W:
  2357. if (shutdown(af->fd, option == OPT_R ? SHUT_RD : SHUT_WR) == 0) {
  2358. return JIM_OK;
  2359. }
  2360. JimAioSetError(interp, NULL);
  2361. return JIM_ERR;
  2362. #endif
  2363. #if UNIX_SOCKETS
  2364. case OPT_NODELETE:
  2365. if (af->addr_family == PF_UNIX) {
  2366. af->flags |= AIO_NODELETE;
  2367. break;
  2368. }
  2369. #endif
  2370. default:
  2371. Jim_SetResultString(interp, "not supported", -1);
  2372. return JIM_ERR;
  2373. }
  2374. }
  2375. af->flags &= ~AIO_KEEPOPEN;
  2376. return Jim_DeleteCommand(interp, argv[0]);
  2377. }
  2378. static int aio_cmd_seek(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2379. {
  2380. AioFile *af = Jim_CmdPrivData(interp);
  2381. int orig = SEEK_SET;
  2382. jim_wide offset;
  2383. if (argc == 2) {
  2384. if (Jim_CompareStringImmediate(interp, argv[1], "start"))
  2385. orig = SEEK_SET;
  2386. else if (Jim_CompareStringImmediate(interp, argv[1], "current"))
  2387. orig = SEEK_CUR;
  2388. else if (Jim_CompareStringImmediate(interp, argv[1], "end"))
  2389. orig = SEEK_END;
  2390. else {
  2391. return -1;
  2392. }
  2393. }
  2394. if (Jim_GetWide(interp, argv[0], &offset) != JIM_OK) {
  2395. return JIM_ERR;
  2396. }
  2397. if (orig != SEEK_CUR || offset != 0) {
  2398. aio_flush(interp, af);
  2399. }
  2400. if (Jim_Lseek(af->fd, offset, orig) == -1) {
  2401. JimAioSetError(interp, af->filename);
  2402. return JIM_ERR;
  2403. }
  2404. if (af->readbuf) {
  2405. Jim_FreeNewObj(interp, af->readbuf);
  2406. af->readbuf = NULL;
  2407. }
  2408. af->flags &= ~AIO_EOF;
  2409. return JIM_OK;
  2410. }
  2411. static int aio_cmd_tell(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2412. {
  2413. AioFile *af = Jim_CmdPrivData(interp);
  2414. Jim_SetResultInt(interp, Jim_Lseek(af->fd, 0, SEEK_CUR));
  2415. return JIM_OK;
  2416. }
  2417. static int aio_cmd_filename(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2418. {
  2419. AioFile *af = Jim_CmdPrivData(interp);
  2420. Jim_SetResult(interp, af->filename);
  2421. return JIM_OK;
  2422. }
  2423. #ifdef O_NDELAY
  2424. static int aio_cmd_ndelay(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2425. {
  2426. AioFile *af = Jim_CmdPrivData(interp);
  2427. if (argc) {
  2428. long nb;
  2429. if (Jim_GetLong(interp, argv[0], &nb) != JIM_OK) {
  2430. return JIM_ERR;
  2431. }
  2432. aio_set_nonblocking(af, nb);
  2433. }
  2434. Jim_SetResultInt(interp, (af->flags & AIO_NONBLOCK) ? 1 : 0);
  2435. return JIM_OK;
  2436. }
  2437. #endif
  2438. #ifdef HAVE_FSYNC
  2439. static int aio_cmd_sync(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2440. {
  2441. AioFile *af = Jim_CmdPrivData(interp);
  2442. if (aio_flush(interp, af) != JIM_OK) {
  2443. return JIM_ERR;
  2444. }
  2445. fsync(af->fd);
  2446. return JIM_OK;
  2447. }
  2448. #endif
  2449. static int aio_cmd_buffering(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2450. {
  2451. AioFile *af = Jim_CmdPrivData(interp);
  2452. Jim_Obj *resultObj;
  2453. static const char * const options[] = {
  2454. "none",
  2455. "line",
  2456. "full",
  2457. NULL
  2458. };
  2459. if (argc) {
  2460. if (Jim_GetEnum(interp, argv[0], options, &af->wbuft, NULL, JIM_ERRMSG) != JIM_OK) {
  2461. return JIM_ERR;
  2462. }
  2463. if (af->wbuft == WBUF_OPT_FULL && argc == 2) {
  2464. long l;
  2465. if (Jim_GetLong(interp, argv[1], &l) != JIM_OK || l <= 0) {
  2466. return JIM_ERR;
  2467. }
  2468. af->wbuf_limit = l;
  2469. }
  2470. if (af->wbuft == WBUF_OPT_NONE) {
  2471. if (aio_flush(interp, af) != JIM_OK) {
  2472. return JIM_ERR;
  2473. }
  2474. }
  2475. }
  2476. resultObj = Jim_NewListObj(interp, NULL, 0);
  2477. Jim_ListAppendElement(interp, resultObj, Jim_NewStringObj(interp, options[af->wbuft], -1));
  2478. if (af->wbuft == WBUF_OPT_FULL) {
  2479. Jim_ListAppendElement(interp, resultObj, Jim_NewIntObj(interp, af->wbuf_limit));
  2480. }
  2481. Jim_SetResult(interp, resultObj);
  2482. return JIM_OK;
  2483. }
  2484. static int aio_cmd_readsize(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2485. {
  2486. AioFile *af = Jim_CmdPrivData(interp);
  2487. if (argc) {
  2488. long l;
  2489. if (Jim_GetLong(interp, argv[0], &l) != JIM_OK || l <= 0) {
  2490. return JIM_ERR;
  2491. }
  2492. af->rbuf_len = l;
  2493. if (af->rbuf) {
  2494. af->rbuf = Jim_Realloc(af->rbuf, af->rbuf_len);
  2495. }
  2496. }
  2497. Jim_SetResultInt(interp, af->rbuf_len);
  2498. return JIM_OK;
  2499. }
  2500. #ifdef jim_ext_eventloop
  2501. static int aio_cmd_timeout(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2502. {
  2503. #ifdef HAVE_SELECT
  2504. AioFile *af = Jim_CmdPrivData(interp);
  2505. if (argc == 1) {
  2506. if (Jim_GetLong(interp, argv[0], &af->timeout) != JIM_OK) {
  2507. return JIM_ERR;
  2508. }
  2509. }
  2510. Jim_SetResultInt(interp, af->timeout);
  2511. return JIM_OK;
  2512. #else
  2513. Jim_SetResultString(interp, "timeout not supported", -1);
  2514. return JIM_ERR;
  2515. #endif
  2516. }
  2517. static int aio_eventinfo(Jim_Interp *interp, AioFile * af, unsigned mask,
  2518. int argc, Jim_Obj * const *argv)
  2519. {
  2520. if (argc == 0) {
  2521. Jim_Obj *objPtr = Jim_FindFileHandler(interp, af->fd, mask);
  2522. if (objPtr) {
  2523. Jim_SetResult(interp, objPtr);
  2524. }
  2525. return JIM_OK;
  2526. }
  2527. Jim_DeleteFileHandler(interp, af->fd, mask);
  2528. if (Jim_Length(argv[0])) {
  2529. Jim_CreateScriptFileHandler(interp, af->fd, mask, argv[0]);
  2530. }
  2531. return JIM_OK;
  2532. }
  2533. static int aio_cmd_readable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2534. {
  2535. AioFile *af = Jim_CmdPrivData(interp);
  2536. return aio_eventinfo(interp, af, JIM_EVENT_READABLE, argc, argv);
  2537. }
  2538. static int aio_cmd_writable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2539. {
  2540. AioFile *af = Jim_CmdPrivData(interp);
  2541. return aio_eventinfo(interp, af, JIM_EVENT_WRITABLE, argc, argv);
  2542. }
  2543. static int aio_cmd_onexception(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2544. {
  2545. AioFile *af = Jim_CmdPrivData(interp);
  2546. return aio_eventinfo(interp, af, JIM_EVENT_EXCEPTION, argc, argv);
  2547. }
  2548. #endif
  2549. #if defined(jim_ext_file) && defined(Jim_FileStat)
  2550. static int aio_cmd_stat(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2551. {
  2552. jim_stat_t sb;
  2553. AioFile *af = Jim_CmdPrivData(interp);
  2554. if (Jim_FileStat(af->fd, &sb) == -1) {
  2555. JimAioSetError(interp, NULL);
  2556. return JIM_ERR;
  2557. }
  2558. return Jim_FileStoreStatData(interp, argc == 0 ? NULL : argv[0], &sb);
  2559. }
  2560. #endif
  2561. static const jim_subcmd_type aio_command_table[] = {
  2562. { "read",
  2563. "?-nonewline|len?",
  2564. aio_cmd_read,
  2565. 0,
  2566. 2,
  2567. },
  2568. { "copyto",
  2569. "handle ?size?",
  2570. aio_cmd_copy,
  2571. 1,
  2572. 2,
  2573. },
  2574. { "getfd",
  2575. NULL,
  2576. aio_cmd_getfd,
  2577. 0,
  2578. 0,
  2579. },
  2580. { "gets",
  2581. "?var?",
  2582. aio_cmd_gets,
  2583. 0,
  2584. 1,
  2585. },
  2586. { "puts",
  2587. "?-nonewline? str",
  2588. aio_cmd_puts,
  2589. 1,
  2590. 2,
  2591. },
  2592. { "isatty",
  2593. NULL,
  2594. aio_cmd_isatty,
  2595. 0,
  2596. 0,
  2597. },
  2598. { "flush",
  2599. NULL,
  2600. aio_cmd_flush,
  2601. 0,
  2602. 0,
  2603. },
  2604. { "eof",
  2605. NULL,
  2606. aio_cmd_eof,
  2607. 0,
  2608. 0,
  2609. },
  2610. { "close",
  2611. "?r(ead)|w(rite)?",
  2612. aio_cmd_close,
  2613. 0,
  2614. 1,
  2615. JIM_MODFLAG_FULLARGV,
  2616. },
  2617. { "seek",
  2618. "offset ?start|current|end",
  2619. aio_cmd_seek,
  2620. 1,
  2621. 2,
  2622. },
  2623. { "tell",
  2624. NULL,
  2625. aio_cmd_tell,
  2626. 0,
  2627. 0,
  2628. },
  2629. { "filename",
  2630. NULL,
  2631. aio_cmd_filename,
  2632. 0,
  2633. 0,
  2634. },
  2635. #ifdef O_NDELAY
  2636. { "ndelay",
  2637. "?0|1?",
  2638. aio_cmd_ndelay,
  2639. 0,
  2640. 1,
  2641. },
  2642. #endif
  2643. #ifdef HAVE_FSYNC
  2644. { "sync",
  2645. NULL,
  2646. aio_cmd_sync,
  2647. 0,
  2648. 0,
  2649. },
  2650. #endif
  2651. { "buffering",
  2652. "?none|line|full? ?size?",
  2653. aio_cmd_buffering,
  2654. 0,
  2655. 2,
  2656. },
  2657. { "readsize",
  2658. "?size?",
  2659. aio_cmd_readsize,
  2660. 0,
  2661. 1,
  2662. },
  2663. #if defined(jim_ext_file) && defined(Jim_FileStat)
  2664. { "stat",
  2665. "?var?",
  2666. aio_cmd_stat,
  2667. 0,
  2668. 1,
  2669. },
  2670. #endif
  2671. #ifdef jim_ext_eventloop
  2672. { "readable",
  2673. "?readable-script?",
  2674. aio_cmd_readable,
  2675. 0,
  2676. 1,
  2677. },
  2678. { "writable",
  2679. "?writable-script?",
  2680. aio_cmd_writable,
  2681. 0,
  2682. 1,
  2683. },
  2684. { "onexception",
  2685. "?exception-script?",
  2686. aio_cmd_onexception,
  2687. 0,
  2688. 1,
  2689. },
  2690. { "timeout",
  2691. "?ms?",
  2692. aio_cmd_timeout,
  2693. 0,
  2694. 1,
  2695. },
  2696. #endif
  2697. { NULL }
  2698. };
  2699. static int JimAioSubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2700. {
  2701. return Jim_CallSubCmd(interp, Jim_ParseSubCmd(interp, aio_command_table, argc, argv), argc, argv);
  2702. }
  2703. static int parse_posix_open_mode(Jim_Interp *interp, Jim_Obj *modeObj)
  2704. {
  2705. int i;
  2706. int flags = 0;
  2707. #ifndef O_NOCTTY
  2708. #define O_NOCTTY 0
  2709. #endif
  2710. static const char * const modetypes[] = {
  2711. "RDONLY", "WRONLY", "RDWR", "APPEND", "BINARY", "CREAT", "EXCL", "NOCTTY", "TRUNC", NULL
  2712. };
  2713. static const int modeflags[] = {
  2714. O_RDONLY, O_WRONLY, O_RDWR, O_APPEND, 0, O_CREAT, O_EXCL, O_NOCTTY, O_TRUNC,
  2715. };
  2716. for (i = 0; i < Jim_ListLength(interp, modeObj); i++) {
  2717. int opt;
  2718. Jim_Obj *objPtr = Jim_ListGetIndex(interp, modeObj, i);
  2719. if (Jim_GetEnum(interp, objPtr, modetypes, &opt, "access mode", JIM_ERRMSG) != JIM_OK) {
  2720. return -1;
  2721. }
  2722. flags |= modeflags[opt];
  2723. }
  2724. return flags;
  2725. }
  2726. static int parse_open_mode(Jim_Interp *interp, Jim_Obj *filenameObj, Jim_Obj *modeObj)
  2727. {
  2728. int flags;
  2729. const char *mode = Jim_String(modeObj);
  2730. if (*mode == 'R' || *mode == 'W') {
  2731. return parse_posix_open_mode(interp, modeObj);
  2732. }
  2733. if (*mode == 'r') {
  2734. flags = O_RDONLY;
  2735. }
  2736. else if (*mode == 'w') {
  2737. flags = O_WRONLY | O_CREAT | O_TRUNC;
  2738. }
  2739. else if (*mode == 'a') {
  2740. flags = O_WRONLY | O_CREAT | O_APPEND;
  2741. }
  2742. else {
  2743. Jim_SetResultFormatted(interp, "%s: invalid open mode '%s'", Jim_String(filenameObj), mode);
  2744. return -1;
  2745. }
  2746. mode++;
  2747. if (*mode == 'b') {
  2748. #ifdef O_BINARY
  2749. flags |= O_BINARY;
  2750. #endif
  2751. mode++;
  2752. }
  2753. if (*mode == 't') {
  2754. #ifdef O_TEXT
  2755. flags |= O_TEXT;
  2756. #endif
  2757. mode++;
  2758. }
  2759. if (*mode == '+') {
  2760. mode++;
  2761. flags &= ~(O_RDONLY | O_WRONLY);
  2762. flags |= O_RDWR;
  2763. }
  2764. if (*mode == 'x') {
  2765. mode++;
  2766. #ifdef O_EXCL
  2767. flags |= O_EXCL;
  2768. #endif
  2769. }
  2770. if (*mode == 'F') {
  2771. mode++;
  2772. #ifdef O_LARGEFILE
  2773. flags |= O_LARGEFILE;
  2774. #endif
  2775. }
  2776. if (*mode == 'e') {
  2777. mode++;
  2778. }
  2779. return flags;
  2780. }
  2781. static int JimAioOpenCommand(Jim_Interp *interp, int argc,
  2782. Jim_Obj *const *argv)
  2783. {
  2784. int openflags;
  2785. const char *filename;
  2786. int fd = -1;
  2787. int n = 0;
  2788. int flags = 0;
  2789. if (argc > 2 && Jim_CompareStringImmediate(interp, argv[2], "-noclose")) {
  2790. flags = AIO_KEEPOPEN;
  2791. n++;
  2792. }
  2793. if (argc < 2 || argc > 3 + n) {
  2794. Jim_WrongNumArgs(interp, 1, argv, "filename ?-noclose? ?mode?");
  2795. return JIM_ERR;
  2796. }
  2797. filename = Jim_String(argv[1]);
  2798. #ifdef jim_ext_tclcompat
  2799. {
  2800. if (*filename == '|') {
  2801. Jim_Obj *evalObj[3];
  2802. int i = 0;
  2803. evalObj[i++] = Jim_NewStringObj(interp, "::popen", -1);
  2804. evalObj[i++] = Jim_NewStringObj(interp, filename + 1, -1);
  2805. if (argc == 3 + n) {
  2806. evalObj[i++] = argv[2 + n];
  2807. }
  2808. return Jim_EvalObjVector(interp, i, evalObj);
  2809. }
  2810. }
  2811. #endif
  2812. if (argc == 3 + n) {
  2813. openflags = parse_open_mode(interp, argv[1], argv[2 + n]);
  2814. if (openflags == -1) {
  2815. return JIM_ERR;
  2816. }
  2817. }
  2818. else {
  2819. openflags = O_RDONLY;
  2820. }
  2821. fd = open(filename, openflags, 0666);
  2822. if (fd < 0) {
  2823. JimAioSetError(interp, argv[1]);
  2824. return JIM_ERR;
  2825. }
  2826. return JimMakeChannel(interp, fd, argv[1], "aio.handle%ld", 0, flags) ? JIM_OK : JIM_ERR;
  2827. }
  2828. static AioFile *JimMakeChannel(Jim_Interp *interp, int fd, Jim_Obj *filename,
  2829. const char *hdlfmt, int family, int flags)
  2830. {
  2831. AioFile *af;
  2832. char buf[AIO_CMD_LEN];
  2833. Jim_Obj *cmdname;
  2834. snprintf(buf, sizeof(buf), hdlfmt, Jim_GetId(interp));
  2835. cmdname = Jim_NewStringObj(interp, buf, -1);
  2836. if (!filename) {
  2837. filename = cmdname;
  2838. }
  2839. Jim_IncrRefCount(filename);
  2840. af = Jim_Alloc(sizeof(*af));
  2841. memset(af, 0, sizeof(*af));
  2842. af->filename = filename;
  2843. af->fd = fd;
  2844. af->addr_family = family;
  2845. af->fops = &stdio_fops;
  2846. af->ssl = NULL;
  2847. if (flags & AIO_WBUF_NONE) {
  2848. af->wbuft = WBUF_OPT_NONE;
  2849. }
  2850. else {
  2851. #ifdef HAVE_ISATTY
  2852. af->wbuft = isatty(af->fd) ? WBUF_OPT_LINE : WBUF_OPT_FULL;
  2853. #else
  2854. af->wbuft = WBUF_OPT_FULL;
  2855. #endif
  2856. }
  2857. #ifdef FD_CLOEXEC
  2858. if ((flags & AIO_KEEPOPEN) == 0) {
  2859. (void)fcntl(af->fd, F_SETFD, FD_CLOEXEC);
  2860. }
  2861. #endif
  2862. aio_set_nonblocking(af, !!(flags & AIO_NONBLOCK));
  2863. af->flags |= flags;
  2864. af->writebuf = Jim_NewStringObj(interp, NULL, 0);
  2865. Jim_IncrRefCount(af->writebuf);
  2866. af->wbuf_limit = AIO_DEFAULT_WBUF_LIMIT;
  2867. af->rbuf_len = AIO_DEFAULT_RBUF_LEN;
  2868. Jim_CreateCommand(interp, buf, JimAioSubCmdProc, af, JimAioDelProc);
  2869. Jim_SetResult(interp, Jim_MakeGlobalNamespaceName(interp, cmdname));
  2870. return af;
  2871. }
  2872. #if defined(HAVE_PIPE) || (defined(HAVE_SOCKETPAIR) && UNIX_SOCKETS) || defined(HAVE_OPENPTY)
  2873. static int JimMakeChannelPair(Jim_Interp *interp, int p[2], Jim_Obj *filename,
  2874. const char *hdlfmt, int family, int flags)
  2875. {
  2876. if (JimMakeChannel(interp, p[0], filename, hdlfmt, family, flags)) {
  2877. Jim_Obj *objPtr = Jim_NewListObj(interp, NULL, 0);
  2878. Jim_ListAppendElement(interp, objPtr, Jim_GetResult(interp));
  2879. if (JimMakeChannel(interp, p[1], filename, hdlfmt, family, flags)) {
  2880. Jim_ListAppendElement(interp, objPtr, Jim_GetResult(interp));
  2881. Jim_SetResult(interp, objPtr);
  2882. return JIM_OK;
  2883. }
  2884. }
  2885. close(p[0]);
  2886. close(p[1]);
  2887. JimAioSetError(interp, NULL);
  2888. return JIM_ERR;
  2889. }
  2890. #endif
  2891. #ifdef HAVE_PIPE
  2892. static int JimCreatePipe(Jim_Interp *interp, Jim_Obj *filenameObj, int flags)
  2893. {
  2894. int p[2];
  2895. if (pipe(p) != 0) {
  2896. JimAioSetError(interp, NULL);
  2897. return JIM_ERR;
  2898. }
  2899. return JimMakeChannelPair(interp, p, filenameObj, "aio.pipe%ld", 0, flags);
  2900. }
  2901. static int JimAioPipeCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2902. {
  2903. if (argc != 1) {
  2904. Jim_WrongNumArgs(interp, 1, argv, "");
  2905. return JIM_ERR;
  2906. }
  2907. return JimCreatePipe(interp, argv[0], 0);
  2908. }
  2909. #endif
  2910. #ifdef HAVE_OPENPTY
  2911. static int JimAioOpenPtyCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2912. {
  2913. int p[2];
  2914. char path[MAXPATHLEN];
  2915. if (argc != 1) {
  2916. Jim_WrongNumArgs(interp, 1, argv, "");
  2917. return JIM_ERR;
  2918. }
  2919. if (openpty(&p[0], &p[1], path, NULL, NULL) != 0) {
  2920. JimAioSetError(interp, NULL);
  2921. return JIM_ERR;
  2922. }
  2923. return JimMakeChannelPair(interp, p, Jim_NewStringObj(interp, path, -1), "aio.pty%ld", 0, 0);
  2924. return JimMakeChannelPair(interp, p, Jim_NewStringObj(interp, path, -1), "aio.pty%ld", 0, 0);
  2925. }
  2926. #endif
  2927. int Jim_aioInit(Jim_Interp *interp)
  2928. {
  2929. if (Jim_PackageProvide(interp, "aio", "1.0", JIM_ERRMSG))
  2930. return JIM_ERR;
  2931. #if defined(JIM_SSL)
  2932. Jim_CreateCommand(interp, "load_ssl_certs", JimAioLoadSSLCertsCommand, NULL, NULL);
  2933. #endif
  2934. Jim_CreateCommand(interp, "open", JimAioOpenCommand, NULL, NULL);
  2935. #ifdef HAVE_SOCKETS
  2936. Jim_CreateCommand(interp, "socket", JimAioSockCommand, NULL, NULL);
  2937. #endif
  2938. #ifdef HAVE_PIPE
  2939. Jim_CreateCommand(interp, "pipe", JimAioPipeCommand, NULL, NULL);
  2940. #endif
  2941. JimMakeChannel(interp, fileno(stdin), NULL, "stdin", 0, AIO_KEEPOPEN);
  2942. JimMakeChannel(interp, fileno(stdout), NULL, "stdout", 0, AIO_KEEPOPEN);
  2943. JimMakeChannel(interp, fileno(stderr), NULL, "stderr", 0, AIO_KEEPOPEN | AIO_WBUF_NONE);
  2944. return JIM_OK;
  2945. }
  2946. #include <errno.h>
  2947. #include <stdio.h>
  2948. #include <string.h>
  2949. #ifdef HAVE_DIRENT_H
  2950. #include <dirent.h>
  2951. #endif
  2952. int Jim_ReaddirCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  2953. {
  2954. const char *dirPath;
  2955. DIR *dirPtr;
  2956. struct dirent *entryPtr;
  2957. int nocomplain = 0;
  2958. if (argc == 3 && Jim_CompareStringImmediate(interp, argv[1], "-nocomplain")) {
  2959. nocomplain = 1;
  2960. }
  2961. if (argc != 2 && !nocomplain) {
  2962. Jim_WrongNumArgs(interp, 1, argv, "?-nocomplain? dirPath");
  2963. return JIM_ERR;
  2964. }
  2965. dirPath = Jim_String(argv[1 + nocomplain]);
  2966. dirPtr = opendir(dirPath);
  2967. if (dirPtr == NULL) {
  2968. if (nocomplain) {
  2969. return JIM_OK;
  2970. }
  2971. Jim_SetResultString(interp, strerror(errno), -1);
  2972. return JIM_ERR;
  2973. }
  2974. else {
  2975. Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
  2976. while ((entryPtr = readdir(dirPtr)) != NULL) {
  2977. if (entryPtr->d_name[0] == '.') {
  2978. if (entryPtr->d_name[1] == '\0') {
  2979. continue;
  2980. }
  2981. if ((entryPtr->d_name[1] == '.') && (entryPtr->d_name[2] == '\0'))
  2982. continue;
  2983. }
  2984. Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, entryPtr->d_name, -1));
  2985. }
  2986. closedir(dirPtr);
  2987. Jim_SetResult(interp, listObj);
  2988. return JIM_OK;
  2989. }
  2990. }
  2991. int Jim_readdirInit(Jim_Interp *interp)
  2992. {
  2993. Jim_PackageProvideCheck(interp, "readdir");
  2994. Jim_CreateCommand(interp, "readdir", Jim_ReaddirCmd, NULL, NULL);
  2995. return JIM_OK;
  2996. }
  2997. #include <stdlib.h>
  2998. #include <string.h>
  2999. #if defined(JIM_REGEXP)
  3000. #else
  3001. #include <regex.h>
  3002. #define jim_regcomp regcomp
  3003. #define jim_regexec regexec
  3004. #define jim_regerror regerror
  3005. #define jim_regfree regfree
  3006. #endif
  3007. static void FreeRegexpInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
  3008. {
  3009. jim_regfree(objPtr->internalRep.ptrIntValue.ptr);
  3010. Jim_Free(objPtr->internalRep.ptrIntValue.ptr);
  3011. }
  3012. static const Jim_ObjType regexpObjType = {
  3013. "regexp",
  3014. FreeRegexpInternalRep,
  3015. NULL,
  3016. NULL,
  3017. JIM_TYPE_NONE
  3018. };
  3019. static regex_t *SetRegexpFromAny(Jim_Interp *interp, Jim_Obj *objPtr, unsigned flags)
  3020. {
  3021. regex_t *compre;
  3022. const char *pattern;
  3023. int ret;
  3024. if (objPtr->typePtr == &regexpObjType &&
  3025. objPtr->internalRep.ptrIntValue.ptr && objPtr->internalRep.ptrIntValue.int1 == flags) {
  3026. return objPtr->internalRep.ptrIntValue.ptr;
  3027. }
  3028. pattern = Jim_String(objPtr);
  3029. compre = Jim_Alloc(sizeof(regex_t));
  3030. if ((ret = jim_regcomp(compre, pattern, REG_EXTENDED | flags)) != 0) {
  3031. char buf[100];
  3032. jim_regerror(ret, compre, buf, sizeof(buf));
  3033. Jim_SetResultFormatted(interp, "couldn't compile regular expression pattern: %s", buf);
  3034. jim_regfree(compre);
  3035. Jim_Free(compre);
  3036. return NULL;
  3037. }
  3038. Jim_FreeIntRep(interp, objPtr);
  3039. objPtr->typePtr = &regexpObjType;
  3040. objPtr->internalRep.ptrIntValue.int1 = flags;
  3041. objPtr->internalRep.ptrIntValue.ptr = compre;
  3042. return compre;
  3043. }
  3044. int Jim_RegexpCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3045. {
  3046. int opt_indices = 0;
  3047. int opt_all = 0;
  3048. int opt_inline = 0;
  3049. regex_t *regex;
  3050. int match, i, j;
  3051. int offset = 0;
  3052. regmatch_t *pmatch = NULL;
  3053. int source_len;
  3054. int result = JIM_OK;
  3055. const char *pattern;
  3056. const char *source_str;
  3057. int num_matches = 0;
  3058. int num_vars;
  3059. Jim_Obj *resultListObj = NULL;
  3060. int regcomp_flags = 0;
  3061. int eflags = 0;
  3062. int option;
  3063. enum {
  3064. OPT_INDICES, OPT_NOCASE, OPT_LINE, OPT_ALL, OPT_INLINE, OPT_START, OPT_END
  3065. };
  3066. static const char * const options[] = {
  3067. "-indices", "-nocase", "-line", "-all", "-inline", "-start", "--", NULL
  3068. };
  3069. if (argc < 3) {
  3070. wrongNumArgs:
  3071. Jim_WrongNumArgs(interp, 1, argv,
  3072. "?-switch ...? exp string ?matchVar? ?subMatchVar ...?");
  3073. return JIM_ERR;
  3074. }
  3075. for (i = 1; i < argc; i++) {
  3076. const char *opt = Jim_String(argv[i]);
  3077. if (*opt != '-') {
  3078. break;
  3079. }
  3080. if (Jim_GetEnum(interp, argv[i], options, &option, "switch", JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
  3081. return JIM_ERR;
  3082. }
  3083. if (option == OPT_END) {
  3084. i++;
  3085. break;
  3086. }
  3087. switch (option) {
  3088. case OPT_INDICES:
  3089. opt_indices = 1;
  3090. break;
  3091. case OPT_NOCASE:
  3092. regcomp_flags |= REG_ICASE;
  3093. break;
  3094. case OPT_LINE:
  3095. regcomp_flags |= REG_NEWLINE;
  3096. break;
  3097. case OPT_ALL:
  3098. opt_all = 1;
  3099. break;
  3100. case OPT_INLINE:
  3101. opt_inline = 1;
  3102. break;
  3103. case OPT_START:
  3104. if (++i == argc) {
  3105. goto wrongNumArgs;
  3106. }
  3107. if (Jim_GetIndex(interp, argv[i], &offset) != JIM_OK) {
  3108. return JIM_ERR;
  3109. }
  3110. break;
  3111. }
  3112. }
  3113. if (argc - i < 2) {
  3114. goto wrongNumArgs;
  3115. }
  3116. regex = SetRegexpFromAny(interp, argv[i], regcomp_flags);
  3117. if (!regex) {
  3118. return JIM_ERR;
  3119. }
  3120. pattern = Jim_String(argv[i]);
  3121. source_str = Jim_GetString(argv[i + 1], &source_len);
  3122. num_vars = argc - i - 2;
  3123. if (opt_inline) {
  3124. if (num_vars) {
  3125. Jim_SetResultString(interp, "regexp match variables not allowed when using -inline",
  3126. -1);
  3127. result = JIM_ERR;
  3128. goto done;
  3129. }
  3130. num_vars = regex->re_nsub + 1;
  3131. }
  3132. pmatch = Jim_Alloc((num_vars + 1) * sizeof(*pmatch));
  3133. if (offset) {
  3134. if (offset < 0) {
  3135. offset += source_len + 1;
  3136. }
  3137. if (offset > source_len) {
  3138. source_str += source_len;
  3139. }
  3140. else if (offset > 0) {
  3141. source_str += utf8_index(source_str, offset);
  3142. }
  3143. eflags |= REG_NOTBOL;
  3144. }
  3145. if (opt_inline) {
  3146. resultListObj = Jim_NewListObj(interp, NULL, 0);
  3147. }
  3148. next_match:
  3149. match = jim_regexec(regex, source_str, num_vars + 1, pmatch, eflags);
  3150. if (match >= REG_BADPAT) {
  3151. char buf[100];
  3152. jim_regerror(match, regex, buf, sizeof(buf));
  3153. Jim_SetResultFormatted(interp, "error while matching pattern: %s", buf);
  3154. result = JIM_ERR;
  3155. goto done;
  3156. }
  3157. if (match == REG_NOMATCH) {
  3158. goto done;
  3159. }
  3160. num_matches++;
  3161. if (opt_all && !opt_inline) {
  3162. goto try_next_match;
  3163. }
  3164. j = 0;
  3165. for (i += 2; opt_inline ? j < num_vars : i < argc; i++, j++) {
  3166. Jim_Obj *resultObj;
  3167. if (opt_indices) {
  3168. resultObj = Jim_NewListObj(interp, NULL, 0);
  3169. }
  3170. else {
  3171. resultObj = Jim_NewStringObj(interp, "", 0);
  3172. }
  3173. if (pmatch[j].rm_so == -1) {
  3174. if (opt_indices) {
  3175. Jim_ListAppendElement(interp, resultObj, Jim_NewIntObj(interp, -1));
  3176. Jim_ListAppendElement(interp, resultObj, Jim_NewIntObj(interp, -1));
  3177. }
  3178. }
  3179. else {
  3180. if (opt_indices) {
  3181. int so = utf8_strlen(source_str, pmatch[j].rm_so);
  3182. int eo = utf8_strlen(source_str, pmatch[j].rm_eo);
  3183. Jim_ListAppendElement(interp, resultObj, Jim_NewIntObj(interp, offset + so));
  3184. Jim_ListAppendElement(interp, resultObj, Jim_NewIntObj(interp, offset + eo - 1));
  3185. }
  3186. else {
  3187. Jim_AppendString(interp, resultObj, source_str + pmatch[j].rm_so, pmatch[j].rm_eo - pmatch[j].rm_so);
  3188. }
  3189. }
  3190. if (opt_inline) {
  3191. Jim_ListAppendElement(interp, resultListObj, resultObj);
  3192. }
  3193. else {
  3194. result = Jim_SetVariable(interp, argv[i], resultObj);
  3195. if (result != JIM_OK) {
  3196. Jim_FreeObj(interp, resultObj);
  3197. break;
  3198. }
  3199. }
  3200. }
  3201. try_next_match:
  3202. if (opt_all && (pattern[0] != '^' || (regcomp_flags & REG_NEWLINE)) && *source_str) {
  3203. if (pmatch[0].rm_eo) {
  3204. offset += utf8_strlen(source_str, pmatch[0].rm_eo);
  3205. source_str += pmatch[0].rm_eo;
  3206. }
  3207. else {
  3208. source_str++;
  3209. offset++;
  3210. }
  3211. if (*source_str) {
  3212. eflags = REG_NOTBOL;
  3213. goto next_match;
  3214. }
  3215. }
  3216. done:
  3217. if (result == JIM_OK) {
  3218. if (opt_inline) {
  3219. Jim_SetResult(interp, resultListObj);
  3220. }
  3221. else {
  3222. Jim_SetResultInt(interp, num_matches);
  3223. }
  3224. }
  3225. Jim_Free(pmatch);
  3226. return result;
  3227. }
  3228. #define MAX_SUB_MATCHES 50
  3229. int Jim_RegsubCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3230. {
  3231. int regcomp_flags = 0;
  3232. int regexec_flags = 0;
  3233. int opt_all = 0;
  3234. int opt_command = 0;
  3235. int offset = 0;
  3236. regex_t *regex;
  3237. const char *p;
  3238. int result = JIM_OK;
  3239. regmatch_t pmatch[MAX_SUB_MATCHES + 1];
  3240. int num_matches = 0;
  3241. int i, j, n;
  3242. Jim_Obj *varname;
  3243. Jim_Obj *resultObj;
  3244. Jim_Obj *cmd_prefix = NULL;
  3245. Jim_Obj *regcomp_obj = NULL;
  3246. const char *source_str;
  3247. int source_len;
  3248. const char *replace_str = NULL;
  3249. int replace_len;
  3250. const char *pattern;
  3251. int option;
  3252. enum {
  3253. OPT_NOCASE, OPT_LINE, OPT_ALL, OPT_START, OPT_COMMAND, OPT_END
  3254. };
  3255. static const char * const options[] = {
  3256. "-nocase", "-line", "-all", "-start", "-command", "--", NULL
  3257. };
  3258. if (argc < 4) {
  3259. wrongNumArgs:
  3260. Jim_WrongNumArgs(interp, 1, argv,
  3261. "?-switch ...? exp string subSpec ?varName?");
  3262. return JIM_ERR;
  3263. }
  3264. for (i = 1; i < argc; i++) {
  3265. const char *opt = Jim_String(argv[i]);
  3266. if (*opt != '-') {
  3267. break;
  3268. }
  3269. if (Jim_GetEnum(interp, argv[i], options, &option, "switch", JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
  3270. return JIM_ERR;
  3271. }
  3272. if (option == OPT_END) {
  3273. i++;
  3274. break;
  3275. }
  3276. switch (option) {
  3277. case OPT_NOCASE:
  3278. regcomp_flags |= REG_ICASE;
  3279. break;
  3280. case OPT_LINE:
  3281. regcomp_flags |= REG_NEWLINE;
  3282. break;
  3283. case OPT_ALL:
  3284. opt_all = 1;
  3285. break;
  3286. case OPT_START:
  3287. if (++i == argc) {
  3288. goto wrongNumArgs;
  3289. }
  3290. if (Jim_GetIndex(interp, argv[i], &offset) != JIM_OK) {
  3291. return JIM_ERR;
  3292. }
  3293. break;
  3294. case OPT_COMMAND:
  3295. opt_command = 1;
  3296. break;
  3297. }
  3298. }
  3299. if (argc - i != 3 && argc - i != 4) {
  3300. goto wrongNumArgs;
  3301. }
  3302. regcomp_obj = Jim_DuplicateObj(interp, argv[i]);
  3303. Jim_IncrRefCount(regcomp_obj);
  3304. regex = SetRegexpFromAny(interp, regcomp_obj, regcomp_flags);
  3305. if (!regex) {
  3306. Jim_DecrRefCount(interp, regcomp_obj);
  3307. return JIM_ERR;
  3308. }
  3309. pattern = Jim_String(argv[i]);
  3310. source_str = Jim_GetString(argv[i + 1], &source_len);
  3311. if (opt_command) {
  3312. cmd_prefix = argv[i + 2];
  3313. if (Jim_ListLength(interp, cmd_prefix) == 0) {
  3314. Jim_SetResultString(interp, "command prefix must be a list of at least one element", -1);
  3315. Jim_DecrRefCount(interp, regcomp_obj);
  3316. return JIM_ERR;
  3317. }
  3318. Jim_IncrRefCount(cmd_prefix);
  3319. }
  3320. else {
  3321. replace_str = Jim_GetString(argv[i + 2], &replace_len);
  3322. }
  3323. varname = argv[i + 3];
  3324. resultObj = Jim_NewStringObj(interp, "", 0);
  3325. if (offset) {
  3326. if (offset < 0) {
  3327. offset += source_len + 1;
  3328. }
  3329. if (offset > source_len) {
  3330. offset = source_len;
  3331. }
  3332. else if (offset < 0) {
  3333. offset = 0;
  3334. }
  3335. }
  3336. offset = utf8_index(source_str, offset);
  3337. Jim_AppendString(interp, resultObj, source_str, offset);
  3338. n = source_len - offset;
  3339. p = source_str + offset;
  3340. do {
  3341. int match = jim_regexec(regex, p, MAX_SUB_MATCHES, pmatch, regexec_flags);
  3342. if (match >= REG_BADPAT) {
  3343. char buf[100];
  3344. jim_regerror(match, regex, buf, sizeof(buf));
  3345. Jim_SetResultFormatted(interp, "error while matching pattern: %s", buf);
  3346. return JIM_ERR;
  3347. }
  3348. if (match == REG_NOMATCH) {
  3349. break;
  3350. }
  3351. num_matches++;
  3352. Jim_AppendString(interp, resultObj, p, pmatch[0].rm_so);
  3353. if (opt_command) {
  3354. Jim_Obj *cmdListObj = Jim_DuplicateObj(interp, cmd_prefix);
  3355. for (j = 0; j < MAX_SUB_MATCHES; j++) {
  3356. if (pmatch[j].rm_so == -1) {
  3357. break;
  3358. }
  3359. else {
  3360. Jim_Obj *srcObj = Jim_NewStringObj(interp, p + pmatch[j].rm_so, pmatch[j].rm_eo - pmatch[j].rm_so);
  3361. Jim_ListAppendElement(interp, cmdListObj, srcObj);
  3362. }
  3363. }
  3364. Jim_IncrRefCount(cmdListObj);
  3365. result = Jim_EvalObj(interp, cmdListObj);
  3366. Jim_DecrRefCount(interp, cmdListObj);
  3367. if (result != JIM_OK) {
  3368. goto cmd_error;
  3369. }
  3370. Jim_AppendString(interp, resultObj, Jim_String(Jim_GetResult(interp)), -1);
  3371. }
  3372. else {
  3373. for (j = 0; j < replace_len; j++) {
  3374. int idx;
  3375. int c = replace_str[j];
  3376. if (c == '&') {
  3377. idx = 0;
  3378. }
  3379. else if (c == '\\' && j < replace_len) {
  3380. c = replace_str[++j];
  3381. if ((c >= '0') && (c <= '9')) {
  3382. idx = c - '0';
  3383. }
  3384. else if ((c == '\\') || (c == '&')) {
  3385. Jim_AppendString(interp, resultObj, replace_str + j, 1);
  3386. continue;
  3387. }
  3388. else {
  3389. Jim_AppendString(interp, resultObj, replace_str + j - 1, (j == replace_len) ? 1 : 2);
  3390. continue;
  3391. }
  3392. }
  3393. else {
  3394. Jim_AppendString(interp, resultObj, replace_str + j, 1);
  3395. continue;
  3396. }
  3397. if ((idx < MAX_SUB_MATCHES) && pmatch[idx].rm_so != -1 && pmatch[idx].rm_eo != -1) {
  3398. Jim_AppendString(interp, resultObj, p + pmatch[idx].rm_so,
  3399. pmatch[idx].rm_eo - pmatch[idx].rm_so);
  3400. }
  3401. }
  3402. }
  3403. p += pmatch[0].rm_eo;
  3404. n -= pmatch[0].rm_eo;
  3405. if (!opt_all || n == 0) {
  3406. break;
  3407. }
  3408. if ((regcomp_flags & REG_NEWLINE) == 0 && pattern[0] == '^') {
  3409. break;
  3410. }
  3411. if (pattern[0] == '\0' && n) {
  3412. Jim_AppendString(interp, resultObj, p, 1);
  3413. p++;
  3414. n--;
  3415. }
  3416. if (pmatch[0].rm_eo == pmatch[0].rm_so) {
  3417. regexec_flags = REG_NOTBOL;
  3418. }
  3419. else {
  3420. regexec_flags = 0;
  3421. }
  3422. } while (n);
  3423. Jim_AppendString(interp, resultObj, p, -1);
  3424. cmd_error:
  3425. if (result == JIM_OK) {
  3426. if (argc - i == 4) {
  3427. result = Jim_SetVariable(interp, varname, resultObj);
  3428. if (result == JIM_OK) {
  3429. Jim_SetResultInt(interp, num_matches);
  3430. }
  3431. else {
  3432. Jim_FreeObj(interp, resultObj);
  3433. }
  3434. }
  3435. else {
  3436. Jim_SetResult(interp, resultObj);
  3437. result = JIM_OK;
  3438. }
  3439. }
  3440. else {
  3441. Jim_FreeObj(interp, resultObj);
  3442. }
  3443. if (opt_command) {
  3444. Jim_DecrRefCount(interp, cmd_prefix);
  3445. }
  3446. Jim_DecrRefCount(interp, regcomp_obj);
  3447. return result;
  3448. }
  3449. int Jim_regexpInit(Jim_Interp *interp)
  3450. {
  3451. Jim_PackageProvideCheck(interp, "regexp");
  3452. Jim_CreateCommand(interp, "regexp", Jim_RegexpCmd, NULL, NULL);
  3453. Jim_CreateCommand(interp, "regsub", Jim_RegsubCmd, NULL, NULL);
  3454. return JIM_OK;
  3455. }
  3456. #include <limits.h>
  3457. #include <stdlib.h>
  3458. #include <string.h>
  3459. #include <stdio.h>
  3460. #include <errno.h>
  3461. #ifdef HAVE_UTIMES
  3462. #include <sys/time.h>
  3463. #endif
  3464. #ifdef HAVE_UNISTD_H
  3465. #include <unistd.h>
  3466. #elif defined(_MSC_VER)
  3467. #include <direct.h>
  3468. #define F_OK 0
  3469. #define W_OK 2
  3470. #define R_OK 4
  3471. #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
  3472. #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
  3473. #endif
  3474. # ifndef MAXPATHLEN
  3475. # ifdef PATH_MAX
  3476. # define MAXPATHLEN PATH_MAX
  3477. # else
  3478. # define MAXPATHLEN JIM_PATH_LEN
  3479. # endif
  3480. # endif
  3481. #if defined(__MINGW32__) || defined(__MSYS__) || defined(_MSC_VER)
  3482. #define ISWINDOWS 1
  3483. #undef HAVE_SYMLINK
  3484. #else
  3485. #define ISWINDOWS 0
  3486. #endif
  3487. #if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
  3488. #define STAT_MTIME_US(STAT) ((STAT).st_mtimespec.tv_sec * 1000000ll + (STAT).st_mtimespec.tv_nsec / 1000)
  3489. #elif defined(HAVE_STRUCT_STAT_ST_MTIM)
  3490. #define STAT_MTIME_US(STAT) ((STAT).st_mtim.tv_sec * 1000000ll + (STAT).st_mtim.tv_nsec / 1000)
  3491. #endif
  3492. static void JimFixPath(char *path)
  3493. {
  3494. if (ISWINDOWS) {
  3495. char *p = path;
  3496. while ((p = strchr(p, '\\')) != NULL) {
  3497. *p++ = '/';
  3498. }
  3499. }
  3500. }
  3501. static const char *JimGetFileType(int mode)
  3502. {
  3503. if (S_ISREG(mode)) {
  3504. return "file";
  3505. }
  3506. else if (S_ISDIR(mode)) {
  3507. return "directory";
  3508. }
  3509. #ifdef S_ISCHR
  3510. else if (S_ISCHR(mode)) {
  3511. return "characterSpecial";
  3512. }
  3513. #endif
  3514. #ifdef S_ISBLK
  3515. else if (S_ISBLK(mode)) {
  3516. return "blockSpecial";
  3517. }
  3518. #endif
  3519. #ifdef S_ISFIFO
  3520. else if (S_ISFIFO(mode)) {
  3521. return "fifo";
  3522. }
  3523. #endif
  3524. #ifdef S_ISLNK
  3525. else if (S_ISLNK(mode)) {
  3526. return "link";
  3527. }
  3528. #endif
  3529. #ifdef S_ISSOCK
  3530. else if (S_ISSOCK(mode)) {
  3531. return "socket";
  3532. }
  3533. #endif
  3534. return "unknown";
  3535. }
  3536. static void AppendStatElement(Jim_Interp *interp, Jim_Obj *listObj, const char *key, jim_wide value)
  3537. {
  3538. Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, key, -1));
  3539. Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, value));
  3540. }
  3541. int Jim_FileStoreStatData(Jim_Interp *interp, Jim_Obj *varName, const jim_stat_t *sb)
  3542. {
  3543. Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
  3544. AppendStatElement(interp, listObj, "dev", sb->st_dev);
  3545. AppendStatElement(interp, listObj, "ino", sb->st_ino);
  3546. AppendStatElement(interp, listObj, "mode", sb->st_mode);
  3547. AppendStatElement(interp, listObj, "nlink", sb->st_nlink);
  3548. AppendStatElement(interp, listObj, "uid", sb->st_uid);
  3549. AppendStatElement(interp, listObj, "gid", sb->st_gid);
  3550. AppendStatElement(interp, listObj, "size", sb->st_size);
  3551. AppendStatElement(interp, listObj, "atime", sb->st_atime);
  3552. AppendStatElement(interp, listObj, "mtime", sb->st_mtime);
  3553. AppendStatElement(interp, listObj, "ctime", sb->st_ctime);
  3554. #ifdef STAT_MTIME_US
  3555. AppendStatElement(interp, listObj, "mtimeus", STAT_MTIME_US(*sb));
  3556. #endif
  3557. Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "type", -1));
  3558. Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, JimGetFileType((int)sb->st_mode), -1));
  3559. if (varName) {
  3560. Jim_Obj *objPtr;
  3561. objPtr = Jim_GetVariable(interp, varName, JIM_NONE);
  3562. if (objPtr) {
  3563. Jim_Obj *objv[2];
  3564. objv[0] = objPtr;
  3565. objv[1] = listObj;
  3566. objPtr = Jim_DictMerge(interp, 2, objv);
  3567. if (objPtr == NULL) {
  3568. Jim_SetResultFormatted(interp, "can't set \"%#s(dev)\": variable isn't array", varName);
  3569. Jim_FreeNewObj(interp, listObj);
  3570. return JIM_ERR;
  3571. }
  3572. Jim_InvalidateStringRep(objPtr);
  3573. Jim_FreeNewObj(interp, listObj);
  3574. listObj = objPtr;
  3575. }
  3576. Jim_SetVariable(interp, varName, listObj);
  3577. }
  3578. Jim_SetResult(interp, listObj);
  3579. return JIM_OK;
  3580. }
  3581. static int JimPathLenNoTrailingSlashes(const char *path, int len)
  3582. {
  3583. int i;
  3584. for (i = len; i > 1 && path[i - 1] == '/'; i--) {
  3585. if (ISWINDOWS && path[i - 2] == ':') {
  3586. break;
  3587. }
  3588. }
  3589. return i;
  3590. }
  3591. static Jim_Obj *JimStripTrailingSlashes(Jim_Interp *interp, Jim_Obj *objPtr)
  3592. {
  3593. int len = Jim_Length(objPtr);
  3594. const char *path = Jim_String(objPtr);
  3595. int i = JimPathLenNoTrailingSlashes(path, len);
  3596. if (i != len) {
  3597. objPtr = Jim_NewStringObj(interp, path, i);
  3598. }
  3599. Jim_IncrRefCount(objPtr);
  3600. return objPtr;
  3601. }
  3602. static int file_cmd_dirname(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3603. {
  3604. Jim_Obj *objPtr = JimStripTrailingSlashes(interp, argv[0]);
  3605. const char *path = Jim_String(objPtr);
  3606. const char *p = strrchr(path, '/');
  3607. if (!p) {
  3608. Jim_SetResultString(interp, ".", -1);
  3609. }
  3610. else if (p[1] == 0) {
  3611. Jim_SetResult(interp, objPtr);
  3612. }
  3613. else if (p == path) {
  3614. Jim_SetResultString(interp, "/", -1);
  3615. }
  3616. else if (ISWINDOWS && p[-1] == ':') {
  3617. Jim_SetResultString(interp, path, p - path + 1);
  3618. }
  3619. else {
  3620. int len = JimPathLenNoTrailingSlashes(path, p - path);
  3621. Jim_SetResultString(interp, path, len);
  3622. }
  3623. Jim_DecrRefCount(interp, objPtr);
  3624. return JIM_OK;
  3625. }
  3626. static int file_cmd_split(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3627. {
  3628. Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
  3629. const char *path = Jim_String(argv[0]);
  3630. if (*path == '/') {
  3631. Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "/", 1));
  3632. }
  3633. while (1) {
  3634. while (*path == '/') {
  3635. path++;
  3636. }
  3637. if (*path) {
  3638. const char *pt = strchr(path, '/');
  3639. if (pt) {
  3640. Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, path, pt - path));
  3641. path = pt;
  3642. continue;
  3643. }
  3644. Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, path, -1));
  3645. }
  3646. break;
  3647. }
  3648. Jim_SetResult(interp, listObj);
  3649. return JIM_OK;
  3650. }
  3651. static int file_cmd_rootname(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3652. {
  3653. const char *path = Jim_String(argv[0]);
  3654. const char *lastSlash = strrchr(path, '/');
  3655. const char *p = strrchr(path, '.');
  3656. if (p == NULL || (lastSlash != NULL && lastSlash > p)) {
  3657. Jim_SetResult(interp, argv[0]);
  3658. }
  3659. else {
  3660. Jim_SetResultString(interp, path, p - path);
  3661. }
  3662. return JIM_OK;
  3663. }
  3664. static int file_cmd_extension(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3665. {
  3666. Jim_Obj *objPtr = JimStripTrailingSlashes(interp, argv[0]);
  3667. const char *path = Jim_String(objPtr);
  3668. const char *lastSlash = strrchr(path, '/');
  3669. const char *p = strrchr(path, '.');
  3670. if (p == NULL || (lastSlash != NULL && lastSlash >= p)) {
  3671. p = "";
  3672. }
  3673. Jim_SetResultString(interp, p, -1);
  3674. Jim_DecrRefCount(interp, objPtr);
  3675. return JIM_OK;
  3676. }
  3677. static int file_cmd_tail(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3678. {
  3679. Jim_Obj *objPtr = JimStripTrailingSlashes(interp, argv[0]);
  3680. const char *path = Jim_String(objPtr);
  3681. const char *lastSlash = strrchr(path, '/');
  3682. if (lastSlash) {
  3683. Jim_SetResultString(interp, lastSlash + 1, -1);
  3684. }
  3685. else {
  3686. Jim_SetResult(interp, objPtr);
  3687. }
  3688. Jim_DecrRefCount(interp, objPtr);
  3689. return JIM_OK;
  3690. }
  3691. #ifndef HAVE_RESTRICT
  3692. #define restrict
  3693. #endif
  3694. static char *JimRealPath(const char *restrict path, char *restrict resolved_path, size_t len)
  3695. {
  3696. #if defined(HAVE__FULLPATH)
  3697. return _fullpath(resolved_path, path, len);
  3698. #elif defined(HAVE_REALPATH)
  3699. return realpath(path, resolved_path);
  3700. #else
  3701. return NULL;
  3702. #endif
  3703. }
  3704. static int file_cmd_normalize(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3705. {
  3706. const char *path = Jim_String(argv[0]);
  3707. char *newname = Jim_Alloc(MAXPATHLEN);
  3708. if (JimRealPath(path, newname, MAXPATHLEN)) {
  3709. JimFixPath(newname);
  3710. Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, newname, -1));
  3711. return JIM_OK;
  3712. }
  3713. Jim_Free(newname);
  3714. Jim_SetResultFormatted(interp, "can't normalize \"%#s\": %s", argv[0], strerror(errno));
  3715. return JIM_ERR;
  3716. }
  3717. static int file_cmd_join(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3718. {
  3719. int i;
  3720. char *newname = Jim_Alloc(MAXPATHLEN + 1);
  3721. char *last = newname;
  3722. *newname = 0;
  3723. for (i = 0; i < argc; i++) {
  3724. int len;
  3725. const char *part = Jim_GetString(argv[i], &len);
  3726. if (*part == '/') {
  3727. last = newname;
  3728. }
  3729. else if (ISWINDOWS && strchr(part, ':')) {
  3730. last = newname;
  3731. }
  3732. else if (part[0] == '.') {
  3733. if (part[1] == '/') {
  3734. part += 2;
  3735. len -= 2;
  3736. }
  3737. else if (part[1] == 0 && last != newname) {
  3738. continue;
  3739. }
  3740. }
  3741. if (last != newname && last[-1] != '/') {
  3742. *last++ = '/';
  3743. }
  3744. if (len) {
  3745. if (last + len - newname >= MAXPATHLEN) {
  3746. Jim_Free(newname);
  3747. Jim_SetResultString(interp, "Path too long", -1);
  3748. return JIM_ERR;
  3749. }
  3750. memcpy(last, part, len);
  3751. last += len;
  3752. }
  3753. if (last > newname + 1 && last[-1] == '/') {
  3754. if (!ISWINDOWS || !(last > newname + 2 && last[-2] == ':')) {
  3755. *--last = 0;
  3756. }
  3757. }
  3758. }
  3759. *last = 0;
  3760. Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, newname, last - newname));
  3761. return JIM_OK;
  3762. }
  3763. static int file_access(Jim_Interp *interp, Jim_Obj *filename, int mode)
  3764. {
  3765. Jim_SetResultBool(interp, access(Jim_String(filename), mode) != -1);
  3766. return JIM_OK;
  3767. }
  3768. static int file_cmd_readable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3769. {
  3770. return file_access(interp, argv[0], R_OK);
  3771. }
  3772. static int file_cmd_writable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3773. {
  3774. return file_access(interp, argv[0], W_OK);
  3775. }
  3776. static int file_cmd_executable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3777. {
  3778. #ifdef X_OK
  3779. return file_access(interp, argv[0], X_OK);
  3780. #else
  3781. Jim_SetResultBool(interp, 1);
  3782. return JIM_OK;
  3783. #endif
  3784. }
  3785. static int file_cmd_exists(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3786. {
  3787. return file_access(interp, argv[0], F_OK);
  3788. }
  3789. static int file_cmd_delete(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3790. {
  3791. int force = Jim_CompareStringImmediate(interp, argv[0], "-force");
  3792. if (force || Jim_CompareStringImmediate(interp, argv[0], "--")) {
  3793. argc--;
  3794. argv++;
  3795. }
  3796. while (argc--) {
  3797. const char *path = Jim_String(argv[0]);
  3798. if (unlink(path) == -1 && errno != ENOENT) {
  3799. if (rmdir(path) == -1) {
  3800. if (!force || Jim_EvalPrefix(interp, "file delete force", 1, argv) != JIM_OK) {
  3801. Jim_SetResultFormatted(interp, "couldn't delete file \"%s\": %s", path,
  3802. strerror(errno));
  3803. return JIM_ERR;
  3804. }
  3805. }
  3806. }
  3807. argv++;
  3808. }
  3809. return JIM_OK;
  3810. }
  3811. #ifdef HAVE_MKDIR_ONE_ARG
  3812. #define MKDIR_DEFAULT(PATHNAME) mkdir(PATHNAME)
  3813. #else
  3814. #define MKDIR_DEFAULT(PATHNAME) mkdir(PATHNAME, 0755)
  3815. #endif
  3816. static int mkdir_all(char *path)
  3817. {
  3818. int ok = 1;
  3819. goto first;
  3820. while (ok--) {
  3821. {
  3822. char *slash = strrchr(path, '/');
  3823. if (slash && slash != path) {
  3824. *slash = 0;
  3825. if (mkdir_all(path) != 0) {
  3826. return -1;
  3827. }
  3828. *slash = '/';
  3829. }
  3830. }
  3831. first:
  3832. if (MKDIR_DEFAULT(path) == 0) {
  3833. return 0;
  3834. }
  3835. if (errno == ENOENT) {
  3836. continue;
  3837. }
  3838. if (errno == EEXIST) {
  3839. jim_stat_t sb;
  3840. if (Jim_Stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
  3841. return 0;
  3842. }
  3843. errno = EEXIST;
  3844. }
  3845. break;
  3846. }
  3847. return -1;
  3848. }
  3849. static int file_cmd_mkdir(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3850. {
  3851. while (argc--) {
  3852. char *path = Jim_StrDup(Jim_String(argv[0]));
  3853. int rc = mkdir_all(path);
  3854. Jim_Free(path);
  3855. if (rc != 0) {
  3856. Jim_SetResultFormatted(interp, "can't create directory \"%#s\": %s", argv[0],
  3857. strerror(errno));
  3858. return JIM_ERR;
  3859. }
  3860. argv++;
  3861. }
  3862. return JIM_OK;
  3863. }
  3864. static int file_cmd_tempfile(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3865. {
  3866. int fd = Jim_MakeTempFile(interp, (argc >= 1) ? Jim_String(argv[0]) : NULL, 0);
  3867. if (fd < 0) {
  3868. return JIM_ERR;
  3869. }
  3870. close(fd);
  3871. return JIM_OK;
  3872. }
  3873. static int file_cmd_rename(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3874. {
  3875. const char *source;
  3876. const char *dest;
  3877. int force = 0;
  3878. if (argc == 3) {
  3879. if (!Jim_CompareStringImmediate(interp, argv[0], "-force")) {
  3880. return -1;
  3881. }
  3882. force++;
  3883. argv++;
  3884. argc--;
  3885. }
  3886. source = Jim_String(argv[0]);
  3887. dest = Jim_String(argv[1]);
  3888. if (!force && access(dest, F_OK) == 0) {
  3889. Jim_SetResultFormatted(interp, "error renaming \"%#s\" to \"%#s\": target exists", argv[0],
  3890. argv[1]);
  3891. return JIM_ERR;
  3892. }
  3893. #if ISWINDOWS
  3894. if (access(dest, F_OK) == 0) {
  3895. remove(dest);
  3896. }
  3897. #endif
  3898. if (rename(source, dest) != 0) {
  3899. Jim_SetResultFormatted(interp, "error renaming \"%#s\" to \"%#s\": %s", argv[0], argv[1],
  3900. strerror(errno));
  3901. return JIM_ERR;
  3902. }
  3903. return JIM_OK;
  3904. }
  3905. #if defined(HAVE_LINK) && defined(HAVE_SYMLINK)
  3906. static int file_cmd_link(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3907. {
  3908. int ret;
  3909. const char *source;
  3910. const char *dest;
  3911. static const char * const options[] = { "-hard", "-symbolic", NULL };
  3912. enum { OPT_HARD, OPT_SYMBOLIC, };
  3913. int option = OPT_HARD;
  3914. if (argc == 3) {
  3915. if (Jim_GetEnum(interp, argv[0], options, &option, NULL, JIM_ENUM_ABBREV | JIM_ERRMSG) != JIM_OK) {
  3916. return JIM_ERR;
  3917. }
  3918. argv++;
  3919. argc--;
  3920. }
  3921. dest = Jim_String(argv[0]);
  3922. source = Jim_String(argv[1]);
  3923. if (option == OPT_HARD) {
  3924. ret = link(source, dest);
  3925. }
  3926. else {
  3927. ret = symlink(source, dest);
  3928. }
  3929. if (ret != 0) {
  3930. Jim_SetResultFormatted(interp, "error linking \"%#s\" to \"%#s\": %s", argv[0], argv[1],
  3931. strerror(errno));
  3932. return JIM_ERR;
  3933. }
  3934. return JIM_OK;
  3935. }
  3936. #endif
  3937. static int file_stat(Jim_Interp *interp, Jim_Obj *filename, jim_stat_t *sb)
  3938. {
  3939. const char *path = Jim_String(filename);
  3940. if (Jim_Stat(path, sb) == -1) {
  3941. Jim_SetResultFormatted(interp, "could not read \"%#s\": %s", filename, strerror(errno));
  3942. return JIM_ERR;
  3943. }
  3944. return JIM_OK;
  3945. }
  3946. #ifdef Jim_LinkStat
  3947. static int file_lstat(Jim_Interp *interp, Jim_Obj *filename, jim_stat_t *sb)
  3948. {
  3949. const char *path = Jim_String(filename);
  3950. if (Jim_LinkStat(path, sb) == -1) {
  3951. Jim_SetResultFormatted(interp, "could not read \"%#s\": %s", filename, strerror(errno));
  3952. return JIM_ERR;
  3953. }
  3954. return JIM_OK;
  3955. }
  3956. #else
  3957. #define file_lstat file_stat
  3958. #endif
  3959. static int file_cmd_atime(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3960. {
  3961. jim_stat_t sb;
  3962. if (file_stat(interp, argv[0], &sb) != JIM_OK) {
  3963. return JIM_ERR;
  3964. }
  3965. Jim_SetResultInt(interp, sb.st_atime);
  3966. return JIM_OK;
  3967. }
  3968. static int JimSetFileTimes(Jim_Interp *interp, const char *filename, jim_wide us)
  3969. {
  3970. #ifdef HAVE_UTIMES
  3971. struct timeval times[2];
  3972. times[1].tv_sec = times[0].tv_sec = us / 1000000;
  3973. times[1].tv_usec = times[0].tv_usec = us % 1000000;
  3974. if (utimes(filename, times) != 0) {
  3975. Jim_SetResultFormatted(interp, "can't set time on \"%s\": %s", filename, strerror(errno));
  3976. return JIM_ERR;
  3977. }
  3978. return JIM_OK;
  3979. #else
  3980. Jim_SetResultString(interp, "Not implemented", -1);
  3981. return JIM_ERR;
  3982. #endif
  3983. }
  3984. static int file_cmd_mtime(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  3985. {
  3986. jim_stat_t sb;
  3987. if (argc == 2) {
  3988. jim_wide secs;
  3989. if (Jim_GetWide(interp, argv[1], &secs) != JIM_OK) {
  3990. return JIM_ERR;
  3991. }
  3992. return JimSetFileTimes(interp, Jim_String(argv[0]), secs * 1000000);
  3993. }
  3994. if (file_stat(interp, argv[0], &sb) != JIM_OK) {
  3995. return JIM_ERR;
  3996. }
  3997. Jim_SetResultInt(interp, sb.st_mtime);
  3998. return JIM_OK;
  3999. }
  4000. #ifdef STAT_MTIME_US
  4001. static int file_cmd_mtimeus(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  4002. {
  4003. jim_stat_t sb;
  4004. if (argc == 2) {
  4005. jim_wide us;
  4006. if (Jim_GetWide(interp, argv[1], &us) != JIM_OK) {
  4007. return JIM_ERR;
  4008. }
  4009. return JimSetFileTimes(interp, Jim_String(argv[0]), us);
  4010. }
  4011. if (file_stat(interp, argv[0], &sb) != JIM_OK) {
  4012. return JIM_ERR;
  4013. }
  4014. Jim_SetResultInt(interp, STAT_MTIME_US(sb));
  4015. return JIM_OK;
  4016. }
  4017. #endif
  4018. static int file_cmd_copy(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  4019. {
  4020. return Jim_EvalPrefix(interp, "file copy", argc, argv);
  4021. }
  4022. static int file_cmd_size(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  4023. {
  4024. jim_stat_t sb;
  4025. if (file_stat(interp, argv[0], &sb) != JIM_OK) {
  4026. return JIM_ERR;
  4027. }
  4028. Jim_SetResultInt(interp, sb.st_size);
  4029. return JIM_OK;
  4030. }
  4031. static int file_cmd_isdirectory(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  4032. {
  4033. jim_stat_t sb;
  4034. int ret = 0;
  4035. if (file_stat(interp, argv[0], &sb) == JIM_OK) {
  4036. ret = S_ISDIR(sb.st_mode);
  4037. }
  4038. Jim_SetResultInt(interp, ret);
  4039. return JIM_OK;
  4040. }
  4041. static int file_cmd_isfile(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  4042. {
  4043. jim_stat_t sb;
  4044. int ret = 0;
  4045. if (file_stat(interp, argv[0], &sb) == JIM_OK) {
  4046. ret = S_ISREG(sb.st_mode);
  4047. }
  4048. Jim_SetResultInt(interp, ret);
  4049. return JIM_OK;
  4050. }
  4051. #ifdef HAVE_GETEUID
  4052. static int file_cmd_owned(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  4053. {
  4054. jim_stat_t sb;
  4055. int ret = 0;
  4056. if (file_stat(interp, argv[0], &sb) == JIM_OK) {
  4057. ret = (geteuid() == sb.st_uid);
  4058. }
  4059. Jim_SetResultInt(interp, ret);
  4060. return JIM_OK;
  4061. }
  4062. #endif
  4063. #if defined(HAVE_READLINK)
  4064. static int file_cmd_readlink(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  4065. {
  4066. const char *path = Jim_String(argv[0]);
  4067. char *linkValue = Jim_Alloc(MAXPATHLEN + 1);
  4068. int linkLength = readlink(path, linkValue, MAXPATHLEN);
  4069. if (linkLength == -1) {
  4070. Jim_Free(linkValue);
  4071. Jim_SetResultFormatted(interp, "could not read link \"%#s\": %s", argv[0], strerror(errno));
  4072. return JIM_ERR;
  4073. }
  4074. linkValue[linkLength] = 0;
  4075. Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, linkValue, linkLength));
  4076. return JIM_OK;
  4077. }
  4078. #endif
  4079. static int file_cmd_type(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  4080. {
  4081. jim_stat_t sb;
  4082. if (file_lstat(interp, argv[0], &sb) != JIM_OK) {
  4083. return JIM_ERR;
  4084. }
  4085. Jim_SetResultString(interp, JimGetFileType((int)sb.st_mode), -1);
  4086. return JIM_OK;
  4087. }
  4088. #ifdef Jim_LinkStat
  4089. static int file_cmd_lstat(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  4090. {
  4091. jim_stat_t sb;
  4092. if (file_lstat(interp, argv[0], &sb) != JIM_OK) {
  4093. return JIM_ERR;
  4094. }
  4095. return Jim_FileStoreStatData(interp, argc == 2 ? argv[1] : NULL, &sb);
  4096. }
  4097. #else
  4098. #define file_cmd_lstat file_cmd_stat
  4099. #endif
  4100. static int file_cmd_stat(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  4101. {
  4102. jim_stat_t sb;
  4103. if (file_stat(interp, argv[0], &sb) != JIM_OK) {
  4104. return JIM_ERR;
  4105. }
  4106. return Jim_FileStoreStatData(interp, argc == 2 ? argv[1] : NULL, &sb);
  4107. }
  4108. static const jim_subcmd_type file_command_table[] = {
  4109. { "atime",
  4110. "name",
  4111. file_cmd_atime,
  4112. 1,
  4113. 1,
  4114. },
  4115. { "mtime",
  4116. "name ?time?",
  4117. file_cmd_mtime,
  4118. 1,
  4119. 2,
  4120. },
  4121. #ifdef STAT_MTIME_US
  4122. { "mtimeus",
  4123. "name ?time?",
  4124. file_cmd_mtimeus,
  4125. 1,
  4126. 2,
  4127. },
  4128. #endif
  4129. { "copy",
  4130. "?-force? source dest",
  4131. file_cmd_copy,
  4132. 2,
  4133. 3,
  4134. },
  4135. { "dirname",
  4136. "name",
  4137. file_cmd_dirname,
  4138. 1,
  4139. 1,
  4140. },
  4141. { "rootname",
  4142. "name",
  4143. file_cmd_rootname,
  4144. 1,
  4145. 1,
  4146. },
  4147. { "extension",
  4148. "name",
  4149. file_cmd_extension,
  4150. 1,
  4151. 1,
  4152. },
  4153. { "tail",
  4154. "name",
  4155. file_cmd_tail,
  4156. 1,
  4157. 1,
  4158. },
  4159. { "split",
  4160. "name",
  4161. file_cmd_split,
  4162. 1,
  4163. 1,
  4164. },
  4165. { "normalize",
  4166. "name",
  4167. file_cmd_normalize,
  4168. 1,
  4169. 1,
  4170. },
  4171. { "join",
  4172. "name ?name ...?",
  4173. file_cmd_join,
  4174. 1,
  4175. -1,
  4176. },
  4177. { "readable",
  4178. "name",
  4179. file_cmd_readable,
  4180. 1,
  4181. 1,
  4182. },
  4183. { "writable",
  4184. "name",
  4185. file_cmd_writable,
  4186. 1,
  4187. 1,
  4188. },
  4189. { "executable",
  4190. "name",
  4191. file_cmd_executable,
  4192. 1,
  4193. 1,
  4194. },
  4195. { "exists",
  4196. "name",
  4197. file_cmd_exists,
  4198. 1,
  4199. 1,
  4200. },
  4201. { "delete",
  4202. "?-force|--? name ...",
  4203. file_cmd_delete,
  4204. 1,
  4205. -1,
  4206. },
  4207. { "mkdir",
  4208. "dir ...",
  4209. file_cmd_mkdir,
  4210. 1,
  4211. -1,
  4212. },
  4213. { "tempfile",
  4214. "?template?",
  4215. file_cmd_tempfile,
  4216. 0,
  4217. 1,
  4218. },
  4219. { "rename",
  4220. "?-force? source dest",
  4221. file_cmd_rename,
  4222. 2,
  4223. 3,
  4224. },
  4225. #if defined(HAVE_LINK) && defined(HAVE_SYMLINK)
  4226. { "link",
  4227. "?-symbolic|-hard? newname target",
  4228. file_cmd_link,
  4229. 2,
  4230. 3,
  4231. },
  4232. #endif
  4233. #if defined(HAVE_READLINK)
  4234. { "readlink",
  4235. "name",
  4236. file_cmd_readlink,
  4237. 1,
  4238. 1,
  4239. },
  4240. #endif
  4241. { "size",
  4242. "name",
  4243. file_cmd_size,
  4244. 1,
  4245. 1,
  4246. },
  4247. { "stat",
  4248. "name ?var?",
  4249. file_cmd_stat,
  4250. 1,
  4251. 2,
  4252. },
  4253. { "lstat",
  4254. "name ?var?",
  4255. file_cmd_lstat,
  4256. 1,
  4257. 2,
  4258. },
  4259. { "type",
  4260. "name",
  4261. file_cmd_type,
  4262. 1,
  4263. 1,
  4264. },
  4265. #ifdef HAVE_GETEUID
  4266. { "owned",
  4267. "name",
  4268. file_cmd_owned,
  4269. 1,
  4270. 1,
  4271. },
  4272. #endif
  4273. { "isdirectory",
  4274. "name",
  4275. file_cmd_isdirectory,
  4276. 1,
  4277. 1,
  4278. },
  4279. { "isfile",
  4280. "name",
  4281. file_cmd_isfile,
  4282. 1,
  4283. 1,
  4284. },
  4285. {
  4286. NULL
  4287. }
  4288. };
  4289. static int Jim_CdCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  4290. {
  4291. const char *path;
  4292. if (argc != 2) {
  4293. Jim_WrongNumArgs(interp, 1, argv, "dirname");
  4294. return JIM_ERR;
  4295. }
  4296. path = Jim_String(argv[1]);
  4297. if (chdir(path) != 0) {
  4298. Jim_SetResultFormatted(interp, "couldn't change working directory to \"%s\": %s", path,
  4299. strerror(errno));
  4300. return JIM_ERR;
  4301. }
  4302. return JIM_OK;
  4303. }
  4304. static int Jim_PwdCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  4305. {
  4306. char *cwd = Jim_Alloc(MAXPATHLEN);
  4307. if (getcwd(cwd, MAXPATHLEN) == NULL) {
  4308. Jim_SetResultString(interp, "Failed to get pwd", -1);
  4309. Jim_Free(cwd);
  4310. return JIM_ERR;
  4311. }
  4312. JimFixPath(cwd);
  4313. Jim_SetResultString(interp, cwd, -1);
  4314. Jim_Free(cwd);
  4315. return JIM_OK;
  4316. }
  4317. int Jim_fileInit(Jim_Interp *interp)
  4318. {
  4319. Jim_PackageProvideCheck(interp, "file");
  4320. Jim_CreateCommand(interp, "file", Jim_SubCmdProc, (void *)file_command_table, NULL);
  4321. Jim_CreateCommand(interp, "pwd", Jim_PwdCmd, NULL, NULL);
  4322. Jim_CreateCommand(interp, "cd", Jim_CdCmd, NULL, NULL);
  4323. return JIM_OK;
  4324. }
  4325. #include <string.h>
  4326. #include <ctype.h>
  4327. #if (!(defined(HAVE_VFORK) || defined(HAVE_FORK)) || !defined(HAVE_WAITPID)) && !defined(__MINGW32__)
  4328. static int Jim_ExecCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  4329. {
  4330. Jim_Obj *cmdlineObj = Jim_NewEmptyStringObj(interp);
  4331. int i, j;
  4332. int rc;
  4333. for (i = 1; i < argc; i++) {
  4334. int len;
  4335. const char *arg = Jim_GetString(argv[i], &len);
  4336. if (i > 1) {
  4337. Jim_AppendString(interp, cmdlineObj, " ", 1);
  4338. }
  4339. if (strpbrk(arg, "\\\" ") == NULL) {
  4340. Jim_AppendString(interp, cmdlineObj, arg, len);
  4341. continue;
  4342. }
  4343. Jim_AppendString(interp, cmdlineObj, "\"", 1);
  4344. for (j = 0; j < len; j++) {
  4345. if (arg[j] == '\\' || arg[j] == '"') {
  4346. Jim_AppendString(interp, cmdlineObj, "\\", 1);
  4347. }
  4348. Jim_AppendString(interp, cmdlineObj, &arg[j], 1);
  4349. }
  4350. Jim_AppendString(interp, cmdlineObj, "\"", 1);
  4351. }
  4352. rc = system(Jim_String(cmdlineObj));
  4353. Jim_FreeNewObj(interp, cmdlineObj);
  4354. if (rc) {
  4355. Jim_Obj *errorCode = Jim_NewListObj(interp, NULL, 0);
  4356. Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "CHILDSTATUS", -1));
  4357. Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, 0));
  4358. Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, rc));
  4359. Jim_SetGlobalVariableStr(interp, "errorCode", errorCode);
  4360. return JIM_ERR;
  4361. }
  4362. return JIM_OK;
  4363. }
  4364. int Jim_execInit(Jim_Interp *interp)
  4365. {
  4366. Jim_PackageProvideCheck(interp, "exec");
  4367. Jim_CreateCommand(interp, "exec", Jim_ExecCmd, NULL, NULL);
  4368. return JIM_OK;
  4369. }
  4370. #else
  4371. #include <errno.h>
  4372. #include <signal.h>
  4373. #include <sys/stat.h>
  4374. struct WaitInfoTable;
  4375. static char **JimOriginalEnviron(void);
  4376. static char **JimSaveEnv(char **env);
  4377. static void JimRestoreEnv(char **env);
  4378. static int JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv,
  4379. phandle_t **pidArrayPtr, int *inPipePtr, int *outPipePtr, int *errFilePtr);
  4380. static void JimDetachPids(struct WaitInfoTable *table, int numPids, const phandle_t *pidPtr);
  4381. static int JimCleanupChildren(Jim_Interp *interp, int numPids, phandle_t *pidPtr, Jim_Obj *errStrObj);
  4382. static int Jim_WaitCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
  4383. #if defined(__MINGW32__)
  4384. static phandle_t JimStartWinProcess(Jim_Interp *interp, char **argv, char **env, int inputId, int outputId, int errorId);
  4385. #endif
  4386. static void Jim_RemoveTrailingNewline(Jim_Obj *objPtr)
  4387. {
  4388. int len;
  4389. const char *s = Jim_GetString(objPtr, &len);
  4390. if (len > 0 && s[len - 1] == '\n') {
  4391. objPtr->length--;
  4392. objPtr->bytes[objPtr->length] = '\0';
  4393. }
  4394. }
  4395. static int JimAppendStreamToString(Jim_Interp *interp, int fd, Jim_Obj *strObj)
  4396. {
  4397. char buf[256];
  4398. int ret = 0;
  4399. while (1) {
  4400. int retval = read(fd, buf, sizeof(buf));
  4401. if (retval > 0) {
  4402. ret = 1;
  4403. Jim_AppendString(interp, strObj, buf, retval);
  4404. }
  4405. if (retval <= 0) {
  4406. break;
  4407. }
  4408. }
  4409. close(fd);
  4410. return ret;
  4411. }
  4412. static char **JimBuildEnv(Jim_Interp *interp)
  4413. {
  4414. int i;
  4415. int size;
  4416. int num;
  4417. int n;
  4418. char **envptr;
  4419. char *envdata;
  4420. Jim_Obj *objPtr = Jim_GetGlobalVariableStr(interp, "env", JIM_NONE);
  4421. if (!objPtr) {
  4422. return JimOriginalEnviron();
  4423. }
  4424. num = Jim_ListLength(interp, objPtr);
  4425. if (num % 2) {
  4426. num--;
  4427. }
  4428. size = Jim_Length(objPtr) + 2;
  4429. envptr = Jim_Alloc(sizeof(*envptr) * (num / 2 + 1) + size);
  4430. envdata = (char *)&envptr[num / 2 + 1];
  4431. n = 0;
  4432. for (i = 0; i < num; i += 2) {
  4433. const char *s1, *s2;
  4434. Jim_Obj *elemObj;
  4435. Jim_ListIndex(interp, objPtr, i, &elemObj, JIM_NONE);
  4436. s1 = Jim_String(elemObj);
  4437. Jim_ListIndex(interp, objPtr, i + 1, &elemObj, JIM_NONE);
  4438. s2 = Jim_String(elemObj);
  4439. envptr[n] = envdata;
  4440. envdata += sprintf(envdata, "%s=%s", s1, s2);
  4441. envdata++;
  4442. n++;
  4443. }
  4444. envptr[n] = NULL;
  4445. *envdata = 0;
  4446. return envptr;
  4447. }
  4448. static void JimFreeEnv(char **env, char **original_environ)
  4449. {
  4450. if (env != original_environ) {
  4451. Jim_Free(env);
  4452. }
  4453. }
  4454. static Jim_Obj *JimMakeErrorCode(Jim_Interp *interp, long pid, int waitStatus, Jim_Obj *errStrObj)
  4455. {
  4456. Jim_Obj *errorCode = Jim_NewListObj(interp, NULL, 0);
  4457. if (pid <= 0) {
  4458. Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "NONE", -1));
  4459. Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, pid));
  4460. Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, -1));
  4461. }
  4462. else if (WIFEXITED(waitStatus)) {
  4463. Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "CHILDSTATUS", -1));
  4464. Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, pid));
  4465. Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, WEXITSTATUS(waitStatus)));
  4466. }
  4467. else {
  4468. const char *type;
  4469. const char *action;
  4470. const char *signame;
  4471. if (WIFSIGNALED(waitStatus)) {
  4472. type = "CHILDKILLED";
  4473. action = "killed";
  4474. signame = Jim_SignalId(WTERMSIG(waitStatus));
  4475. }
  4476. else {
  4477. type = "CHILDSUSP";
  4478. action = "suspended";
  4479. signame = "none";
  4480. }
  4481. Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, type, -1));
  4482. if (errStrObj) {
  4483. Jim_AppendStrings(interp, errStrObj, "child ", action, " by signal ", Jim_SignalId(WTERMSIG(waitStatus)), "\n", NULL);
  4484. }
  4485. Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, pid));
  4486. Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, signame, -1));
  4487. }
  4488. return errorCode;
  4489. }
  4490. static int JimCheckWaitStatus(Jim_Interp *interp, long pid, int waitStatus, Jim_Obj *errStrObj)
  4491. {
  4492. if (WIFEXITED(waitStatus) && WEXITSTATUS(waitStatus) == 0) {
  4493. return JIM_OK;
  4494. }
  4495. Jim_SetGlobalVariableStr(interp, "errorCode", JimMakeErrorCode(interp, pid, waitStatus, errStrObj));
  4496. return JIM_ERR;
  4497. }
  4498. struct WaitInfo
  4499. {
  4500. phandle_t phandle;
  4501. int status;
  4502. int flags;
  4503. };
  4504. struct WaitInfoTable {
  4505. struct WaitInfo *info;
  4506. int size;
  4507. int used;
  4508. int refcount;
  4509. };
  4510. #define WI_DETACHED 2
  4511. #define WAIT_TABLE_GROW_BY 4
  4512. static void JimFreeWaitInfoTable(struct Jim_Interp *interp, void *privData)
  4513. {
  4514. struct WaitInfoTable *table = privData;
  4515. if (--table->refcount == 0) {
  4516. Jim_Free(table->info);
  4517. Jim_Free(table);
  4518. }
  4519. }
  4520. static struct WaitInfoTable *JimAllocWaitInfoTable(void)
  4521. {
  4522. struct WaitInfoTable *table = Jim_Alloc(sizeof(*table));
  4523. table->info = NULL;
  4524. table->size = table->used = 0;
  4525. table->refcount = 1;
  4526. return table;
  4527. }
  4528. static int JimWaitRemove(struct WaitInfoTable *table, phandle_t phandle)
  4529. {
  4530. int i;
  4531. for (i = 0; i < table->used; i++) {
  4532. if (phandle == table->info[i].phandle) {
  4533. if (i != table->used - 1) {
  4534. table->info[i] = table->info[table->used - 1];
  4535. }
  4536. table->used--;
  4537. return 0;
  4538. }
  4539. }
  4540. return -1;
  4541. }
  4542. static int Jim_ExecCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  4543. {
  4544. int outputId;
  4545. int errorId;
  4546. phandle_t *pidPtr;
  4547. int numPids, result;
  4548. int child_siginfo = 1;
  4549. Jim_Obj *childErrObj;
  4550. Jim_Obj *errStrObj;
  4551. struct WaitInfoTable *table = Jim_CmdPrivData(interp);
  4552. if (argc > 1 && Jim_CompareStringImmediate(interp, argv[argc - 1], "&")) {
  4553. Jim_Obj *listObj;
  4554. int i;
  4555. argc--;
  4556. numPids = JimCreatePipeline(interp, argc - 1, argv + 1, &pidPtr, NULL, NULL, NULL);
  4557. if (numPids < 0) {
  4558. return JIM_ERR;
  4559. }
  4560. listObj = Jim_NewListObj(interp, NULL, 0);
  4561. for (i = 0; i < numPids; i++) {
  4562. Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, JimProcessPid(pidPtr[i])));
  4563. }
  4564. Jim_SetResult(interp, listObj);
  4565. JimDetachPids(table, numPids, pidPtr);
  4566. Jim_Free(pidPtr);
  4567. return JIM_OK;
  4568. }
  4569. numPids =
  4570. JimCreatePipeline(interp, argc - 1, argv + 1, &pidPtr, NULL, &outputId, &errorId);
  4571. if (numPids < 0) {
  4572. return JIM_ERR;
  4573. }
  4574. result = JIM_OK;
  4575. errStrObj = Jim_NewStringObj(interp, "", 0);
  4576. if (outputId != -1) {
  4577. if (JimAppendStreamToString(interp, outputId, errStrObj) < 0) {
  4578. result = JIM_ERR;
  4579. Jim_SetResultErrno(interp, "error reading from output pipe");
  4580. }
  4581. }
  4582. childErrObj = Jim_NewStringObj(interp, "", 0);
  4583. Jim_IncrRefCount(childErrObj);
  4584. if (JimCleanupChildren(interp, numPids, pidPtr, childErrObj) != JIM_OK) {
  4585. result = JIM_ERR;
  4586. }
  4587. if (errorId != -1) {
  4588. int ret;
  4589. Jim_Lseek(errorId, 0, SEEK_SET);
  4590. ret = JimAppendStreamToString(interp, errorId, errStrObj);
  4591. if (ret < 0) {
  4592. Jim_SetResultErrno(interp, "error reading from error pipe");
  4593. result = JIM_ERR;
  4594. }
  4595. else if (ret > 0) {
  4596. child_siginfo = 0;
  4597. }
  4598. }
  4599. if (child_siginfo) {
  4600. Jim_AppendObj(interp, errStrObj, childErrObj);
  4601. }
  4602. Jim_DecrRefCount(interp, childErrObj);
  4603. Jim_RemoveTrailingNewline(errStrObj);
  4604. Jim_SetResult(interp, errStrObj);
  4605. return result;
  4606. }
  4607. static long JimWaitForProcess(struct WaitInfoTable *table, phandle_t phandle, int *statusPtr)
  4608. {
  4609. if (JimWaitRemove(table, phandle) == 0) {
  4610. return waitpid(phandle, statusPtr, 0);
  4611. }
  4612. return -1;
  4613. }
  4614. static void JimDetachPids(struct WaitInfoTable *table, int numPids, const phandle_t *pidPtr)
  4615. {
  4616. int j;
  4617. for (j = 0; j < numPids; j++) {
  4618. int i;
  4619. for (i = 0; i < table->used; i++) {
  4620. if (pidPtr[j] == table->info[i].phandle) {
  4621. table->info[i].flags |= WI_DETACHED;
  4622. break;
  4623. }
  4624. }
  4625. }
  4626. }
  4627. static int JimGetChannelFd(Jim_Interp *interp, const char *name)
  4628. {
  4629. Jim_Obj *objv[2];
  4630. objv[0] = Jim_NewStringObj(interp, name, -1);
  4631. objv[1] = Jim_NewStringObj(interp, "getfd", -1);
  4632. if (Jim_EvalObjVector(interp, 2, objv) == JIM_OK) {
  4633. jim_wide fd;
  4634. if (Jim_GetWide(interp, Jim_GetResult(interp), &fd) == JIM_OK) {
  4635. return fd;
  4636. }
  4637. }
  4638. return -1;
  4639. }
  4640. static void JimReapDetachedPids(struct WaitInfoTable *table)
  4641. {
  4642. struct WaitInfo *waitPtr;
  4643. int count;
  4644. int dest;
  4645. if (!table) {
  4646. return;
  4647. }
  4648. waitPtr = table->info;
  4649. dest = 0;
  4650. for (count = table->used; count > 0; waitPtr++, count--) {
  4651. if (waitPtr->flags & WI_DETACHED) {
  4652. int status;
  4653. long pid = waitpid(waitPtr->phandle, &status, WNOHANG);
  4654. if (pid > 0) {
  4655. table->used--;
  4656. continue;
  4657. }
  4658. }
  4659. if (waitPtr != &table->info[dest]) {
  4660. table->info[dest] = *waitPtr;
  4661. }
  4662. dest++;
  4663. }
  4664. }
  4665. static int Jim_WaitCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  4666. {
  4667. struct WaitInfoTable *table = Jim_CmdPrivData(interp);
  4668. int nohang = 0;
  4669. long pid;
  4670. phandle_t phandle;
  4671. int status;
  4672. Jim_Obj *errCodeObj;
  4673. if (argc == 1) {
  4674. JimReapDetachedPids(table);
  4675. return JIM_OK;
  4676. }
  4677. if (argc > 1 && Jim_CompareStringImmediate(interp, argv[1], "-nohang")) {
  4678. nohang = 1;
  4679. }
  4680. if (argc != nohang + 2) {
  4681. Jim_WrongNumArgs(interp, 1, argv, "?-nohang? ?pid?");
  4682. return JIM_ERR;
  4683. }
  4684. if (Jim_GetLong(interp, argv[nohang + 1], &pid) != JIM_OK) {
  4685. return JIM_ERR;
  4686. }
  4687. phandle = JimWaitPid(pid, &status, nohang ? WNOHANG : 0);
  4688. if (phandle == JIM_BAD_PHANDLE) {
  4689. pid = -1;
  4690. }
  4691. #ifndef __MINGW32__
  4692. else if (pid < 0) {
  4693. pid = phandle;
  4694. }
  4695. #endif
  4696. errCodeObj = JimMakeErrorCode(interp, pid, status, NULL);
  4697. if (phandle != JIM_BAD_PHANDLE && (WIFEXITED(status) || WIFSIGNALED(status))) {
  4698. JimWaitRemove(table, phandle);
  4699. }
  4700. Jim_SetResult(interp, errCodeObj);
  4701. return JIM_OK;
  4702. }
  4703. static int Jim_PidCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  4704. {
  4705. if (argc != 1) {
  4706. Jim_WrongNumArgs(interp, 1, argv, "");
  4707. return JIM_ERR;
  4708. }
  4709. Jim_SetResultInt(interp, (jim_wide)getpid());
  4710. return JIM_OK;
  4711. }
  4712. static int
  4713. JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv, phandle_t **pidArrayPtr,
  4714. int *inPipePtr, int *outPipePtr, int *errFilePtr)
  4715. {
  4716. phandle_t *pidPtr = NULL; /* Points to alloc-ed array holding all
  4717. * the pids of child processes. */
  4718. int numPids = 0; /* Actual number of processes that exist
  4719. * at *pidPtr right now. */
  4720. int cmdCount; /* Count of number of distinct commands
  4721. * found in argc/argv. */
  4722. const char *input = NULL; /* Describes input for pipeline, depending
  4723. * on "inputFile". NULL means take input
  4724. * from stdin/pipe. */
  4725. int input_len = 0;
  4726. #define FILE_NAME 0
  4727. #define FILE_APPEND 1
  4728. #define FILE_HANDLE 2
  4729. #define FILE_TEXT 3
  4730. int inputFile = FILE_NAME; /* 1 means input is name of input file.
  4731. * 2 means input is filehandle name.
  4732. * 0 means input holds actual
  4733. * text to be input to command. */
  4734. int outputFile = FILE_NAME; /* 0 means output is the name of output file.
  4735. * 1 means output is the name of output file, and append.
  4736. * 2 means output is filehandle name.
  4737. * All this is ignored if output is NULL
  4738. */
  4739. int errorFile = FILE_NAME; /* 0 means error is the name of error file.
  4740. * 1 means error is the name of error file, and append.
  4741. * 2 means error is filehandle name.
  4742. * All this is ignored if error is NULL
  4743. */
  4744. const char *output = NULL; /* Holds name of output file to pipe to,
  4745. * or NULL if output goes to stdout/pipe. */
  4746. const char *error = NULL; /* Holds name of stderr file to pipe to,
  4747. * or NULL if stderr goes to stderr/pipe. */
  4748. int inputId = -1;
  4749. int outputId = -1;
  4750. int errorId = -1;
  4751. int lastOutputId = -1;
  4752. int pipeIds[2];
  4753. int firstArg, lastArg; /* Indexes of first and last arguments in
  4754. * current command. */
  4755. int lastBar;
  4756. int i;
  4757. phandle_t phandle;
  4758. char **save_environ;
  4759. #if defined(HAVE_EXECVPE) && !defined(__MINGW32__)
  4760. char **child_environ;
  4761. #endif
  4762. struct WaitInfoTable *table = Jim_CmdPrivData(interp);
  4763. char **arg_array = Jim_Alloc(sizeof(*arg_array) * (argc + 1));
  4764. int arg_count = 0;
  4765. if (inPipePtr != NULL) {
  4766. *inPipePtr = -1;
  4767. }
  4768. if (outPipePtr != NULL) {
  4769. *outPipePtr = -1;
  4770. }
  4771. if (errFilePtr != NULL) {
  4772. *errFilePtr = -1;
  4773. }
  4774. pipeIds[0] = pipeIds[1] = -1;
  4775. cmdCount = 1;
  4776. lastBar = -1;
  4777. for (i = 0; i < argc; i++) {
  4778. const char *arg = Jim_String(argv[i]);
  4779. if (arg[0] == '<') {
  4780. inputFile = FILE_NAME;
  4781. input = arg + 1;
  4782. if (*input == '<') {
  4783. inputFile = FILE_TEXT;
  4784. input_len = Jim_Length(argv[i]) - 2;
  4785. input++;
  4786. }
  4787. else if (*input == '@') {
  4788. inputFile = FILE_HANDLE;
  4789. input++;
  4790. }
  4791. if (!*input && ++i < argc) {
  4792. input = Jim_GetString(argv[i], &input_len);
  4793. }
  4794. }
  4795. else if (arg[0] == '>') {
  4796. int dup_error = 0;
  4797. outputFile = FILE_NAME;
  4798. output = arg + 1;
  4799. if (*output == '>') {
  4800. outputFile = FILE_APPEND;
  4801. output++;
  4802. }
  4803. if (*output == '&') {
  4804. output++;
  4805. dup_error = 1;
  4806. }
  4807. if (*output == '@') {
  4808. outputFile = FILE_HANDLE;
  4809. output++;
  4810. }
  4811. if (!*output && ++i < argc) {
  4812. output = Jim_String(argv[i]);
  4813. }
  4814. if (dup_error) {
  4815. errorFile = outputFile;
  4816. error = output;
  4817. }
  4818. }
  4819. else if (arg[0] == '2' && arg[1] == '>') {
  4820. error = arg + 2;
  4821. errorFile = FILE_NAME;
  4822. if (*error == '@') {
  4823. errorFile = FILE_HANDLE;
  4824. error++;
  4825. }
  4826. else if (*error == '>') {
  4827. errorFile = FILE_APPEND;
  4828. error++;
  4829. }
  4830. if (!*error && ++i < argc) {
  4831. error = Jim_String(argv[i]);
  4832. }
  4833. }
  4834. else {
  4835. if (strcmp(arg, "|") == 0 || strcmp(arg, "|&") == 0) {
  4836. if (i == lastBar + 1 || i == argc - 1) {
  4837. Jim_SetResultString(interp, "illegal use of | or |& in command", -1);
  4838. goto badargs;
  4839. }
  4840. lastBar = i;
  4841. cmdCount++;
  4842. }
  4843. arg_array[arg_count++] = (char *)arg;
  4844. continue;
  4845. }
  4846. if (i >= argc) {
  4847. Jim_SetResultFormatted(interp, "can't specify \"%s\" as last word in command", arg);
  4848. goto badargs;
  4849. }
  4850. }
  4851. if (arg_count == 0) {
  4852. Jim_SetResultString(interp, "didn't specify command to execute", -1);
  4853. badargs:
  4854. Jim_Free(arg_array);
  4855. return -1;
  4856. }
  4857. save_environ = JimSaveEnv(JimBuildEnv(interp));
  4858. if (input != NULL) {
  4859. if (inputFile == FILE_TEXT) {
  4860. inputId = Jim_MakeTempFile(interp, NULL, 1);
  4861. if (inputId == -1) {
  4862. goto error;
  4863. }
  4864. if (write(inputId, input, input_len) != input_len) {
  4865. Jim_SetResultErrno(interp, "couldn't write temp file");
  4866. close(inputId);
  4867. goto error;
  4868. }
  4869. Jim_Lseek(inputId, 0L, SEEK_SET);
  4870. }
  4871. else if (inputFile == FILE_HANDLE) {
  4872. int fd = JimGetChannelFd(interp, input);
  4873. if (fd < 0) {
  4874. goto error;
  4875. }
  4876. inputId = dup(fd);
  4877. }
  4878. else {
  4879. inputId = Jim_OpenForRead(input);
  4880. if (inputId == -1) {
  4881. Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", input, strerror(Jim_Errno()));
  4882. goto error;
  4883. }
  4884. }
  4885. }
  4886. else if (inPipePtr != NULL) {
  4887. if (pipe(pipeIds) != 0) {
  4888. Jim_SetResultErrno(interp, "couldn't create input pipe for command");
  4889. goto error;
  4890. }
  4891. inputId = pipeIds[0];
  4892. *inPipePtr = pipeIds[1];
  4893. pipeIds[0] = pipeIds[1] = -1;
  4894. }
  4895. if (output != NULL) {
  4896. if (outputFile == FILE_HANDLE) {
  4897. int fd = JimGetChannelFd(interp, output);
  4898. if (fd < 0) {
  4899. goto error;
  4900. }
  4901. lastOutputId = dup(fd);
  4902. }
  4903. else {
  4904. lastOutputId = Jim_OpenForWrite(output, outputFile == FILE_APPEND);
  4905. if (lastOutputId == -1) {
  4906. Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", output, strerror(Jim_Errno()));
  4907. goto error;
  4908. }
  4909. }
  4910. }
  4911. else if (outPipePtr != NULL) {
  4912. if (pipe(pipeIds) != 0) {
  4913. Jim_SetResultErrno(interp, "couldn't create output pipe");
  4914. goto error;
  4915. }
  4916. lastOutputId = pipeIds[1];
  4917. *outPipePtr = pipeIds[0];
  4918. pipeIds[0] = pipeIds[1] = -1;
  4919. }
  4920. if (error != NULL) {
  4921. if (errorFile == FILE_HANDLE) {
  4922. if (strcmp(error, "1") == 0) {
  4923. if (lastOutputId != -1) {
  4924. errorId = dup(lastOutputId);
  4925. }
  4926. else {
  4927. error = "stdout";
  4928. }
  4929. }
  4930. if (errorId == -1) {
  4931. int fd = JimGetChannelFd(interp, error);
  4932. if (fd < 0) {
  4933. goto error;
  4934. }
  4935. errorId = dup(fd);
  4936. }
  4937. }
  4938. else {
  4939. errorId = Jim_OpenForWrite(error, errorFile == FILE_APPEND);
  4940. if (errorId == -1) {
  4941. Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", error, strerror(Jim_Errno()));
  4942. goto error;
  4943. }
  4944. }
  4945. }
  4946. else if (errFilePtr != NULL) {
  4947. errorId = Jim_MakeTempFile(interp, NULL, 1);
  4948. if (errorId == -1) {
  4949. goto error;
  4950. }
  4951. *errFilePtr = dup(errorId);
  4952. }
  4953. pidPtr = Jim_Alloc(cmdCount * sizeof(*pidPtr));
  4954. for (firstArg = 0; firstArg < arg_count; numPids++, firstArg = lastArg + 1) {
  4955. int pipe_dup_err = 0;
  4956. int origErrorId = errorId;
  4957. for (lastArg = firstArg; lastArg < arg_count; lastArg++) {
  4958. if (strcmp(arg_array[lastArg], "|") == 0) {
  4959. break;
  4960. }
  4961. if (strcmp(arg_array[lastArg], "|&") == 0) {
  4962. pipe_dup_err = 1;
  4963. break;
  4964. }
  4965. }
  4966. if (lastArg == firstArg) {
  4967. Jim_SetResultString(interp, "missing command to exec", -1);
  4968. goto error;
  4969. }
  4970. arg_array[lastArg] = NULL;
  4971. if (lastArg == arg_count) {
  4972. outputId = lastOutputId;
  4973. lastOutputId = -1;
  4974. }
  4975. else {
  4976. if (pipe(pipeIds) != 0) {
  4977. Jim_SetResultErrno(interp, "couldn't create pipe");
  4978. goto error;
  4979. }
  4980. outputId = pipeIds[1];
  4981. }
  4982. if (pipe_dup_err) {
  4983. errorId = outputId;
  4984. }
  4985. #ifdef __MINGW32__
  4986. phandle = JimStartWinProcess(interp, &arg_array[firstArg], save_environ, inputId, outputId, errorId);
  4987. if (phandle == JIM_BAD_PHANDLE) {
  4988. Jim_SetResultFormatted(interp, "couldn't exec \"%s\"", arg_array[firstArg]);
  4989. goto error;
  4990. }
  4991. #else
  4992. i = strlen(arg_array[firstArg]);
  4993. #ifdef HAVE_EXECVPE
  4994. child_environ = Jim_GetEnviron();
  4995. #endif
  4996. #ifdef HAVE_VFORK
  4997. phandle = vfork();
  4998. #else
  4999. phandle = fork();
  5000. #endif
  5001. if (phandle < 0) {
  5002. Jim_SetResultErrno(interp, "couldn't fork child process");
  5003. goto error;
  5004. }
  5005. if (phandle == 0) {
  5006. if (inputId != -1 && inputId != fileno(stdin)) {
  5007. dup2(inputId, fileno(stdin));
  5008. close(inputId);
  5009. }
  5010. if (outputId != -1 && outputId != fileno(stdout)) {
  5011. dup2(outputId, fileno(stdout));
  5012. if (outputId != errorId) {
  5013. close(outputId);
  5014. }
  5015. }
  5016. if (errorId != -1 && errorId != fileno(stderr)) {
  5017. dup2(errorId, fileno(stderr));
  5018. close(errorId);
  5019. }
  5020. if (outPipePtr && *outPipePtr != -1) {
  5021. close(*outPipePtr);
  5022. }
  5023. if (errFilePtr && *errFilePtr != -1) {
  5024. close(*errFilePtr);
  5025. }
  5026. if (pipeIds[0] != -1) {
  5027. close(pipeIds[0]);
  5028. }
  5029. if (lastOutputId != -1) {
  5030. close(lastOutputId);
  5031. }
  5032. execvpe(arg_array[firstArg], &arg_array[firstArg], child_environ);
  5033. if (write(fileno(stderr), "couldn't exec \"", 15) &&
  5034. write(fileno(stderr), arg_array[firstArg], i) &&
  5035. write(fileno(stderr), "\"\n", 2)) {
  5036. }
  5037. #ifdef JIM_MAINTAINER
  5038. {
  5039. static char *const false_argv[2] = {"false", NULL};
  5040. execvp(false_argv[0],false_argv);
  5041. }
  5042. #endif
  5043. _exit(127);
  5044. }
  5045. #endif
  5046. if (table->used == table->size) {
  5047. table->size += WAIT_TABLE_GROW_BY;
  5048. table->info = Jim_Realloc(table->info, table->size * sizeof(*table->info));
  5049. }
  5050. table->info[table->used].phandle = phandle;
  5051. table->info[table->used].flags = 0;
  5052. table->used++;
  5053. pidPtr[numPids] = phandle;
  5054. errorId = origErrorId;
  5055. if (inputId != -1) {
  5056. close(inputId);
  5057. }
  5058. if (outputId != -1) {
  5059. close(outputId);
  5060. }
  5061. inputId = pipeIds[0];
  5062. pipeIds[0] = pipeIds[1] = -1;
  5063. }
  5064. *pidArrayPtr = pidPtr;
  5065. cleanup:
  5066. if (inputId != -1) {
  5067. close(inputId);
  5068. }
  5069. if (lastOutputId != -1) {
  5070. close(lastOutputId);
  5071. }
  5072. if (errorId != -1) {
  5073. close(errorId);
  5074. }
  5075. Jim_Free(arg_array);
  5076. JimRestoreEnv(save_environ);
  5077. return numPids;
  5078. error:
  5079. if ((inPipePtr != NULL) && (*inPipePtr != -1)) {
  5080. close(*inPipePtr);
  5081. *inPipePtr = -1;
  5082. }
  5083. if ((outPipePtr != NULL) && (*outPipePtr != -1)) {
  5084. close(*outPipePtr);
  5085. *outPipePtr = -1;
  5086. }
  5087. if ((errFilePtr != NULL) && (*errFilePtr != -1)) {
  5088. close(*errFilePtr);
  5089. *errFilePtr = -1;
  5090. }
  5091. if (pipeIds[0] != -1) {
  5092. close(pipeIds[0]);
  5093. }
  5094. if (pipeIds[1] != -1) {
  5095. close(pipeIds[1]);
  5096. }
  5097. if (pidPtr != NULL) {
  5098. for (i = 0; i < numPids; i++) {
  5099. if (pidPtr[i] != JIM_BAD_PHANDLE) {
  5100. JimDetachPids(table, 1, &pidPtr[i]);
  5101. }
  5102. }
  5103. Jim_Free(pidPtr);
  5104. }
  5105. numPids = -1;
  5106. goto cleanup;
  5107. }
  5108. static int JimCleanupChildren(Jim_Interp *interp, int numPids, phandle_t *pidPtr, Jim_Obj *errStrObj)
  5109. {
  5110. struct WaitInfoTable *table = Jim_CmdPrivData(interp);
  5111. int result = JIM_OK;
  5112. int i;
  5113. for (i = 0; i < numPids; i++) {
  5114. int waitStatus = 0;
  5115. long pid = JimWaitForProcess(table, pidPtr[i], &waitStatus);
  5116. if (pid > 0) {
  5117. if (JimCheckWaitStatus(interp, pid, waitStatus, errStrObj) != JIM_OK) {
  5118. result = JIM_ERR;
  5119. }
  5120. }
  5121. }
  5122. Jim_Free(pidPtr);
  5123. return result;
  5124. }
  5125. int Jim_execInit(Jim_Interp *interp)
  5126. {
  5127. struct WaitInfoTable *waitinfo;
  5128. Jim_PackageProvideCheck(interp, "exec");
  5129. waitinfo = JimAllocWaitInfoTable();
  5130. Jim_CreateCommand(interp, "exec", Jim_ExecCmd, waitinfo, JimFreeWaitInfoTable);
  5131. waitinfo->refcount++;
  5132. Jim_CreateCommand(interp, "wait", Jim_WaitCommand, waitinfo, JimFreeWaitInfoTable);
  5133. Jim_CreateCommand(interp, "pid", Jim_PidCommand, 0, 0);
  5134. return JIM_OK;
  5135. }
  5136. #if defined(__MINGW32__)
  5137. static int
  5138. JimWinFindExecutable(const char *originalName, char fullPath[MAX_PATH])
  5139. {
  5140. int i;
  5141. static char extensions[][5] = {".exe", "", ".bat"};
  5142. for (i = 0; i < (int) (sizeof(extensions) / sizeof(extensions[0])); i++) {
  5143. snprintf(fullPath, MAX_PATH, "%s%s", originalName, extensions[i]);
  5144. if (SearchPath(NULL, fullPath, NULL, MAX_PATH, fullPath, NULL) == 0) {
  5145. continue;
  5146. }
  5147. if (GetFileAttributes(fullPath) & FILE_ATTRIBUTE_DIRECTORY) {
  5148. continue;
  5149. }
  5150. return 0;
  5151. }
  5152. return -1;
  5153. }
  5154. static char **JimSaveEnv(char **env)
  5155. {
  5156. return env;
  5157. }
  5158. static void JimRestoreEnv(char **env)
  5159. {
  5160. JimFreeEnv(env, Jim_GetEnviron());
  5161. }
  5162. static char **JimOriginalEnviron(void)
  5163. {
  5164. return NULL;
  5165. }
  5166. static Jim_Obj *
  5167. JimWinBuildCommandLine(Jim_Interp *interp, char **argv)
  5168. {
  5169. char *start, *special;
  5170. int quote, i;
  5171. Jim_Obj *strObj = Jim_NewStringObj(interp, "", 0);
  5172. for (i = 0; argv[i]; i++) {
  5173. if (i > 0) {
  5174. Jim_AppendString(interp, strObj, " ", 1);
  5175. }
  5176. if (argv[i][0] == '\0') {
  5177. quote = 1;
  5178. }
  5179. else {
  5180. quote = 0;
  5181. for (start = argv[i]; *start != '\0'; start++) {
  5182. if (isspace(UCHAR(*start))) {
  5183. quote = 1;
  5184. break;
  5185. }
  5186. }
  5187. }
  5188. if (quote) {
  5189. Jim_AppendString(interp, strObj, "\"" , 1);
  5190. }
  5191. start = argv[i];
  5192. for (special = argv[i]; ; ) {
  5193. if ((*special == '\\') && (special[1] == '\\' ||
  5194. special[1] == '"' || (quote && special[1] == '\0'))) {
  5195. Jim_AppendString(interp, strObj, start, special - start);
  5196. start = special;
  5197. while (1) {
  5198. special++;
  5199. if (*special == '"' || (quote && *special == '\0')) {
  5200. Jim_AppendString(interp, strObj, start, special - start);
  5201. break;
  5202. }
  5203. if (*special != '\\') {
  5204. break;
  5205. }
  5206. }
  5207. Jim_AppendString(interp, strObj, start, special - start);
  5208. start = special;
  5209. }
  5210. if (*special == '"') {
  5211. if (special == start) {
  5212. Jim_AppendString(interp, strObj, "\"", 1);
  5213. }
  5214. else {
  5215. Jim_AppendString(interp, strObj, start, special - start);
  5216. }
  5217. Jim_AppendString(interp, strObj, "\\\"", 2);
  5218. start = special + 1;
  5219. }
  5220. if (*special == '\0') {
  5221. break;
  5222. }
  5223. special++;
  5224. }
  5225. Jim_AppendString(interp, strObj, start, special - start);
  5226. if (quote) {
  5227. Jim_AppendString(interp, strObj, "\"", 1);
  5228. }
  5229. }
  5230. return strObj;
  5231. }
  5232. static phandle_t
  5233. JimStartWinProcess(Jim_Interp *interp, char **argv, char **env, int inputId, int outputId, int errorId)
  5234. {
  5235. STARTUPINFO startInfo;
  5236. PROCESS_INFORMATION procInfo;
  5237. HANDLE hProcess;
  5238. char execPath[MAX_PATH];
  5239. phandle_t phandle = INVALID_HANDLE_VALUE;
  5240. Jim_Obj *cmdLineObj;
  5241. char *winenv;
  5242. if (JimWinFindExecutable(argv[0], execPath) < 0) {
  5243. return phandle;
  5244. }
  5245. argv[0] = execPath;
  5246. hProcess = GetCurrentProcess();
  5247. cmdLineObj = JimWinBuildCommandLine(interp, argv);
  5248. ZeroMemory(&startInfo, sizeof(startInfo));
  5249. startInfo.cb = sizeof(startInfo);
  5250. startInfo.dwFlags = STARTF_USESTDHANDLES;
  5251. startInfo.hStdInput = INVALID_HANDLE_VALUE;
  5252. startInfo.hStdOutput= INVALID_HANDLE_VALUE;
  5253. startInfo.hStdError = INVALID_HANDLE_VALUE;
  5254. if (inputId == -1) {
  5255. inputId = _fileno(stdin);
  5256. }
  5257. DuplicateHandle(hProcess, (HANDLE)_get_osfhandle(inputId), hProcess, &startInfo.hStdInput,
  5258. 0, TRUE, DUPLICATE_SAME_ACCESS);
  5259. if (startInfo.hStdInput == INVALID_HANDLE_VALUE) {
  5260. goto end;
  5261. }
  5262. if (outputId == -1) {
  5263. outputId = _fileno(stdout);
  5264. }
  5265. DuplicateHandle(hProcess, (HANDLE)_get_osfhandle(outputId), hProcess, &startInfo.hStdOutput,
  5266. 0, TRUE, DUPLICATE_SAME_ACCESS);
  5267. if (startInfo.hStdOutput == INVALID_HANDLE_VALUE) {
  5268. goto end;
  5269. }
  5270. if (errorId == -1) {
  5271. errorId = _fileno(stderr);
  5272. }
  5273. DuplicateHandle(hProcess, (HANDLE)_get_osfhandle(errorId), hProcess, &startInfo.hStdError,
  5274. 0, TRUE, DUPLICATE_SAME_ACCESS);
  5275. if (startInfo.hStdError == INVALID_HANDLE_VALUE) {
  5276. goto end;
  5277. }
  5278. if (env == NULL) {
  5279. winenv = NULL;
  5280. }
  5281. else if (env[0] == NULL) {
  5282. winenv = (char *)"\0";
  5283. }
  5284. else {
  5285. winenv = env[0];
  5286. }
  5287. if (!CreateProcess(NULL, (char *)Jim_String(cmdLineObj), NULL, NULL, TRUE,
  5288. 0, winenv, NULL, &startInfo, &procInfo)) {
  5289. goto end;
  5290. }
  5291. WaitForInputIdle(procInfo.hProcess, 5000);
  5292. CloseHandle(procInfo.hThread);
  5293. phandle = procInfo.hProcess;
  5294. end:
  5295. Jim_FreeNewObj(interp, cmdLineObj);
  5296. if (startInfo.hStdInput != INVALID_HANDLE_VALUE) {
  5297. CloseHandle(startInfo.hStdInput);
  5298. }
  5299. if (startInfo.hStdOutput != INVALID_HANDLE_VALUE) {
  5300. CloseHandle(startInfo.hStdOutput);
  5301. }
  5302. if (startInfo.hStdError != INVALID_HANDLE_VALUE) {
  5303. CloseHandle(startInfo.hStdError);
  5304. }
  5305. return phandle;
  5306. }
  5307. #else
  5308. static char **JimOriginalEnviron(void)
  5309. {
  5310. return Jim_GetEnviron();
  5311. }
  5312. static char **JimSaveEnv(char **env)
  5313. {
  5314. char **saveenv = Jim_GetEnviron();
  5315. Jim_SetEnviron(env);
  5316. return saveenv;
  5317. }
  5318. static void JimRestoreEnv(char **env)
  5319. {
  5320. JimFreeEnv(Jim_GetEnviron(), env);
  5321. Jim_SetEnviron(env);
  5322. }
  5323. #endif
  5324. #endif
  5325. #include <stdlib.h>
  5326. #include <string.h>
  5327. #include <stdio.h>
  5328. #include <time.h>
  5329. #ifdef HAVE_SYS_TIME_H
  5330. #include <sys/time.h>
  5331. #endif
  5332. struct clock_options {
  5333. int gmt;
  5334. const char *format;
  5335. };
  5336. static int parse_clock_options(Jim_Interp *interp, int argc, Jim_Obj *const *argv, struct clock_options *opts)
  5337. {
  5338. static const char * const options[] = { "-gmt", "-format", NULL };
  5339. enum { OPT_GMT, OPT_FORMAT, };
  5340. int i;
  5341. for (i = 0; i < argc; i += 2) {
  5342. int option;
  5343. if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
  5344. return JIM_ERR;
  5345. }
  5346. switch (option) {
  5347. case OPT_GMT:
  5348. if (Jim_GetBoolean(interp, argv[i + 1], &opts->gmt) != JIM_OK) {
  5349. return JIM_ERR;
  5350. }
  5351. break;
  5352. case OPT_FORMAT:
  5353. opts->format = Jim_String(argv[i + 1]);
  5354. break;
  5355. }
  5356. }
  5357. return JIM_OK;
  5358. }
  5359. static int clock_cmd_format(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  5360. {
  5361. char buf[100];
  5362. time_t t;
  5363. jim_wide seconds;
  5364. struct clock_options options = { 0, "%a %b %d %H:%M:%S %Z %Y" };
  5365. struct tm *tm;
  5366. if (Jim_GetWide(interp, argv[0], &seconds) != JIM_OK) {
  5367. return JIM_ERR;
  5368. }
  5369. if (argc % 2 == 0) {
  5370. return -1;
  5371. }
  5372. if (parse_clock_options(interp, argc - 1, argv + 1, &options) == JIM_ERR) {
  5373. return JIM_ERR;
  5374. }
  5375. t = seconds;
  5376. tm = options.gmt ? gmtime(&t) : localtime(&t);
  5377. if (tm == NULL || strftime(buf, sizeof(buf), options.format, tm) == 0) {
  5378. Jim_SetResultString(interp, "format string too long or invalid time", -1);
  5379. return JIM_ERR;
  5380. }
  5381. Jim_SetResultString(interp, buf, -1);
  5382. return JIM_OK;
  5383. }
  5384. #ifdef HAVE_STRPTIME
  5385. static time_t jim_timegm(const struct tm *tm)
  5386. {
  5387. int m = tm->tm_mon + 1;
  5388. int y = 1900 + tm->tm_year - (m <= 2);
  5389. int era = (y >= 0 ? y : y - 399) / 400;
  5390. unsigned yoe = (unsigned)(y - era * 400);
  5391. unsigned doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + tm->tm_mday - 1;
  5392. unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
  5393. long days = (era * 146097 + (int)doe - 719468);
  5394. int secs = tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
  5395. return days * 24 * 60 * 60 + secs;
  5396. }
  5397. static int clock_cmd_scan(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  5398. {
  5399. char *pt;
  5400. struct tm tm;
  5401. time_t now = time(NULL);
  5402. struct clock_options options = { 0, NULL };
  5403. if (argc % 2 == 0) {
  5404. return -1;
  5405. }
  5406. if (parse_clock_options(interp, argc - 1, argv + 1, &options) == JIM_ERR) {
  5407. return JIM_ERR;
  5408. }
  5409. if (options.format == NULL) {
  5410. return -1;
  5411. }
  5412. localtime_r(&now, &tm);
  5413. pt = strptime(Jim_String(argv[0]), options.format, &tm);
  5414. if (pt == 0 || *pt != 0) {
  5415. Jim_SetResultString(interp, "Failed to parse time according to format", -1);
  5416. return JIM_ERR;
  5417. }
  5418. tm.tm_isdst = options.gmt ? 0 : -1;
  5419. Jim_SetResultInt(interp, options.gmt ? jim_timegm(&tm) : mktime(&tm));
  5420. return JIM_OK;
  5421. }
  5422. #endif
  5423. static int clock_cmd_seconds(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  5424. {
  5425. Jim_SetResultInt(interp, Jim_GetTimeUsec(CLOCK_REALTIME) / 1000000);
  5426. return JIM_OK;
  5427. }
  5428. static int clock_cmd_clicks(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  5429. {
  5430. Jim_SetResultInt(interp, Jim_GetTimeUsec(CLOCK_MONOTONIC_RAW));
  5431. return JIM_OK;
  5432. }
  5433. static int clock_cmd_micros(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  5434. {
  5435. Jim_SetResultInt(interp, Jim_GetTimeUsec(CLOCK_REALTIME));
  5436. return JIM_OK;
  5437. }
  5438. static int clock_cmd_millis(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  5439. {
  5440. Jim_SetResultInt(interp, Jim_GetTimeUsec(CLOCK_REALTIME) / 1000);
  5441. return JIM_OK;
  5442. }
  5443. static const jim_subcmd_type clock_command_table[] = {
  5444. { "clicks",
  5445. NULL,
  5446. clock_cmd_clicks,
  5447. 0,
  5448. 0,
  5449. },
  5450. { "format",
  5451. "seconds ?-format string? ?-gmt boolean?",
  5452. clock_cmd_format,
  5453. 1,
  5454. 5,
  5455. },
  5456. { "microseconds",
  5457. NULL,
  5458. clock_cmd_micros,
  5459. 0,
  5460. 0,
  5461. },
  5462. { "milliseconds",
  5463. NULL,
  5464. clock_cmd_millis,
  5465. 0,
  5466. 0,
  5467. },
  5468. #ifdef HAVE_STRPTIME
  5469. { "scan",
  5470. "str -format format ?-gmt boolean?",
  5471. clock_cmd_scan,
  5472. 3,
  5473. 5,
  5474. },
  5475. #endif
  5476. { "seconds",
  5477. NULL,
  5478. clock_cmd_seconds,
  5479. 0,
  5480. 0,
  5481. },
  5482. { NULL }
  5483. };
  5484. int Jim_clockInit(Jim_Interp *interp)
  5485. {
  5486. Jim_PackageProvideCheck(interp, "clock");
  5487. Jim_CreateCommand(interp, "clock", Jim_SubCmdProc, (void *)clock_command_table, NULL);
  5488. return JIM_OK;
  5489. }
  5490. #include <limits.h>
  5491. #include <stdlib.h>
  5492. #include <string.h>
  5493. #include <stdio.h>
  5494. #include <errno.h>
  5495. static int array_cmd_exists(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  5496. {
  5497. Jim_Obj *dictObj = Jim_GetVariable(interp, argv[0], JIM_UNSHARED);
  5498. Jim_SetResultInt(interp, dictObj && Jim_DictSize(interp, dictObj) != -1);
  5499. return JIM_OK;
  5500. }
  5501. static int array_cmd_get(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  5502. {
  5503. Jim_Obj *objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
  5504. Jim_Obj *patternObj;
  5505. if (!objPtr) {
  5506. return JIM_OK;
  5507. }
  5508. patternObj = (argc == 1) ? NULL : argv[1];
  5509. if (patternObj == NULL || Jim_CompareStringImmediate(interp, patternObj, "*")) {
  5510. if (Jim_IsList(objPtr) && Jim_ListLength(interp, objPtr) % 2 == 0) {
  5511. Jim_SetResult(interp, objPtr);
  5512. return JIM_OK;
  5513. }
  5514. }
  5515. return Jim_DictMatchTypes(interp, objPtr, patternObj, JIM_DICTMATCH_KEYS, JIM_DICTMATCH_KEYS | JIM_DICTMATCH_VALUES);
  5516. }
  5517. static int array_cmd_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  5518. {
  5519. Jim_Obj *objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
  5520. if (!objPtr) {
  5521. return JIM_OK;
  5522. }
  5523. return Jim_DictMatchTypes(interp, objPtr, argc == 1 ? NULL : argv[1], JIM_DICTMATCH_KEYS, JIM_DICTMATCH_KEYS);
  5524. }
  5525. static int array_cmd_unset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  5526. {
  5527. int i;
  5528. int len;
  5529. Jim_Obj *resultObj;
  5530. Jim_Obj *objPtr;
  5531. Jim_Obj **dictValuesObj;
  5532. if (argc == 1 || Jim_CompareStringImmediate(interp, argv[1], "*")) {
  5533. Jim_UnsetVariable(interp, argv[0], JIM_NONE);
  5534. return JIM_OK;
  5535. }
  5536. objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
  5537. if (objPtr == NULL) {
  5538. return JIM_OK;
  5539. }
  5540. dictValuesObj = Jim_DictPairs(interp, objPtr, &len);
  5541. if (dictValuesObj == NULL) {
  5542. Jim_SetResultString(interp, "", -1);
  5543. return JIM_OK;
  5544. }
  5545. resultObj = Jim_NewDictObj(interp, NULL, 0);
  5546. for (i = 0; i < len; i += 2) {
  5547. if (!Jim_StringMatchObj(interp, argv[1], dictValuesObj[i], 0)) {
  5548. Jim_DictAddElement(interp, resultObj, dictValuesObj[i], dictValuesObj[i + 1]);
  5549. }
  5550. }
  5551. Jim_SetVariable(interp, argv[0], resultObj);
  5552. return JIM_OK;
  5553. }
  5554. static int array_cmd_size(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  5555. {
  5556. Jim_Obj *objPtr;
  5557. int len = 0;
  5558. objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
  5559. if (objPtr) {
  5560. len = Jim_DictSize(interp, objPtr);
  5561. if (len < 0) {
  5562. Jim_SetResultInt(interp, 0);
  5563. return JIM_OK;
  5564. }
  5565. }
  5566. Jim_SetResultInt(interp, len);
  5567. return JIM_OK;
  5568. }
  5569. static int array_cmd_stat(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  5570. {
  5571. Jim_Obj *objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
  5572. if (objPtr) {
  5573. return Jim_DictInfo(interp, objPtr);
  5574. }
  5575. Jim_SetResultFormatted(interp, "\"%#s\" isn't an array", argv[0], NULL);
  5576. return JIM_ERR;
  5577. }
  5578. static int array_cmd_set(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  5579. {
  5580. int i;
  5581. int len;
  5582. Jim_Obj *listObj = argv[1];
  5583. Jim_Obj *dictObj;
  5584. len = Jim_ListLength(interp, listObj);
  5585. if (len % 2) {
  5586. Jim_SetResultString(interp, "list must have an even number of elements", -1);
  5587. return JIM_ERR;
  5588. }
  5589. dictObj = Jim_GetVariable(interp, argv[0], JIM_UNSHARED);
  5590. if (!dictObj) {
  5591. return Jim_SetVariable(interp, argv[0], listObj);
  5592. }
  5593. else if (Jim_DictSize(interp, dictObj) < 0) {
  5594. return JIM_ERR;
  5595. }
  5596. if (Jim_IsShared(dictObj)) {
  5597. dictObj = Jim_DuplicateObj(interp, dictObj);
  5598. }
  5599. for (i = 0; i < len; i += 2) {
  5600. Jim_Obj *nameObj;
  5601. Jim_Obj *valueObj;
  5602. Jim_ListIndex(interp, listObj, i, &nameObj, JIM_NONE);
  5603. Jim_ListIndex(interp, listObj, i + 1, &valueObj, JIM_NONE);
  5604. Jim_DictAddElement(interp, dictObj, nameObj, valueObj);
  5605. }
  5606. return Jim_SetVariable(interp, argv[0], dictObj);
  5607. }
  5608. static const jim_subcmd_type array_command_table[] = {
  5609. { "exists",
  5610. "arrayName",
  5611. array_cmd_exists,
  5612. 1,
  5613. 1,
  5614. },
  5615. { "get",
  5616. "arrayName ?pattern?",
  5617. array_cmd_get,
  5618. 1,
  5619. 2,
  5620. },
  5621. { "names",
  5622. "arrayName ?pattern?",
  5623. array_cmd_names,
  5624. 1,
  5625. 2,
  5626. },
  5627. { "set",
  5628. "arrayName list",
  5629. array_cmd_set,
  5630. 2,
  5631. 2,
  5632. },
  5633. { "size",
  5634. "arrayName",
  5635. array_cmd_size,
  5636. 1,
  5637. 1,
  5638. },
  5639. { "stat",
  5640. "arrayName",
  5641. array_cmd_stat,
  5642. 1,
  5643. 1,
  5644. },
  5645. { "unset",
  5646. "arrayName ?pattern?",
  5647. array_cmd_unset,
  5648. 1,
  5649. 2,
  5650. },
  5651. { NULL
  5652. }
  5653. };
  5654. int Jim_arrayInit(Jim_Interp *interp)
  5655. {
  5656. Jim_PackageProvideCheck(interp, "array");
  5657. Jim_CreateCommand(interp, "array", Jim_SubCmdProc, (void *)array_command_table, NULL);
  5658. return JIM_OK;
  5659. }
  5660. int Jim_InitStaticExtensions(Jim_Interp *interp)
  5661. {
  5662. extern int Jim_bootstrapInit(Jim_Interp *);
  5663. extern int Jim_aioInit(Jim_Interp *);
  5664. extern int Jim_readdirInit(Jim_Interp *);
  5665. extern int Jim_regexpInit(Jim_Interp *);
  5666. extern int Jim_fileInit(Jim_Interp *);
  5667. extern int Jim_globInit(Jim_Interp *);
  5668. extern int Jim_execInit(Jim_Interp *);
  5669. extern int Jim_clockInit(Jim_Interp *);
  5670. extern int Jim_arrayInit(Jim_Interp *);
  5671. extern int Jim_stdlibInit(Jim_Interp *);
  5672. extern int Jim_tclcompatInit(Jim_Interp *);
  5673. Jim_bootstrapInit(interp);
  5674. Jim_aioInit(interp);
  5675. Jim_readdirInit(interp);
  5676. Jim_regexpInit(interp);
  5677. Jim_fileInit(interp);
  5678. Jim_globInit(interp);
  5679. Jim_execInit(interp);
  5680. Jim_clockInit(interp);
  5681. Jim_arrayInit(interp);
  5682. Jim_stdlibInit(interp);
  5683. Jim_tclcompatInit(interp);
  5684. return JIM_OK;
  5685. }
  5686. #ifndef JIM_TINY
  5687. #define JIM_OPTIMIZATION
  5688. #endif
  5689. #include <stdio.h>
  5690. #include <stdlib.h>
  5691. #include <string.h>
  5692. #include <stdarg.h>
  5693. #include <ctype.h>
  5694. #include <limits.h>
  5695. #include <assert.h>
  5696. #include <errno.h>
  5697. #include <time.h>
  5698. #include <setjmp.h>
  5699. #ifdef HAVE_SYS_TIME_H
  5700. #include <sys/time.h>
  5701. #endif
  5702. #ifdef HAVE_EXECINFO_H
  5703. #include <execinfo.h>
  5704. #endif
  5705. #ifdef HAVE_CRT_EXTERNS_H
  5706. #include <crt_externs.h>
  5707. #endif
  5708. #include <math.h>
  5709. #ifndef TCL_LIBRARY
  5710. #define TCL_LIBRARY "."
  5711. #endif
  5712. #ifndef TCL_PLATFORM_OS
  5713. #define TCL_PLATFORM_OS "unknown"
  5714. #endif
  5715. #ifndef TCL_PLATFORM_PLATFORM
  5716. #define TCL_PLATFORM_PLATFORM "unknown"
  5717. #endif
  5718. #ifndef TCL_PLATFORM_PATH_SEPARATOR
  5719. #define TCL_PLATFORM_PATH_SEPARATOR ":"
  5720. #endif
  5721. #ifdef JIM_MAINTAINER
  5722. #define JIM_DEBUG_COMMAND
  5723. #define JIM_DEBUG_PANIC
  5724. #endif
  5725. #define JIM_INTEGER_SPACE 24
  5726. #if defined(DEBUG_SHOW_SCRIPT) || defined(DEBUG_SHOW_SCRIPT_TOKENS) || defined(JIM_DEBUG_COMMAND) || defined(DEBUG_SHOW_SUBST)
  5727. static const char *jim_tt_name(int type);
  5728. #endif
  5729. #ifdef JIM_DEBUG_PANIC
  5730. static void JimPanicDump(int fail_condition, const char *fmt, ...);
  5731. #define JimPanic(X) JimPanicDump X
  5732. #else
  5733. #define JimPanic(X)
  5734. #endif
  5735. #ifdef JIM_OPTIMIZATION
  5736. static int JimIsWide(Jim_Obj *objPtr);
  5737. #define JIM_IF_OPTIM(X) X
  5738. #else
  5739. #define JIM_IF_OPTIM(X)
  5740. #endif
  5741. static char JimEmptyStringRep[] = "";
  5742. static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf, int action);
  5743. static int ListSetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int listindex, Jim_Obj *newObjPtr,
  5744. int flags);
  5745. static int Jim_ListIndices(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *const *indexv, int indexc,
  5746. Jim_Obj **resultObj, int flags);
  5747. static int JimDeleteLocalProcs(Jim_Interp *interp, Jim_Stack *localCommands);
  5748. static Jim_Obj *JimExpandDictSugar(Jim_Interp *interp, Jim_Obj *objPtr);
  5749. static void SetDictSubstFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
  5750. static void JimSetFailedEnumResult(Jim_Interp *interp, const char *arg, const char *badtype,
  5751. const char *prefix, const char *const *tablePtr, const char *name);
  5752. static int JimCallProcedure(Jim_Interp *interp, Jim_Cmd *cmd, int argc, Jim_Obj *const *argv);
  5753. static int JimGetWideNoErr(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr);
  5754. static int JimSign(jim_wide w);
  5755. static void JimPrngSeed(Jim_Interp *interp, unsigned char *seed, int seedLen);
  5756. static void JimRandomBytes(Jim_Interp *interp, void *dest, unsigned int len);
  5757. static int JimSetNewVariable(Jim_HashTable *ht, Jim_Obj *nameObjPtr, Jim_VarVal *vv);
  5758. static Jim_VarVal *JimFindVariable(Jim_HashTable *ht, Jim_Obj *nameObjPtr);
  5759. static int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
  5760. #define JIM_DICT_SUGAR 100
  5761. #define JimWideValue(objPtr) (objPtr)->internalRep.wideValue
  5762. #define JimObjTypeName(O) ((O)->typePtr ? (O)->typePtr->name : "none")
  5763. static int utf8_tounicode_case(const char *s, int *uc, int upper)
  5764. {
  5765. int l = utf8_tounicode(s, uc);
  5766. if (upper) {
  5767. *uc = utf8_upper(*uc);
  5768. }
  5769. return l;
  5770. }
  5771. static Jim_Obj *JimPushInterpObjImpl(Jim_Obj **iop, Jim_Obj *no)
  5772. {
  5773. Jim_Obj *io = *iop;
  5774. Jim_IncrRefCount(no);
  5775. *iop = no;
  5776. return io;
  5777. }
  5778. #define JimPushInterpObj(IO, NO) JimPushInterpObjImpl(&(IO), NO)
  5779. #define JimPopInterpObj(I, IO, SO) do { Jim_DecrRefCount(I, IO); IO = SO; } while (0)
  5780. #define JIM_CHARSET_SCAN 2
  5781. #define JIM_CHARSET_GLOB 0
  5782. static const char *JimCharsetMatch(const char *pattern, int plen, int c, int flags)
  5783. {
  5784. int not = 0;
  5785. int pchar;
  5786. int match = 0;
  5787. int nocase = 0;
  5788. int n;
  5789. if (flags & JIM_NOCASE) {
  5790. nocase++;
  5791. c = utf8_upper(c);
  5792. }
  5793. if (flags & JIM_CHARSET_SCAN) {
  5794. if (*pattern == '^') {
  5795. not++;
  5796. pattern++;
  5797. plen--;
  5798. }
  5799. if (*pattern == ']') {
  5800. goto first;
  5801. }
  5802. }
  5803. while (plen && *pattern != ']') {
  5804. if (pattern[0] == '\\') {
  5805. first:
  5806. n = utf8_tounicode_case(pattern, &pchar, nocase);
  5807. pattern += n;
  5808. plen -= n;
  5809. }
  5810. else {
  5811. int start;
  5812. int end;
  5813. n = utf8_tounicode_case(pattern, &start, nocase);
  5814. pattern += n;
  5815. plen -= n;
  5816. if (pattern[0] == '-' && plen > 1) {
  5817. n = 1 + utf8_tounicode_case(pattern + 1, &end, nocase);
  5818. pattern += n;
  5819. plen -= n;
  5820. if ((c >= start && c <= end) || (c >= end && c <= start)) {
  5821. match = 1;
  5822. }
  5823. continue;
  5824. }
  5825. pchar = start;
  5826. }
  5827. if (pchar == c) {
  5828. match = 1;
  5829. }
  5830. }
  5831. if (not) {
  5832. match = !match;
  5833. }
  5834. return match ? pattern : NULL;
  5835. }
  5836. static int JimGlobMatch(const char *pattern, int plen, const char *string, int slen, int nocase)
  5837. {
  5838. int c;
  5839. int pchar;
  5840. int n;
  5841. const char *p;
  5842. while (plen) {
  5843. switch (pattern[0]) {
  5844. case '*':
  5845. while (pattern[1] == '*' && plen) {
  5846. pattern++;
  5847. plen--;
  5848. }
  5849. pattern++;
  5850. plen--;
  5851. if (!plen) {
  5852. return 1;
  5853. }
  5854. while (slen) {
  5855. if (JimGlobMatch(pattern, plen, string, slen, nocase))
  5856. return 1;
  5857. n = utf8_tounicode(string, &c);
  5858. string += n;
  5859. slen -= n;
  5860. }
  5861. return 0;
  5862. case '?':
  5863. n = utf8_tounicode(string, &c);
  5864. string += n;
  5865. slen -= n;
  5866. break;
  5867. case '[': {
  5868. n = utf8_tounicode(string, &c);
  5869. string += n;
  5870. slen -= n;
  5871. p = JimCharsetMatch(pattern + 1, plen - 1, c, nocase ? JIM_NOCASE : 0);
  5872. if (!p) {
  5873. return 0;
  5874. }
  5875. plen -= p - pattern;
  5876. pattern = p;
  5877. if (!plen) {
  5878. continue;
  5879. }
  5880. break;
  5881. }
  5882. case '\\':
  5883. if (pattern[1]) {
  5884. pattern++;
  5885. plen--;
  5886. }
  5887. default:
  5888. n = utf8_tounicode_case(string, &c, nocase);
  5889. string += n;
  5890. slen -= n;
  5891. utf8_tounicode_case(pattern, &pchar, nocase);
  5892. if (pchar != c) {
  5893. return 0;
  5894. }
  5895. break;
  5896. }
  5897. n = utf8_tounicode_case(pattern, &pchar, nocase);
  5898. pattern += n;
  5899. plen -= n;
  5900. if (!slen) {
  5901. while (*pattern == '*' && plen) {
  5902. pattern++;
  5903. plen--;
  5904. }
  5905. break;
  5906. }
  5907. }
  5908. if (!plen && !slen) {
  5909. return 1;
  5910. }
  5911. return 0;
  5912. }
  5913. static int JimStringCompareUtf8(const char *s1, int l1, const char *s2, int l2, int nocase)
  5914. {
  5915. int minlen = l1;
  5916. if (l2 < l1) {
  5917. minlen = l2;
  5918. }
  5919. while (minlen) {
  5920. int c1, c2;
  5921. s1 += utf8_tounicode_case(s1, &c1, nocase);
  5922. s2 += utf8_tounicode_case(s2, &c2, nocase);
  5923. if (c1 != c2) {
  5924. return JimSign(c1 - c2);
  5925. }
  5926. minlen--;
  5927. }
  5928. if (l1 < l2) {
  5929. return -1;
  5930. }
  5931. if (l1 > l2) {
  5932. return 1;
  5933. }
  5934. return 0;
  5935. }
  5936. static int JimStringFirst(const char *s1, int l1, const char *s2, int l2, int idx)
  5937. {
  5938. int i;
  5939. int l1bytelen;
  5940. if (!l1 || !l2 || l1 > l2) {
  5941. return -1;
  5942. }
  5943. if (idx < 0)
  5944. idx = 0;
  5945. s2 += utf8_index(s2, idx);
  5946. l1bytelen = utf8_index(s1, l1);
  5947. for (i = idx; i <= l2 - l1; i++) {
  5948. int c;
  5949. if (memcmp(s2, s1, l1bytelen) == 0) {
  5950. return i;
  5951. }
  5952. s2 += utf8_tounicode(s2, &c);
  5953. }
  5954. return -1;
  5955. }
  5956. static int JimStringLast(const char *s1, int l1, const char *s2, int l2)
  5957. {
  5958. const char *p;
  5959. if (!l1 || !l2 || l1 > l2)
  5960. return -1;
  5961. for (p = s2 + l2 - 1; p != s2 - 1; p--) {
  5962. if (*p == *s1 && memcmp(s1, p, l1) == 0) {
  5963. return p - s2;
  5964. }
  5965. }
  5966. return -1;
  5967. }
  5968. #ifdef JIM_UTF8
  5969. static int JimStringLastUtf8(const char *s1, int l1, const char *s2, int l2)
  5970. {
  5971. int n = JimStringLast(s1, utf8_index(s1, l1), s2, utf8_index(s2, l2));
  5972. if (n > 0) {
  5973. n = utf8_strlen(s2, n);
  5974. }
  5975. return n;
  5976. }
  5977. #endif
  5978. static int JimCheckConversion(const char *str, const char *endptr)
  5979. {
  5980. if (str[0] == '\0' || str == endptr) {
  5981. return JIM_ERR;
  5982. }
  5983. if (endptr[0] != '\0') {
  5984. while (*endptr) {
  5985. if (!isspace(UCHAR(*endptr))) {
  5986. return JIM_ERR;
  5987. }
  5988. endptr++;
  5989. }
  5990. }
  5991. return JIM_OK;
  5992. }
  5993. static int JimNumberBase(const char *str, int *base, int *sign)
  5994. {
  5995. int i = 0;
  5996. *base = 0;
  5997. while (isspace(UCHAR(str[i]))) {
  5998. i++;
  5999. }
  6000. if (str[i] == '-') {
  6001. *sign = -1;
  6002. i++;
  6003. }
  6004. else {
  6005. if (str[i] == '+') {
  6006. i++;
  6007. }
  6008. *sign = 1;
  6009. }
  6010. if (str[i] != '0') {
  6011. return 0;
  6012. }
  6013. switch (str[i + 1]) {
  6014. case 'x': case 'X': *base = 16; break;
  6015. case 'o': case 'O': *base = 8; break;
  6016. case 'b': case 'B': *base = 2; break;
  6017. case 'd': case 'D': *base = 10; break;
  6018. default: return 0;
  6019. }
  6020. i += 2;
  6021. if (str[i] != '-' && str[i] != '+' && !isspace(UCHAR(str[i]))) {
  6022. return i;
  6023. }
  6024. *base = 0;
  6025. return 0;
  6026. }
  6027. static long jim_strtol(const char *str, char **endptr)
  6028. {
  6029. int sign;
  6030. int base;
  6031. int i = JimNumberBase(str, &base, &sign);
  6032. if (base != 0) {
  6033. long value = strtol(str + i, endptr, base);
  6034. if (endptr == NULL || *endptr != str + i) {
  6035. return value * sign;
  6036. }
  6037. }
  6038. return strtol(str, endptr, 10);
  6039. }
  6040. static jim_wide jim_strtoull(const char *str, char **endptr)
  6041. {
  6042. #ifdef HAVE_LONG_LONG
  6043. int sign;
  6044. int base;
  6045. int i = JimNumberBase(str, &base, &sign);
  6046. if (base != 0) {
  6047. jim_wide value = strtoull(str + i, endptr, base);
  6048. if (endptr == NULL || *endptr != str + i) {
  6049. return value * sign;
  6050. }
  6051. }
  6052. return strtoull(str, endptr, 10);
  6053. #else
  6054. return (unsigned long)jim_strtol(str, endptr);
  6055. #endif
  6056. }
  6057. int Jim_StringToWide(const char *str, jim_wide * widePtr, int base)
  6058. {
  6059. char *endptr;
  6060. if (base) {
  6061. *widePtr = strtoull(str, &endptr, base);
  6062. }
  6063. else {
  6064. *widePtr = jim_strtoull(str, &endptr);
  6065. }
  6066. return JimCheckConversion(str, endptr);
  6067. }
  6068. int Jim_StringToDouble(const char *str, double *doublePtr)
  6069. {
  6070. char *endptr;
  6071. errno = 0;
  6072. *doublePtr = strtod(str, &endptr);
  6073. return JimCheckConversion(str, endptr);
  6074. }
  6075. static jim_wide JimPowWide(jim_wide b, jim_wide e)
  6076. {
  6077. jim_wide res = 1;
  6078. if (b == 1) {
  6079. return 1;
  6080. }
  6081. if (e < 0) {
  6082. if (b != -1) {
  6083. return 0;
  6084. }
  6085. e = -e;
  6086. }
  6087. while (e)
  6088. {
  6089. if (e & 1) {
  6090. res *= b;
  6091. }
  6092. e >>= 1;
  6093. b *= b;
  6094. }
  6095. return res;
  6096. }
  6097. #ifdef JIM_DEBUG_PANIC
  6098. static void JimPanicDump(int condition, const char *fmt, ...)
  6099. {
  6100. va_list ap;
  6101. if (!condition) {
  6102. return;
  6103. }
  6104. va_start(ap, fmt);
  6105. fprintf(stderr, "\nJIM INTERPRETER PANIC: ");
  6106. vfprintf(stderr, fmt, ap);
  6107. fprintf(stderr, "\n\n");
  6108. va_end(ap);
  6109. #if defined(HAVE_BACKTRACE)
  6110. {
  6111. void *array[40];
  6112. int size, i;
  6113. char **strings;
  6114. size = backtrace(array, 40);
  6115. strings = backtrace_symbols(array, size);
  6116. for (i = 0; i < size; i++)
  6117. fprintf(stderr, "[backtrace] %s\n", strings[i]);
  6118. fprintf(stderr, "[backtrace] Include the above lines and the output\n");
  6119. fprintf(stderr, "[backtrace] of 'nm <executable>' in the bug report.\n");
  6120. }
  6121. #endif
  6122. exit(1);
  6123. }
  6124. #endif
  6125. void *JimDefaultAllocator(void *ptr, size_t size)
  6126. {
  6127. if (size == 0) {
  6128. free(ptr);
  6129. return NULL;
  6130. }
  6131. else if (ptr) {
  6132. return realloc(ptr, size);
  6133. }
  6134. else {
  6135. return malloc(size);
  6136. }
  6137. }
  6138. void *(*Jim_Allocator)(void *ptr, size_t size) = JimDefaultAllocator;
  6139. char *Jim_StrDup(const char *s)
  6140. {
  6141. return Jim_StrDupLen(s, strlen(s));
  6142. }
  6143. char *Jim_StrDupLen(const char *s, int l)
  6144. {
  6145. char *copy = Jim_Alloc(l + 1);
  6146. memcpy(copy, s, l);
  6147. copy[l] = 0;
  6148. return copy;
  6149. }
  6150. jim_wide Jim_GetTimeUsec(unsigned type)
  6151. {
  6152. long long now;
  6153. struct timeval tv;
  6154. #if defined(HAVE_CLOCK_GETTIME)
  6155. struct timespec ts;
  6156. if (clock_gettime(type, &ts) == 0) {
  6157. now = ts.tv_sec * 1000000LL + ts.tv_nsec / 1000;
  6158. }
  6159. else
  6160. #endif
  6161. {
  6162. gettimeofday(&tv, NULL);
  6163. now = tv.tv_sec * 1000000LL + tv.tv_usec;
  6164. }
  6165. return now;
  6166. }
  6167. static void JimExpandHashTableIfNeeded(Jim_HashTable *ht);
  6168. static unsigned int JimHashTableNextPower(unsigned int size);
  6169. static Jim_HashEntry *JimInsertHashEntry(Jim_HashTable *ht, const void *key, int replace);
  6170. unsigned int Jim_IntHashFunction(unsigned int key)
  6171. {
  6172. key += ~(key << 15);
  6173. key ^= (key >> 10);
  6174. key += (key << 3);
  6175. key ^= (key >> 6);
  6176. key += ~(key << 11);
  6177. key ^= (key >> 16);
  6178. return key;
  6179. }
  6180. unsigned int Jim_GenHashFunction(const unsigned char *string, int length)
  6181. {
  6182. unsigned result = 0;
  6183. string += length;
  6184. while (length--) {
  6185. result += (result << 3) + (unsigned char)(*--string);
  6186. }
  6187. return result;
  6188. }
  6189. static void JimResetHashTable(Jim_HashTable *ht)
  6190. {
  6191. ht->table = NULL;
  6192. ht->size = 0;
  6193. ht->sizemask = 0;
  6194. ht->used = 0;
  6195. ht->collisions = 0;
  6196. #ifdef JIM_RANDOMISE_HASH
  6197. ht->uniq = (rand() ^ time(NULL) ^ clock());
  6198. #else
  6199. ht->uniq = 0;
  6200. #endif
  6201. }
  6202. static void JimInitHashTableIterator(Jim_HashTable *ht, Jim_HashTableIterator *iter)
  6203. {
  6204. iter->ht = ht;
  6205. iter->index = -1;
  6206. iter->entry = NULL;
  6207. iter->nextEntry = NULL;
  6208. }
  6209. int Jim_InitHashTable(Jim_HashTable *ht, const Jim_HashTableType *type, void *privDataPtr)
  6210. {
  6211. JimResetHashTable(ht);
  6212. ht->type = type;
  6213. ht->privdata = privDataPtr;
  6214. return JIM_OK;
  6215. }
  6216. void Jim_ExpandHashTable(Jim_HashTable *ht, unsigned int size)
  6217. {
  6218. Jim_HashTable n;
  6219. unsigned int realsize = JimHashTableNextPower(size), i;
  6220. if (size <= ht->used)
  6221. return;
  6222. Jim_InitHashTable(&n, ht->type, ht->privdata);
  6223. n.size = realsize;
  6224. n.sizemask = realsize - 1;
  6225. n.table = Jim_Alloc(realsize * sizeof(Jim_HashEntry *));
  6226. n.uniq = ht->uniq;
  6227. memset(n.table, 0, realsize * sizeof(Jim_HashEntry *));
  6228. n.used = ht->used;
  6229. for (i = 0; ht->used > 0; i++) {
  6230. Jim_HashEntry *he, *nextHe;
  6231. if (ht->table[i] == NULL)
  6232. continue;
  6233. he = ht->table[i];
  6234. while (he) {
  6235. unsigned int h;
  6236. nextHe = he->next;
  6237. h = Jim_HashKey(ht, he->key) & n.sizemask;
  6238. he->next = n.table[h];
  6239. n.table[h] = he;
  6240. ht->used--;
  6241. he = nextHe;
  6242. }
  6243. }
  6244. assert(ht->used == 0);
  6245. Jim_Free(ht->table);
  6246. *ht = n;
  6247. }
  6248. int Jim_AddHashEntry(Jim_HashTable *ht, const void *key, void *val)
  6249. {
  6250. Jim_HashEntry *entry = JimInsertHashEntry(ht, key, 0);;
  6251. if (entry == NULL)
  6252. return JIM_ERR;
  6253. Jim_SetHashKey(ht, entry, key);
  6254. Jim_SetHashVal(ht, entry, val);
  6255. return JIM_OK;
  6256. }
  6257. int Jim_ReplaceHashEntry(Jim_HashTable *ht, const void *key, void *val)
  6258. {
  6259. int existed;
  6260. Jim_HashEntry *entry;
  6261. entry = JimInsertHashEntry(ht, key, 1);
  6262. if (entry->key) {
  6263. if (ht->type->valDestructor && ht->type->valDup) {
  6264. void *newval = ht->type->valDup(ht->privdata, val);
  6265. ht->type->valDestructor(ht->privdata, entry->u.val);
  6266. entry->u.val = newval;
  6267. }
  6268. else {
  6269. Jim_FreeEntryVal(ht, entry);
  6270. Jim_SetHashVal(ht, entry, val);
  6271. }
  6272. existed = 1;
  6273. }
  6274. else {
  6275. Jim_SetHashKey(ht, entry, key);
  6276. Jim_SetHashVal(ht, entry, val);
  6277. existed = 0;
  6278. }
  6279. return existed;
  6280. }
  6281. int Jim_DeleteHashEntry(Jim_HashTable *ht, const void *key)
  6282. {
  6283. if (ht->used) {
  6284. unsigned int h = Jim_HashKey(ht, key) & ht->sizemask;
  6285. Jim_HashEntry *prevHe = NULL;
  6286. Jim_HashEntry *he = ht->table[h];
  6287. while (he) {
  6288. if (Jim_CompareHashKeys(ht, key, he->key)) {
  6289. if (prevHe)
  6290. prevHe->next = he->next;
  6291. else
  6292. ht->table[h] = he->next;
  6293. ht->used--;
  6294. Jim_FreeEntryKey(ht, he);
  6295. Jim_FreeEntryVal(ht, he);
  6296. Jim_Free(he);
  6297. return JIM_OK;
  6298. }
  6299. prevHe = he;
  6300. he = he->next;
  6301. }
  6302. }
  6303. return JIM_ERR;
  6304. }
  6305. void Jim_ClearHashTable(Jim_HashTable *ht)
  6306. {
  6307. unsigned int i;
  6308. for (i = 0; ht->used > 0; i++) {
  6309. Jim_HashEntry *he, *nextHe;
  6310. he = ht->table[i];
  6311. while (he) {
  6312. nextHe = he->next;
  6313. Jim_FreeEntryKey(ht, he);
  6314. Jim_FreeEntryVal(ht, he);
  6315. Jim_Free(he);
  6316. ht->used--;
  6317. he = nextHe;
  6318. }
  6319. ht->table[i] = NULL;
  6320. }
  6321. }
  6322. int Jim_FreeHashTable(Jim_HashTable *ht)
  6323. {
  6324. Jim_ClearHashTable(ht);
  6325. Jim_Free(ht->table);
  6326. JimResetHashTable(ht);
  6327. return JIM_OK;
  6328. }
  6329. Jim_HashEntry *Jim_FindHashEntry(Jim_HashTable *ht, const void *key)
  6330. {
  6331. Jim_HashEntry *he;
  6332. unsigned int h;
  6333. if (ht->used == 0)
  6334. return NULL;
  6335. h = Jim_HashKey(ht, key) & ht->sizemask;
  6336. he = ht->table[h];
  6337. while (he) {
  6338. if (Jim_CompareHashKeys(ht, key, he->key))
  6339. return he;
  6340. he = he->next;
  6341. }
  6342. return NULL;
  6343. }
  6344. Jim_HashTableIterator *Jim_GetHashTableIterator(Jim_HashTable *ht)
  6345. {
  6346. Jim_HashTableIterator *iter = Jim_Alloc(sizeof(*iter));
  6347. JimInitHashTableIterator(ht, iter);
  6348. return iter;
  6349. }
  6350. Jim_HashEntry *Jim_NextHashEntry(Jim_HashTableIterator *iter)
  6351. {
  6352. while (1) {
  6353. if (iter->entry == NULL) {
  6354. iter->index++;
  6355. if (iter->index >= (signed)iter->ht->size)
  6356. break;
  6357. iter->entry = iter->ht->table[iter->index];
  6358. }
  6359. else {
  6360. iter->entry = iter->nextEntry;
  6361. }
  6362. if (iter->entry) {
  6363. iter->nextEntry = iter->entry->next;
  6364. return iter->entry;
  6365. }
  6366. }
  6367. return NULL;
  6368. }
  6369. static void JimExpandHashTableIfNeeded(Jim_HashTable *ht)
  6370. {
  6371. if (ht->size == 0)
  6372. Jim_ExpandHashTable(ht, JIM_HT_INITIAL_SIZE);
  6373. if (ht->size == ht->used)
  6374. Jim_ExpandHashTable(ht, ht->size * 2);
  6375. }
  6376. static unsigned int JimHashTableNextPower(unsigned int size)
  6377. {
  6378. unsigned int i = JIM_HT_INITIAL_SIZE;
  6379. if (size >= 2147483648U)
  6380. return 2147483648U;
  6381. while (1) {
  6382. if (i >= size)
  6383. return i;
  6384. i *= 2;
  6385. }
  6386. }
  6387. static Jim_HashEntry *JimInsertHashEntry(Jim_HashTable *ht, const void *key, int replace)
  6388. {
  6389. unsigned int h;
  6390. Jim_HashEntry *he;
  6391. JimExpandHashTableIfNeeded(ht);
  6392. h = Jim_HashKey(ht, key) & ht->sizemask;
  6393. he = ht->table[h];
  6394. while (he) {
  6395. if (Jim_CompareHashKeys(ht, key, he->key))
  6396. return replace ? he : NULL;
  6397. he = he->next;
  6398. }
  6399. he = Jim_Alloc(sizeof(*he));
  6400. he->next = ht->table[h];
  6401. ht->table[h] = he;
  6402. ht->used++;
  6403. he->key = NULL;
  6404. return he;
  6405. }
  6406. static unsigned int JimStringCopyHTHashFunction(const void *key)
  6407. {
  6408. return Jim_GenHashFunction(key, strlen(key));
  6409. }
  6410. static void *JimStringCopyHTDup(void *privdata, const void *key)
  6411. {
  6412. return Jim_StrDup(key);
  6413. }
  6414. static int JimStringCopyHTKeyCompare(void *privdata, const void *key1, const void *key2)
  6415. {
  6416. return strcmp(key1, key2) == 0;
  6417. }
  6418. static void JimStringCopyHTKeyDestructor(void *privdata, void *key)
  6419. {
  6420. Jim_Free(key);
  6421. }
  6422. static const Jim_HashTableType JimPackageHashTableType = {
  6423. JimStringCopyHTHashFunction,
  6424. JimStringCopyHTDup,
  6425. NULL,
  6426. JimStringCopyHTKeyCompare,
  6427. JimStringCopyHTKeyDestructor,
  6428. NULL
  6429. };
  6430. typedef struct AssocDataValue
  6431. {
  6432. Jim_InterpDeleteProc *delProc;
  6433. void *data;
  6434. } AssocDataValue;
  6435. static void JimAssocDataHashTableValueDestructor(void *privdata, void *data)
  6436. {
  6437. AssocDataValue *assocPtr = (AssocDataValue *) data;
  6438. if (assocPtr->delProc != NULL)
  6439. assocPtr->delProc((Jim_Interp *)privdata, assocPtr->data);
  6440. Jim_Free(data);
  6441. }
  6442. static const Jim_HashTableType JimAssocDataHashTableType = {
  6443. JimStringCopyHTHashFunction,
  6444. JimStringCopyHTDup,
  6445. NULL,
  6446. JimStringCopyHTKeyCompare,
  6447. JimStringCopyHTKeyDestructor,
  6448. JimAssocDataHashTableValueDestructor
  6449. };
  6450. void Jim_InitStack(Jim_Stack *stack)
  6451. {
  6452. stack->len = 0;
  6453. stack->maxlen = 0;
  6454. stack->vector = NULL;
  6455. }
  6456. void Jim_FreeStack(Jim_Stack *stack)
  6457. {
  6458. Jim_Free(stack->vector);
  6459. }
  6460. int Jim_StackLen(Jim_Stack *stack)
  6461. {
  6462. return stack->len;
  6463. }
  6464. void Jim_StackPush(Jim_Stack *stack, void *element)
  6465. {
  6466. int neededLen = stack->len + 1;
  6467. if (neededLen > stack->maxlen) {
  6468. stack->maxlen = neededLen < 20 ? 20 : neededLen * 2;
  6469. stack->vector = Jim_Realloc(stack->vector, sizeof(void *) * stack->maxlen);
  6470. }
  6471. stack->vector[stack->len] = element;
  6472. stack->len++;
  6473. }
  6474. void *Jim_StackPop(Jim_Stack *stack)
  6475. {
  6476. if (stack->len == 0)
  6477. return NULL;
  6478. stack->len--;
  6479. return stack->vector[stack->len];
  6480. }
  6481. void *Jim_StackPeek(Jim_Stack *stack)
  6482. {
  6483. if (stack->len == 0)
  6484. return NULL;
  6485. return stack->vector[stack->len - 1];
  6486. }
  6487. void Jim_FreeStackElements(Jim_Stack *stack, void (*freeFunc) (void *ptr))
  6488. {
  6489. int i;
  6490. for (i = 0; i < stack->len; i++)
  6491. freeFunc(stack->vector[i]);
  6492. }
  6493. #define JIM_TT_NONE 0
  6494. #define JIM_TT_STR 1
  6495. #define JIM_TT_ESC 2
  6496. #define JIM_TT_VAR 3
  6497. #define JIM_TT_DICTSUGAR 4
  6498. #define JIM_TT_CMD 5
  6499. #define JIM_TT_SEP 6
  6500. #define JIM_TT_EOL 7
  6501. #define JIM_TT_EOF 8
  6502. #define JIM_TT_LINE 9
  6503. #define JIM_TT_WORD 10
  6504. #define JIM_TT_SUBEXPR_START 11
  6505. #define JIM_TT_SUBEXPR_END 12
  6506. #define JIM_TT_SUBEXPR_COMMA 13
  6507. #define JIM_TT_EXPR_INT 14
  6508. #define JIM_TT_EXPR_DOUBLE 15
  6509. #define JIM_TT_EXPR_BOOLEAN 16
  6510. #define JIM_TT_EXPRSUGAR 17
  6511. #define JIM_TT_EXPR_OP 20
  6512. #define TOKEN_IS_SEP(type) (type >= JIM_TT_SEP && type <= JIM_TT_EOF)
  6513. #define TOKEN_IS_EXPR_START(type) (type == JIM_TT_NONE || type == JIM_TT_SUBEXPR_START || type == JIM_TT_SUBEXPR_COMMA)
  6514. #define TOKEN_IS_EXPR_OP(type) (type >= JIM_TT_EXPR_OP)
  6515. struct JimParseMissing {
  6516. int ch;
  6517. int line;
  6518. };
  6519. struct JimParserCtx
  6520. {
  6521. const char *p;
  6522. int len;
  6523. int linenr;
  6524. const char *tstart;
  6525. const char *tend;
  6526. int tline;
  6527. int tt;
  6528. int eof;
  6529. int inquote;
  6530. int comment;
  6531. struct JimParseMissing missing;
  6532. const char *errmsg;
  6533. };
  6534. static int JimParseScript(struct JimParserCtx *pc);
  6535. static int JimParseSep(struct JimParserCtx *pc);
  6536. static int JimParseEol(struct JimParserCtx *pc);
  6537. static int JimParseCmd(struct JimParserCtx *pc);
  6538. static int JimParseQuote(struct JimParserCtx *pc);
  6539. static int JimParseVar(struct JimParserCtx *pc);
  6540. static int JimParseBrace(struct JimParserCtx *pc);
  6541. static int JimParseStr(struct JimParserCtx *pc);
  6542. static int JimParseComment(struct JimParserCtx *pc);
  6543. static void JimParseSubCmd(struct JimParserCtx *pc);
  6544. static int JimParseSubQuote(struct JimParserCtx *pc);
  6545. static Jim_Obj *JimParserGetTokenObj(Jim_Interp *interp, struct JimParserCtx *pc);
  6546. static void JimParserInit(struct JimParserCtx *pc, const char *prg, int len, int linenr)
  6547. {
  6548. pc->p = prg;
  6549. pc->len = len;
  6550. pc->tstart = NULL;
  6551. pc->tend = NULL;
  6552. pc->tline = 0;
  6553. pc->tt = JIM_TT_NONE;
  6554. pc->eof = 0;
  6555. pc->inquote = 0;
  6556. pc->linenr = linenr;
  6557. pc->comment = 1;
  6558. pc->missing.ch = ' ';
  6559. pc->missing.line = linenr;
  6560. }
  6561. static int JimParseScript(struct JimParserCtx *pc)
  6562. {
  6563. while (1) {
  6564. if (!pc->len) {
  6565. pc->tstart = pc->p;
  6566. pc->tend = pc->p - 1;
  6567. pc->tline = pc->linenr;
  6568. pc->tt = JIM_TT_EOL;
  6569. if (pc->inquote) {
  6570. pc->missing.ch = '"';
  6571. }
  6572. pc->eof = 1;
  6573. return JIM_OK;
  6574. }
  6575. switch (*(pc->p)) {
  6576. case '\\':
  6577. if (*(pc->p + 1) == '\n' && !pc->inquote) {
  6578. return JimParseSep(pc);
  6579. }
  6580. pc->comment = 0;
  6581. return JimParseStr(pc);
  6582. case ' ':
  6583. case '\t':
  6584. case '\r':
  6585. case '\f':
  6586. if (!pc->inquote)
  6587. return JimParseSep(pc);
  6588. pc->comment = 0;
  6589. return JimParseStr(pc);
  6590. case '\n':
  6591. case ';':
  6592. pc->comment = 1;
  6593. if (!pc->inquote)
  6594. return JimParseEol(pc);
  6595. return JimParseStr(pc);
  6596. case '[':
  6597. pc->comment = 0;
  6598. return JimParseCmd(pc);
  6599. case '$':
  6600. pc->comment = 0;
  6601. if (JimParseVar(pc) == JIM_ERR) {
  6602. pc->tstart = pc->tend = pc->p++;
  6603. pc->len--;
  6604. pc->tt = JIM_TT_ESC;
  6605. }
  6606. return JIM_OK;
  6607. case '#':
  6608. if (pc->comment) {
  6609. JimParseComment(pc);
  6610. continue;
  6611. }
  6612. return JimParseStr(pc);
  6613. default:
  6614. pc->comment = 0;
  6615. return JimParseStr(pc);
  6616. }
  6617. return JIM_OK;
  6618. }
  6619. }
  6620. static int JimParseSep(struct JimParserCtx *pc)
  6621. {
  6622. pc->tstart = pc->p;
  6623. pc->tline = pc->linenr;
  6624. while (isspace(UCHAR(*pc->p)) || (*pc->p == '\\' && *(pc->p + 1) == '\n')) {
  6625. if (*pc->p == '\n') {
  6626. break;
  6627. }
  6628. if (*pc->p == '\\') {
  6629. pc->p++;
  6630. pc->len--;
  6631. pc->linenr++;
  6632. }
  6633. pc->p++;
  6634. pc->len--;
  6635. }
  6636. pc->tend = pc->p - 1;
  6637. pc->tt = JIM_TT_SEP;
  6638. return JIM_OK;
  6639. }
  6640. static int JimParseEol(struct JimParserCtx *pc)
  6641. {
  6642. pc->tstart = pc->p;
  6643. pc->tline = pc->linenr;
  6644. while (isspace(UCHAR(*pc->p)) || *pc->p == ';') {
  6645. if (*pc->p == '\n')
  6646. pc->linenr++;
  6647. pc->p++;
  6648. pc->len--;
  6649. }
  6650. pc->tend = pc->p - 1;
  6651. pc->tt = JIM_TT_EOL;
  6652. return JIM_OK;
  6653. }
  6654. static void JimParseSubBrace(struct JimParserCtx *pc)
  6655. {
  6656. int level = 1;
  6657. pc->p++;
  6658. pc->len--;
  6659. while (pc->len) {
  6660. switch (*pc->p) {
  6661. case '\\':
  6662. if (pc->len > 1) {
  6663. if (*++pc->p == '\n') {
  6664. pc->linenr++;
  6665. }
  6666. pc->len--;
  6667. }
  6668. break;
  6669. case '{':
  6670. level++;
  6671. break;
  6672. case '}':
  6673. if (--level == 0) {
  6674. pc->tend = pc->p - 1;
  6675. pc->p++;
  6676. pc->len--;
  6677. return;
  6678. }
  6679. break;
  6680. case '\n':
  6681. pc->linenr++;
  6682. break;
  6683. }
  6684. pc->p++;
  6685. pc->len--;
  6686. }
  6687. pc->missing.ch = '{';
  6688. pc->missing.line = pc->tline;
  6689. pc->tend = pc->p - 1;
  6690. }
  6691. static int JimParseSubQuote(struct JimParserCtx *pc)
  6692. {
  6693. int tt = JIM_TT_STR;
  6694. int line = pc->tline;
  6695. pc->p++;
  6696. pc->len--;
  6697. while (pc->len) {
  6698. switch (*pc->p) {
  6699. case '\\':
  6700. if (pc->len > 1) {
  6701. if (*++pc->p == '\n') {
  6702. pc->linenr++;
  6703. }
  6704. pc->len--;
  6705. tt = JIM_TT_ESC;
  6706. }
  6707. break;
  6708. case '"':
  6709. pc->tend = pc->p - 1;
  6710. pc->p++;
  6711. pc->len--;
  6712. return tt;
  6713. case '[':
  6714. JimParseSubCmd(pc);
  6715. tt = JIM_TT_ESC;
  6716. continue;
  6717. case '\n':
  6718. pc->linenr++;
  6719. break;
  6720. case '$':
  6721. tt = JIM_TT_ESC;
  6722. break;
  6723. }
  6724. pc->p++;
  6725. pc->len--;
  6726. }
  6727. pc->missing.ch = '"';
  6728. pc->missing.line = line;
  6729. pc->tend = pc->p - 1;
  6730. return tt;
  6731. }
  6732. static void JimParseSubCmd(struct JimParserCtx *pc)
  6733. {
  6734. int level = 1;
  6735. int startofword = 1;
  6736. int line = pc->tline;
  6737. pc->p++;
  6738. pc->len--;
  6739. while (pc->len) {
  6740. switch (*pc->p) {
  6741. case '\\':
  6742. if (pc->len > 1) {
  6743. if (*++pc->p == '\n') {
  6744. pc->linenr++;
  6745. }
  6746. pc->len--;
  6747. }
  6748. break;
  6749. case '[':
  6750. level++;
  6751. break;
  6752. case ']':
  6753. if (--level == 0) {
  6754. pc->tend = pc->p - 1;
  6755. pc->p++;
  6756. pc->len--;
  6757. return;
  6758. }
  6759. break;
  6760. case '"':
  6761. if (startofword) {
  6762. JimParseSubQuote(pc);
  6763. if (pc->missing.ch == '"') {
  6764. return;
  6765. }
  6766. continue;
  6767. }
  6768. break;
  6769. case '{':
  6770. JimParseSubBrace(pc);
  6771. startofword = 0;
  6772. continue;
  6773. case '\n':
  6774. pc->linenr++;
  6775. break;
  6776. }
  6777. startofword = isspace(UCHAR(*pc->p));
  6778. pc->p++;
  6779. pc->len--;
  6780. }
  6781. pc->missing.ch = '[';
  6782. pc->missing.line = line;
  6783. pc->tend = pc->p - 1;
  6784. }
  6785. static int JimParseBrace(struct JimParserCtx *pc)
  6786. {
  6787. pc->tstart = pc->p + 1;
  6788. pc->tline = pc->linenr;
  6789. pc->tt = JIM_TT_STR;
  6790. JimParseSubBrace(pc);
  6791. return JIM_OK;
  6792. }
  6793. static int JimParseCmd(struct JimParserCtx *pc)
  6794. {
  6795. pc->tstart = pc->p + 1;
  6796. pc->tline = pc->linenr;
  6797. pc->tt = JIM_TT_CMD;
  6798. JimParseSubCmd(pc);
  6799. return JIM_OK;
  6800. }
  6801. static int JimParseQuote(struct JimParserCtx *pc)
  6802. {
  6803. pc->tstart = pc->p + 1;
  6804. pc->tline = pc->linenr;
  6805. pc->tt = JimParseSubQuote(pc);
  6806. return JIM_OK;
  6807. }
  6808. static int JimParseVar(struct JimParserCtx *pc)
  6809. {
  6810. pc->p++;
  6811. pc->len--;
  6812. #ifdef EXPRSUGAR_BRACKET
  6813. if (*pc->p == '[') {
  6814. JimParseCmd(pc);
  6815. pc->tt = JIM_TT_EXPRSUGAR;
  6816. return JIM_OK;
  6817. }
  6818. #endif
  6819. pc->tstart = pc->p;
  6820. pc->tt = JIM_TT_VAR;
  6821. pc->tline = pc->linenr;
  6822. if (*pc->p == '{') {
  6823. pc->tstart = ++pc->p;
  6824. pc->len--;
  6825. while (pc->len && *pc->p != '}') {
  6826. if (*pc->p == '\n') {
  6827. pc->linenr++;
  6828. }
  6829. pc->p++;
  6830. pc->len--;
  6831. }
  6832. pc->tend = pc->p - 1;
  6833. if (pc->len) {
  6834. pc->p++;
  6835. pc->len--;
  6836. }
  6837. }
  6838. else {
  6839. while (1) {
  6840. if (pc->p[0] == ':' && pc->p[1] == ':') {
  6841. while (*pc->p == ':') {
  6842. pc->p++;
  6843. pc->len--;
  6844. }
  6845. continue;
  6846. }
  6847. if (isalnum(UCHAR(*pc->p)) || *pc->p == '_' || UCHAR(*pc->p) >= 0x80) {
  6848. pc->p++;
  6849. pc->len--;
  6850. continue;
  6851. }
  6852. break;
  6853. }
  6854. if (*pc->p == '(') {
  6855. int count = 1;
  6856. const char *paren = NULL;
  6857. pc->tt = JIM_TT_DICTSUGAR;
  6858. while (count && pc->len) {
  6859. pc->p++;
  6860. pc->len--;
  6861. if (*pc->p == '\\' && pc->len >= 1) {
  6862. pc->p++;
  6863. pc->len--;
  6864. }
  6865. else if (*pc->p == '(') {
  6866. count++;
  6867. }
  6868. else if (*pc->p == ')') {
  6869. paren = pc->p;
  6870. count--;
  6871. }
  6872. }
  6873. if (count == 0) {
  6874. pc->p++;
  6875. pc->len--;
  6876. }
  6877. else if (paren) {
  6878. paren++;
  6879. pc->len += (pc->p - paren);
  6880. pc->p = paren;
  6881. }
  6882. #ifndef EXPRSUGAR_BRACKET
  6883. if (*pc->tstart == '(') {
  6884. pc->tt = JIM_TT_EXPRSUGAR;
  6885. }
  6886. #endif
  6887. }
  6888. pc->tend = pc->p - 1;
  6889. }
  6890. if (pc->tstart == pc->p) {
  6891. pc->p--;
  6892. pc->len++;
  6893. return JIM_ERR;
  6894. }
  6895. return JIM_OK;
  6896. }
  6897. static int JimParseStr(struct JimParserCtx *pc)
  6898. {
  6899. if (pc->tt == JIM_TT_SEP || pc->tt == JIM_TT_EOL ||
  6900. pc->tt == JIM_TT_NONE || pc->tt == JIM_TT_STR) {
  6901. if (*pc->p == '{') {
  6902. return JimParseBrace(pc);
  6903. }
  6904. if (*pc->p == '"') {
  6905. pc->inquote = 1;
  6906. pc->p++;
  6907. pc->len--;
  6908. pc->missing.line = pc->tline;
  6909. }
  6910. }
  6911. pc->tstart = pc->p;
  6912. pc->tline = pc->linenr;
  6913. while (1) {
  6914. if (pc->len == 0) {
  6915. if (pc->inquote) {
  6916. pc->missing.ch = '"';
  6917. }
  6918. pc->tend = pc->p - 1;
  6919. pc->tt = JIM_TT_ESC;
  6920. return JIM_OK;
  6921. }
  6922. switch (*pc->p) {
  6923. case '\\':
  6924. if (!pc->inquote && *(pc->p + 1) == '\n') {
  6925. pc->tend = pc->p - 1;
  6926. pc->tt = JIM_TT_ESC;
  6927. return JIM_OK;
  6928. }
  6929. if (pc->len >= 2) {
  6930. if (*(pc->p + 1) == '\n') {
  6931. pc->linenr++;
  6932. }
  6933. pc->p++;
  6934. pc->len--;
  6935. }
  6936. else if (pc->len == 1) {
  6937. pc->missing.ch = '\\';
  6938. }
  6939. break;
  6940. case '(':
  6941. if (pc->len > 1 && pc->p[1] != '$') {
  6942. break;
  6943. }
  6944. case ')':
  6945. if (*pc->p == '(' || pc->tt == JIM_TT_VAR) {
  6946. if (pc->p == pc->tstart) {
  6947. pc->p++;
  6948. pc->len--;
  6949. }
  6950. pc->tend = pc->p - 1;
  6951. pc->tt = JIM_TT_ESC;
  6952. return JIM_OK;
  6953. }
  6954. break;
  6955. case '$':
  6956. case '[':
  6957. pc->tend = pc->p - 1;
  6958. pc->tt = JIM_TT_ESC;
  6959. return JIM_OK;
  6960. case ' ':
  6961. case '\t':
  6962. case '\n':
  6963. case '\r':
  6964. case '\f':
  6965. case ';':
  6966. if (!pc->inquote) {
  6967. pc->tend = pc->p - 1;
  6968. pc->tt = JIM_TT_ESC;
  6969. return JIM_OK;
  6970. }
  6971. else if (*pc->p == '\n') {
  6972. pc->linenr++;
  6973. }
  6974. break;
  6975. case '"':
  6976. if (pc->inquote) {
  6977. pc->tend = pc->p - 1;
  6978. pc->tt = JIM_TT_ESC;
  6979. pc->p++;
  6980. pc->len--;
  6981. pc->inquote = 0;
  6982. return JIM_OK;
  6983. }
  6984. break;
  6985. }
  6986. pc->p++;
  6987. pc->len--;
  6988. }
  6989. return JIM_OK;
  6990. }
  6991. static int JimParseComment(struct JimParserCtx *pc)
  6992. {
  6993. while (*pc->p) {
  6994. if (*pc->p == '\\') {
  6995. pc->p++;
  6996. pc->len--;
  6997. if (pc->len == 0) {
  6998. pc->missing.ch = '\\';
  6999. return JIM_OK;
  7000. }
  7001. if (*pc->p == '\n') {
  7002. pc->linenr++;
  7003. }
  7004. }
  7005. else if (*pc->p == '\n') {
  7006. pc->p++;
  7007. pc->len--;
  7008. pc->linenr++;
  7009. break;
  7010. }
  7011. pc->p++;
  7012. pc->len--;
  7013. }
  7014. return JIM_OK;
  7015. }
  7016. static int xdigitval(int c)
  7017. {
  7018. if (c >= '0' && c <= '9')
  7019. return c - '0';
  7020. if (c >= 'a' && c <= 'f')
  7021. return c - 'a' + 10;
  7022. if (c >= 'A' && c <= 'F')
  7023. return c - 'A' + 10;
  7024. return -1;
  7025. }
  7026. static int odigitval(int c)
  7027. {
  7028. if (c >= '0' && c <= '7')
  7029. return c - '0';
  7030. return -1;
  7031. }
  7032. static int JimEscape(char *dest, const char *s, int slen)
  7033. {
  7034. char *p = dest;
  7035. int i, len;
  7036. for (i = 0; i < slen; i++) {
  7037. switch (s[i]) {
  7038. case '\\':
  7039. switch (s[i + 1]) {
  7040. case 'a':
  7041. *p++ = 0x7;
  7042. i++;
  7043. break;
  7044. case 'b':
  7045. *p++ = 0x8;
  7046. i++;
  7047. break;
  7048. case 'f':
  7049. *p++ = 0xc;
  7050. i++;
  7051. break;
  7052. case 'n':
  7053. *p++ = 0xa;
  7054. i++;
  7055. break;
  7056. case 'r':
  7057. *p++ = 0xd;
  7058. i++;
  7059. break;
  7060. case 't':
  7061. *p++ = 0x9;
  7062. i++;
  7063. break;
  7064. case 'u':
  7065. case 'U':
  7066. case 'x':
  7067. {
  7068. unsigned val = 0;
  7069. int k;
  7070. int maxchars = 2;
  7071. i++;
  7072. if (s[i] == 'U') {
  7073. maxchars = 8;
  7074. }
  7075. else if (s[i] == 'u') {
  7076. if (s[i + 1] == '{') {
  7077. maxchars = 6;
  7078. i++;
  7079. }
  7080. else {
  7081. maxchars = 4;
  7082. }
  7083. }
  7084. for (k = 0; k < maxchars; k++) {
  7085. int c = xdigitval(s[i + k + 1]);
  7086. if (c == -1) {
  7087. break;
  7088. }
  7089. val = (val << 4) | c;
  7090. }
  7091. if (s[i] == '{') {
  7092. if (k == 0 || val > 0x1fffff || s[i + k + 1] != '}') {
  7093. i--;
  7094. k = 0;
  7095. }
  7096. else {
  7097. k++;
  7098. }
  7099. }
  7100. if (k) {
  7101. if (s[i] == 'x') {
  7102. *p++ = val;
  7103. }
  7104. else {
  7105. p += utf8_fromunicode(p, val);
  7106. }
  7107. i += k;
  7108. break;
  7109. }
  7110. *p++ = s[i];
  7111. }
  7112. break;
  7113. case 'v':
  7114. *p++ = 0xb;
  7115. i++;
  7116. break;
  7117. case '\0':
  7118. *p++ = '\\';
  7119. i++;
  7120. break;
  7121. case '\n':
  7122. *p++ = ' ';
  7123. do {
  7124. i++;
  7125. } while (s[i + 1] == ' ' || s[i + 1] == '\t');
  7126. break;
  7127. case '0':
  7128. case '1':
  7129. case '2':
  7130. case '3':
  7131. case '4':
  7132. case '5':
  7133. case '6':
  7134. case '7':
  7135. {
  7136. int val = 0;
  7137. int c = odigitval(s[i + 1]);
  7138. val = c;
  7139. c = odigitval(s[i + 2]);
  7140. if (c == -1) {
  7141. *p++ = val;
  7142. i++;
  7143. break;
  7144. }
  7145. val = (val * 8) + c;
  7146. c = odigitval(s[i + 3]);
  7147. if (c == -1) {
  7148. *p++ = val;
  7149. i += 2;
  7150. break;
  7151. }
  7152. val = (val * 8) + c;
  7153. *p++ = val;
  7154. i += 3;
  7155. }
  7156. break;
  7157. default:
  7158. *p++ = s[i + 1];
  7159. i++;
  7160. break;
  7161. }
  7162. break;
  7163. default:
  7164. *p++ = s[i];
  7165. break;
  7166. }
  7167. }
  7168. len = p - dest;
  7169. *p = '\0';
  7170. return len;
  7171. }
  7172. static Jim_Obj *JimParserGetTokenObj(Jim_Interp *interp, struct JimParserCtx *pc)
  7173. {
  7174. const char *start, *end;
  7175. char *token;
  7176. int len;
  7177. start = pc->tstart;
  7178. end = pc->tend;
  7179. len = (end - start) + 1;
  7180. if (len < 0) {
  7181. len = 0;
  7182. }
  7183. token = Jim_Alloc(len + 1);
  7184. if (pc->tt != JIM_TT_ESC) {
  7185. memcpy(token, start, len);
  7186. token[len] = '\0';
  7187. }
  7188. else {
  7189. len = JimEscape(token, start, len);
  7190. }
  7191. return Jim_NewStringObjNoAlloc(interp, token, len);
  7192. }
  7193. static int JimParseListSep(struct JimParserCtx *pc);
  7194. static int JimParseListStr(struct JimParserCtx *pc);
  7195. static int JimParseListQuote(struct JimParserCtx *pc);
  7196. static int JimParseList(struct JimParserCtx *pc)
  7197. {
  7198. if (isspace(UCHAR(*pc->p))) {
  7199. return JimParseListSep(pc);
  7200. }
  7201. switch (*pc->p) {
  7202. case '"':
  7203. return JimParseListQuote(pc);
  7204. case '{':
  7205. return JimParseBrace(pc);
  7206. default:
  7207. if (pc->len) {
  7208. return JimParseListStr(pc);
  7209. }
  7210. break;
  7211. }
  7212. pc->tstart = pc->tend = pc->p;
  7213. pc->tline = pc->linenr;
  7214. pc->tt = JIM_TT_EOL;
  7215. pc->eof = 1;
  7216. return JIM_OK;
  7217. }
  7218. static int JimParseListSep(struct JimParserCtx *pc)
  7219. {
  7220. pc->tstart = pc->p;
  7221. pc->tline = pc->linenr;
  7222. while (isspace(UCHAR(*pc->p))) {
  7223. if (*pc->p == '\n') {
  7224. pc->linenr++;
  7225. }
  7226. pc->p++;
  7227. pc->len--;
  7228. }
  7229. pc->tend = pc->p - 1;
  7230. pc->tt = JIM_TT_SEP;
  7231. return JIM_OK;
  7232. }
  7233. static int JimParseListQuote(struct JimParserCtx *pc)
  7234. {
  7235. pc->p++;
  7236. pc->len--;
  7237. pc->tstart = pc->p;
  7238. pc->tline = pc->linenr;
  7239. pc->tt = JIM_TT_STR;
  7240. while (pc->len) {
  7241. switch (*pc->p) {
  7242. case '\\':
  7243. pc->tt = JIM_TT_ESC;
  7244. if (--pc->len == 0) {
  7245. pc->tend = pc->p;
  7246. return JIM_OK;
  7247. }
  7248. pc->p++;
  7249. break;
  7250. case '\n':
  7251. pc->linenr++;
  7252. break;
  7253. case '"':
  7254. pc->tend = pc->p - 1;
  7255. pc->p++;
  7256. pc->len--;
  7257. return JIM_OK;
  7258. }
  7259. pc->p++;
  7260. pc->len--;
  7261. }
  7262. pc->tend = pc->p - 1;
  7263. return JIM_OK;
  7264. }
  7265. static int JimParseListStr(struct JimParserCtx *pc)
  7266. {
  7267. pc->tstart = pc->p;
  7268. pc->tline = pc->linenr;
  7269. pc->tt = JIM_TT_STR;
  7270. while (pc->len) {
  7271. if (isspace(UCHAR(*pc->p))) {
  7272. pc->tend = pc->p - 1;
  7273. return JIM_OK;
  7274. }
  7275. if (*pc->p == '\\') {
  7276. if (--pc->len == 0) {
  7277. pc->tend = pc->p;
  7278. return JIM_OK;
  7279. }
  7280. pc->tt = JIM_TT_ESC;
  7281. pc->p++;
  7282. }
  7283. pc->p++;
  7284. pc->len--;
  7285. }
  7286. pc->tend = pc->p - 1;
  7287. return JIM_OK;
  7288. }
  7289. Jim_Obj *Jim_NewObj(Jim_Interp *interp)
  7290. {
  7291. Jim_Obj *objPtr;
  7292. if (interp->freeList != NULL) {
  7293. objPtr = interp->freeList;
  7294. interp->freeList = objPtr->nextObjPtr;
  7295. }
  7296. else {
  7297. objPtr = Jim_Alloc(sizeof(*objPtr));
  7298. }
  7299. objPtr->refCount = 0;
  7300. objPtr->prevObjPtr = NULL;
  7301. objPtr->nextObjPtr = interp->liveList;
  7302. if (interp->liveList)
  7303. interp->liveList->prevObjPtr = objPtr;
  7304. interp->liveList = objPtr;
  7305. return objPtr;
  7306. }
  7307. void Jim_FreeObj(Jim_Interp *interp, Jim_Obj *objPtr)
  7308. {
  7309. JimPanic((objPtr->refCount != 0, "!!!Object %p freed with bad refcount %d, type=%s", objPtr,
  7310. objPtr->refCount, objPtr->typePtr ? objPtr->typePtr->name : "<none>"));
  7311. Jim_FreeIntRep(interp, objPtr);
  7312. if (objPtr->bytes != NULL) {
  7313. if (objPtr->bytes != JimEmptyStringRep)
  7314. Jim_Free(objPtr->bytes);
  7315. }
  7316. if (objPtr->prevObjPtr)
  7317. objPtr->prevObjPtr->nextObjPtr = objPtr->nextObjPtr;
  7318. if (objPtr->nextObjPtr)
  7319. objPtr->nextObjPtr->prevObjPtr = objPtr->prevObjPtr;
  7320. if (interp->liveList == objPtr)
  7321. interp->liveList = objPtr->nextObjPtr;
  7322. #ifdef JIM_DISABLE_OBJECT_POOL
  7323. Jim_Free(objPtr);
  7324. #else
  7325. objPtr->prevObjPtr = NULL;
  7326. objPtr->nextObjPtr = interp->freeList;
  7327. if (interp->freeList)
  7328. interp->freeList->prevObjPtr = objPtr;
  7329. interp->freeList = objPtr;
  7330. objPtr->refCount = -1;
  7331. #endif
  7332. }
  7333. void Jim_InvalidateStringRep(Jim_Obj *objPtr)
  7334. {
  7335. if (objPtr->bytes != NULL) {
  7336. if (objPtr->bytes != JimEmptyStringRep)
  7337. Jim_Free(objPtr->bytes);
  7338. }
  7339. objPtr->bytes = NULL;
  7340. }
  7341. Jim_Obj *Jim_DuplicateObj(Jim_Interp *interp, Jim_Obj *objPtr)
  7342. {
  7343. Jim_Obj *dupPtr;
  7344. dupPtr = Jim_NewObj(interp);
  7345. if (objPtr->bytes == NULL) {
  7346. dupPtr->bytes = NULL;
  7347. }
  7348. else if (objPtr->length == 0) {
  7349. dupPtr->bytes = JimEmptyStringRep;
  7350. dupPtr->length = 0;
  7351. dupPtr->typePtr = NULL;
  7352. return dupPtr;
  7353. }
  7354. else {
  7355. dupPtr->bytes = Jim_Alloc(objPtr->length + 1);
  7356. dupPtr->length = objPtr->length;
  7357. memcpy(dupPtr->bytes, objPtr->bytes, objPtr->length + 1);
  7358. }
  7359. dupPtr->typePtr = objPtr->typePtr;
  7360. if (objPtr->typePtr != NULL) {
  7361. if (objPtr->typePtr->dupIntRepProc == NULL) {
  7362. dupPtr->internalRep = objPtr->internalRep;
  7363. }
  7364. else {
  7365. objPtr->typePtr->dupIntRepProc(interp, objPtr, dupPtr);
  7366. }
  7367. }
  7368. return dupPtr;
  7369. }
  7370. const char *Jim_GetString(Jim_Obj *objPtr, int *lenPtr)
  7371. {
  7372. if (objPtr->bytes == NULL) {
  7373. JimPanic((objPtr->typePtr->updateStringProc == NULL, "UpdateStringProc called against '%s' type.", objPtr->typePtr->name));
  7374. objPtr->typePtr->updateStringProc(objPtr);
  7375. }
  7376. if (lenPtr)
  7377. *lenPtr = objPtr->length;
  7378. return objPtr->bytes;
  7379. }
  7380. int Jim_Length(Jim_Obj *objPtr)
  7381. {
  7382. if (objPtr->bytes == NULL) {
  7383. Jim_GetString(objPtr, NULL);
  7384. }
  7385. return objPtr->length;
  7386. }
  7387. const char *Jim_String(Jim_Obj *objPtr)
  7388. {
  7389. if (objPtr->bytes == NULL) {
  7390. Jim_GetString(objPtr, NULL);
  7391. }
  7392. return objPtr->bytes;
  7393. }
  7394. static void JimSetStringBytes(Jim_Obj *objPtr, const char *str)
  7395. {
  7396. objPtr->bytes = Jim_StrDup(str);
  7397. objPtr->length = strlen(str);
  7398. }
  7399. static void FreeDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
  7400. static void DupDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
  7401. static const Jim_ObjType dictSubstObjType = {
  7402. "dict-substitution",
  7403. FreeDictSubstInternalRep,
  7404. DupDictSubstInternalRep,
  7405. NULL,
  7406. JIM_TYPE_NONE,
  7407. };
  7408. static void FreeInterpolatedInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
  7409. static void DupInterpolatedInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
  7410. static const Jim_ObjType interpolatedObjType = {
  7411. "interpolated",
  7412. FreeInterpolatedInternalRep,
  7413. DupInterpolatedInternalRep,
  7414. NULL,
  7415. JIM_TYPE_NONE,
  7416. };
  7417. static void FreeInterpolatedInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
  7418. {
  7419. Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.indexObjPtr);
  7420. }
  7421. static void DupInterpolatedInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
  7422. {
  7423. dupPtr->internalRep = srcPtr->internalRep;
  7424. Jim_IncrRefCount(dupPtr->internalRep.dictSubstValue.indexObjPtr);
  7425. }
  7426. static void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
  7427. static int SetStringFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
  7428. static const Jim_ObjType stringObjType = {
  7429. "string",
  7430. NULL,
  7431. DupStringInternalRep,
  7432. NULL,
  7433. JIM_TYPE_REFERENCES,
  7434. };
  7435. static void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
  7436. {
  7437. JIM_NOTUSED(interp);
  7438. dupPtr->internalRep.strValue.maxLength = srcPtr->length;
  7439. dupPtr->internalRep.strValue.charLength = srcPtr->internalRep.strValue.charLength;
  7440. }
  7441. static int SetStringFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
  7442. {
  7443. if (objPtr->typePtr != &stringObjType) {
  7444. if (objPtr->bytes == NULL) {
  7445. JimPanic((objPtr->typePtr->updateStringProc == NULL, "UpdateStringProc called against '%s' type.", objPtr->typePtr->name));
  7446. objPtr->typePtr->updateStringProc(objPtr);
  7447. }
  7448. Jim_FreeIntRep(interp, objPtr);
  7449. objPtr->typePtr = &stringObjType;
  7450. objPtr->internalRep.strValue.maxLength = objPtr->length;
  7451. objPtr->internalRep.strValue.charLength = -1;
  7452. }
  7453. return JIM_OK;
  7454. }
  7455. int Jim_Utf8Length(Jim_Interp *interp, Jim_Obj *objPtr)
  7456. {
  7457. #ifdef JIM_UTF8
  7458. SetStringFromAny(interp, objPtr);
  7459. if (objPtr->internalRep.strValue.charLength < 0) {
  7460. objPtr->internalRep.strValue.charLength = utf8_strlen(objPtr->bytes, objPtr->length);
  7461. }
  7462. return objPtr->internalRep.strValue.charLength;
  7463. #else
  7464. return Jim_Length(objPtr);
  7465. #endif
  7466. }
  7467. Jim_Obj *Jim_NewStringObj(Jim_Interp *interp, const char *s, int len)
  7468. {
  7469. Jim_Obj *objPtr = Jim_NewObj(interp);
  7470. if (len == -1)
  7471. len = strlen(s);
  7472. if (len == 0) {
  7473. objPtr->bytes = JimEmptyStringRep;
  7474. }
  7475. else {
  7476. objPtr->bytes = Jim_StrDupLen(s, len);
  7477. }
  7478. objPtr->length = len;
  7479. objPtr->typePtr = NULL;
  7480. return objPtr;
  7481. }
  7482. Jim_Obj *Jim_NewStringObjUtf8(Jim_Interp *interp, const char *s, int charlen)
  7483. {
  7484. #ifdef JIM_UTF8
  7485. int bytelen = utf8_index(s, charlen);
  7486. Jim_Obj *objPtr = Jim_NewStringObj(interp, s, bytelen);
  7487. objPtr->typePtr = &stringObjType;
  7488. objPtr->internalRep.strValue.maxLength = bytelen;
  7489. objPtr->internalRep.strValue.charLength = charlen;
  7490. return objPtr;
  7491. #else
  7492. return Jim_NewStringObj(interp, s, charlen);
  7493. #endif
  7494. }
  7495. Jim_Obj *Jim_NewStringObjNoAlloc(Jim_Interp *interp, char *s, int len)
  7496. {
  7497. Jim_Obj *objPtr = Jim_NewObj(interp);
  7498. objPtr->bytes = s;
  7499. objPtr->length = (len == -1) ? strlen(s) : len;
  7500. objPtr->typePtr = NULL;
  7501. return objPtr;
  7502. }
  7503. static void StringAppendString(Jim_Obj *objPtr, const char *str, int len)
  7504. {
  7505. int needlen;
  7506. if (len == -1)
  7507. len = strlen(str);
  7508. needlen = objPtr->length + len;
  7509. if (objPtr->internalRep.strValue.maxLength < needlen ||
  7510. objPtr->internalRep.strValue.maxLength == 0) {
  7511. needlen *= 2;
  7512. if (needlen < 7) {
  7513. needlen = 7;
  7514. }
  7515. if (objPtr->bytes == JimEmptyStringRep) {
  7516. objPtr->bytes = Jim_Alloc(needlen + 1);
  7517. }
  7518. else {
  7519. objPtr->bytes = Jim_Realloc(objPtr->bytes, needlen + 1);
  7520. }
  7521. objPtr->internalRep.strValue.maxLength = needlen;
  7522. }
  7523. memcpy(objPtr->bytes + objPtr->length, str, len);
  7524. objPtr->bytes[objPtr->length + len] = '\0';
  7525. if (objPtr->internalRep.strValue.charLength >= 0) {
  7526. objPtr->internalRep.strValue.charLength += utf8_strlen(objPtr->bytes + objPtr->length, len);
  7527. }
  7528. objPtr->length += len;
  7529. }
  7530. void Jim_AppendString(Jim_Interp *interp, Jim_Obj *objPtr, const char *str, int len)
  7531. {
  7532. JimPanic((Jim_IsShared(objPtr), "Jim_AppendString called with shared object"));
  7533. SetStringFromAny(interp, objPtr);
  7534. StringAppendString(objPtr, str, len);
  7535. }
  7536. void Jim_AppendObj(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *appendObjPtr)
  7537. {
  7538. int len;
  7539. const char *str = Jim_GetString(appendObjPtr, &len);
  7540. Jim_AppendString(interp, objPtr, str, len);
  7541. }
  7542. void Jim_AppendStrings(Jim_Interp *interp, Jim_Obj *objPtr, ...)
  7543. {
  7544. va_list ap;
  7545. SetStringFromAny(interp, objPtr);
  7546. va_start(ap, objPtr);
  7547. while (1) {
  7548. const char *s = va_arg(ap, const char *);
  7549. if (s == NULL)
  7550. break;
  7551. Jim_AppendString(interp, objPtr, s, -1);
  7552. }
  7553. va_end(ap);
  7554. }
  7555. int Jim_StringEqObj(Jim_Obj *aObjPtr, Jim_Obj *bObjPtr)
  7556. {
  7557. if (aObjPtr == bObjPtr) {
  7558. return 1;
  7559. }
  7560. else {
  7561. int Alen, Blen;
  7562. const char *sA = Jim_GetString(aObjPtr, &Alen);
  7563. const char *sB = Jim_GetString(bObjPtr, &Blen);
  7564. return Alen == Blen && memcmp(sA, sB, Alen) == 0;
  7565. }
  7566. }
  7567. int Jim_StringMatchObj(Jim_Interp *interp, Jim_Obj *patternObjPtr, Jim_Obj *objPtr, int nocase)
  7568. {
  7569. int plen, slen;
  7570. const char *pattern = Jim_GetString(patternObjPtr, &plen);
  7571. const char *string = Jim_GetString(objPtr, &slen);
  7572. return JimGlobMatch(pattern, plen, string, slen, nocase);
  7573. }
  7574. int Jim_StringCompareObj(Jim_Interp *interp, Jim_Obj *firstObjPtr, Jim_Obj *secondObjPtr, int nocase)
  7575. {
  7576. const char *s1 = Jim_String(firstObjPtr);
  7577. int l1 = Jim_Utf8Length(interp, firstObjPtr);
  7578. const char *s2 = Jim_String(secondObjPtr);
  7579. int l2 = Jim_Utf8Length(interp, secondObjPtr);
  7580. return JimStringCompareUtf8(s1, l1, s2, l2, nocase);
  7581. }
  7582. static int JimRelToAbsIndex(int len, int idx)
  7583. {
  7584. if (idx < 0 && idx > -INT_MAX)
  7585. return len + idx;
  7586. return idx;
  7587. }
  7588. static void JimRelToAbsRange(int len, int *firstPtr, int *lastPtr, int *rangeLenPtr)
  7589. {
  7590. int rangeLen;
  7591. if (*firstPtr > *lastPtr) {
  7592. rangeLen = 0;
  7593. }
  7594. else {
  7595. rangeLen = *lastPtr - *firstPtr + 1;
  7596. if (rangeLen) {
  7597. if (*firstPtr < 0) {
  7598. rangeLen += *firstPtr;
  7599. *firstPtr = 0;
  7600. }
  7601. if (*lastPtr >= len) {
  7602. rangeLen -= (*lastPtr - (len - 1));
  7603. *lastPtr = len - 1;
  7604. }
  7605. }
  7606. }
  7607. if (rangeLen < 0)
  7608. rangeLen = 0;
  7609. *rangeLenPtr = rangeLen;
  7610. }
  7611. static int JimStringGetRange(Jim_Interp *interp, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr,
  7612. int len, int *first, int *last, int *range)
  7613. {
  7614. if (Jim_GetIndex(interp, firstObjPtr, first) != JIM_OK) {
  7615. return JIM_ERR;
  7616. }
  7617. if (Jim_GetIndex(interp, lastObjPtr, last) != JIM_OK) {
  7618. return JIM_ERR;
  7619. }
  7620. *first = JimRelToAbsIndex(len, *first);
  7621. *last = JimRelToAbsIndex(len, *last);
  7622. JimRelToAbsRange(len, first, last, range);
  7623. return JIM_OK;
  7624. }
  7625. Jim_Obj *Jim_StringByteRangeObj(Jim_Interp *interp,
  7626. Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)
  7627. {
  7628. int first, last;
  7629. const char *str;
  7630. int rangeLen;
  7631. int bytelen;
  7632. str = Jim_GetString(strObjPtr, &bytelen);
  7633. if (JimStringGetRange(interp, firstObjPtr, lastObjPtr, bytelen, &first, &last, &rangeLen) != JIM_OK) {
  7634. return NULL;
  7635. }
  7636. if (first == 0 && rangeLen == bytelen) {
  7637. return strObjPtr;
  7638. }
  7639. return Jim_NewStringObj(interp, str + first, rangeLen);
  7640. }
  7641. Jim_Obj *Jim_StringRangeObj(Jim_Interp *interp,
  7642. Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)
  7643. {
  7644. #ifdef JIM_UTF8
  7645. int first, last;
  7646. const char *str;
  7647. int len, rangeLen;
  7648. int bytelen;
  7649. str = Jim_GetString(strObjPtr, &bytelen);
  7650. len = Jim_Utf8Length(interp, strObjPtr);
  7651. if (JimStringGetRange(interp, firstObjPtr, lastObjPtr, len, &first, &last, &rangeLen) != JIM_OK) {
  7652. return NULL;
  7653. }
  7654. if (first == 0 && rangeLen == len) {
  7655. return strObjPtr;
  7656. }
  7657. if (len == bytelen) {
  7658. return Jim_NewStringObj(interp, str + first, rangeLen);
  7659. }
  7660. return Jim_NewStringObjUtf8(interp, str + utf8_index(str, first), rangeLen);
  7661. #else
  7662. return Jim_StringByteRangeObj(interp, strObjPtr, firstObjPtr, lastObjPtr);
  7663. #endif
  7664. }
  7665. Jim_Obj *JimStringReplaceObj(Jim_Interp *interp,
  7666. Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr, Jim_Obj *newStrObj)
  7667. {
  7668. int first, last;
  7669. const char *str;
  7670. int len, rangeLen;
  7671. Jim_Obj *objPtr;
  7672. len = Jim_Utf8Length(interp, strObjPtr);
  7673. if (JimStringGetRange(interp, firstObjPtr, lastObjPtr, len, &first, &last, &rangeLen) != JIM_OK) {
  7674. return NULL;
  7675. }
  7676. if (last < first) {
  7677. return strObjPtr;
  7678. }
  7679. str = Jim_String(strObjPtr);
  7680. objPtr = Jim_NewStringObjUtf8(interp, str, first);
  7681. if (newStrObj) {
  7682. Jim_AppendObj(interp, objPtr, newStrObj);
  7683. }
  7684. Jim_AppendString(interp, objPtr, str + utf8_index(str, last + 1), len - last - 1);
  7685. return objPtr;
  7686. }
  7687. static void JimStrCopyUpperLower(char *dest, const char *str, int uc)
  7688. {
  7689. while (*str) {
  7690. int c;
  7691. str += utf8_tounicode(str, &c);
  7692. dest += utf8_getchars(dest, uc ? utf8_upper(c) : utf8_lower(c));
  7693. }
  7694. *dest = 0;
  7695. }
  7696. static Jim_Obj *JimStringToLower(Jim_Interp *interp, Jim_Obj *strObjPtr)
  7697. {
  7698. char *buf;
  7699. int len;
  7700. const char *str;
  7701. str = Jim_GetString(strObjPtr, &len);
  7702. #ifdef JIM_UTF8
  7703. len *= 2;
  7704. #endif
  7705. buf = Jim_Alloc(len + 1);
  7706. JimStrCopyUpperLower(buf, str, 0);
  7707. return Jim_NewStringObjNoAlloc(interp, buf, -1);
  7708. }
  7709. static Jim_Obj *JimStringToUpper(Jim_Interp *interp, Jim_Obj *strObjPtr)
  7710. {
  7711. char *buf;
  7712. const char *str;
  7713. int len;
  7714. str = Jim_GetString(strObjPtr, &len);
  7715. #ifdef JIM_UTF8
  7716. len *= 2;
  7717. #endif
  7718. buf = Jim_Alloc(len + 1);
  7719. JimStrCopyUpperLower(buf, str, 1);
  7720. return Jim_NewStringObjNoAlloc(interp, buf, -1);
  7721. }
  7722. static Jim_Obj *JimStringToTitle(Jim_Interp *interp, Jim_Obj *strObjPtr)
  7723. {
  7724. char *buf, *p;
  7725. int len;
  7726. int c;
  7727. const char *str;
  7728. str = Jim_GetString(strObjPtr, &len);
  7729. #ifdef JIM_UTF8
  7730. len *= 2;
  7731. #endif
  7732. buf = p = Jim_Alloc(len + 1);
  7733. str += utf8_tounicode(str, &c);
  7734. p += utf8_getchars(p, utf8_title(c));
  7735. JimStrCopyUpperLower(p, str, 0);
  7736. return Jim_NewStringObjNoAlloc(interp, buf, -1);
  7737. }
  7738. static const char *utf8_memchr(const char *str, int len, int c)
  7739. {
  7740. #ifdef JIM_UTF8
  7741. while (len) {
  7742. int sc;
  7743. int n = utf8_tounicode(str, &sc);
  7744. if (sc == c) {
  7745. return str;
  7746. }
  7747. str += n;
  7748. len -= n;
  7749. }
  7750. return NULL;
  7751. #else
  7752. return memchr(str, c, len);
  7753. #endif
  7754. }
  7755. static const char *JimFindTrimLeft(const char *str, int len, const char *trimchars, int trimlen)
  7756. {
  7757. while (len) {
  7758. int c;
  7759. int n = utf8_tounicode(str, &c);
  7760. if (utf8_memchr(trimchars, trimlen, c) == NULL) {
  7761. break;
  7762. }
  7763. str += n;
  7764. len -= n;
  7765. }
  7766. return str;
  7767. }
  7768. static const char *JimFindTrimRight(const char *str, int len, const char *trimchars, int trimlen)
  7769. {
  7770. str += len;
  7771. while (len) {
  7772. int c;
  7773. int n = utf8_prev_len(str, len);
  7774. len -= n;
  7775. str -= n;
  7776. n = utf8_tounicode(str, &c);
  7777. if (utf8_memchr(trimchars, trimlen, c) == NULL) {
  7778. return str + n;
  7779. }
  7780. }
  7781. return NULL;
  7782. }
  7783. static const char default_trim_chars[] = " \t\n\r";
  7784. static int default_trim_chars_len = sizeof(default_trim_chars);
  7785. static Jim_Obj *JimStringTrimLeft(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
  7786. {
  7787. int len;
  7788. const char *str = Jim_GetString(strObjPtr, &len);
  7789. const char *trimchars = default_trim_chars;
  7790. int trimcharslen = default_trim_chars_len;
  7791. const char *newstr;
  7792. if (trimcharsObjPtr) {
  7793. trimchars = Jim_GetString(trimcharsObjPtr, &trimcharslen);
  7794. }
  7795. newstr = JimFindTrimLeft(str, len, trimchars, trimcharslen);
  7796. if (newstr == str) {
  7797. return strObjPtr;
  7798. }
  7799. return Jim_NewStringObj(interp, newstr, len - (newstr - str));
  7800. }
  7801. static Jim_Obj *JimStringTrimRight(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
  7802. {
  7803. int len;
  7804. const char *trimchars = default_trim_chars;
  7805. int trimcharslen = default_trim_chars_len;
  7806. const char *nontrim;
  7807. if (trimcharsObjPtr) {
  7808. trimchars = Jim_GetString(trimcharsObjPtr, &trimcharslen);
  7809. }
  7810. SetStringFromAny(interp, strObjPtr);
  7811. len = Jim_Length(strObjPtr);
  7812. nontrim = JimFindTrimRight(strObjPtr->bytes, len, trimchars, trimcharslen);
  7813. if (nontrim == NULL) {
  7814. return Jim_NewEmptyStringObj(interp);
  7815. }
  7816. if (nontrim == strObjPtr->bytes + len) {
  7817. return strObjPtr;
  7818. }
  7819. if (Jim_IsShared(strObjPtr)) {
  7820. strObjPtr = Jim_NewStringObj(interp, strObjPtr->bytes, (nontrim - strObjPtr->bytes));
  7821. }
  7822. else {
  7823. strObjPtr->bytes[nontrim - strObjPtr->bytes] = 0;
  7824. strObjPtr->length = (nontrim - strObjPtr->bytes);
  7825. }
  7826. return strObjPtr;
  7827. }
  7828. static Jim_Obj *JimStringTrim(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
  7829. {
  7830. Jim_Obj *objPtr = JimStringTrimLeft(interp, strObjPtr, trimcharsObjPtr);
  7831. strObjPtr = JimStringTrimRight(interp, objPtr, trimcharsObjPtr);
  7832. if (objPtr != strObjPtr && objPtr->refCount == 0) {
  7833. Jim_FreeNewObj(interp, objPtr);
  7834. }
  7835. return strObjPtr;
  7836. }
  7837. #ifdef HAVE_ISASCII
  7838. #define jim_isascii isascii
  7839. #else
  7840. static int jim_isascii(int c)
  7841. {
  7842. return !(c & ~0x7f);
  7843. }
  7844. #endif
  7845. static int JimStringIs(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *strClass, int strict)
  7846. {
  7847. static const char * const strclassnames[] = {
  7848. "integer", "alpha", "alnum", "ascii", "digit",
  7849. "double", "lower", "upper", "space", "xdigit",
  7850. "control", "print", "graph", "punct", "boolean",
  7851. NULL
  7852. };
  7853. enum {
  7854. STR_IS_INTEGER, STR_IS_ALPHA, STR_IS_ALNUM, STR_IS_ASCII, STR_IS_DIGIT,
  7855. STR_IS_DOUBLE, STR_IS_LOWER, STR_IS_UPPER, STR_IS_SPACE, STR_IS_XDIGIT,
  7856. STR_IS_CONTROL, STR_IS_PRINT, STR_IS_GRAPH, STR_IS_PUNCT, STR_IS_BOOLEAN,
  7857. };
  7858. int strclass;
  7859. int len;
  7860. int i;
  7861. const char *str;
  7862. int (*isclassfunc)(int c) = NULL;
  7863. if (Jim_GetEnum(interp, strClass, strclassnames, &strclass, "class", JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
  7864. return JIM_ERR;
  7865. }
  7866. str = Jim_GetString(strObjPtr, &len);
  7867. if (len == 0) {
  7868. Jim_SetResultBool(interp, !strict);
  7869. return JIM_OK;
  7870. }
  7871. switch (strclass) {
  7872. case STR_IS_INTEGER:
  7873. {
  7874. jim_wide w;
  7875. Jim_SetResultBool(interp, JimGetWideNoErr(interp, strObjPtr, &w) == JIM_OK);
  7876. return JIM_OK;
  7877. }
  7878. case STR_IS_DOUBLE:
  7879. {
  7880. double d;
  7881. Jim_SetResultBool(interp, Jim_GetDouble(interp, strObjPtr, &d) == JIM_OK && errno != ERANGE);
  7882. return JIM_OK;
  7883. }
  7884. case STR_IS_BOOLEAN:
  7885. {
  7886. int b;
  7887. Jim_SetResultBool(interp, Jim_GetBoolean(interp, strObjPtr, &b) == JIM_OK);
  7888. return JIM_OK;
  7889. }
  7890. case STR_IS_ALPHA: isclassfunc = isalpha; break;
  7891. case STR_IS_ALNUM: isclassfunc = isalnum; break;
  7892. case STR_IS_ASCII: isclassfunc = jim_isascii; break;
  7893. case STR_IS_DIGIT: isclassfunc = isdigit; break;
  7894. case STR_IS_LOWER: isclassfunc = islower; break;
  7895. case STR_IS_UPPER: isclassfunc = isupper; break;
  7896. case STR_IS_SPACE: isclassfunc = isspace; break;
  7897. case STR_IS_XDIGIT: isclassfunc = isxdigit; break;
  7898. case STR_IS_CONTROL: isclassfunc = iscntrl; break;
  7899. case STR_IS_PRINT: isclassfunc = isprint; break;
  7900. case STR_IS_GRAPH: isclassfunc = isgraph; break;
  7901. case STR_IS_PUNCT: isclassfunc = ispunct; break;
  7902. default:
  7903. return JIM_ERR;
  7904. }
  7905. for (i = 0; i < len; i++) {
  7906. if (!isclassfunc(UCHAR(str[i]))) {
  7907. Jim_SetResultBool(interp, 0);
  7908. return JIM_OK;
  7909. }
  7910. }
  7911. Jim_SetResultBool(interp, 1);
  7912. return JIM_OK;
  7913. }
  7914. static const Jim_ObjType comparedStringObjType = {
  7915. "compared-string",
  7916. NULL,
  7917. NULL,
  7918. NULL,
  7919. JIM_TYPE_REFERENCES,
  7920. };
  7921. int Jim_CompareStringImmediate(Jim_Interp *interp, Jim_Obj *objPtr, const char *str)
  7922. {
  7923. if (objPtr->typePtr == &comparedStringObjType && objPtr->internalRep.ptr == str) {
  7924. return 1;
  7925. }
  7926. else {
  7927. if (strcmp(str, Jim_String(objPtr)) != 0)
  7928. return 0;
  7929. if (objPtr->typePtr != &comparedStringObjType) {
  7930. Jim_FreeIntRep(interp, objPtr);
  7931. objPtr->typePtr = &comparedStringObjType;
  7932. }
  7933. objPtr->internalRep.ptr = (char *)str;
  7934. return 1;
  7935. }
  7936. }
  7937. static int qsortCompareStringPointers(const void *a, const void *b)
  7938. {
  7939. char *const *sa = (char *const *)a;
  7940. char *const *sb = (char *const *)b;
  7941. return strcmp(*sa, *sb);
  7942. }
  7943. static void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
  7944. static void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
  7945. static const Jim_ObjType sourceObjType = {
  7946. "source",
  7947. FreeSourceInternalRep,
  7948. DupSourceInternalRep,
  7949. NULL,
  7950. JIM_TYPE_REFERENCES,
  7951. };
  7952. void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
  7953. {
  7954. Jim_DecrRefCount(interp, objPtr->internalRep.sourceValue.fileNameObj);
  7955. }
  7956. void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
  7957. {
  7958. dupPtr->internalRep.sourceValue = srcPtr->internalRep.sourceValue;
  7959. Jim_IncrRefCount(dupPtr->internalRep.sourceValue.fileNameObj);
  7960. }
  7961. static const Jim_ObjType scriptLineObjType = {
  7962. "scriptline",
  7963. NULL,
  7964. NULL,
  7965. NULL,
  7966. JIM_NONE,
  7967. };
  7968. static Jim_Obj *JimNewScriptLineObj(Jim_Interp *interp, int argc, int line)
  7969. {
  7970. Jim_Obj *objPtr;
  7971. #ifdef DEBUG_SHOW_SCRIPT
  7972. char buf[100];
  7973. snprintf(buf, sizeof(buf), "line=%d, argc=%d", line, argc);
  7974. objPtr = Jim_NewStringObj(interp, buf, -1);
  7975. #else
  7976. objPtr = Jim_NewEmptyStringObj(interp);
  7977. #endif
  7978. objPtr->typePtr = &scriptLineObjType;
  7979. objPtr->internalRep.scriptLineValue.argc = argc;
  7980. objPtr->internalRep.scriptLineValue.line = line;
  7981. return objPtr;
  7982. }
  7983. static void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
  7984. static void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
  7985. static const Jim_ObjType scriptObjType = {
  7986. "script",
  7987. FreeScriptInternalRep,
  7988. DupScriptInternalRep,
  7989. NULL,
  7990. JIM_TYPE_NONE,
  7991. };
  7992. typedef struct ScriptToken
  7993. {
  7994. Jim_Obj *objPtr;
  7995. int type;
  7996. } ScriptToken;
  7997. typedef struct ScriptObj
  7998. {
  7999. ScriptToken *token;
  8000. Jim_Obj *fileNameObj;
  8001. int len;
  8002. int substFlags;
  8003. int inUse; /* Used to share a ScriptObj. Currently
  8004. only used by Jim_EvalObj() as protection against
  8005. shimmering of the currently evaluated object. */
  8006. int firstline;
  8007. int linenr;
  8008. int missing;
  8009. } ScriptObj;
  8010. static void JimSetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
  8011. static int JimParseCheckMissing(Jim_Interp *interp, int ch);
  8012. static ScriptObj *JimGetScript(Jim_Interp *interp, Jim_Obj *objPtr);
  8013. static void JimSetErrorStack(Jim_Interp *interp, ScriptObj *script);
  8014. void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
  8015. {
  8016. int i;
  8017. struct ScriptObj *script = (void *)objPtr->internalRep.ptr;
  8018. if (--script->inUse != 0)
  8019. return;
  8020. for (i = 0; i < script->len; i++) {
  8021. Jim_DecrRefCount(interp, script->token[i].objPtr);
  8022. }
  8023. Jim_Free(script->token);
  8024. Jim_DecrRefCount(interp, script->fileNameObj);
  8025. Jim_Free(script);
  8026. }
  8027. void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
  8028. {
  8029. JIM_NOTUSED(interp);
  8030. JIM_NOTUSED(srcPtr);
  8031. dupPtr->typePtr = NULL;
  8032. }
  8033. typedef struct
  8034. {
  8035. const char *token;
  8036. int len;
  8037. int type;
  8038. int line;
  8039. } ParseToken;
  8040. typedef struct
  8041. {
  8042. ParseToken *list;
  8043. int size;
  8044. int count;
  8045. ParseToken static_list[20];
  8046. } ParseTokenList;
  8047. static void ScriptTokenListInit(ParseTokenList *tokenlist)
  8048. {
  8049. tokenlist->list = tokenlist->static_list;
  8050. tokenlist->size = sizeof(tokenlist->static_list) / sizeof(ParseToken);
  8051. tokenlist->count = 0;
  8052. }
  8053. static void ScriptTokenListFree(ParseTokenList *tokenlist)
  8054. {
  8055. if (tokenlist->list != tokenlist->static_list) {
  8056. Jim_Free(tokenlist->list);
  8057. }
  8058. }
  8059. static void ScriptAddToken(ParseTokenList *tokenlist, const char *token, int len, int type,
  8060. int line)
  8061. {
  8062. ParseToken *t;
  8063. if (tokenlist->count == tokenlist->size) {
  8064. tokenlist->size *= 2;
  8065. if (tokenlist->list != tokenlist->static_list) {
  8066. tokenlist->list =
  8067. Jim_Realloc(tokenlist->list, tokenlist->size * sizeof(*tokenlist->list));
  8068. }
  8069. else {
  8070. tokenlist->list = Jim_Alloc(tokenlist->size * sizeof(*tokenlist->list));
  8071. memcpy(tokenlist->list, tokenlist->static_list,
  8072. tokenlist->count * sizeof(*tokenlist->list));
  8073. }
  8074. }
  8075. t = &tokenlist->list[tokenlist->count++];
  8076. t->token = token;
  8077. t->len = len;
  8078. t->type = type;
  8079. t->line = line;
  8080. }
  8081. static int JimCountWordTokens(struct ScriptObj *script, ParseToken *t)
  8082. {
  8083. int expand = 1;
  8084. int count = 0;
  8085. if (t->type == JIM_TT_STR && !TOKEN_IS_SEP(t[1].type)) {
  8086. if ((t->len == 1 && *t->token == '*') || (t->len == 6 && strncmp(t->token, "expand", 6) == 0)) {
  8087. expand = -1;
  8088. t++;
  8089. }
  8090. else {
  8091. if (script->missing == ' ') {
  8092. script->missing = '}';
  8093. script->linenr = t[1].line;
  8094. }
  8095. }
  8096. }
  8097. while (!TOKEN_IS_SEP(t->type)) {
  8098. t++;
  8099. count++;
  8100. }
  8101. return count * expand;
  8102. }
  8103. static Jim_Obj *JimMakeScriptObj(Jim_Interp *interp, const ParseToken *t)
  8104. {
  8105. Jim_Obj *objPtr;
  8106. if (t->type == JIM_TT_ESC && memchr(t->token, '\\', t->len) != NULL) {
  8107. int len = t->len;
  8108. char *str = Jim_Alloc(len + 1);
  8109. len = JimEscape(str, t->token, len);
  8110. objPtr = Jim_NewStringObjNoAlloc(interp, str, len);
  8111. }
  8112. else {
  8113. objPtr = Jim_NewStringObj(interp, t->token, t->len);
  8114. }
  8115. return objPtr;
  8116. }
  8117. static void ScriptObjAddTokens(Jim_Interp *interp, struct ScriptObj *script,
  8118. ParseTokenList *tokenlist)
  8119. {
  8120. int i;
  8121. struct ScriptToken *token;
  8122. int lineargs = 0;
  8123. ScriptToken *linefirst;
  8124. int count;
  8125. int linenr;
  8126. #ifdef DEBUG_SHOW_SCRIPT_TOKENS
  8127. printf("==== Tokens ====\n");
  8128. for (i = 0; i < tokenlist->count; i++) {
  8129. printf("[%2d]@%d %s '%.*s'\n", i, tokenlist->list[i].line, jim_tt_name(tokenlist->list[i].type),
  8130. tokenlist->list[i].len, tokenlist->list[i].token);
  8131. }
  8132. #endif
  8133. count = tokenlist->count;
  8134. for (i = 0; i < tokenlist->count; i++) {
  8135. if (tokenlist->list[i].type == JIM_TT_EOL) {
  8136. count++;
  8137. }
  8138. }
  8139. linenr = script->firstline = tokenlist->list[0].line;
  8140. token = script->token = Jim_Alloc(sizeof(ScriptToken) * count);
  8141. linefirst = token++;
  8142. for (i = 0; i < tokenlist->count; ) {
  8143. int wordtokens;
  8144. while (tokenlist->list[i].type == JIM_TT_SEP) {
  8145. i++;
  8146. }
  8147. wordtokens = JimCountWordTokens(script, tokenlist->list + i);
  8148. if (wordtokens == 0) {
  8149. if (lineargs) {
  8150. linefirst->type = JIM_TT_LINE;
  8151. linefirst->objPtr = JimNewScriptLineObj(interp, lineargs, linenr);
  8152. Jim_IncrRefCount(linefirst->objPtr);
  8153. lineargs = 0;
  8154. linefirst = token++;
  8155. }
  8156. i++;
  8157. continue;
  8158. }
  8159. else if (wordtokens != 1) {
  8160. token->type = JIM_TT_WORD;
  8161. token->objPtr = Jim_NewIntObj(interp, wordtokens);
  8162. Jim_IncrRefCount(token->objPtr);
  8163. token++;
  8164. if (wordtokens < 0) {
  8165. i++;
  8166. wordtokens = -wordtokens - 1;
  8167. lineargs--;
  8168. }
  8169. }
  8170. if (lineargs == 0) {
  8171. linenr = tokenlist->list[i].line;
  8172. }
  8173. lineargs++;
  8174. while (wordtokens--) {
  8175. const ParseToken *t = &tokenlist->list[i++];
  8176. token->type = t->type;
  8177. token->objPtr = JimMakeScriptObj(interp, t);
  8178. Jim_IncrRefCount(token->objPtr);
  8179. Jim_SetSourceInfo(interp, token->objPtr, script->fileNameObj, t->line);
  8180. token++;
  8181. }
  8182. }
  8183. if (lineargs == 0) {
  8184. token--;
  8185. }
  8186. script->len = token - script->token;
  8187. JimPanic((script->len >= count, "allocated script array is too short"));
  8188. #ifdef DEBUG_SHOW_SCRIPT
  8189. printf("==== Script (%s) ====\n", Jim_String(script->fileNameObj));
  8190. for (i = 0; i < script->len; i++) {
  8191. const ScriptToken *t = &script->token[i];
  8192. printf("[%2d] %s %s\n", i, jim_tt_name(t->type), Jim_String(t->objPtr));
  8193. }
  8194. #endif
  8195. }
  8196. int Jim_ScriptIsComplete(Jim_Interp *interp, Jim_Obj *scriptObj, char *stateCharPtr)
  8197. {
  8198. ScriptObj *script = JimGetScript(interp, scriptObj);
  8199. if (stateCharPtr) {
  8200. *stateCharPtr = script->missing;
  8201. }
  8202. return script->missing == ' ' || script->missing == '}';
  8203. }
  8204. static int JimParseCheckMissing(Jim_Interp *interp, int ch)
  8205. {
  8206. const char *msg;
  8207. switch (ch) {
  8208. case '\\':
  8209. case ' ':
  8210. return JIM_OK;
  8211. case '[':
  8212. msg = "unmatched \"[\"";
  8213. break;
  8214. case '{':
  8215. msg = "missing close-brace";
  8216. break;
  8217. case '}':
  8218. msg = "extra characters after close-brace";
  8219. break;
  8220. case '"':
  8221. default:
  8222. msg = "missing quote";
  8223. break;
  8224. }
  8225. Jim_SetResultString(interp, msg, -1);
  8226. return JIM_ERR;
  8227. }
  8228. Jim_Obj *Jim_GetSourceInfo(Jim_Interp *interp, Jim_Obj *objPtr, int *lineptr)
  8229. {
  8230. int line;
  8231. Jim_Obj *fileNameObj;
  8232. if (objPtr->typePtr == &sourceObjType) {
  8233. fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
  8234. line = objPtr->internalRep.sourceValue.lineNumber;
  8235. }
  8236. else if (objPtr->typePtr == &scriptObjType) {
  8237. ScriptObj *script = JimGetScript(interp, objPtr);
  8238. fileNameObj = script->fileNameObj;
  8239. line = script->firstline;
  8240. }
  8241. else {
  8242. fileNameObj = interp->emptyObj;
  8243. line = 1;
  8244. }
  8245. *lineptr = line;
  8246. return fileNameObj;
  8247. }
  8248. void Jim_SetSourceInfo(Jim_Interp *interp, Jim_Obj *objPtr,
  8249. Jim_Obj *fileNameObj, int lineNumber)
  8250. {
  8251. JimPanic((Jim_IsShared(objPtr), "Jim_SetSourceInfo called with shared object"));
  8252. Jim_FreeIntRep(interp, objPtr);
  8253. Jim_IncrRefCount(fileNameObj);
  8254. objPtr->internalRep.sourceValue.fileNameObj = fileNameObj;
  8255. objPtr->internalRep.sourceValue.lineNumber = lineNumber;
  8256. objPtr->typePtr = &sourceObjType;
  8257. }
  8258. static void SubstObjAddTokens(Jim_Interp *interp, struct ScriptObj *script,
  8259. ParseTokenList *tokenlist)
  8260. {
  8261. int i;
  8262. struct ScriptToken *token;
  8263. token = script->token = Jim_Alloc(sizeof(ScriptToken) * tokenlist->count);
  8264. for (i = 0; i < tokenlist->count; i++) {
  8265. const ParseToken *t = &tokenlist->list[i];
  8266. token->type = t->type;
  8267. token->objPtr = JimMakeScriptObj(interp, t);
  8268. Jim_IncrRefCount(token->objPtr);
  8269. token++;
  8270. }
  8271. script->len = i;
  8272. }
  8273. static void JimSetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
  8274. {
  8275. int scriptTextLen;
  8276. const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);
  8277. struct JimParserCtx parser;
  8278. struct ScriptObj *script;
  8279. ParseTokenList tokenlist;
  8280. Jim_Obj *fileNameObj;
  8281. int line;
  8282. fileNameObj = Jim_GetSourceInfo(interp, objPtr, &line);
  8283. ScriptTokenListInit(&tokenlist);
  8284. JimParserInit(&parser, scriptText, scriptTextLen, line);
  8285. while (!parser.eof) {
  8286. JimParseScript(&parser);
  8287. ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
  8288. parser.tline);
  8289. }
  8290. ScriptAddToken(&tokenlist, scriptText + scriptTextLen, 0, JIM_TT_EOF, 0);
  8291. script = Jim_Alloc(sizeof(*script));
  8292. memset(script, 0, sizeof(*script));
  8293. script->inUse = 1;
  8294. script->fileNameObj = fileNameObj;
  8295. Jim_IncrRefCount(script->fileNameObj);
  8296. script->missing = parser.missing.ch;
  8297. script->linenr = parser.missing.line;
  8298. ScriptObjAddTokens(interp, script, &tokenlist);
  8299. ScriptTokenListFree(&tokenlist);
  8300. Jim_FreeIntRep(interp, objPtr);
  8301. Jim_SetIntRepPtr(objPtr, script);
  8302. objPtr->typePtr = &scriptObjType;
  8303. }
  8304. static ScriptObj *JimGetScript(Jim_Interp *interp, Jim_Obj *objPtr)
  8305. {
  8306. if (objPtr == interp->emptyObj) {
  8307. objPtr = interp->nullScriptObj;
  8308. }
  8309. if (objPtr->typePtr != &scriptObjType || ((struct ScriptObj *)Jim_GetIntRepPtr(objPtr))->substFlags) {
  8310. JimSetScriptFromAny(interp, objPtr);
  8311. }
  8312. return (ScriptObj *)Jim_GetIntRepPtr(objPtr);
  8313. }
  8314. void Jim_InterpIncrProcEpoch(Jim_Interp *interp)
  8315. {
  8316. interp->procEpoch++;
  8317. while (interp->oldCmdCache) {
  8318. Jim_Cmd *next = interp->oldCmdCache->prevCmd;
  8319. Jim_Free(interp->oldCmdCache);
  8320. interp->oldCmdCache = next;
  8321. }
  8322. interp->oldCmdCacheSize = 0;
  8323. }
  8324. static void JimIncrCmdRefCount(Jim_Cmd *cmdPtr)
  8325. {
  8326. cmdPtr->inUse++;
  8327. }
  8328. static void JimDecrCmdRefCount(Jim_Interp *interp, Jim_Cmd *cmdPtr)
  8329. {
  8330. if (--cmdPtr->inUse == 0) {
  8331. if (cmdPtr->isproc) {
  8332. Jim_DecrRefCount(interp, cmdPtr->u.proc.argListObjPtr);
  8333. Jim_DecrRefCount(interp, cmdPtr->u.proc.bodyObjPtr);
  8334. Jim_DecrRefCount(interp, cmdPtr->u.proc.nsObj);
  8335. if (cmdPtr->u.proc.staticVars) {
  8336. Jim_FreeHashTable(cmdPtr->u.proc.staticVars);
  8337. Jim_Free(cmdPtr->u.proc.staticVars);
  8338. }
  8339. }
  8340. else {
  8341. if (cmdPtr->u.native.delProc) {
  8342. cmdPtr->u.native.delProc(interp, cmdPtr->u.native.privData);
  8343. }
  8344. }
  8345. if (cmdPtr->prevCmd) {
  8346. JimDecrCmdRefCount(interp, cmdPtr->prevCmd);
  8347. }
  8348. cmdPtr->prevCmd = interp->oldCmdCache;
  8349. interp->oldCmdCache = cmdPtr;
  8350. if (!interp->quitting && ++interp->oldCmdCacheSize >= 1000) {
  8351. Jim_InterpIncrProcEpoch(interp);
  8352. }
  8353. }
  8354. }
  8355. static void JimIncrVarRef(Jim_VarVal *vv)
  8356. {
  8357. vv->refCount++;
  8358. }
  8359. static void JimDecrVarRef(Jim_Interp *interp, Jim_VarVal *vv)
  8360. {
  8361. assert(vv->refCount > 0);
  8362. if (--vv->refCount == 0) {
  8363. if (vv->objPtr) {
  8364. Jim_DecrRefCount(interp, vv->objPtr);
  8365. }
  8366. Jim_Free(vv);
  8367. }
  8368. }
  8369. static void JimVariablesHTValDestructor(void *interp, void *val)
  8370. {
  8371. JimDecrVarRef(interp, val);
  8372. }
  8373. static unsigned int JimObjectHTHashFunction(const void *key)
  8374. {
  8375. Jim_Obj *keyObj = (Jim_Obj *)key;
  8376. int length;
  8377. const char *string;
  8378. #ifdef JIM_OPTIMIZATION
  8379. if (JimIsWide(keyObj) && keyObj->bytes == NULL) {
  8380. jim_wide objValue = JimWideValue(keyObj);
  8381. if (objValue > INT_MIN && objValue < INT_MAX) {
  8382. unsigned result = 0;
  8383. unsigned value = (unsigned)objValue;
  8384. if (objValue < 0) {
  8385. value = (unsigned)-objValue;
  8386. }
  8387. do {
  8388. result += (result << 3) + (value % 10 + '0');
  8389. value /= 10;
  8390. } while (value);
  8391. if (objValue < 0) {
  8392. result += (result << 3) + '-';
  8393. }
  8394. return result;
  8395. }
  8396. }
  8397. #endif
  8398. string = Jim_GetString(keyObj, &length);
  8399. return Jim_GenHashFunction((const unsigned char *)string, length);
  8400. }
  8401. static int JimObjectHTKeyCompare(void *privdata, const void *key1, const void *key2)
  8402. {
  8403. return Jim_StringEqObj((Jim_Obj *)key1, (Jim_Obj *)key2);
  8404. }
  8405. static void *JimObjectHTKeyValDup(void *privdata, const void *val)
  8406. {
  8407. Jim_IncrRefCount((Jim_Obj *)val);
  8408. return (void *)val;
  8409. }
  8410. static void JimObjectHTKeyValDestructor(void *interp, void *val)
  8411. {
  8412. Jim_DecrRefCount(interp, (Jim_Obj *)val);
  8413. }
  8414. static void *JimVariablesHTValDup(void *privdata, const void *val)
  8415. {
  8416. JimIncrVarRef((Jim_VarVal *)val);
  8417. return (void *)val;
  8418. }
  8419. static const Jim_HashTableType JimVariablesHashTableType = {
  8420. JimObjectHTHashFunction,
  8421. JimObjectHTKeyValDup,
  8422. JimVariablesHTValDup,
  8423. JimObjectHTKeyCompare,
  8424. JimObjectHTKeyValDestructor,
  8425. JimVariablesHTValDestructor
  8426. };
  8427. static const char *Jim_GetStringNoQualifier(Jim_Obj *objPtr, int *length)
  8428. {
  8429. int len;
  8430. const char *str = Jim_GetString(objPtr, &len);
  8431. if (len >= 2 && str[0] == ':' && str[1] == ':') {
  8432. while (len && *str == ':') {
  8433. len--;
  8434. str++;
  8435. }
  8436. }
  8437. *length = len;
  8438. return str;
  8439. }
  8440. static unsigned int JimCommandsHT_HashFunction(const void *key)
  8441. {
  8442. int len;
  8443. const char *str = Jim_GetStringNoQualifier((Jim_Obj *)key, &len);
  8444. return Jim_GenHashFunction((const unsigned char *)str, len);
  8445. }
  8446. static int JimCommandsHT_KeyCompare(void *privdata, const void *key1, const void *key2)
  8447. {
  8448. int len1, len2;
  8449. const char *str1 = Jim_GetStringNoQualifier((Jim_Obj *)key1, &len1);
  8450. const char *str2 = Jim_GetStringNoQualifier((Jim_Obj *)key2, &len2);
  8451. return len1 == len2 && memcmp(str1, str2, len1) == 0;
  8452. }
  8453. static void JimCommandsHT_ValDestructor(void *interp, void *val)
  8454. {
  8455. JimDecrCmdRefCount(interp, val);
  8456. }
  8457. static const Jim_HashTableType JimCommandsHashTableType = {
  8458. JimCommandsHT_HashFunction,
  8459. JimObjectHTKeyValDup,
  8460. NULL,
  8461. JimCommandsHT_KeyCompare,
  8462. JimObjectHTKeyValDestructor,
  8463. JimCommandsHT_ValDestructor
  8464. };
  8465. Jim_Obj *Jim_MakeGlobalNamespaceName(Jim_Interp *interp, Jim_Obj *nameObjPtr)
  8466. {
  8467. #ifdef jim_ext_namespace
  8468. Jim_Obj *resultObj;
  8469. const char *name = Jim_String(nameObjPtr);
  8470. if (name[0] == ':' && name[1] == ':') {
  8471. return nameObjPtr;
  8472. }
  8473. Jim_IncrRefCount(nameObjPtr);
  8474. resultObj = Jim_NewStringObj(interp, "::", -1);
  8475. Jim_AppendObj(interp, resultObj, nameObjPtr);
  8476. Jim_DecrRefCount(interp, nameObjPtr);
  8477. return resultObj;
  8478. #else
  8479. return nameObjPtr;
  8480. #endif
  8481. }
  8482. static Jim_Obj *JimQualifyName(Jim_Interp *interp, Jim_Obj *objPtr)
  8483. {
  8484. #ifdef jim_ext_namespace
  8485. if (Jim_Length(interp->framePtr->nsObj)) {
  8486. int len;
  8487. const char *name = Jim_GetString(objPtr, &len);
  8488. if (len < 2 || name[0] != ':' || name[1] != ':') {
  8489. objPtr = Jim_DuplicateObj(interp, interp->framePtr->nsObj);
  8490. Jim_AppendStrings(interp, objPtr, "::", name, NULL);
  8491. }
  8492. }
  8493. #endif
  8494. Jim_IncrRefCount(objPtr);
  8495. return objPtr;
  8496. }
  8497. static void JimCreateCommand(Jim_Interp *interp, Jim_Obj *nameObjPtr, Jim_Cmd *cmd)
  8498. {
  8499. JimPanic((nameObjPtr->refCount == 0, "JimCreateCommand called with zero ref count name"));
  8500. if (interp->local) {
  8501. Jim_HashEntry *he = Jim_FindHashEntry(&interp->commands, nameObjPtr);
  8502. if (he) {
  8503. cmd->prevCmd = Jim_GetHashEntryVal(he);
  8504. Jim_SetHashVal(&interp->commands, he, cmd);
  8505. Jim_InterpIncrProcEpoch(interp);
  8506. return;
  8507. }
  8508. }
  8509. Jim_ReplaceHashEntry(&interp->commands, nameObjPtr, cmd);
  8510. }
  8511. int Jim_CreateCommandObj(Jim_Interp *interp, Jim_Obj *cmdNameObj,
  8512. Jim_CmdProc *cmdProc, void *privData, Jim_DelCmdProc *delProc)
  8513. {
  8514. Jim_Cmd *cmdPtr = Jim_Alloc(sizeof(*cmdPtr));
  8515. memset(cmdPtr, 0, sizeof(*cmdPtr));
  8516. cmdPtr->inUse = 1;
  8517. cmdPtr->u.native.delProc = delProc;
  8518. cmdPtr->u.native.cmdProc = cmdProc;
  8519. cmdPtr->u.native.privData = privData;
  8520. Jim_IncrRefCount(cmdNameObj);
  8521. JimCreateCommand(interp, cmdNameObj, cmdPtr);
  8522. Jim_DecrRefCount(interp, cmdNameObj);
  8523. return JIM_OK;
  8524. }
  8525. int Jim_CreateCommand(Jim_Interp *interp, const char *cmdNameStr,
  8526. Jim_CmdProc *cmdProc, void *privData, Jim_DelCmdProc *delProc)
  8527. {
  8528. return Jim_CreateCommandObj(interp, Jim_NewStringObj(interp, cmdNameStr, -1), cmdProc, privData, delProc);
  8529. }
  8530. static int JimCreateProcedureStatics(Jim_Interp *interp, Jim_Cmd *cmdPtr, Jim_Obj *staticsListObjPtr)
  8531. {
  8532. int len, i;
  8533. len = Jim_ListLength(interp, staticsListObjPtr);
  8534. if (len == 0) {
  8535. return JIM_OK;
  8536. }
  8537. cmdPtr->u.proc.staticVars = Jim_Alloc(sizeof(Jim_HashTable));
  8538. Jim_InitHashTable(cmdPtr->u.proc.staticVars, &JimVariablesHashTableType, interp);
  8539. for (i = 0; i < len; i++) {
  8540. Jim_Obj *initObjPtr = NULL;
  8541. Jim_Obj *nameObjPtr;
  8542. Jim_VarVal *vv = NULL;
  8543. Jim_Obj *objPtr = Jim_ListGetIndex(interp, staticsListObjPtr, i);
  8544. int subLen = Jim_ListLength(interp, objPtr);
  8545. int byref = 0;
  8546. if (subLen != 1 && subLen != 2) {
  8547. Jim_SetResultFormatted(interp, "too many fields in static specifier \"%#s\"",
  8548. objPtr);
  8549. return JIM_ERR;
  8550. }
  8551. nameObjPtr = Jim_ListGetIndex(interp, objPtr, 0);
  8552. if (subLen == 1) {
  8553. int len;
  8554. const char *pt = Jim_GetString(nameObjPtr, &len);
  8555. if (*pt == '&') {
  8556. nameObjPtr = Jim_NewStringObj(interp, pt + 1, len - 1);
  8557. byref = 1;
  8558. }
  8559. }
  8560. Jim_IncrRefCount(nameObjPtr);
  8561. if (subLen == 1) {
  8562. switch (SetVariableFromAny(interp, nameObjPtr)) {
  8563. case JIM_DICT_SUGAR:
  8564. if (byref) {
  8565. Jim_SetResultFormatted(interp, "Can't link to array element \"%#s\"", nameObjPtr);
  8566. }
  8567. else {
  8568. Jim_SetResultFormatted(interp, "Can't initialise array element \"%#s\"", nameObjPtr);
  8569. }
  8570. Jim_DecrRefCount(interp, nameObjPtr);
  8571. return JIM_ERR;
  8572. case JIM_OK:
  8573. if (byref) {
  8574. vv = nameObjPtr->internalRep.varValue.vv;
  8575. }
  8576. else {
  8577. initObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_NONE);
  8578. }
  8579. break;
  8580. case JIM_ERR:
  8581. Jim_SetResultFormatted(interp,
  8582. "variable for initialization of static \"%#s\" not found in the local context",
  8583. nameObjPtr);
  8584. Jim_DecrRefCount(interp, nameObjPtr);
  8585. return JIM_ERR;
  8586. }
  8587. }
  8588. else {
  8589. initObjPtr = Jim_ListGetIndex(interp, objPtr, 1);
  8590. }
  8591. if (vv == NULL) {
  8592. vv = Jim_Alloc(sizeof(*vv));
  8593. vv->objPtr = initObjPtr;
  8594. Jim_IncrRefCount(vv->objPtr);
  8595. vv->linkFramePtr = NULL;
  8596. vv->refCount = 0;
  8597. }
  8598. if (JimSetNewVariable(cmdPtr->u.proc.staticVars, nameObjPtr, vv) != JIM_OK) {
  8599. Jim_SetResultFormatted(interp,
  8600. "static variable name \"%#s\" duplicated in statics list", nameObjPtr);
  8601. JimIncrVarRef(vv);
  8602. JimDecrVarRef(interp, vv);
  8603. Jim_DecrRefCount(interp, nameObjPtr);
  8604. return JIM_ERR;
  8605. }
  8606. Jim_DecrRefCount(interp, nameObjPtr);
  8607. }
  8608. return JIM_OK;
  8609. }
  8610. #ifdef jim_ext_namespace
  8611. static const char *Jim_memrchr(const char *p, int c, int len)
  8612. {
  8613. int i;
  8614. for (i = len; i > 0; i--) {
  8615. if (p[i] == c) {
  8616. return p + i;
  8617. }
  8618. }
  8619. return NULL;
  8620. }
  8621. #endif
  8622. static void JimUpdateProcNamespace(Jim_Interp *interp, Jim_Cmd *cmdPtr, Jim_Obj *nameObjPtr)
  8623. {
  8624. #ifdef jim_ext_namespace
  8625. if (cmdPtr->isproc) {
  8626. int len;
  8627. const char *cmdname = Jim_GetStringNoQualifier(nameObjPtr, &len);
  8628. const char *pt = Jim_memrchr(cmdname, ':', len);
  8629. if (pt && pt != cmdname && pt[-1] == ':') {
  8630. pt++;
  8631. Jim_DecrRefCount(interp, cmdPtr->u.proc.nsObj);
  8632. cmdPtr->u.proc.nsObj = Jim_NewStringObj(interp, cmdname, pt - cmdname - 2);
  8633. Jim_IncrRefCount(cmdPtr->u.proc.nsObj);
  8634. Jim_Obj *tempObj = Jim_NewStringObj(interp, pt, len - (pt - cmdname));
  8635. if (Jim_FindHashEntry(&interp->commands, tempObj)) {
  8636. Jim_InterpIncrProcEpoch(interp);
  8637. }
  8638. Jim_FreeNewObj(interp, tempObj);
  8639. }
  8640. }
  8641. #endif
  8642. }
  8643. static Jim_Cmd *JimCreateProcedureCmd(Jim_Interp *interp, Jim_Obj *argListObjPtr,
  8644. Jim_Obj *staticsListObjPtr, Jim_Obj *bodyObjPtr, Jim_Obj *nsObj)
  8645. {
  8646. Jim_Cmd *cmdPtr;
  8647. int argListLen;
  8648. int i;
  8649. argListLen = Jim_ListLength(interp, argListObjPtr);
  8650. cmdPtr = Jim_Alloc(sizeof(*cmdPtr) + sizeof(struct Jim_ProcArg) * argListLen);
  8651. assert(cmdPtr);
  8652. memset(cmdPtr, 0, sizeof(*cmdPtr));
  8653. cmdPtr->inUse = 1;
  8654. cmdPtr->isproc = 1;
  8655. cmdPtr->u.proc.argListObjPtr = argListObjPtr;
  8656. cmdPtr->u.proc.argListLen = argListLen;
  8657. cmdPtr->u.proc.bodyObjPtr = bodyObjPtr;
  8658. cmdPtr->u.proc.argsPos = -1;
  8659. cmdPtr->u.proc.arglist = (struct Jim_ProcArg *)(cmdPtr + 1);
  8660. cmdPtr->u.proc.nsObj = nsObj ? nsObj : interp->emptyObj;
  8661. Jim_IncrRefCount(argListObjPtr);
  8662. Jim_IncrRefCount(bodyObjPtr);
  8663. Jim_IncrRefCount(cmdPtr->u.proc.nsObj);
  8664. if (staticsListObjPtr && JimCreateProcedureStatics(interp, cmdPtr, staticsListObjPtr) != JIM_OK) {
  8665. goto err;
  8666. }
  8667. for (i = 0; i < argListLen; i++) {
  8668. Jim_Obj *argPtr;
  8669. Jim_Obj *nameObjPtr;
  8670. Jim_Obj *defaultObjPtr;
  8671. int len;
  8672. argPtr = Jim_ListGetIndex(interp, argListObjPtr, i);
  8673. len = Jim_ListLength(interp, argPtr);
  8674. if (len == 0) {
  8675. Jim_SetResultString(interp, "argument with no name", -1);
  8676. err:
  8677. JimDecrCmdRefCount(interp, cmdPtr);
  8678. return NULL;
  8679. }
  8680. if (len > 2) {
  8681. Jim_SetResultFormatted(interp, "too many fields in argument specifier \"%#s\"", argPtr);
  8682. goto err;
  8683. }
  8684. if (len == 2) {
  8685. nameObjPtr = Jim_ListGetIndex(interp, argPtr, 0);
  8686. defaultObjPtr = Jim_ListGetIndex(interp, argPtr, 1);
  8687. }
  8688. else {
  8689. nameObjPtr = argPtr;
  8690. defaultObjPtr = NULL;
  8691. }
  8692. if (Jim_CompareStringImmediate(interp, nameObjPtr, "args")) {
  8693. if (cmdPtr->u.proc.argsPos >= 0) {
  8694. Jim_SetResultString(interp, "'args' specified more than once", -1);
  8695. goto err;
  8696. }
  8697. cmdPtr->u.proc.argsPos = i;
  8698. }
  8699. else {
  8700. if (len == 2) {
  8701. cmdPtr->u.proc.optArity++;
  8702. }
  8703. else {
  8704. cmdPtr->u.proc.reqArity++;
  8705. }
  8706. }
  8707. cmdPtr->u.proc.arglist[i].nameObjPtr = nameObjPtr;
  8708. cmdPtr->u.proc.arglist[i].defaultObjPtr = defaultObjPtr;
  8709. }
  8710. return cmdPtr;
  8711. }
  8712. int Jim_DeleteCommand(Jim_Interp *interp, Jim_Obj *nameObj)
  8713. {
  8714. int ret = JIM_OK;
  8715. nameObj = JimQualifyName(interp, nameObj);
  8716. if (Jim_DeleteHashEntry(&interp->commands, nameObj) == JIM_ERR) {
  8717. Jim_SetResultFormatted(interp, "can't delete \"%#s\": command doesn't exist", nameObj);
  8718. ret = JIM_ERR;
  8719. }
  8720. Jim_DecrRefCount(interp, nameObj);
  8721. return ret;
  8722. }
  8723. int Jim_RenameCommand(Jim_Interp *interp, Jim_Obj *oldNameObj, Jim_Obj *newNameObj)
  8724. {
  8725. int ret = JIM_ERR;
  8726. Jim_HashEntry *he;
  8727. Jim_Cmd *cmdPtr;
  8728. if (Jim_Length(newNameObj) == 0) {
  8729. return Jim_DeleteCommand(interp, oldNameObj);
  8730. }
  8731. oldNameObj = JimQualifyName(interp, oldNameObj);
  8732. newNameObj = JimQualifyName(interp, newNameObj);
  8733. he = Jim_FindHashEntry(&interp->commands, oldNameObj);
  8734. if (he == NULL) {
  8735. Jim_SetResultFormatted(interp, "can't rename \"%#s\": command doesn't exist", oldNameObj);
  8736. }
  8737. else if (Jim_FindHashEntry(&interp->commands, newNameObj)) {
  8738. Jim_SetResultFormatted(interp, "can't rename to \"%#s\": command already exists", newNameObj);
  8739. }
  8740. else {
  8741. cmdPtr = Jim_GetHashEntryVal(he);
  8742. if (cmdPtr->prevCmd) {
  8743. Jim_SetResultFormatted(interp, "can't rename local command \"%#s\"", oldNameObj);
  8744. }
  8745. else {
  8746. JimIncrCmdRefCount(cmdPtr);
  8747. JimUpdateProcNamespace(interp, cmdPtr, newNameObj);
  8748. Jim_AddHashEntry(&interp->commands, newNameObj, cmdPtr);
  8749. Jim_DeleteHashEntry(&interp->commands, oldNameObj);
  8750. Jim_InterpIncrProcEpoch(interp);
  8751. ret = JIM_OK;
  8752. }
  8753. }
  8754. Jim_DecrRefCount(interp, oldNameObj);
  8755. Jim_DecrRefCount(interp, newNameObj);
  8756. return ret;
  8757. }
  8758. static void FreeCommandInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
  8759. {
  8760. Jim_DecrRefCount(interp, objPtr->internalRep.cmdValue.nsObj);
  8761. }
  8762. static void DupCommandInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
  8763. {
  8764. dupPtr->internalRep.cmdValue = srcPtr->internalRep.cmdValue;
  8765. dupPtr->typePtr = srcPtr->typePtr;
  8766. Jim_IncrRefCount(dupPtr->internalRep.cmdValue.nsObj);
  8767. }
  8768. static const Jim_ObjType commandObjType = {
  8769. "command",
  8770. FreeCommandInternalRep,
  8771. DupCommandInternalRep,
  8772. NULL,
  8773. JIM_TYPE_REFERENCES,
  8774. };
  8775. Jim_Cmd *Jim_GetCommand(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
  8776. {
  8777. Jim_Cmd *cmd;
  8778. if (objPtr->typePtr == &commandObjType
  8779. && objPtr->internalRep.cmdValue.procEpoch == interp->procEpoch
  8780. #ifdef jim_ext_namespace
  8781. && Jim_StringEqObj(objPtr->internalRep.cmdValue.nsObj, interp->framePtr->nsObj)
  8782. #endif
  8783. && objPtr->internalRep.cmdValue.cmdPtr->inUse) {
  8784. cmd = objPtr->internalRep.cmdValue.cmdPtr;
  8785. }
  8786. else {
  8787. Jim_Obj *qualifiedNameObj = JimQualifyName(interp, objPtr);
  8788. Jim_HashEntry *he = Jim_FindHashEntry(&interp->commands, qualifiedNameObj);
  8789. #ifdef jim_ext_namespace
  8790. if (he == NULL && Jim_Length(interp->framePtr->nsObj)) {
  8791. he = Jim_FindHashEntry(&interp->commands, objPtr);
  8792. }
  8793. #endif
  8794. if (he == NULL) {
  8795. if (flags & JIM_ERRMSG) {
  8796. Jim_SetResultFormatted(interp, "invalid command name \"%#s\"", objPtr);
  8797. }
  8798. Jim_DecrRefCount(interp, qualifiedNameObj);
  8799. return NULL;
  8800. }
  8801. cmd = Jim_GetHashEntryVal(he);
  8802. cmd->cmdNameObj = Jim_GetHashEntryKey(he);
  8803. Jim_FreeIntRep(interp, objPtr);
  8804. objPtr->typePtr = &commandObjType;
  8805. objPtr->internalRep.cmdValue.procEpoch = interp->procEpoch;
  8806. objPtr->internalRep.cmdValue.cmdPtr = cmd;
  8807. objPtr->internalRep.cmdValue.nsObj = interp->framePtr->nsObj;
  8808. Jim_IncrRefCount(interp->framePtr->nsObj);
  8809. Jim_DecrRefCount(interp, qualifiedNameObj);
  8810. }
  8811. while (cmd->u.proc.upcall) {
  8812. cmd = cmd->prevCmd;
  8813. }
  8814. return cmd;
  8815. }
  8816. static const Jim_ObjType variableObjType = {
  8817. "variable",
  8818. NULL,
  8819. NULL,
  8820. NULL,
  8821. JIM_TYPE_REFERENCES,
  8822. };
  8823. static int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
  8824. {
  8825. const char *varName;
  8826. Jim_CallFrame *framePtr;
  8827. int global;
  8828. int len;
  8829. Jim_VarVal *vv;
  8830. if (objPtr->typePtr == &variableObjType) {
  8831. framePtr = objPtr->internalRep.varValue.global ? interp->topFramePtr : interp->framePtr;
  8832. if (objPtr->internalRep.varValue.callFrameId == framePtr->id) {
  8833. return JIM_OK;
  8834. }
  8835. }
  8836. else if (objPtr->typePtr == &dictSubstObjType) {
  8837. return JIM_DICT_SUGAR;
  8838. }
  8839. varName = Jim_GetString(objPtr, &len);
  8840. if (len && varName[len - 1] == ')' && strchr(varName, '(') != NULL) {
  8841. return JIM_DICT_SUGAR;
  8842. }
  8843. if (varName[0] == ':' && varName[1] == ':') {
  8844. while (*varName == ':') {
  8845. varName++;
  8846. len--;
  8847. }
  8848. global = 1;
  8849. framePtr = interp->topFramePtr;
  8850. Jim_Obj *tempObj = Jim_NewStringObj(interp, varName, len);
  8851. vv = JimFindVariable(&framePtr->vars, tempObj);
  8852. Jim_FreeNewObj(interp, tempObj);
  8853. }
  8854. else {
  8855. global = 0;
  8856. framePtr = interp->framePtr;
  8857. vv = JimFindVariable(&framePtr->vars, objPtr);
  8858. if (vv == NULL && framePtr->staticVars) {
  8859. vv = JimFindVariable(framePtr->staticVars, objPtr);
  8860. }
  8861. }
  8862. if (vv == NULL) {
  8863. return JIM_ERR;
  8864. }
  8865. Jim_FreeIntRep(interp, objPtr);
  8866. objPtr->typePtr = &variableObjType;
  8867. objPtr->internalRep.varValue.callFrameId = framePtr->id;
  8868. objPtr->internalRep.varValue.vv = vv;
  8869. objPtr->internalRep.varValue.global = global;
  8870. return JIM_OK;
  8871. }
  8872. static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *ObjPtr, Jim_Obj *valObjPtr);
  8873. static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *ObjPtr, int flags);
  8874. static int JimSetNewVariable(Jim_HashTable *ht, Jim_Obj *nameObjPtr, Jim_VarVal *vv)
  8875. {
  8876. return Jim_AddHashEntry(ht, nameObjPtr, vv);
  8877. }
  8878. static Jim_VarVal *JimFindVariable(Jim_HashTable *ht, Jim_Obj *nameObjPtr)
  8879. {
  8880. Jim_HashEntry *he = Jim_FindHashEntry(ht, nameObjPtr);
  8881. if (he) {
  8882. return (Jim_VarVal *)Jim_GetHashEntryVal(he);
  8883. }
  8884. return NULL;
  8885. }
  8886. static int JimUnsetVariable(Jim_HashTable *ht, Jim_Obj *nameObjPtr)
  8887. {
  8888. return Jim_DeleteHashEntry(ht, nameObjPtr);
  8889. }
  8890. static Jim_VarVal *JimCreateVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr)
  8891. {
  8892. const char *name;
  8893. Jim_CallFrame *framePtr;
  8894. int global;
  8895. int len;
  8896. Jim_VarVal *vv = Jim_Alloc(sizeof(*vv));
  8897. vv->objPtr = valObjPtr;
  8898. Jim_IncrRefCount(valObjPtr);
  8899. vv->linkFramePtr = NULL;
  8900. vv->refCount = 0;
  8901. name = Jim_GetString(nameObjPtr, &len);
  8902. if (name[0] == ':' && name[1] == ':') {
  8903. while (*name == ':') {
  8904. name++;
  8905. len--;
  8906. }
  8907. framePtr = interp->topFramePtr;
  8908. global = 1;
  8909. JimSetNewVariable(&framePtr->vars, Jim_NewStringObj(interp, name, len), vv);
  8910. }
  8911. else {
  8912. framePtr = interp->framePtr;
  8913. global = 0;
  8914. JimSetNewVariable(&framePtr->vars, nameObjPtr, vv);
  8915. }
  8916. Jim_FreeIntRep(interp, nameObjPtr);
  8917. nameObjPtr->typePtr = &variableObjType;
  8918. nameObjPtr->internalRep.varValue.callFrameId = framePtr->id;
  8919. nameObjPtr->internalRep.varValue.vv = vv;
  8920. nameObjPtr->internalRep.varValue.global = global;
  8921. return vv;
  8922. }
  8923. int Jim_SetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr)
  8924. {
  8925. int err;
  8926. Jim_VarVal *vv;
  8927. switch (SetVariableFromAny(interp, nameObjPtr)) {
  8928. case JIM_DICT_SUGAR:
  8929. return JimDictSugarSet(interp, nameObjPtr, valObjPtr);
  8930. case JIM_ERR:
  8931. JimCreateVariable(interp, nameObjPtr, valObjPtr);
  8932. break;
  8933. case JIM_OK:
  8934. vv = nameObjPtr->internalRep.varValue.vv;
  8935. if (vv->linkFramePtr == NULL) {
  8936. Jim_IncrRefCount(valObjPtr);
  8937. Jim_DecrRefCount(interp, vv->objPtr);
  8938. vv->objPtr = valObjPtr;
  8939. }
  8940. else {
  8941. Jim_CallFrame *savedCallFrame;
  8942. savedCallFrame = interp->framePtr;
  8943. interp->framePtr = vv->linkFramePtr;
  8944. err = Jim_SetVariable(interp, vv->objPtr, valObjPtr);
  8945. interp->framePtr = savedCallFrame;
  8946. if (err != JIM_OK)
  8947. return err;
  8948. }
  8949. }
  8950. return JIM_OK;
  8951. }
  8952. int Jim_SetVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)
  8953. {
  8954. Jim_Obj *nameObjPtr;
  8955. int result;
  8956. nameObjPtr = Jim_NewStringObj(interp, name, -1);
  8957. Jim_IncrRefCount(nameObjPtr);
  8958. result = Jim_SetVariable(interp, nameObjPtr, objPtr);
  8959. Jim_DecrRefCount(interp, nameObjPtr);
  8960. return result;
  8961. }
  8962. int Jim_SetGlobalVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)
  8963. {
  8964. Jim_CallFrame *savedFramePtr;
  8965. int result;
  8966. savedFramePtr = interp->framePtr;
  8967. interp->framePtr = interp->topFramePtr;
  8968. result = Jim_SetVariableStr(interp, name, objPtr);
  8969. interp->framePtr = savedFramePtr;
  8970. return result;
  8971. }
  8972. int Jim_SetVariableStrWithStr(Jim_Interp *interp, const char *name, const char *val)
  8973. {
  8974. Jim_Obj *valObjPtr;
  8975. int result;
  8976. valObjPtr = Jim_NewStringObj(interp, val, -1);
  8977. Jim_IncrRefCount(valObjPtr);
  8978. result = Jim_SetVariableStr(interp, name, valObjPtr);
  8979. Jim_DecrRefCount(interp, valObjPtr);
  8980. return result;
  8981. }
  8982. int Jim_SetVariableLink(Jim_Interp *interp, Jim_Obj *nameObjPtr,
  8983. Jim_Obj *targetNameObjPtr, Jim_CallFrame *targetCallFrame)
  8984. {
  8985. const char *varName;
  8986. const char *targetName;
  8987. Jim_CallFrame *framePtr;
  8988. Jim_VarVal *vv;
  8989. int len;
  8990. int varnamelen;
  8991. switch (SetVariableFromAny(interp, nameObjPtr)) {
  8992. case JIM_DICT_SUGAR:
  8993. Jim_SetResultFormatted(interp, "bad variable name \"%#s\": upvar won't create a scalar variable that looks like an array element", nameObjPtr);
  8994. return JIM_ERR;
  8995. case JIM_OK:
  8996. vv = nameObjPtr->internalRep.varValue.vv;
  8997. if (vv->linkFramePtr == NULL) {
  8998. Jim_SetResultFormatted(interp, "variable \"%#s\" already exists", nameObjPtr);
  8999. return JIM_ERR;
  9000. }
  9001. vv->linkFramePtr = NULL;
  9002. break;
  9003. }
  9004. varName = Jim_GetString(nameObjPtr, &varnamelen);
  9005. if (varName[0] == ':' && varName[1] == ':') {
  9006. while (*varName == ':') {
  9007. varName++;
  9008. varnamelen--;
  9009. }
  9010. framePtr = interp->topFramePtr;
  9011. }
  9012. else {
  9013. framePtr = interp->framePtr;
  9014. }
  9015. targetName = Jim_GetString(targetNameObjPtr, &len);
  9016. if (targetName[0] == ':' && targetName[1] == ':') {
  9017. while (*targetName == ':') {
  9018. targetName++;
  9019. len--;
  9020. }
  9021. targetNameObjPtr = Jim_NewStringObj(interp, targetName, len);
  9022. targetCallFrame = interp->topFramePtr;
  9023. }
  9024. Jim_IncrRefCount(targetNameObjPtr);
  9025. if (framePtr->level < targetCallFrame->level) {
  9026. Jim_SetResultFormatted(interp,
  9027. "bad variable name \"%#s\": upvar won't create namespace variable that refers to procedure variable",
  9028. nameObjPtr);
  9029. Jim_DecrRefCount(interp, targetNameObjPtr);
  9030. return JIM_ERR;
  9031. }
  9032. if (framePtr == targetCallFrame) {
  9033. Jim_Obj *objPtr = targetNameObjPtr;
  9034. while (1) {
  9035. if (Jim_Length(objPtr) == varnamelen && memcmp(Jim_String(objPtr), varName, varnamelen) == 0) {
  9036. Jim_SetResultString(interp, "can't upvar from variable to itself", -1);
  9037. Jim_DecrRefCount(interp, targetNameObjPtr);
  9038. return JIM_ERR;
  9039. }
  9040. if (SetVariableFromAny(interp, objPtr) != JIM_OK)
  9041. break;
  9042. vv = objPtr->internalRep.varValue.vv;
  9043. if (vv->linkFramePtr != targetCallFrame)
  9044. break;
  9045. objPtr = vv->objPtr;
  9046. }
  9047. }
  9048. Jim_SetVariable(interp, nameObjPtr, targetNameObjPtr);
  9049. nameObjPtr->internalRep.varValue.vv->linkFramePtr = targetCallFrame;
  9050. Jim_DecrRefCount(interp, targetNameObjPtr);
  9051. return JIM_OK;
  9052. }
  9053. Jim_Obj *Jim_GetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
  9054. {
  9055. if (interp->safeexpr) {
  9056. return nameObjPtr;
  9057. }
  9058. switch (SetVariableFromAny(interp, nameObjPtr)) {
  9059. case JIM_OK:{
  9060. Jim_VarVal *vv = nameObjPtr->internalRep.varValue.vv;
  9061. if (vv->linkFramePtr == NULL) {
  9062. return vv->objPtr;
  9063. }
  9064. else {
  9065. Jim_Obj *objPtr;
  9066. Jim_CallFrame *savedCallFrame = interp->framePtr;
  9067. interp->framePtr = vv->linkFramePtr;
  9068. objPtr = Jim_GetVariable(interp, vv->objPtr, flags);
  9069. interp->framePtr = savedCallFrame;
  9070. if (objPtr) {
  9071. return objPtr;
  9072. }
  9073. }
  9074. }
  9075. break;
  9076. case JIM_DICT_SUGAR:
  9077. return JimDictSugarGet(interp, nameObjPtr, flags);
  9078. }
  9079. if (flags & JIM_ERRMSG) {
  9080. Jim_SetResultFormatted(interp, "can't read \"%#s\": no such variable", nameObjPtr);
  9081. }
  9082. return NULL;
  9083. }
  9084. Jim_Obj *Jim_GetGlobalVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
  9085. {
  9086. Jim_CallFrame *savedFramePtr;
  9087. Jim_Obj *objPtr;
  9088. savedFramePtr = interp->framePtr;
  9089. interp->framePtr = interp->topFramePtr;
  9090. objPtr = Jim_GetVariable(interp, nameObjPtr, flags);
  9091. interp->framePtr = savedFramePtr;
  9092. return objPtr;
  9093. }
  9094. Jim_Obj *Jim_GetVariableStr(Jim_Interp *interp, const char *name, int flags)
  9095. {
  9096. Jim_Obj *nameObjPtr, *varObjPtr;
  9097. nameObjPtr = Jim_NewStringObj(interp, name, -1);
  9098. Jim_IncrRefCount(nameObjPtr);
  9099. varObjPtr = Jim_GetVariable(interp, nameObjPtr, flags);
  9100. Jim_DecrRefCount(interp, nameObjPtr);
  9101. return varObjPtr;
  9102. }
  9103. Jim_Obj *Jim_GetGlobalVariableStr(Jim_Interp *interp, const char *name, int flags)
  9104. {
  9105. Jim_CallFrame *savedFramePtr;
  9106. Jim_Obj *objPtr;
  9107. savedFramePtr = interp->framePtr;
  9108. interp->framePtr = interp->topFramePtr;
  9109. objPtr = Jim_GetVariableStr(interp, name, flags);
  9110. interp->framePtr = savedFramePtr;
  9111. return objPtr;
  9112. }
  9113. int Jim_UnsetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
  9114. {
  9115. Jim_VarVal *vv;
  9116. int retval;
  9117. Jim_CallFrame *framePtr;
  9118. retval = SetVariableFromAny(interp, nameObjPtr);
  9119. if (retval == JIM_DICT_SUGAR) {
  9120. return JimDictSugarSet(interp, nameObjPtr, NULL);
  9121. }
  9122. else if (retval == JIM_OK) {
  9123. vv = nameObjPtr->internalRep.varValue.vv;
  9124. if (vv->linkFramePtr) {
  9125. framePtr = interp->framePtr;
  9126. interp->framePtr = vv->linkFramePtr;
  9127. retval = Jim_UnsetVariable(interp, vv->objPtr, JIM_NONE);
  9128. interp->framePtr = framePtr;
  9129. }
  9130. else {
  9131. if (nameObjPtr->internalRep.varValue.global) {
  9132. int len;
  9133. const char *name = Jim_GetString(nameObjPtr, &len);
  9134. while (*name == ':') {
  9135. name++;
  9136. len--;
  9137. }
  9138. framePtr = interp->topFramePtr;
  9139. Jim_Obj *tempObj = Jim_NewStringObj(interp, name, len);
  9140. retval = JimUnsetVariable(&framePtr->vars, tempObj);
  9141. Jim_FreeNewObj(interp, tempObj);
  9142. }
  9143. else {
  9144. framePtr = interp->framePtr;
  9145. retval = JimUnsetVariable(&framePtr->vars, nameObjPtr);
  9146. }
  9147. if (retval == JIM_OK) {
  9148. framePtr->id = interp->callFrameEpoch++;
  9149. }
  9150. }
  9151. }
  9152. if (retval != JIM_OK && (flags & JIM_ERRMSG)) {
  9153. Jim_SetResultFormatted(interp, "can't unset \"%#s\": no such variable", nameObjPtr);
  9154. }
  9155. return retval;
  9156. }
  9157. static void JimDictSugarParseVarKey(Jim_Interp *interp, Jim_Obj *objPtr,
  9158. Jim_Obj **varPtrPtr, Jim_Obj **keyPtrPtr)
  9159. {
  9160. const char *str, *p;
  9161. int len, keyLen;
  9162. Jim_Obj *varObjPtr, *keyObjPtr;
  9163. str = Jim_GetString(objPtr, &len);
  9164. p = strchr(str, '(');
  9165. JimPanic((p == NULL, "JimDictSugarParseVarKey() called for non-dict-sugar (%s)", str));
  9166. varObjPtr = Jim_NewStringObj(interp, str, p - str);
  9167. p++;
  9168. keyLen = (str + len) - p;
  9169. if (str[len - 1] == ')') {
  9170. keyLen--;
  9171. }
  9172. keyObjPtr = Jim_NewStringObj(interp, p, keyLen);
  9173. Jim_IncrRefCount(varObjPtr);
  9174. Jim_IncrRefCount(keyObjPtr);
  9175. *varPtrPtr = varObjPtr;
  9176. *keyPtrPtr = keyObjPtr;
  9177. }
  9178. static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *valObjPtr)
  9179. {
  9180. int err;
  9181. SetDictSubstFromAny(interp, objPtr);
  9182. err = Jim_SetDictKeysVector(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr,
  9183. &objPtr->internalRep.dictSubstValue.indexObjPtr, 1, valObjPtr, JIM_MUSTEXIST);
  9184. if (err == JIM_OK) {
  9185. Jim_SetEmptyResult(interp);
  9186. }
  9187. else {
  9188. if (!valObjPtr) {
  9189. if (Jim_GetVariable(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr, JIM_NONE)) {
  9190. Jim_SetResultFormatted(interp, "can't unset \"%#s\": no such element in array",
  9191. objPtr);
  9192. return err;
  9193. }
  9194. }
  9195. Jim_SetResultFormatted(interp, "can't %s \"%#s\": variable isn't array",
  9196. (valObjPtr ? "set" : "unset"), objPtr);
  9197. }
  9198. return err;
  9199. }
  9200. static Jim_Obj *JimDictExpandArrayVariable(Jim_Interp *interp, Jim_Obj *varObjPtr,
  9201. Jim_Obj *keyObjPtr, int flags)
  9202. {
  9203. Jim_Obj *dictObjPtr;
  9204. Jim_Obj *resObjPtr = NULL;
  9205. int ret;
  9206. dictObjPtr = Jim_GetVariable(interp, varObjPtr, JIM_ERRMSG);
  9207. if (!dictObjPtr) {
  9208. return NULL;
  9209. }
  9210. ret = Jim_DictKey(interp, dictObjPtr, keyObjPtr, &resObjPtr, JIM_NONE);
  9211. if (ret != JIM_OK) {
  9212. Jim_SetResultFormatted(interp,
  9213. "can't read \"%#s(%#s)\": %s array", varObjPtr, keyObjPtr,
  9214. ret < 0 ? "variable isn't" : "no such element in");
  9215. }
  9216. else if ((flags & JIM_UNSHARED) && Jim_IsShared(dictObjPtr)) {
  9217. Jim_SetVariable(interp, varObjPtr, Jim_DuplicateObj(interp, dictObjPtr));
  9218. }
  9219. return resObjPtr;
  9220. }
  9221. static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
  9222. {
  9223. SetDictSubstFromAny(interp, objPtr);
  9224. return JimDictExpandArrayVariable(interp,
  9225. objPtr->internalRep.dictSubstValue.varNameObjPtr,
  9226. objPtr->internalRep.dictSubstValue.indexObjPtr, flags);
  9227. }
  9228. void FreeDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
  9229. {
  9230. Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr);
  9231. Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.indexObjPtr);
  9232. }
  9233. static void DupDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
  9234. {
  9235. dupPtr->internalRep = srcPtr->internalRep;
  9236. Jim_IncrRefCount(dupPtr->internalRep.dictSubstValue.varNameObjPtr);
  9237. Jim_IncrRefCount(dupPtr->internalRep.dictSubstValue.indexObjPtr);
  9238. }
  9239. static void SetDictSubstFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
  9240. {
  9241. if (objPtr->typePtr != &dictSubstObjType) {
  9242. Jim_Obj *varObjPtr, *keyObjPtr;
  9243. if (objPtr->typePtr == &interpolatedObjType) {
  9244. varObjPtr = objPtr->internalRep.dictSubstValue.varNameObjPtr;
  9245. keyObjPtr = objPtr->internalRep.dictSubstValue.indexObjPtr;
  9246. Jim_IncrRefCount(varObjPtr);
  9247. Jim_IncrRefCount(keyObjPtr);
  9248. }
  9249. else {
  9250. JimDictSugarParseVarKey(interp, objPtr, &varObjPtr, &keyObjPtr);
  9251. }
  9252. Jim_FreeIntRep(interp, objPtr);
  9253. objPtr->typePtr = &dictSubstObjType;
  9254. objPtr->internalRep.dictSubstValue.varNameObjPtr = varObjPtr;
  9255. objPtr->internalRep.dictSubstValue.indexObjPtr = keyObjPtr;
  9256. }
  9257. }
  9258. static Jim_Obj *JimExpandDictSugar(Jim_Interp *interp, Jim_Obj *objPtr)
  9259. {
  9260. Jim_Obj *resObjPtr = NULL;
  9261. Jim_Obj *substKeyObjPtr = NULL;
  9262. if (interp->safeexpr) {
  9263. return objPtr;
  9264. }
  9265. SetDictSubstFromAny(interp, objPtr);
  9266. if (Jim_SubstObj(interp, objPtr->internalRep.dictSubstValue.indexObjPtr,
  9267. &substKeyObjPtr, JIM_NONE)
  9268. != JIM_OK) {
  9269. return NULL;
  9270. }
  9271. Jim_IncrRefCount(substKeyObjPtr);
  9272. resObjPtr =
  9273. JimDictExpandArrayVariable(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr,
  9274. substKeyObjPtr, 0);
  9275. Jim_DecrRefCount(interp, substKeyObjPtr);
  9276. return resObjPtr;
  9277. }
  9278. static Jim_CallFrame *JimCreateCallFrame(Jim_Interp *interp, Jim_CallFrame *parent, Jim_Obj *nsObj)
  9279. {
  9280. Jim_CallFrame *cf;
  9281. if (interp->freeFramesList) {
  9282. cf = interp->freeFramesList;
  9283. interp->freeFramesList = cf->next;
  9284. cf->argv = NULL;
  9285. cf->argc = 0;
  9286. cf->procArgsObjPtr = NULL;
  9287. cf->procBodyObjPtr = NULL;
  9288. cf->next = NULL;
  9289. cf->staticVars = NULL;
  9290. cf->localCommands = NULL;
  9291. cf->tailcallObj = NULL;
  9292. cf->tailcallCmd = NULL;
  9293. }
  9294. else {
  9295. cf = Jim_Alloc(sizeof(*cf));
  9296. memset(cf, 0, sizeof(*cf));
  9297. Jim_InitHashTable(&cf->vars, &JimVariablesHashTableType, interp);
  9298. }
  9299. cf->id = interp->callFrameEpoch++;
  9300. cf->parent = parent;
  9301. cf->level = parent ? parent->level + 1 : 0;
  9302. cf->nsObj = nsObj;
  9303. Jim_IncrRefCount(nsObj);
  9304. return cf;
  9305. }
  9306. static int JimDeleteLocalProcs(Jim_Interp *interp, Jim_Stack *localCommands)
  9307. {
  9308. if (localCommands) {
  9309. Jim_Obj *cmdNameObj;
  9310. while ((cmdNameObj = Jim_StackPop(localCommands)) != NULL) {
  9311. Jim_HashTable *ht = &interp->commands;
  9312. Jim_HashEntry *he = Jim_FindHashEntry(ht, cmdNameObj);
  9313. if (he) {
  9314. Jim_Cmd *cmd = Jim_GetHashEntryVal(he);
  9315. if (cmd->prevCmd) {
  9316. Jim_Cmd *prevCmd = cmd->prevCmd;
  9317. cmd->prevCmd = NULL;
  9318. JimDecrCmdRefCount(interp, cmd);
  9319. Jim_SetHashVal(ht, he, prevCmd);
  9320. }
  9321. else {
  9322. Jim_DeleteHashEntry(ht, cmdNameObj);
  9323. }
  9324. }
  9325. Jim_DecrRefCount(interp, cmdNameObj);
  9326. }
  9327. Jim_FreeStack(localCommands);
  9328. Jim_Free(localCommands);
  9329. }
  9330. return JIM_OK;
  9331. }
  9332. static int JimInvokeDefer(Jim_Interp *interp, int retcode)
  9333. {
  9334. Jim_Obj *objPtr;
  9335. if (JimFindVariable(&interp->framePtr->vars, interp->defer) == NULL) {
  9336. return retcode;
  9337. }
  9338. objPtr = Jim_GetVariable(interp, interp->defer, JIM_NONE);
  9339. if (objPtr) {
  9340. int ret = JIM_OK;
  9341. int i;
  9342. int listLen = Jim_ListLength(interp, objPtr);
  9343. Jim_Obj *resultObjPtr;
  9344. Jim_IncrRefCount(objPtr);
  9345. resultObjPtr = Jim_GetResult(interp);
  9346. Jim_IncrRefCount(resultObjPtr);
  9347. Jim_SetEmptyResult(interp);
  9348. for (i = listLen; i > 0; i--) {
  9349. Jim_Obj *scriptObjPtr = Jim_ListGetIndex(interp, objPtr, i - 1);
  9350. ret = Jim_EvalObj(interp, scriptObjPtr);
  9351. if (ret != JIM_OK) {
  9352. break;
  9353. }
  9354. }
  9355. if (ret == JIM_OK || retcode == JIM_ERR) {
  9356. Jim_SetResult(interp, resultObjPtr);
  9357. }
  9358. else {
  9359. retcode = ret;
  9360. }
  9361. Jim_DecrRefCount(interp, resultObjPtr);
  9362. Jim_DecrRefCount(interp, objPtr);
  9363. }
  9364. return retcode;
  9365. }
  9366. #define JIM_FCF_FULL 0
  9367. #define JIM_FCF_REUSE 1
  9368. static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf, int action)
  9369. {
  9370. JimDeleteLocalProcs(interp, cf->localCommands);
  9371. if (cf->procArgsObjPtr)
  9372. Jim_DecrRefCount(interp, cf->procArgsObjPtr);
  9373. if (cf->procBodyObjPtr)
  9374. Jim_DecrRefCount(interp, cf->procBodyObjPtr);
  9375. Jim_DecrRefCount(interp, cf->nsObj);
  9376. if (action == JIM_FCF_FULL || cf->vars.size != JIM_HT_INITIAL_SIZE)
  9377. Jim_FreeHashTable(&cf->vars);
  9378. else {
  9379. Jim_ClearHashTable(&cf->vars);
  9380. }
  9381. cf->next = interp->freeFramesList;
  9382. interp->freeFramesList = cf;
  9383. }
  9384. int Jim_IsBigEndian(void)
  9385. {
  9386. union {
  9387. unsigned short s;
  9388. unsigned char c[2];
  9389. } uval = {0x0102};
  9390. return uval.c[0] == 1;
  9391. }
  9392. Jim_Interp *Jim_CreateInterp(void)
  9393. {
  9394. Jim_Interp *i = Jim_Alloc(sizeof(*i));
  9395. memset(i, 0, sizeof(*i));
  9396. i->maxCallFrameDepth = JIM_MAX_CALLFRAME_DEPTH;
  9397. i->maxEvalDepth = JIM_MAX_EVAL_DEPTH;
  9398. i->lastCollectTime = Jim_GetTimeUsec(CLOCK_MONOTONIC_RAW);
  9399. Jim_InitHashTable(&i->commands, &JimCommandsHashTableType, i);
  9400. #ifdef JIM_REFERENCES
  9401. Jim_InitHashTable(&i->references, &JimReferencesHashTableType, i);
  9402. #endif
  9403. Jim_InitHashTable(&i->assocData, &JimAssocDataHashTableType, i);
  9404. Jim_InitHashTable(&i->packages, &JimPackageHashTableType, NULL);
  9405. i->emptyObj = Jim_NewEmptyStringObj(i);
  9406. i->trueObj = Jim_NewIntObj(i, 1);
  9407. i->falseObj = Jim_NewIntObj(i, 0);
  9408. i->framePtr = i->topFramePtr = JimCreateCallFrame(i, NULL, i->emptyObj);
  9409. i->result = i->emptyObj;
  9410. i->stackTrace = Jim_NewListObj(i, NULL, 0);
  9411. i->unknown = Jim_NewStringObj(i, "unknown", -1);
  9412. i->defer = Jim_NewStringObj(i, "jim::defer", -1);
  9413. i->errorProc = i->emptyObj;
  9414. i->nullScriptObj = Jim_NewEmptyStringObj(i);
  9415. i->evalFrame = &i->topEvalFrame;
  9416. i->currentFilenameObj = Jim_NewEmptyStringObj(i);
  9417. Jim_IncrRefCount(i->emptyObj);
  9418. Jim_IncrRefCount(i->result);
  9419. Jim_IncrRefCount(i->stackTrace);
  9420. Jim_IncrRefCount(i->unknown);
  9421. Jim_IncrRefCount(i->defer);
  9422. Jim_IncrRefCount(i->nullScriptObj);
  9423. Jim_IncrRefCount(i->errorProc);
  9424. Jim_IncrRefCount(i->trueObj);
  9425. Jim_IncrRefCount(i->falseObj);
  9426. Jim_IncrRefCount(i->currentFilenameObj);
  9427. Jim_SetVariableStrWithStr(i, JIM_LIBPATH, TCL_LIBRARY);
  9428. Jim_SetVariableStrWithStr(i, JIM_INTERACTIVE, "0");
  9429. Jim_SetVariableStrWithStr(i, "tcl_platform(engine)", "Jim");
  9430. Jim_SetVariableStrWithStr(i, "tcl_platform(os)", TCL_PLATFORM_OS);
  9431. Jim_SetVariableStrWithStr(i, "tcl_platform(platform)", TCL_PLATFORM_PLATFORM);
  9432. Jim_SetVariableStrWithStr(i, "tcl_platform(pathSeparator)", TCL_PLATFORM_PATH_SEPARATOR);
  9433. Jim_SetVariableStrWithStr(i, "tcl_platform(byteOrder)", Jim_IsBigEndian() ? "bigEndian" : "littleEndian");
  9434. Jim_SetVariableStrWithStr(i, "tcl_platform(threaded)", "0");
  9435. Jim_SetVariableStrWithStr(i, "tcl_platform(bootstrap)", "0");
  9436. Jim_SetVariableStr(i, "tcl_platform(pointerSize)", Jim_NewIntObj(i, sizeof(void *)));
  9437. Jim_SetVariableStr(i, "tcl_platform(wordSize)", Jim_NewIntObj(i, sizeof(jim_wide)));
  9438. Jim_SetVariableStr(i, "tcl_platform(stackFormat)", Jim_NewIntObj(i, 4));
  9439. return i;
  9440. }
  9441. void Jim_FreeInterp(Jim_Interp *i)
  9442. {
  9443. Jim_CallFrame *cf, *cfx;
  9444. Jim_Obj *objPtr, *nextObjPtr;
  9445. i->quitting = 1;
  9446. for (cf = i->framePtr; cf; cf = cfx) {
  9447. JimInvokeDefer(i, JIM_OK);
  9448. cfx = cf->parent;
  9449. JimFreeCallFrame(i, cf, JIM_FCF_FULL);
  9450. }
  9451. Jim_FreeHashTable(&i->commands);
  9452. Jim_DecrRefCount(i, i->emptyObj);
  9453. Jim_DecrRefCount(i, i->trueObj);
  9454. Jim_DecrRefCount(i, i->falseObj);
  9455. Jim_DecrRefCount(i, i->result);
  9456. Jim_DecrRefCount(i, i->stackTrace);
  9457. Jim_DecrRefCount(i, i->errorProc);
  9458. Jim_DecrRefCount(i, i->unknown);
  9459. Jim_DecrRefCount(i, i->defer);
  9460. Jim_DecrRefCount(i, i->nullScriptObj);
  9461. Jim_DecrRefCount(i, i->currentFilenameObj);
  9462. Jim_InterpIncrProcEpoch(i);
  9463. #ifdef JIM_REFERENCES
  9464. Jim_FreeHashTable(&i->references);
  9465. #endif
  9466. Jim_FreeHashTable(&i->packages);
  9467. Jim_Free(i->prngState);
  9468. Jim_FreeHashTable(&i->assocData);
  9469. if (i->traceCmdObj) {
  9470. Jim_DecrRefCount(i, i->traceCmdObj);
  9471. }
  9472. #ifdef JIM_MAINTAINER
  9473. if (i->liveList != NULL) {
  9474. objPtr = i->liveList;
  9475. printf("\n-------------------------------------\n");
  9476. printf("Objects still in the free list:\n");
  9477. while (objPtr) {
  9478. const char *type = objPtr->typePtr ? objPtr->typePtr->name : "string";
  9479. Jim_String(objPtr);
  9480. if (objPtr->bytes && strlen(objPtr->bytes) > 20) {
  9481. printf("%p (%d) %-10s: '%.20s...'\n",
  9482. (void *)objPtr, objPtr->refCount, type, objPtr->bytes);
  9483. }
  9484. else {
  9485. printf("%p (%d) %-10s: '%s'\n",
  9486. (void *)objPtr, objPtr->refCount, type, objPtr->bytes ? objPtr->bytes : "(null)");
  9487. }
  9488. if (objPtr->typePtr == &sourceObjType) {
  9489. printf("FILE %s LINE %d\n",
  9490. Jim_String(objPtr->internalRep.sourceValue.fileNameObj),
  9491. objPtr->internalRep.sourceValue.lineNumber);
  9492. }
  9493. objPtr = objPtr->nextObjPtr;
  9494. }
  9495. printf("-------------------------------------\n\n");
  9496. JimPanic((1, "Live list non empty freeing the interpreter! Leak?"));
  9497. }
  9498. #endif
  9499. objPtr = i->freeList;
  9500. while (objPtr) {
  9501. nextObjPtr = objPtr->nextObjPtr;
  9502. Jim_Free(objPtr);
  9503. objPtr = nextObjPtr;
  9504. }
  9505. for (cf = i->freeFramesList; cf; cf = cfx) {
  9506. cfx = cf->next;
  9507. if (cf->vars.table)
  9508. Jim_FreeHashTable(&cf->vars);
  9509. Jim_Free(cf);
  9510. }
  9511. Jim_Free(i);
  9512. }
  9513. Jim_CallFrame *Jim_GetCallFrameByLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr)
  9514. {
  9515. long level;
  9516. const char *str;
  9517. Jim_CallFrame *framePtr;
  9518. if (levelObjPtr) {
  9519. str = Jim_String(levelObjPtr);
  9520. if (str[0] == '#') {
  9521. char *endptr;
  9522. level = jim_strtol(str + 1, &endptr);
  9523. if (str[1] == '\0' || endptr[0] != '\0') {
  9524. level = -1;
  9525. }
  9526. }
  9527. else {
  9528. if (Jim_GetLong(interp, levelObjPtr, &level) != JIM_OK || level < 0) {
  9529. level = -1;
  9530. }
  9531. else {
  9532. level = interp->framePtr->level - level;
  9533. }
  9534. }
  9535. }
  9536. else {
  9537. str = "1";
  9538. level = interp->framePtr->level - 1;
  9539. }
  9540. if (level == 0) {
  9541. return interp->topFramePtr;
  9542. }
  9543. if (level > 0) {
  9544. for (framePtr = interp->framePtr; framePtr; framePtr = framePtr->parent) {
  9545. if (framePtr->level == level) {
  9546. return framePtr;
  9547. }
  9548. }
  9549. }
  9550. Jim_SetResultFormatted(interp, "bad level \"%s\"", str);
  9551. return NULL;
  9552. }
  9553. static Jim_CallFrame *JimGetCallFrameByInteger(Jim_Interp *interp, long level)
  9554. {
  9555. Jim_CallFrame *framePtr;
  9556. if (level == 0) {
  9557. return interp->framePtr;
  9558. }
  9559. if (level < 0) {
  9560. level = interp->framePtr->level + level;
  9561. }
  9562. if (level > 0) {
  9563. for (framePtr = interp->framePtr; framePtr; framePtr = framePtr->parent) {
  9564. if (framePtr->level == level) {
  9565. return framePtr;
  9566. }
  9567. }
  9568. }
  9569. return NULL;
  9570. }
  9571. static Jim_EvalFrame *JimGetEvalFrameByProcLevel(Jim_Interp *interp, int proclevel)
  9572. {
  9573. Jim_EvalFrame *evalFrame;
  9574. if (proclevel == 0) {
  9575. return interp->evalFrame;
  9576. }
  9577. if (proclevel < 0) {
  9578. proclevel = interp->procLevel + proclevel;
  9579. }
  9580. if (proclevel >= 0) {
  9581. for (evalFrame = interp->evalFrame; evalFrame; evalFrame = evalFrame->parent) {
  9582. if (evalFrame->procLevel == proclevel) {
  9583. return evalFrame;
  9584. }
  9585. }
  9586. }
  9587. return NULL;
  9588. }
  9589. static Jim_Obj *JimProcForEvalFrame(Jim_Interp *interp, Jim_EvalFrame *frame)
  9590. {
  9591. if (frame == interp->evalFrame || (frame->cmd && frame->cmd->cmdNameObj)) {
  9592. Jim_EvalFrame *e;
  9593. for (e = frame->parent; e; e = e->parent) {
  9594. if (e->cmd && e->cmd->isproc && e->cmd->cmdNameObj) {
  9595. break;
  9596. }
  9597. }
  9598. if (e && e->cmd && e->cmd->cmdNameObj) {
  9599. return e->cmd->cmdNameObj;
  9600. }
  9601. }
  9602. return NULL;
  9603. }
  9604. static void JimAddStackFrame(Jim_Interp *interp, Jim_EvalFrame *frame, Jim_Obj *listObj)
  9605. {
  9606. Jim_Obj *procNameObj = JimProcForEvalFrame(interp, frame);
  9607. Jim_Obj *fileNameObj = interp->emptyObj;
  9608. int linenr = 1;
  9609. if (frame->scriptObj) {
  9610. ScriptObj *script = JimGetScript(interp, frame->scriptObj);
  9611. fileNameObj = script->fileNameObj;
  9612. linenr = script->linenr;
  9613. }
  9614. Jim_ListAppendElement(interp, listObj, procNameObj ? procNameObj : interp->emptyObj);
  9615. Jim_ListAppendElement(interp, listObj, fileNameObj);
  9616. Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, linenr));
  9617. Jim_ListAppendElement(interp, listObj, Jim_NewListObj(interp, frame->argv, frame->argc));
  9618. }
  9619. static void JimSetStackTrace(Jim_Interp *interp, Jim_Obj *stackTraceObj)
  9620. {
  9621. Jim_IncrRefCount(stackTraceObj);
  9622. Jim_DecrRefCount(interp, interp->stackTrace);
  9623. interp->stackTrace = stackTraceObj;
  9624. interp->errorFlag = 1;
  9625. }
  9626. static void JimSetErrorStack(Jim_Interp *interp, ScriptObj *script)
  9627. {
  9628. if (!interp->errorFlag) {
  9629. int i;
  9630. Jim_Obj *stackTrace = Jim_NewListObj(interp, NULL, 0);
  9631. if (interp->procLevel == 0 && script) {
  9632. Jim_ListAppendElement(interp, stackTrace, interp->emptyObj);
  9633. Jim_ListAppendElement(interp, stackTrace, script->fileNameObj);
  9634. Jim_ListAppendElement(interp, stackTrace, Jim_NewIntObj(interp, script->linenr));
  9635. Jim_ListAppendElement(interp, stackTrace, interp->emptyObj);
  9636. }
  9637. else {
  9638. for (i = 0; i <= interp->procLevel; i++) {
  9639. Jim_EvalFrame *frame = JimGetEvalFrameByProcLevel(interp, -i);
  9640. if (frame) {
  9641. JimAddStackFrame(interp, frame, stackTrace);
  9642. }
  9643. }
  9644. }
  9645. JimSetStackTrace(interp, stackTrace);
  9646. }
  9647. }
  9648. int Jim_SetAssocData(Jim_Interp *interp, const char *key, Jim_InterpDeleteProc * delProc,
  9649. void *data)
  9650. {
  9651. AssocDataValue *assocEntryPtr = (AssocDataValue *) Jim_Alloc(sizeof(AssocDataValue));
  9652. assocEntryPtr->delProc = delProc;
  9653. assocEntryPtr->data = data;
  9654. return Jim_AddHashEntry(&interp->assocData, key, assocEntryPtr);
  9655. }
  9656. void *Jim_GetAssocData(Jim_Interp *interp, const char *key)
  9657. {
  9658. Jim_HashEntry *entryPtr = Jim_FindHashEntry(&interp->assocData, key);
  9659. if (entryPtr != NULL) {
  9660. AssocDataValue *assocEntryPtr = Jim_GetHashEntryVal(entryPtr);
  9661. return assocEntryPtr->data;
  9662. }
  9663. return NULL;
  9664. }
  9665. int Jim_DeleteAssocData(Jim_Interp *interp, const char *key)
  9666. {
  9667. return Jim_DeleteHashEntry(&interp->assocData, key);
  9668. }
  9669. int Jim_GetExitCode(Jim_Interp *interp)
  9670. {
  9671. return interp->exitCode;
  9672. }
  9673. static void UpdateStringOfInt(struct Jim_Obj *objPtr);
  9674. static int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags);
  9675. static const Jim_ObjType intObjType = {
  9676. "int",
  9677. NULL,
  9678. NULL,
  9679. UpdateStringOfInt,
  9680. JIM_TYPE_NONE,
  9681. };
  9682. static const Jim_ObjType coercedDoubleObjType = {
  9683. "coerced-double",
  9684. NULL,
  9685. NULL,
  9686. UpdateStringOfInt,
  9687. JIM_TYPE_NONE,
  9688. };
  9689. static void UpdateStringOfInt(struct Jim_Obj *objPtr)
  9690. {
  9691. char buf[JIM_INTEGER_SPACE + 1];
  9692. jim_wide wideValue = JimWideValue(objPtr);
  9693. int pos = 0;
  9694. if (wideValue == 0) {
  9695. buf[pos++] = '0';
  9696. }
  9697. else {
  9698. char tmp[JIM_INTEGER_SPACE];
  9699. int num = 0;
  9700. int i;
  9701. if (wideValue < 0) {
  9702. buf[pos++] = '-';
  9703. i = wideValue % 10;
  9704. tmp[num++] = (i > 0) ? (10 - i) : -i;
  9705. wideValue /= -10;
  9706. }
  9707. while (wideValue) {
  9708. tmp[num++] = wideValue % 10;
  9709. wideValue /= 10;
  9710. }
  9711. for (i = 0; i < num; i++) {
  9712. buf[pos++] = '0' + tmp[num - i - 1];
  9713. }
  9714. }
  9715. buf[pos] = 0;
  9716. JimSetStringBytes(objPtr, buf);
  9717. }
  9718. static int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
  9719. {
  9720. jim_wide wideValue;
  9721. const char *str;
  9722. if (objPtr->typePtr == &coercedDoubleObjType) {
  9723. objPtr->typePtr = &intObjType;
  9724. return JIM_OK;
  9725. }
  9726. str = Jim_String(objPtr);
  9727. if (Jim_StringToWide(str, &wideValue, 0) != JIM_OK) {
  9728. if (flags & JIM_ERRMSG) {
  9729. Jim_SetResultFormatted(interp, "expected integer but got \"%#s\"", objPtr);
  9730. }
  9731. return JIM_ERR;
  9732. }
  9733. if ((wideValue == JIM_WIDE_MIN || wideValue == JIM_WIDE_MAX) && errno == ERANGE) {
  9734. Jim_SetResultString(interp, "Integer value too big to be represented", -1);
  9735. return JIM_ERR;
  9736. }
  9737. Jim_FreeIntRep(interp, objPtr);
  9738. objPtr->typePtr = &intObjType;
  9739. objPtr->internalRep.wideValue = wideValue;
  9740. return JIM_OK;
  9741. }
  9742. #ifdef JIM_OPTIMIZATION
  9743. static int JimIsWide(Jim_Obj *objPtr)
  9744. {
  9745. return objPtr->typePtr == &intObjType;
  9746. }
  9747. #endif
  9748. int Jim_GetWide(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr)
  9749. {
  9750. if (objPtr->typePtr != &intObjType && SetIntFromAny(interp, objPtr, JIM_ERRMSG) == JIM_ERR)
  9751. return JIM_ERR;
  9752. *widePtr = JimWideValue(objPtr);
  9753. return JIM_OK;
  9754. }
  9755. int Jim_GetWideExpr(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr)
  9756. {
  9757. int ret = JIM_OK;
  9758. if (objPtr->typePtr == &sourceObjType || objPtr->typePtr == NULL) {
  9759. SetIntFromAny(interp, objPtr, 0);
  9760. }
  9761. if (objPtr->typePtr == &intObjType) {
  9762. *widePtr = JimWideValue(objPtr);
  9763. }
  9764. else {
  9765. JimPanic((interp->safeexpr, "interp->safeexpr is set"));
  9766. interp->safeexpr++;
  9767. ret = Jim_EvalExpression(interp, objPtr);
  9768. interp->safeexpr--;
  9769. if (ret == JIM_OK) {
  9770. ret = Jim_GetWide(interp, Jim_GetResult(interp), widePtr);
  9771. }
  9772. if (ret != JIM_OK) {
  9773. Jim_SetResultFormatted(interp, "expected integer expression but got \"%#s\"", objPtr);
  9774. }
  9775. }
  9776. return ret;
  9777. }
  9778. static int JimGetWideNoErr(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr)
  9779. {
  9780. if (objPtr->typePtr != &intObjType && SetIntFromAny(interp, objPtr, JIM_NONE) == JIM_ERR)
  9781. return JIM_ERR;
  9782. *widePtr = JimWideValue(objPtr);
  9783. return JIM_OK;
  9784. }
  9785. int Jim_GetLong(Jim_Interp *interp, Jim_Obj *objPtr, long *longPtr)
  9786. {
  9787. jim_wide wideValue;
  9788. int retval;
  9789. retval = Jim_GetWide(interp, objPtr, &wideValue);
  9790. if (retval == JIM_OK) {
  9791. *longPtr = (long)wideValue;
  9792. return JIM_OK;
  9793. }
  9794. return JIM_ERR;
  9795. }
  9796. Jim_Obj *Jim_NewIntObj(Jim_Interp *interp, jim_wide wideValue)
  9797. {
  9798. Jim_Obj *objPtr;
  9799. objPtr = Jim_NewObj(interp);
  9800. objPtr->typePtr = &intObjType;
  9801. objPtr->bytes = NULL;
  9802. objPtr->internalRep.wideValue = wideValue;
  9803. return objPtr;
  9804. }
  9805. #define JIM_DOUBLE_SPACE 30
  9806. static void UpdateStringOfDouble(struct Jim_Obj *objPtr);
  9807. static int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
  9808. static const Jim_ObjType doubleObjType = {
  9809. "double",
  9810. NULL,
  9811. NULL,
  9812. UpdateStringOfDouble,
  9813. JIM_TYPE_NONE,
  9814. };
  9815. #if !HAVE_DECL_ISNAN
  9816. #undef isnan
  9817. #define isnan(X) ((X) != (X))
  9818. #endif
  9819. #if !HAVE_DECL_ISINF
  9820. #undef isinf
  9821. #define isinf(X) (1.0 / (X) == 0.0)
  9822. #endif
  9823. static void UpdateStringOfDouble(struct Jim_Obj *objPtr)
  9824. {
  9825. double value = objPtr->internalRep.doubleValue;
  9826. if (isnan(value)) {
  9827. JimSetStringBytes(objPtr, "NaN");
  9828. return;
  9829. }
  9830. if (isinf(value)) {
  9831. if (value < 0) {
  9832. JimSetStringBytes(objPtr, "-Inf");
  9833. }
  9834. else {
  9835. JimSetStringBytes(objPtr, "Inf");
  9836. }
  9837. return;
  9838. }
  9839. {
  9840. char buf[JIM_DOUBLE_SPACE + 1];
  9841. int i;
  9842. int len = sprintf(buf, "%.12g", value);
  9843. for (i = 0; i < len; i++) {
  9844. if (buf[i] == '.' || buf[i] == 'e') {
  9845. #if defined(JIM_SPRINTF_DOUBLE_NEEDS_FIX)
  9846. char *e = strchr(buf, 'e');
  9847. if (e && (e[1] == '-' || e[1] == '+') && e[2] == '0') {
  9848. e += 2;
  9849. memmove(e, e + 1, len - (e - buf));
  9850. }
  9851. #endif
  9852. break;
  9853. }
  9854. }
  9855. if (buf[i] == '\0') {
  9856. buf[i++] = '.';
  9857. buf[i++] = '0';
  9858. buf[i] = '\0';
  9859. }
  9860. JimSetStringBytes(objPtr, buf);
  9861. }
  9862. }
  9863. static int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
  9864. {
  9865. double doubleValue;
  9866. jim_wide wideValue;
  9867. const char *str;
  9868. #ifdef HAVE_LONG_LONG
  9869. #define MIN_INT_IN_DOUBLE -(1LL << 53)
  9870. #define MAX_INT_IN_DOUBLE -(MIN_INT_IN_DOUBLE + 1)
  9871. if (objPtr->typePtr == &intObjType
  9872. && JimWideValue(objPtr) >= MIN_INT_IN_DOUBLE
  9873. && JimWideValue(objPtr) <= MAX_INT_IN_DOUBLE) {
  9874. objPtr->typePtr = &coercedDoubleObjType;
  9875. return JIM_OK;
  9876. }
  9877. #endif
  9878. str = Jim_String(objPtr);
  9879. if (Jim_StringToWide(str, &wideValue, 10) == JIM_OK) {
  9880. Jim_FreeIntRep(interp, objPtr);
  9881. objPtr->typePtr = &coercedDoubleObjType;
  9882. objPtr->internalRep.wideValue = wideValue;
  9883. return JIM_OK;
  9884. }
  9885. else {
  9886. if (Jim_StringToDouble(str, &doubleValue) != JIM_OK) {
  9887. Jim_SetResultFormatted(interp, "expected floating-point number but got \"%#s\"", objPtr);
  9888. return JIM_ERR;
  9889. }
  9890. Jim_FreeIntRep(interp, objPtr);
  9891. }
  9892. objPtr->typePtr = &doubleObjType;
  9893. objPtr->internalRep.doubleValue = doubleValue;
  9894. return JIM_OK;
  9895. }
  9896. int Jim_GetDouble(Jim_Interp *interp, Jim_Obj *objPtr, double *doublePtr)
  9897. {
  9898. if (objPtr->typePtr == &coercedDoubleObjType) {
  9899. *doublePtr = JimWideValue(objPtr);
  9900. return JIM_OK;
  9901. }
  9902. if (objPtr->typePtr != &doubleObjType && SetDoubleFromAny(interp, objPtr) == JIM_ERR)
  9903. return JIM_ERR;
  9904. if (objPtr->typePtr == &coercedDoubleObjType) {
  9905. *doublePtr = JimWideValue(objPtr);
  9906. }
  9907. else {
  9908. *doublePtr = objPtr->internalRep.doubleValue;
  9909. }
  9910. return JIM_OK;
  9911. }
  9912. Jim_Obj *Jim_NewDoubleObj(Jim_Interp *interp, double doubleValue)
  9913. {
  9914. Jim_Obj *objPtr;
  9915. objPtr = Jim_NewObj(interp);
  9916. objPtr->typePtr = &doubleObjType;
  9917. objPtr->bytes = NULL;
  9918. objPtr->internalRep.doubleValue = doubleValue;
  9919. return objPtr;
  9920. }
  9921. static int SetBooleanFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags);
  9922. int Jim_GetBoolean(Jim_Interp *interp, Jim_Obj *objPtr, int * booleanPtr)
  9923. {
  9924. if (objPtr->typePtr != &intObjType && SetBooleanFromAny(interp, objPtr, JIM_ERRMSG) == JIM_ERR)
  9925. return JIM_ERR;
  9926. *booleanPtr = (int) JimWideValue(objPtr);
  9927. return JIM_OK;
  9928. }
  9929. static const char * const jim_true_false_strings[8] = {
  9930. "1", "true", "yes", "on",
  9931. "0", "false", "no", "off"
  9932. };
  9933. static const int jim_true_false_lens[8] = {
  9934. 1, 4, 3, 2,
  9935. 1, 5, 2, 3,
  9936. };
  9937. static int SetBooleanFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
  9938. {
  9939. int index = Jim_FindByName(Jim_String(objPtr), jim_true_false_strings,
  9940. sizeof(jim_true_false_strings) / sizeof(*jim_true_false_strings));
  9941. if (index < 0) {
  9942. if (flags & JIM_ERRMSG) {
  9943. Jim_SetResultFormatted(interp, "expected boolean but got \"%#s\"", objPtr);
  9944. }
  9945. return JIM_ERR;
  9946. }
  9947. Jim_FreeIntRep(interp, objPtr);
  9948. objPtr->typePtr = &intObjType;
  9949. objPtr->internalRep.wideValue = index < 4 ? 1 : 0;
  9950. return JIM_OK;
  9951. }
  9952. static void ListInsertElements(Jim_Obj *listPtr, int idx, int elemc, Jim_Obj *const *elemVec);
  9953. static void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr);
  9954. static void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
  9955. static void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
  9956. static void UpdateStringOfList(struct Jim_Obj *objPtr);
  9957. static int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
  9958. static const Jim_ObjType listObjType = {
  9959. "list",
  9960. FreeListInternalRep,
  9961. DupListInternalRep,
  9962. UpdateStringOfList,
  9963. JIM_TYPE_NONE,
  9964. };
  9965. void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
  9966. {
  9967. int i;
  9968. for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
  9969. Jim_DecrRefCount(interp, objPtr->internalRep.listValue.ele[i]);
  9970. }
  9971. Jim_Free(objPtr->internalRep.listValue.ele);
  9972. }
  9973. void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
  9974. {
  9975. int i;
  9976. JIM_NOTUSED(interp);
  9977. dupPtr->internalRep.listValue.len = srcPtr->internalRep.listValue.len;
  9978. dupPtr->internalRep.listValue.maxLen = srcPtr->internalRep.listValue.maxLen;
  9979. dupPtr->internalRep.listValue.ele =
  9980. Jim_Alloc(sizeof(Jim_Obj *) * srcPtr->internalRep.listValue.maxLen);
  9981. memcpy(dupPtr->internalRep.listValue.ele, srcPtr->internalRep.listValue.ele,
  9982. sizeof(Jim_Obj *) * srcPtr->internalRep.listValue.len);
  9983. for (i = 0; i < dupPtr->internalRep.listValue.len; i++) {
  9984. Jim_IncrRefCount(dupPtr->internalRep.listValue.ele[i]);
  9985. }
  9986. dupPtr->typePtr = &listObjType;
  9987. }
  9988. #define JIM_ELESTR_SIMPLE 0
  9989. #define JIM_ELESTR_BRACE 1
  9990. #define JIM_ELESTR_QUOTE 2
  9991. static unsigned char ListElementQuotingType(const char *s, int len)
  9992. {
  9993. int i, level, blevel, trySimple = 1;
  9994. if (len == 0)
  9995. return JIM_ELESTR_BRACE;
  9996. if (s[0] == '"' || s[0] == '{') {
  9997. trySimple = 0;
  9998. goto testbrace;
  9999. }
  10000. for (i = 0; i < len; i++) {
  10001. switch (s[i]) {
  10002. case ' ':
  10003. case '$':
  10004. case '"':
  10005. case '[':
  10006. case ']':
  10007. case ';':
  10008. case '\\':
  10009. case '\r':
  10010. case '\n':
  10011. case '\t':
  10012. case '\f':
  10013. case '\v':
  10014. trySimple = 0;
  10015. case '{':
  10016. case '}':
  10017. goto testbrace;
  10018. }
  10019. }
  10020. return JIM_ELESTR_SIMPLE;
  10021. testbrace:
  10022. if (s[len - 1] == '\\')
  10023. return JIM_ELESTR_QUOTE;
  10024. level = 0;
  10025. blevel = 0;
  10026. for (i = 0; i < len; i++) {
  10027. switch (s[i]) {
  10028. case '{':
  10029. level++;
  10030. break;
  10031. case '}':
  10032. level--;
  10033. if (level < 0)
  10034. return JIM_ELESTR_QUOTE;
  10035. break;
  10036. case '[':
  10037. blevel++;
  10038. break;
  10039. case ']':
  10040. blevel--;
  10041. break;
  10042. case '\\':
  10043. if (s[i + 1] == '\n')
  10044. return JIM_ELESTR_QUOTE;
  10045. else if (s[i + 1] != '\0')
  10046. i++;
  10047. break;
  10048. }
  10049. }
  10050. if (blevel < 0) {
  10051. return JIM_ELESTR_QUOTE;
  10052. }
  10053. if (level == 0) {
  10054. if (!trySimple)
  10055. return JIM_ELESTR_BRACE;
  10056. for (i = 0; i < len; i++) {
  10057. switch (s[i]) {
  10058. case ' ':
  10059. case '$':
  10060. case '"':
  10061. case '[':
  10062. case ']':
  10063. case ';':
  10064. case '\\':
  10065. case '\r':
  10066. case '\n':
  10067. case '\t':
  10068. case '\f':
  10069. case '\v':
  10070. return JIM_ELESTR_BRACE;
  10071. break;
  10072. }
  10073. }
  10074. return JIM_ELESTR_SIMPLE;
  10075. }
  10076. return JIM_ELESTR_QUOTE;
  10077. }
  10078. static int BackslashQuoteString(const char *s, int len, char *q)
  10079. {
  10080. char *p = q;
  10081. while (len--) {
  10082. switch (*s) {
  10083. case ' ':
  10084. case '$':
  10085. case '"':
  10086. case '[':
  10087. case ']':
  10088. case '{':
  10089. case '}':
  10090. case ';':
  10091. case '\\':
  10092. *p++ = '\\';
  10093. *p++ = *s++;
  10094. break;
  10095. case '\n':
  10096. *p++ = '\\';
  10097. *p++ = 'n';
  10098. s++;
  10099. break;
  10100. case '\r':
  10101. *p++ = '\\';
  10102. *p++ = 'r';
  10103. s++;
  10104. break;
  10105. case '\t':
  10106. *p++ = '\\';
  10107. *p++ = 't';
  10108. s++;
  10109. break;
  10110. case '\f':
  10111. *p++ = '\\';
  10112. *p++ = 'f';
  10113. s++;
  10114. break;
  10115. case '\v':
  10116. *p++ = '\\';
  10117. *p++ = 'v';
  10118. s++;
  10119. break;
  10120. default:
  10121. *p++ = *s++;
  10122. break;
  10123. }
  10124. }
  10125. *p = '\0';
  10126. return p - q;
  10127. }
  10128. static void JimMakeListStringRep(Jim_Obj *objPtr, Jim_Obj **objv, int objc)
  10129. {
  10130. #define STATIC_QUOTING_LEN 32
  10131. int i, bufLen, realLength;
  10132. const char *strRep;
  10133. char *p;
  10134. unsigned char *quotingType, staticQuoting[STATIC_QUOTING_LEN];
  10135. if (objc > STATIC_QUOTING_LEN) {
  10136. quotingType = Jim_Alloc(objc);
  10137. }
  10138. else {
  10139. quotingType = staticQuoting;
  10140. }
  10141. bufLen = 0;
  10142. for (i = 0; i < objc; i++) {
  10143. int len;
  10144. strRep = Jim_GetString(objv[i], &len);
  10145. quotingType[i] = ListElementQuotingType(strRep, len);
  10146. switch (quotingType[i]) {
  10147. case JIM_ELESTR_SIMPLE:
  10148. if (i != 0 || strRep[0] != '#') {
  10149. bufLen += len;
  10150. break;
  10151. }
  10152. quotingType[i] = JIM_ELESTR_BRACE;
  10153. case JIM_ELESTR_BRACE:
  10154. bufLen += len + 2;
  10155. break;
  10156. case JIM_ELESTR_QUOTE:
  10157. bufLen += len * 2;
  10158. break;
  10159. }
  10160. bufLen++;
  10161. }
  10162. bufLen++;
  10163. p = objPtr->bytes = Jim_Alloc(bufLen + 1);
  10164. realLength = 0;
  10165. for (i = 0; i < objc; i++) {
  10166. int len, qlen;
  10167. strRep = Jim_GetString(objv[i], &len);
  10168. switch (quotingType[i]) {
  10169. case JIM_ELESTR_SIMPLE:
  10170. memcpy(p, strRep, len);
  10171. p += len;
  10172. realLength += len;
  10173. break;
  10174. case JIM_ELESTR_BRACE:
  10175. *p++ = '{';
  10176. memcpy(p, strRep, len);
  10177. p += len;
  10178. *p++ = '}';
  10179. realLength += len + 2;
  10180. break;
  10181. case JIM_ELESTR_QUOTE:
  10182. if (i == 0 && strRep[0] == '#') {
  10183. *p++ = '\\';
  10184. realLength++;
  10185. }
  10186. qlen = BackslashQuoteString(strRep, len, p);
  10187. p += qlen;
  10188. realLength += qlen;
  10189. break;
  10190. }
  10191. if (i + 1 != objc) {
  10192. *p++ = ' ';
  10193. realLength++;
  10194. }
  10195. }
  10196. *p = '\0';
  10197. objPtr->length = realLength;
  10198. if (quotingType != staticQuoting) {
  10199. Jim_Free(quotingType);
  10200. }
  10201. }
  10202. static void UpdateStringOfList(struct Jim_Obj *objPtr)
  10203. {
  10204. JimMakeListStringRep(objPtr, objPtr->internalRep.listValue.ele, objPtr->internalRep.listValue.len);
  10205. }
  10206. static int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
  10207. {
  10208. struct JimParserCtx parser;
  10209. const char *str;
  10210. int strLen;
  10211. Jim_Obj *fileNameObj;
  10212. int linenr;
  10213. if (objPtr->typePtr == &listObjType) {
  10214. return JIM_OK;
  10215. }
  10216. if (Jim_IsDict(objPtr) && objPtr->bytes == NULL) {
  10217. Jim_Dict *dict = objPtr->internalRep.dictValue;
  10218. objPtr->typePtr = &listObjType;
  10219. objPtr->internalRep.listValue.len = dict->len;
  10220. objPtr->internalRep.listValue.maxLen = dict->maxLen;
  10221. objPtr->internalRep.listValue.ele = dict->table;
  10222. Jim_Free(dict->ht);
  10223. Jim_Free(dict);
  10224. return JIM_OK;
  10225. }
  10226. fileNameObj = Jim_GetSourceInfo(interp, objPtr, &linenr);
  10227. Jim_IncrRefCount(fileNameObj);
  10228. str = Jim_GetString(objPtr, &strLen);
  10229. Jim_FreeIntRep(interp, objPtr);
  10230. objPtr->typePtr = &listObjType;
  10231. objPtr->internalRep.listValue.len = 0;
  10232. objPtr->internalRep.listValue.maxLen = 0;
  10233. objPtr->internalRep.listValue.ele = NULL;
  10234. if (strLen) {
  10235. JimParserInit(&parser, str, strLen, linenr);
  10236. while (!parser.eof) {
  10237. Jim_Obj *elementPtr;
  10238. JimParseList(&parser);
  10239. if (parser.tt != JIM_TT_STR && parser.tt != JIM_TT_ESC)
  10240. continue;
  10241. elementPtr = JimParserGetTokenObj(interp, &parser);
  10242. Jim_SetSourceInfo(interp, elementPtr, fileNameObj, parser.tline);
  10243. ListAppendElement(objPtr, elementPtr);
  10244. }
  10245. }
  10246. Jim_DecrRefCount(interp, fileNameObj);
  10247. return JIM_OK;
  10248. }
  10249. Jim_Obj *Jim_NewListObj(Jim_Interp *interp, Jim_Obj *const *elements, int len)
  10250. {
  10251. Jim_Obj *objPtr;
  10252. objPtr = Jim_NewObj(interp);
  10253. objPtr->typePtr = &listObjType;
  10254. objPtr->bytes = NULL;
  10255. objPtr->internalRep.listValue.ele = NULL;
  10256. objPtr->internalRep.listValue.len = 0;
  10257. objPtr->internalRep.listValue.maxLen = 0;
  10258. if (len) {
  10259. ListInsertElements(objPtr, 0, len, elements);
  10260. }
  10261. return objPtr;
  10262. }
  10263. static void JimListGetElements(Jim_Interp *interp, Jim_Obj *listObj, int *listLen,
  10264. Jim_Obj ***listVec)
  10265. {
  10266. *listLen = Jim_ListLength(interp, listObj);
  10267. *listVec = listObj->internalRep.listValue.ele;
  10268. }
  10269. static int JimSign(jim_wide w)
  10270. {
  10271. if (w == 0) {
  10272. return 0;
  10273. }
  10274. else if (w < 0) {
  10275. return -1;
  10276. }
  10277. return 1;
  10278. }
  10279. struct lsort_info {
  10280. jmp_buf jmpbuf;
  10281. Jim_Obj *command;
  10282. Jim_Interp *interp;
  10283. enum {
  10284. JIM_LSORT_ASCII,
  10285. JIM_LSORT_NOCASE,
  10286. JIM_LSORT_INTEGER,
  10287. JIM_LSORT_REAL,
  10288. JIM_LSORT_COMMAND,
  10289. JIM_LSORT_DICT
  10290. } type;
  10291. int order;
  10292. Jim_Obj **indexv;
  10293. int indexc;
  10294. int unique;
  10295. int (*subfn)(Jim_Obj **, Jim_Obj **);
  10296. };
  10297. static struct lsort_info *sort_info;
  10298. static int ListSortIndexHelper(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
  10299. {
  10300. Jim_Obj *lObj, *rObj;
  10301. if (Jim_ListIndices(sort_info->interp, *lhsObj, sort_info->indexv, sort_info->indexc, &lObj, JIM_ERRMSG) != JIM_OK ||
  10302. Jim_ListIndices(sort_info->interp, *rhsObj, sort_info->indexv, sort_info->indexc, &rObj, JIM_ERRMSG) != JIM_OK) {
  10303. longjmp(sort_info->jmpbuf, JIM_ERR);
  10304. }
  10305. return sort_info->subfn(&lObj, &rObj);
  10306. }
  10307. static int ListSortString(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
  10308. {
  10309. return Jim_StringCompareObj(sort_info->interp, *lhsObj, *rhsObj, 0) * sort_info->order;
  10310. }
  10311. static int ListSortStringNoCase(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
  10312. {
  10313. return Jim_StringCompareObj(sort_info->interp, *lhsObj, *rhsObj, 1) * sort_info->order;
  10314. }
  10315. static int ListSortDict(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
  10316. {
  10317. const char *left = Jim_String(*lhsObj);
  10318. const char *right = Jim_String(*rhsObj);
  10319. while (1) {
  10320. if (isdigit(UCHAR(*left)) && isdigit(UCHAR(*right))) {
  10321. jim_wide lint, rint;
  10322. char *lend, *rend;
  10323. lint = jim_strtoull(left, &lend);
  10324. rint = jim_strtoull(right, &rend);
  10325. if (lint != rint) {
  10326. return JimSign(lint - rint) * sort_info->order;
  10327. }
  10328. if (lend -left != rend - right) {
  10329. return JimSign((lend - left) - (rend - right)) * sort_info->order;
  10330. }
  10331. left = lend;
  10332. right = rend;
  10333. }
  10334. else {
  10335. int cl, cr;
  10336. left += utf8_tounicode_case(left, &cl, 1);
  10337. right += utf8_tounicode_case(right, &cr, 1);
  10338. if (cl != cr) {
  10339. return JimSign(cl - cr) * sort_info->order;
  10340. }
  10341. if (cl == 0) {
  10342. return Jim_StringCompareObj(sort_info->interp, *lhsObj, *rhsObj, 0) * sort_info->order;
  10343. }
  10344. }
  10345. }
  10346. }
  10347. static int ListSortInteger(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
  10348. {
  10349. jim_wide lhs = 0, rhs = 0;
  10350. if (Jim_GetWide(sort_info->interp, *lhsObj, &lhs) != JIM_OK ||
  10351. Jim_GetWide(sort_info->interp, *rhsObj, &rhs) != JIM_OK) {
  10352. longjmp(sort_info->jmpbuf, JIM_ERR);
  10353. }
  10354. return JimSign(lhs - rhs) * sort_info->order;
  10355. }
  10356. static int ListSortReal(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
  10357. {
  10358. double lhs = 0, rhs = 0;
  10359. if (Jim_GetDouble(sort_info->interp, *lhsObj, &lhs) != JIM_OK ||
  10360. Jim_GetDouble(sort_info->interp, *rhsObj, &rhs) != JIM_OK) {
  10361. longjmp(sort_info->jmpbuf, JIM_ERR);
  10362. }
  10363. if (lhs == rhs) {
  10364. return 0;
  10365. }
  10366. if (lhs > rhs) {
  10367. return sort_info->order;
  10368. }
  10369. return -sort_info->order;
  10370. }
  10371. static int ListSortCommand(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
  10372. {
  10373. Jim_Obj *compare_script;
  10374. int rc;
  10375. jim_wide ret = 0;
  10376. compare_script = Jim_DuplicateObj(sort_info->interp, sort_info->command);
  10377. Jim_ListAppendElement(sort_info->interp, compare_script, *lhsObj);
  10378. Jim_ListAppendElement(sort_info->interp, compare_script, *rhsObj);
  10379. rc = Jim_EvalObj(sort_info->interp, compare_script);
  10380. if (rc != JIM_OK || Jim_GetWide(sort_info->interp, Jim_GetResult(sort_info->interp), &ret) != JIM_OK) {
  10381. longjmp(sort_info->jmpbuf, rc);
  10382. }
  10383. return JimSign(ret) * sort_info->order;
  10384. }
  10385. static void ListRemoveDuplicates(Jim_Obj *listObjPtr, int (*comp)(Jim_Obj **lhs, Jim_Obj **rhs))
  10386. {
  10387. int src;
  10388. int dst = 0;
  10389. Jim_Obj **ele = listObjPtr->internalRep.listValue.ele;
  10390. for (src = 1; src < listObjPtr->internalRep.listValue.len; src++) {
  10391. if (comp(&ele[dst], &ele[src]) == 0) {
  10392. Jim_DecrRefCount(sort_info->interp, ele[dst]);
  10393. }
  10394. else {
  10395. dst++;
  10396. }
  10397. ele[dst] = ele[src];
  10398. }
  10399. dst++;
  10400. if (dst < listObjPtr->internalRep.listValue.len) {
  10401. ele[dst] = ele[src];
  10402. }
  10403. listObjPtr->internalRep.listValue.len = dst;
  10404. }
  10405. static int ListSortElements(Jim_Interp *interp, Jim_Obj *listObjPtr, struct lsort_info *info)
  10406. {
  10407. struct lsort_info *prev_info;
  10408. typedef int (qsort_comparator) (const void *, const void *);
  10409. int (*fn) (Jim_Obj **, Jim_Obj **);
  10410. Jim_Obj **vector;
  10411. int len;
  10412. int rc;
  10413. JimPanic((Jim_IsShared(listObjPtr), "ListSortElements called with shared object"));
  10414. SetListFromAny(interp, listObjPtr);
  10415. prev_info = sort_info;
  10416. sort_info = info;
  10417. vector = listObjPtr->internalRep.listValue.ele;
  10418. len = listObjPtr->internalRep.listValue.len;
  10419. switch (info->type) {
  10420. case JIM_LSORT_ASCII:
  10421. fn = ListSortString;
  10422. break;
  10423. case JIM_LSORT_NOCASE:
  10424. fn = ListSortStringNoCase;
  10425. break;
  10426. case JIM_LSORT_INTEGER:
  10427. fn = ListSortInteger;
  10428. break;
  10429. case JIM_LSORT_REAL:
  10430. fn = ListSortReal;
  10431. break;
  10432. case JIM_LSORT_COMMAND:
  10433. fn = ListSortCommand;
  10434. break;
  10435. case JIM_LSORT_DICT:
  10436. fn = ListSortDict;
  10437. break;
  10438. default:
  10439. fn = NULL;
  10440. JimPanic((1, "ListSort called with invalid sort type"));
  10441. return -1;
  10442. }
  10443. if (info->indexc) {
  10444. info->subfn = fn;
  10445. fn = ListSortIndexHelper;
  10446. }
  10447. if ((rc = setjmp(info->jmpbuf)) == 0) {
  10448. qsort(vector, len, sizeof(Jim_Obj *), (qsort_comparator *) fn);
  10449. if (info->unique && len > 1) {
  10450. ListRemoveDuplicates(listObjPtr, fn);
  10451. }
  10452. Jim_InvalidateStringRep(listObjPtr);
  10453. }
  10454. sort_info = prev_info;
  10455. return rc;
  10456. }
  10457. static void ListEnsureLength(Jim_Obj *listPtr, int idx)
  10458. {
  10459. assert(idx >= 0);
  10460. if (idx >= listPtr->internalRep.listValue.maxLen) {
  10461. if (idx < 4) {
  10462. idx = 4;
  10463. }
  10464. listPtr->internalRep.listValue.ele = Jim_Realloc(listPtr->internalRep.listValue.ele,
  10465. sizeof(Jim_Obj *) * idx);
  10466. listPtr->internalRep.listValue.maxLen = idx;
  10467. }
  10468. }
  10469. static void ListInsertElements(Jim_Obj *listPtr, int idx, int elemc, Jim_Obj *const *elemVec)
  10470. {
  10471. int currentLen = listPtr->internalRep.listValue.len;
  10472. int requiredLen = currentLen + elemc;
  10473. int i;
  10474. Jim_Obj **point;
  10475. if (elemc == 0) {
  10476. return;
  10477. }
  10478. if (requiredLen > listPtr->internalRep.listValue.maxLen) {
  10479. if (currentLen) {
  10480. requiredLen *= 2;
  10481. }
  10482. ListEnsureLength(listPtr, requiredLen);
  10483. }
  10484. if (idx < 0) {
  10485. idx = currentLen;
  10486. }
  10487. point = listPtr->internalRep.listValue.ele + idx;
  10488. memmove(point + elemc, point, (currentLen - idx) * sizeof(Jim_Obj *));
  10489. for (i = 0; i < elemc; ++i) {
  10490. point[i] = elemVec[i];
  10491. Jim_IncrRefCount(point[i]);
  10492. }
  10493. listPtr->internalRep.listValue.len += elemc;
  10494. }
  10495. static void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr)
  10496. {
  10497. ListInsertElements(listPtr, -1, 1, &objPtr);
  10498. }
  10499. static void ListAppendList(Jim_Obj *listPtr, Jim_Obj *appendListPtr)
  10500. {
  10501. ListInsertElements(listPtr, -1,
  10502. appendListPtr->internalRep.listValue.len, appendListPtr->internalRep.listValue.ele);
  10503. }
  10504. void Jim_ListAppendElement(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *objPtr)
  10505. {
  10506. JimPanic((Jim_IsShared(listPtr), "Jim_ListAppendElement called with shared object"));
  10507. SetListFromAny(interp, listPtr);
  10508. Jim_InvalidateStringRep(listPtr);
  10509. ListAppendElement(listPtr, objPtr);
  10510. }
  10511. void Jim_ListAppendList(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *appendListPtr)
  10512. {
  10513. JimPanic((Jim_IsShared(listPtr), "Jim_ListAppendList called with shared object"));
  10514. SetListFromAny(interp, listPtr);
  10515. SetListFromAny(interp, appendListPtr);
  10516. Jim_InvalidateStringRep(listPtr);
  10517. ListAppendList(listPtr, appendListPtr);
  10518. }
  10519. int Jim_ListLength(Jim_Interp *interp, Jim_Obj *objPtr)
  10520. {
  10521. SetListFromAny(interp, objPtr);
  10522. return objPtr->internalRep.listValue.len;
  10523. }
  10524. void Jim_ListInsertElements(Jim_Interp *interp, Jim_Obj *listPtr, int idx,
  10525. int objc, Jim_Obj *const *objVec)
  10526. {
  10527. JimPanic((Jim_IsShared(listPtr), "Jim_ListInsertElement called with shared object"));
  10528. SetListFromAny(interp, listPtr);
  10529. if (idx >= 0 && idx > listPtr->internalRep.listValue.len)
  10530. idx = listPtr->internalRep.listValue.len;
  10531. else if (idx < 0)
  10532. idx = 0;
  10533. Jim_InvalidateStringRep(listPtr);
  10534. ListInsertElements(listPtr, idx, objc, objVec);
  10535. }
  10536. Jim_Obj *Jim_ListGetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx)
  10537. {
  10538. SetListFromAny(interp, listPtr);
  10539. if ((idx >= 0 && idx >= listPtr->internalRep.listValue.len) ||
  10540. (idx < 0 && (-idx - 1) >= listPtr->internalRep.listValue.len)) {
  10541. return NULL;
  10542. }
  10543. if (idx < 0)
  10544. idx = listPtr->internalRep.listValue.len + idx;
  10545. return listPtr->internalRep.listValue.ele[idx];
  10546. }
  10547. int Jim_ListIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx, Jim_Obj **objPtrPtr, int flags)
  10548. {
  10549. *objPtrPtr = Jim_ListGetIndex(interp, listPtr, idx);
  10550. if (*objPtrPtr == NULL) {
  10551. if (flags & JIM_ERRMSG) {
  10552. Jim_SetResultString(interp, "list index out of range", -1);
  10553. }
  10554. return JIM_ERR;
  10555. }
  10556. return JIM_OK;
  10557. }
  10558. static int Jim_ListIndices(Jim_Interp *interp, Jim_Obj *listPtr,
  10559. Jim_Obj *const *indexv, int indexc, Jim_Obj **resultObj, int flags)
  10560. {
  10561. int i;
  10562. int static_idxes[5];
  10563. int *idxes = static_idxes;
  10564. int ret = JIM_OK;
  10565. if (indexc > sizeof(static_idxes) / sizeof(*static_idxes)) {
  10566. idxes = Jim_Alloc(indexc * sizeof(*idxes));
  10567. }
  10568. for (i = 0; i < indexc; i++) {
  10569. ret = Jim_GetIndex(interp, indexv[i], &idxes[i]);
  10570. if (ret != JIM_OK) {
  10571. goto err;
  10572. }
  10573. }
  10574. for (i = 0; i < indexc; i++) {
  10575. Jim_Obj *objPtr = Jim_ListGetIndex(interp, listPtr, idxes[i]);
  10576. if (!objPtr) {
  10577. if (flags & JIM_ERRMSG) {
  10578. if (idxes[i] < 0 || idxes[i] > Jim_ListLength(interp, listPtr)) {
  10579. Jim_SetResultFormatted(interp, "index \"%#s\" out of range", indexv[i]);
  10580. }
  10581. else {
  10582. Jim_SetResultFormatted(interp, "element %#s missing from sublist \"%#s\"", indexv[i], listPtr);
  10583. }
  10584. }
  10585. return -1;
  10586. }
  10587. listPtr = objPtr;
  10588. }
  10589. *resultObj = listPtr;
  10590. err:
  10591. if (idxes != static_idxes)
  10592. Jim_Free(idxes);
  10593. return ret;
  10594. }
  10595. static int ListSetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx,
  10596. Jim_Obj *newObjPtr, int flags)
  10597. {
  10598. SetListFromAny(interp, listPtr);
  10599. if ((idx >= 0 && idx >= listPtr->internalRep.listValue.len) ||
  10600. (idx < 0 && (-idx - 1) >= listPtr->internalRep.listValue.len)) {
  10601. if (flags & JIM_ERRMSG) {
  10602. Jim_SetResultString(interp, "list index out of range", -1);
  10603. }
  10604. return JIM_ERR;
  10605. }
  10606. if (idx < 0)
  10607. idx = listPtr->internalRep.listValue.len + idx;
  10608. Jim_DecrRefCount(interp, listPtr->internalRep.listValue.ele[idx]);
  10609. listPtr->internalRep.listValue.ele[idx] = newObjPtr;
  10610. Jim_IncrRefCount(newObjPtr);
  10611. return JIM_OK;
  10612. }
  10613. int Jim_ListSetIndex(Jim_Interp *interp, Jim_Obj *varNamePtr,
  10614. Jim_Obj *const *indexv, int indexc, Jim_Obj *newObjPtr)
  10615. {
  10616. Jim_Obj *varObjPtr, *objPtr, *listObjPtr;
  10617. int shared, i, idx;
  10618. varObjPtr = objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG | JIM_UNSHARED);
  10619. if (objPtr == NULL)
  10620. return JIM_ERR;
  10621. if ((shared = Jim_IsShared(objPtr)))
  10622. varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);
  10623. for (i = 0; i < indexc - 1; i++) {
  10624. listObjPtr = objPtr;
  10625. if (Jim_GetIndex(interp, indexv[i], &idx) != JIM_OK)
  10626. goto err;
  10627. objPtr = Jim_ListGetIndex(interp, listObjPtr, idx);
  10628. if (objPtr == NULL) {
  10629. Jim_SetResultFormatted(interp, "index \"%#s\" out of range", indexv[i]);
  10630. goto err;
  10631. }
  10632. if (Jim_IsShared(objPtr)) {
  10633. objPtr = Jim_DuplicateObj(interp, objPtr);
  10634. ListSetIndex(interp, listObjPtr, idx, objPtr, JIM_NONE);
  10635. }
  10636. Jim_InvalidateStringRep(listObjPtr);
  10637. }
  10638. if (Jim_GetIndex(interp, indexv[indexc - 1], &idx) != JIM_OK)
  10639. goto err;
  10640. if (ListSetIndex(interp, objPtr, idx, newObjPtr, JIM_ERRMSG) == JIM_ERR)
  10641. goto err;
  10642. Jim_InvalidateStringRep(objPtr);
  10643. Jim_InvalidateStringRep(varObjPtr);
  10644. if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK)
  10645. goto err;
  10646. Jim_SetResult(interp, varObjPtr);
  10647. return JIM_OK;
  10648. err:
  10649. if (shared) {
  10650. Jim_FreeNewObj(interp, varObjPtr);
  10651. }
  10652. return JIM_ERR;
  10653. }
  10654. Jim_Obj *Jim_ListJoin(Jim_Interp *interp, Jim_Obj *listObjPtr, const char *joinStr, int joinStrLen)
  10655. {
  10656. int i;
  10657. int listLen = Jim_ListLength(interp, listObjPtr);
  10658. Jim_Obj *resObjPtr = Jim_NewEmptyStringObj(interp);
  10659. for (i = 0; i < listLen; ) {
  10660. Jim_AppendObj(interp, resObjPtr, Jim_ListGetIndex(interp, listObjPtr, i));
  10661. if (++i != listLen) {
  10662. Jim_AppendString(interp, resObjPtr, joinStr, joinStrLen);
  10663. }
  10664. }
  10665. return resObjPtr;
  10666. }
  10667. Jim_Obj *Jim_ConcatObj(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
  10668. {
  10669. int i;
  10670. for (i = 0; i < objc; i++) {
  10671. if (!Jim_IsList(objv[i]))
  10672. break;
  10673. }
  10674. if (i == objc) {
  10675. Jim_Obj *objPtr = Jim_NewListObj(interp, NULL, 0);
  10676. for (i = 0; i < objc; i++)
  10677. ListAppendList(objPtr, objv[i]);
  10678. return objPtr;
  10679. }
  10680. else {
  10681. int len = 0, objLen;
  10682. char *bytes, *p;
  10683. for (i = 0; i < objc; i++) {
  10684. len += Jim_Length(objv[i]);
  10685. }
  10686. if (objc)
  10687. len += objc - 1;
  10688. p = bytes = Jim_Alloc(len + 1);
  10689. for (i = 0; i < objc; i++) {
  10690. const char *s = Jim_GetString(objv[i], &objLen);
  10691. while (objLen && isspace(UCHAR(*s))) {
  10692. s++;
  10693. objLen--;
  10694. len--;
  10695. }
  10696. while (objLen && isspace(UCHAR(s[objLen - 1]))) {
  10697. if (objLen > 1 && s[objLen - 2] == '\\') {
  10698. break;
  10699. }
  10700. objLen--;
  10701. len--;
  10702. }
  10703. memcpy(p, s, objLen);
  10704. p += objLen;
  10705. if (i + 1 != objc) {
  10706. if (objLen)
  10707. *p++ = ' ';
  10708. else {
  10709. len--;
  10710. }
  10711. }
  10712. }
  10713. *p = '\0';
  10714. return Jim_NewStringObjNoAlloc(interp, bytes, len);
  10715. }
  10716. }
  10717. Jim_Obj *Jim_ListRange(Jim_Interp *interp, Jim_Obj *listObjPtr, Jim_Obj *firstObjPtr,
  10718. Jim_Obj *lastObjPtr)
  10719. {
  10720. int first, last;
  10721. int len, rangeLen;
  10722. if (Jim_GetIndex(interp, firstObjPtr, &first) != JIM_OK ||
  10723. Jim_GetIndex(interp, lastObjPtr, &last) != JIM_OK)
  10724. return NULL;
  10725. len = Jim_ListLength(interp, listObjPtr);
  10726. first = JimRelToAbsIndex(len, first);
  10727. last = JimRelToAbsIndex(len, last);
  10728. JimRelToAbsRange(len, &first, &last, &rangeLen);
  10729. if (first == 0 && last == len) {
  10730. return listObjPtr;
  10731. }
  10732. return Jim_NewListObj(interp, listObjPtr->internalRep.listValue.ele + first, rangeLen);
  10733. }
  10734. static void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
  10735. static void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
  10736. static void UpdateStringOfDict(struct Jim_Obj *objPtr);
  10737. static int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
  10738. static const Jim_ObjType dictObjType = {
  10739. "dict",
  10740. FreeDictInternalRep,
  10741. DupDictInternalRep,
  10742. UpdateStringOfDict,
  10743. JIM_TYPE_NONE,
  10744. };
  10745. static void JimFreeDict(Jim_Interp *interp, Jim_Dict *dict)
  10746. {
  10747. int i;
  10748. for (i = 0; i < dict->len; i++) {
  10749. Jim_DecrRefCount(interp, dict->table[i]);
  10750. }
  10751. Jim_Free(dict->table);
  10752. Jim_Free(dict->ht);
  10753. Jim_Free(dict);
  10754. }
  10755. enum {
  10756. DICT_HASH_FIND = -1,
  10757. DICT_HASH_REMOVE = -2,
  10758. DICT_HASH_ADD = -3,
  10759. };
  10760. static int JimDictHashFind(Jim_Dict *dict, Jim_Obj *keyObjPtr, int op_tvoffset)
  10761. {
  10762. unsigned h = (JimObjectHTHashFunction(keyObjPtr) + dict->uniq);
  10763. unsigned idx = h & dict->sizemask;
  10764. int tvoffset = 0;
  10765. unsigned peturb = h;
  10766. unsigned first_removed = ~0;
  10767. if (dict->len) {
  10768. while ((tvoffset = dict->ht[idx].offset)) {
  10769. if (tvoffset == -1) {
  10770. if (first_removed == ~0) {
  10771. first_removed = idx;
  10772. }
  10773. }
  10774. else if (dict->ht[idx].hash == h) {
  10775. if (Jim_StringEqObj(keyObjPtr, dict->table[tvoffset - 1])) {
  10776. break;
  10777. }
  10778. }
  10779. peturb >>= 5;
  10780. idx = (5 * idx + 1 + peturb) & dict->sizemask;
  10781. }
  10782. }
  10783. switch (op_tvoffset) {
  10784. case DICT_HASH_FIND:
  10785. break;
  10786. case DICT_HASH_REMOVE:
  10787. if (tvoffset) {
  10788. dict->ht[idx].offset = -1;
  10789. dict->dummy++;
  10790. }
  10791. break;
  10792. case DICT_HASH_ADD:
  10793. if (tvoffset == 0) {
  10794. if (first_removed != ~0) {
  10795. idx = first_removed;
  10796. dict->dummy--;
  10797. }
  10798. dict->ht[idx].offset = dict->len + 1;
  10799. dict->ht[idx].hash = h;
  10800. }
  10801. break;
  10802. default:
  10803. assert(tvoffset);
  10804. dict->ht[idx].offset = op_tvoffset;
  10805. break;
  10806. }
  10807. return tvoffset;
  10808. }
  10809. static void JimDictExpandHashTable(Jim_Dict *dict, unsigned int size)
  10810. {
  10811. int i;
  10812. struct JimDictHashEntry *prevht = dict->ht;
  10813. int prevsize = dict->size;
  10814. dict->size = JimHashTableNextPower(size);
  10815. dict->sizemask = dict->size - 1;
  10816. dict->ht = Jim_Alloc(dict->size * sizeof(*dict->ht));
  10817. memset(dict->ht, 0, dict->size * sizeof(*dict->ht));
  10818. for (i = 0; i < prevsize; i++) {
  10819. if (prevht[i].offset > 0) {
  10820. unsigned h = prevht[i].hash;
  10821. unsigned idx = h & dict->sizemask;
  10822. unsigned peturb = h;
  10823. while (dict->ht[idx].offset) {
  10824. peturb >>= 5;
  10825. idx = (5 * idx + 1 + peturb) & dict->sizemask;
  10826. }
  10827. dict->ht[idx].offset = prevht[i].offset;
  10828. dict->ht[idx].hash = h;
  10829. }
  10830. }
  10831. Jim_Free(prevht);
  10832. }
  10833. static int JimDictAdd(Jim_Dict *dict, Jim_Obj *keyObjPtr)
  10834. {
  10835. if (dict->size <= dict->len + dict->dummy) {
  10836. JimDictExpandHashTable(dict, dict->size ? dict->size * 2 : 8);
  10837. }
  10838. return JimDictHashFind(dict, keyObjPtr, DICT_HASH_ADD);
  10839. }
  10840. static Jim_Dict *JimDictNew(Jim_Interp *interp, int table_size, int ht_size)
  10841. {
  10842. Jim_Dict *dict = Jim_Alloc(sizeof(*dict));
  10843. memset(dict, 0, sizeof(*dict));
  10844. if (ht_size) {
  10845. JimDictExpandHashTable(dict, ht_size);
  10846. }
  10847. if (table_size) {
  10848. dict->table = Jim_Alloc(table_size * sizeof(*dict->table));
  10849. dict->maxLen = table_size;
  10850. }
  10851. #ifdef JIM_RANDOMISE_HASH
  10852. dict->uniq = (rand() ^ time(NULL) ^ clock());
  10853. #endif
  10854. return dict;
  10855. }
  10856. static void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
  10857. {
  10858. JimFreeDict(interp, objPtr->internalRep.dictValue);
  10859. }
  10860. static void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
  10861. {
  10862. Jim_Dict *oldDict = srcPtr->internalRep.dictValue;
  10863. int i;
  10864. Jim_Dict *newDict = JimDictNew(interp, oldDict->maxLen, oldDict->size);
  10865. for (i = 0; i < oldDict->len; i++) {
  10866. newDict->table[i] = oldDict->table[i];
  10867. Jim_IncrRefCount(newDict->table[i]);
  10868. }
  10869. newDict->len = oldDict->len;
  10870. newDict->uniq = oldDict->uniq;
  10871. memcpy(newDict->ht, oldDict->ht, sizeof(*oldDict->ht) * oldDict->size);
  10872. dupPtr->internalRep.dictValue = newDict;
  10873. dupPtr->typePtr = &dictObjType;
  10874. }
  10875. static void UpdateStringOfDict(struct Jim_Obj *objPtr)
  10876. {
  10877. JimMakeListStringRep(objPtr, objPtr->internalRep.dictValue->table, objPtr->internalRep.dictValue->len);
  10878. }
  10879. static int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
  10880. {
  10881. int listlen;
  10882. if (objPtr->typePtr == &dictObjType) {
  10883. return JIM_OK;
  10884. }
  10885. if (Jim_IsList(objPtr) && Jim_IsShared(objPtr)) {
  10886. Jim_String(objPtr);
  10887. }
  10888. listlen = Jim_ListLength(interp, objPtr);
  10889. if (listlen % 2) {
  10890. Jim_SetResultString(interp, "missing value to go with key", -1);
  10891. return JIM_ERR;
  10892. }
  10893. else {
  10894. Jim_Dict *dict = JimDictNew(interp, 0, listlen);
  10895. int i;
  10896. dict->table = objPtr->internalRep.listValue.ele;
  10897. dict->maxLen = objPtr->internalRep.listValue.maxLen;
  10898. for (i = 0; i < listlen; i += 2) {
  10899. int tvoffset = JimDictAdd(dict, dict->table[i]);
  10900. if (tvoffset) {
  10901. Jim_DecrRefCount(interp, dict->table[tvoffset]);
  10902. dict->table[tvoffset] = dict->table[i + 1];
  10903. Jim_DecrRefCount(interp, dict->table[i]);
  10904. }
  10905. else {
  10906. if (dict->len != i) {
  10907. dict->table[dict->len++] = dict->table[i];
  10908. dict->table[dict->len++] = dict->table[i + 1];
  10909. }
  10910. else {
  10911. dict->len += 2;
  10912. }
  10913. }
  10914. }
  10915. objPtr->typePtr = &dictObjType;
  10916. objPtr->internalRep.dictValue = dict;
  10917. return JIM_OK;
  10918. }
  10919. }
  10920. static int DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
  10921. Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr)
  10922. {
  10923. Jim_Dict *dict = objPtr->internalRep.dictValue;
  10924. if (valueObjPtr == NULL) {
  10925. int tvoffset = JimDictHashFind(dict, keyObjPtr, DICT_HASH_REMOVE);
  10926. if (tvoffset) {
  10927. Jim_DecrRefCount(interp, dict->table[tvoffset - 1]);
  10928. Jim_DecrRefCount(interp, dict->table[tvoffset]);
  10929. dict->len -= 2;
  10930. if (tvoffset != dict->len + 1) {
  10931. dict->table[tvoffset - 1] = dict->table[dict->len];
  10932. dict->table[tvoffset] = dict->table[dict->len + 1];
  10933. JimDictHashFind(dict, dict->table[tvoffset - 1], tvoffset);
  10934. }
  10935. return JIM_OK;
  10936. }
  10937. return JIM_ERR;
  10938. }
  10939. else {
  10940. int tvoffset = JimDictAdd(dict, keyObjPtr);
  10941. if (tvoffset) {
  10942. Jim_IncrRefCount(valueObjPtr);
  10943. Jim_DecrRefCount(interp, dict->table[tvoffset]);
  10944. dict->table[tvoffset] = valueObjPtr;
  10945. }
  10946. else {
  10947. if (dict->maxLen == dict->len) {
  10948. if (dict->maxLen < 4) {
  10949. dict->maxLen = 4;
  10950. }
  10951. else {
  10952. dict->maxLen *= 2;
  10953. }
  10954. dict->table = Jim_Realloc(dict->table, dict->maxLen * sizeof(*dict->table));
  10955. }
  10956. Jim_IncrRefCount(keyObjPtr);
  10957. Jim_IncrRefCount(valueObjPtr);
  10958. dict->table[dict->len++] = keyObjPtr;
  10959. dict->table[dict->len++] = valueObjPtr;
  10960. }
  10961. return JIM_OK;
  10962. }
  10963. }
  10964. int Jim_DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
  10965. Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr)
  10966. {
  10967. JimPanic((Jim_IsShared(objPtr), "Jim_DictAddElement called with shared object"));
  10968. if (SetDictFromAny(interp, objPtr) != JIM_OK) {
  10969. return JIM_ERR;
  10970. }
  10971. Jim_InvalidateStringRep(objPtr);
  10972. return DictAddElement(interp, objPtr, keyObjPtr, valueObjPtr);
  10973. }
  10974. Jim_Obj *Jim_NewDictObj(Jim_Interp *interp, Jim_Obj *const *elements, int len)
  10975. {
  10976. Jim_Obj *objPtr;
  10977. int i;
  10978. JimPanic((len % 2, "Jim_NewDictObj() 'len' argument must be even"));
  10979. objPtr = Jim_NewObj(interp);
  10980. objPtr->typePtr = &dictObjType;
  10981. objPtr->bytes = NULL;
  10982. objPtr->internalRep.dictValue = JimDictNew(interp, len, len);
  10983. for (i = 0; i < len; i += 2)
  10984. DictAddElement(interp, objPtr, elements[i], elements[i + 1]);
  10985. return objPtr;
  10986. }
  10987. int Jim_DictKey(Jim_Interp *interp, Jim_Obj *dictPtr, Jim_Obj *keyPtr,
  10988. Jim_Obj **objPtrPtr, int flags)
  10989. {
  10990. int tvoffset;
  10991. Jim_Dict *dict;
  10992. if (SetDictFromAny(interp, dictPtr) != JIM_OK) {
  10993. return -1;
  10994. }
  10995. dict = dictPtr->internalRep.dictValue;
  10996. tvoffset = JimDictHashFind(dict, keyPtr, DICT_HASH_FIND);
  10997. if (tvoffset == 0) {
  10998. if (flags & JIM_ERRMSG) {
  10999. Jim_SetResultFormatted(interp, "key \"%#s\" not known in dictionary", keyPtr);
  11000. }
  11001. return JIM_ERR;
  11002. }
  11003. *objPtrPtr = dict->table[tvoffset];
  11004. return JIM_OK;
  11005. }
  11006. Jim_Obj **Jim_DictPairs(Jim_Interp *interp, Jim_Obj *dictPtr, int *len)
  11007. {
  11008. if (Jim_IsList(dictPtr)) {
  11009. Jim_Obj **table;
  11010. JimListGetElements(interp, dictPtr, len, &table);
  11011. if (*len % 2 == 0) {
  11012. return table;
  11013. }
  11014. }
  11015. if (SetDictFromAny(interp, dictPtr) != JIM_OK) {
  11016. *len = 1;
  11017. return NULL;
  11018. }
  11019. *len = dictPtr->internalRep.dictValue->len;
  11020. return dictPtr->internalRep.dictValue->table;
  11021. }
  11022. int Jim_DictKeysVector(Jim_Interp *interp, Jim_Obj *dictPtr,
  11023. Jim_Obj *const *keyv, int keyc, Jim_Obj **objPtrPtr, int flags)
  11024. {
  11025. int i;
  11026. if (keyc == 0) {
  11027. *objPtrPtr = dictPtr;
  11028. return JIM_OK;
  11029. }
  11030. for (i = 0; i < keyc; i++) {
  11031. Jim_Obj *objPtr;
  11032. int rc = Jim_DictKey(interp, dictPtr, keyv[i], &objPtr, flags);
  11033. if (rc != JIM_OK) {
  11034. return rc;
  11035. }
  11036. dictPtr = objPtr;
  11037. }
  11038. *objPtrPtr = dictPtr;
  11039. return JIM_OK;
  11040. }
  11041. int Jim_SetDictKeysVector(Jim_Interp *interp, Jim_Obj *varNamePtr,
  11042. Jim_Obj *const *keyv, int keyc, Jim_Obj *newObjPtr, int flags)
  11043. {
  11044. Jim_Obj *varObjPtr, *objPtr, *dictObjPtr;
  11045. int shared, i;
  11046. varObjPtr = objPtr = Jim_GetVariable(interp, varNamePtr, flags);
  11047. if (objPtr == NULL) {
  11048. if (newObjPtr == NULL && (flags & JIM_MUSTEXIST)) {
  11049. return JIM_ERR;
  11050. }
  11051. varObjPtr = objPtr = Jim_NewDictObj(interp, NULL, 0);
  11052. if (Jim_SetVariable(interp, varNamePtr, objPtr) != JIM_OK) {
  11053. Jim_FreeNewObj(interp, varObjPtr);
  11054. return JIM_ERR;
  11055. }
  11056. }
  11057. if ((shared = Jim_IsShared(objPtr)))
  11058. varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);
  11059. for (i = 0; i < keyc; i++) {
  11060. dictObjPtr = objPtr;
  11061. if (SetDictFromAny(interp, dictObjPtr) != JIM_OK) {
  11062. goto err;
  11063. }
  11064. if (i == keyc - 1) {
  11065. if (Jim_DictAddElement(interp, objPtr, keyv[keyc - 1], newObjPtr) != JIM_OK) {
  11066. if (newObjPtr || (flags & JIM_MUSTEXIST)) {
  11067. goto err;
  11068. }
  11069. }
  11070. break;
  11071. }
  11072. Jim_InvalidateStringRep(dictObjPtr);
  11073. if (Jim_DictKey(interp, dictObjPtr, keyv[i], &objPtr,
  11074. newObjPtr ? JIM_NONE : JIM_ERRMSG) == JIM_OK) {
  11075. if (Jim_IsShared(objPtr)) {
  11076. objPtr = Jim_DuplicateObj(interp, objPtr);
  11077. DictAddElement(interp, dictObjPtr, keyv[i], objPtr);
  11078. }
  11079. }
  11080. else {
  11081. if (newObjPtr == NULL) {
  11082. goto err;
  11083. }
  11084. objPtr = Jim_NewDictObj(interp, NULL, 0);
  11085. DictAddElement(interp, dictObjPtr, keyv[i], objPtr);
  11086. }
  11087. }
  11088. Jim_InvalidateStringRep(objPtr);
  11089. Jim_InvalidateStringRep(varObjPtr);
  11090. if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK) {
  11091. goto err;
  11092. }
  11093. if (!(flags & JIM_NORESULT)) {
  11094. Jim_SetResult(interp, varObjPtr);
  11095. }
  11096. return JIM_OK;
  11097. err:
  11098. if (shared) {
  11099. Jim_FreeNewObj(interp, varObjPtr);
  11100. }
  11101. return JIM_ERR;
  11102. }
  11103. static void UpdateStringOfIndex(struct Jim_Obj *objPtr);
  11104. static int SetIndexFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
  11105. static const Jim_ObjType indexObjType = {
  11106. "index",
  11107. NULL,
  11108. NULL,
  11109. UpdateStringOfIndex,
  11110. JIM_TYPE_NONE,
  11111. };
  11112. static void UpdateStringOfIndex(struct Jim_Obj *objPtr)
  11113. {
  11114. if (objPtr->internalRep.intValue == -1) {
  11115. JimSetStringBytes(objPtr, "end");
  11116. }
  11117. else {
  11118. char buf[JIM_INTEGER_SPACE + 1];
  11119. if (objPtr->internalRep.intValue >= 0 || objPtr->internalRep.intValue == -INT_MAX) {
  11120. sprintf(buf, "%d", objPtr->internalRep.intValue);
  11121. }
  11122. else {
  11123. sprintf(buf, "end%d", objPtr->internalRep.intValue + 1);
  11124. }
  11125. JimSetStringBytes(objPtr, buf);
  11126. }
  11127. }
  11128. static int SetIndexFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
  11129. {
  11130. jim_wide idx;
  11131. int end = 0;
  11132. const char *str;
  11133. Jim_Obj *exprObj = objPtr;
  11134. JimPanic((objPtr->refCount == 0, "SetIndexFromAny() called with zero refcount object"));
  11135. str = Jim_String(objPtr);
  11136. if (strncmp(str, "end", 3) == 0) {
  11137. end = 1;
  11138. str += 3;
  11139. idx = 0;
  11140. switch (*str) {
  11141. case '\0':
  11142. exprObj = NULL;
  11143. break;
  11144. case '-':
  11145. case '+':
  11146. exprObj = Jim_NewStringObj(interp, str, -1);
  11147. break;
  11148. default:
  11149. goto badindex;
  11150. }
  11151. }
  11152. if (exprObj) {
  11153. int ret;
  11154. Jim_IncrRefCount(exprObj);
  11155. ret = Jim_GetWideExpr(interp, exprObj, &idx);
  11156. Jim_DecrRefCount(interp, exprObj);
  11157. if (ret != JIM_OK) {
  11158. goto badindex;
  11159. }
  11160. }
  11161. if (end) {
  11162. if (idx > 0) {
  11163. idx = INT_MAX;
  11164. }
  11165. else {
  11166. idx--;
  11167. }
  11168. }
  11169. else if (idx < 0) {
  11170. idx = -INT_MAX;
  11171. }
  11172. Jim_FreeIntRep(interp, objPtr);
  11173. objPtr->typePtr = &indexObjType;
  11174. objPtr->internalRep.intValue = idx;
  11175. return JIM_OK;
  11176. badindex:
  11177. Jim_SetResultFormatted(interp,
  11178. "bad index \"%#s\": must be intexpr or end?[+-]intexpr?", objPtr);
  11179. return JIM_ERR;
  11180. }
  11181. int Jim_GetIndex(Jim_Interp *interp, Jim_Obj *objPtr, int *indexPtr)
  11182. {
  11183. if (objPtr->typePtr == &intObjType) {
  11184. jim_wide val = JimWideValue(objPtr);
  11185. if (val < 0)
  11186. *indexPtr = -INT_MAX;
  11187. else if (val > INT_MAX)
  11188. *indexPtr = INT_MAX;
  11189. else
  11190. *indexPtr = (int)val;
  11191. return JIM_OK;
  11192. }
  11193. if (objPtr->typePtr != &indexObjType && SetIndexFromAny(interp, objPtr) == JIM_ERR)
  11194. return JIM_ERR;
  11195. *indexPtr = objPtr->internalRep.intValue;
  11196. return JIM_OK;
  11197. }
  11198. static const char * const jimReturnCodes[] = {
  11199. "ok",
  11200. "error",
  11201. "return",
  11202. "break",
  11203. "continue",
  11204. "signal",
  11205. "exit",
  11206. "eval",
  11207. NULL
  11208. };
  11209. #define jimReturnCodesSize (sizeof(jimReturnCodes)/sizeof(*jimReturnCodes) - 1)
  11210. static const Jim_ObjType returnCodeObjType = {
  11211. "return-code",
  11212. NULL,
  11213. NULL,
  11214. NULL,
  11215. JIM_TYPE_NONE,
  11216. };
  11217. const char *Jim_ReturnCode(int code)
  11218. {
  11219. if (code < 0 || code >= (int)jimReturnCodesSize) {
  11220. return "?";
  11221. }
  11222. else {
  11223. return jimReturnCodes[code];
  11224. }
  11225. }
  11226. static int SetReturnCodeFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
  11227. {
  11228. int returnCode;
  11229. jim_wide wideValue;
  11230. if (JimGetWideNoErr(interp, objPtr, &wideValue) != JIM_ERR)
  11231. returnCode = (int)wideValue;
  11232. else if (Jim_GetEnum(interp, objPtr, jimReturnCodes, &returnCode, NULL, JIM_NONE) != JIM_OK) {
  11233. Jim_SetResultFormatted(interp, "expected return code but got \"%#s\"", objPtr);
  11234. return JIM_ERR;
  11235. }
  11236. Jim_FreeIntRep(interp, objPtr);
  11237. objPtr->typePtr = &returnCodeObjType;
  11238. objPtr->internalRep.intValue = returnCode;
  11239. return JIM_OK;
  11240. }
  11241. int Jim_GetReturnCode(Jim_Interp *interp, Jim_Obj *objPtr, int *intPtr)
  11242. {
  11243. if (objPtr->typePtr != &returnCodeObjType && SetReturnCodeFromAny(interp, objPtr) == JIM_ERR)
  11244. return JIM_ERR;
  11245. *intPtr = objPtr->internalRep.intValue;
  11246. return JIM_OK;
  11247. }
  11248. static int JimParseExprOperator(struct JimParserCtx *pc);
  11249. static int JimParseExprNumber(struct JimParserCtx *pc);
  11250. static int JimParseExprIrrational(struct JimParserCtx *pc);
  11251. static int JimParseExprBoolean(struct JimParserCtx *pc);
  11252. enum
  11253. {
  11254. JIM_EXPROP_MUL = JIM_TT_EXPR_OP,
  11255. JIM_EXPROP_DIV,
  11256. JIM_EXPROP_MOD,
  11257. JIM_EXPROP_SUB,
  11258. JIM_EXPROP_ADD,
  11259. JIM_EXPROP_LSHIFT,
  11260. JIM_EXPROP_RSHIFT,
  11261. JIM_EXPROP_ROTL,
  11262. JIM_EXPROP_ROTR,
  11263. JIM_EXPROP_LT,
  11264. JIM_EXPROP_GT,
  11265. JIM_EXPROP_LTE,
  11266. JIM_EXPROP_GTE,
  11267. JIM_EXPROP_NUMEQ,
  11268. JIM_EXPROP_NUMNE,
  11269. JIM_EXPROP_BITAND,
  11270. JIM_EXPROP_BITXOR,
  11271. JIM_EXPROP_BITOR,
  11272. JIM_EXPROP_LOGICAND,
  11273. JIM_EXPROP_LOGICOR,
  11274. JIM_EXPROP_TERNARY,
  11275. JIM_EXPROP_COLON,
  11276. JIM_EXPROP_POW,
  11277. JIM_EXPROP_STREQ,
  11278. JIM_EXPROP_STRNE,
  11279. JIM_EXPROP_STRIN,
  11280. JIM_EXPROP_STRNI,
  11281. JIM_EXPROP_STRLT,
  11282. JIM_EXPROP_STRGT,
  11283. JIM_EXPROP_STRLE,
  11284. JIM_EXPROP_STRGE,
  11285. JIM_EXPROP_NOT,
  11286. JIM_EXPROP_BITNOT,
  11287. JIM_EXPROP_UNARYMINUS,
  11288. JIM_EXPROP_UNARYPLUS,
  11289. JIM_EXPROP_FUNC_INT,
  11290. JIM_EXPROP_FUNC_WIDE,
  11291. JIM_EXPROP_FUNC_ABS,
  11292. JIM_EXPROP_FUNC_DOUBLE,
  11293. JIM_EXPROP_FUNC_ROUND,
  11294. JIM_EXPROP_FUNC_RAND,
  11295. JIM_EXPROP_FUNC_SRAND,
  11296. JIM_EXPROP_FUNC_SIN,
  11297. JIM_EXPROP_FUNC_COS,
  11298. JIM_EXPROP_FUNC_TAN,
  11299. JIM_EXPROP_FUNC_ASIN,
  11300. JIM_EXPROP_FUNC_ACOS,
  11301. JIM_EXPROP_FUNC_ATAN,
  11302. JIM_EXPROP_FUNC_ATAN2,
  11303. JIM_EXPROP_FUNC_SINH,
  11304. JIM_EXPROP_FUNC_COSH,
  11305. JIM_EXPROP_FUNC_TANH,
  11306. JIM_EXPROP_FUNC_CEIL,
  11307. JIM_EXPROP_FUNC_FLOOR,
  11308. JIM_EXPROP_FUNC_EXP,
  11309. JIM_EXPROP_FUNC_LOG,
  11310. JIM_EXPROP_FUNC_LOG10,
  11311. JIM_EXPROP_FUNC_SQRT,
  11312. JIM_EXPROP_FUNC_POW,
  11313. JIM_EXPROP_FUNC_HYPOT,
  11314. JIM_EXPROP_FUNC_FMOD,
  11315. };
  11316. struct JimExprNode {
  11317. int type;
  11318. struct Jim_Obj *objPtr;
  11319. struct JimExprNode *left;
  11320. struct JimExprNode *right;
  11321. struct JimExprNode *ternary;
  11322. };
  11323. typedef struct Jim_ExprOperator
  11324. {
  11325. const char *name;
  11326. int (*funcop) (Jim_Interp *interp, struct JimExprNode *opnode);
  11327. unsigned char precedence;
  11328. unsigned char arity;
  11329. unsigned char attr;
  11330. unsigned char namelen;
  11331. } Jim_ExprOperator;
  11332. static int JimExprGetTerm(Jim_Interp *interp, struct JimExprNode *node, Jim_Obj **objPtrPtr);
  11333. static int JimExprGetTermBoolean(Jim_Interp *interp, struct JimExprNode *node);
  11334. static int JimExprEvalTermNode(Jim_Interp *interp, struct JimExprNode *node);
  11335. static int JimExprOpNumUnary(Jim_Interp *interp, struct JimExprNode *node)
  11336. {
  11337. int intresult = 1;
  11338. int rc, bA = 0;
  11339. double dA, dC = 0;
  11340. jim_wide wA, wC = 0;
  11341. Jim_Obj *A;
  11342. if ((rc = JimExprGetTerm(interp, node->left, &A)) != JIM_OK) {
  11343. return rc;
  11344. }
  11345. if ((A->typePtr != &doubleObjType || A->bytes) && JimGetWideNoErr(interp, A, &wA) == JIM_OK) {
  11346. switch (node->type) {
  11347. case JIM_EXPROP_FUNC_INT:
  11348. case JIM_EXPROP_FUNC_WIDE:
  11349. case JIM_EXPROP_FUNC_ROUND:
  11350. case JIM_EXPROP_UNARYPLUS:
  11351. wC = wA;
  11352. break;
  11353. case JIM_EXPROP_FUNC_DOUBLE:
  11354. dC = wA;
  11355. intresult = 0;
  11356. break;
  11357. case JIM_EXPROP_FUNC_ABS:
  11358. wC = wA >= 0 ? wA : -wA;
  11359. break;
  11360. case JIM_EXPROP_UNARYMINUS:
  11361. wC = -wA;
  11362. break;
  11363. case JIM_EXPROP_NOT:
  11364. wC = !wA;
  11365. break;
  11366. default:
  11367. abort();
  11368. }
  11369. }
  11370. else if ((rc = Jim_GetDouble(interp, A, &dA)) == JIM_OK) {
  11371. switch (node->type) {
  11372. case JIM_EXPROP_FUNC_INT:
  11373. case JIM_EXPROP_FUNC_WIDE:
  11374. wC = dA;
  11375. break;
  11376. case JIM_EXPROP_FUNC_ROUND:
  11377. wC = dA < 0 ? (dA - 0.5) : (dA + 0.5);
  11378. break;
  11379. case JIM_EXPROP_FUNC_DOUBLE:
  11380. case JIM_EXPROP_UNARYPLUS:
  11381. dC = dA;
  11382. intresult = 0;
  11383. break;
  11384. case JIM_EXPROP_FUNC_ABS:
  11385. #ifdef JIM_MATH_FUNCTIONS
  11386. dC = fabs(dA);
  11387. #else
  11388. dC = dA >= 0 ? dA : -dA;
  11389. #endif
  11390. intresult = 0;
  11391. break;
  11392. case JIM_EXPROP_UNARYMINUS:
  11393. dC = -dA;
  11394. intresult = 0;
  11395. break;
  11396. case JIM_EXPROP_NOT:
  11397. wC = !dA;
  11398. break;
  11399. default:
  11400. abort();
  11401. }
  11402. }
  11403. else if ((rc = Jim_GetBoolean(interp, A, &bA)) == JIM_OK) {
  11404. switch (node->type) {
  11405. case JIM_EXPROP_NOT:
  11406. wC = !bA;
  11407. break;
  11408. default:
  11409. abort();
  11410. }
  11411. }
  11412. if (rc == JIM_OK) {
  11413. if (intresult) {
  11414. Jim_SetResultInt(interp, wC);
  11415. }
  11416. else {
  11417. Jim_SetResult(interp, Jim_NewDoubleObj(interp, dC));
  11418. }
  11419. }
  11420. Jim_DecrRefCount(interp, A);
  11421. return rc;
  11422. }
  11423. static double JimRandDouble(Jim_Interp *interp)
  11424. {
  11425. unsigned long x;
  11426. JimRandomBytes(interp, &x, sizeof(x));
  11427. return (double)x / (double)~0UL;
  11428. }
  11429. static int JimExprOpIntUnary(Jim_Interp *interp, struct JimExprNode *node)
  11430. {
  11431. jim_wide wA;
  11432. Jim_Obj *A;
  11433. int rc;
  11434. if ((rc = JimExprGetTerm(interp, node->left, &A)) != JIM_OK) {
  11435. return rc;
  11436. }
  11437. rc = Jim_GetWide(interp, A, &wA);
  11438. if (rc == JIM_OK) {
  11439. switch (node->type) {
  11440. case JIM_EXPROP_BITNOT:
  11441. Jim_SetResultInt(interp, ~wA);
  11442. break;
  11443. case JIM_EXPROP_FUNC_SRAND:
  11444. JimPrngSeed(interp, (unsigned char *)&wA, sizeof(wA));
  11445. Jim_SetResult(interp, Jim_NewDoubleObj(interp, JimRandDouble(interp)));
  11446. break;
  11447. default:
  11448. abort();
  11449. }
  11450. }
  11451. Jim_DecrRefCount(interp, A);
  11452. return rc;
  11453. }
  11454. static int JimExprOpNone(Jim_Interp *interp, struct JimExprNode *node)
  11455. {
  11456. JimPanic((node->type != JIM_EXPROP_FUNC_RAND, "JimExprOpNone only support rand()"));
  11457. Jim_SetResult(interp, Jim_NewDoubleObj(interp, JimRandDouble(interp)));
  11458. return JIM_OK;
  11459. }
  11460. #ifdef JIM_MATH_FUNCTIONS
  11461. static int JimExprOpDoubleUnary(Jim_Interp *interp, struct JimExprNode *node)
  11462. {
  11463. int rc;
  11464. double dA, dC;
  11465. Jim_Obj *A;
  11466. if ((rc = JimExprGetTerm(interp, node->left, &A)) != JIM_OK) {
  11467. return rc;
  11468. }
  11469. rc = Jim_GetDouble(interp, A, &dA);
  11470. if (rc == JIM_OK) {
  11471. switch (node->type) {
  11472. case JIM_EXPROP_FUNC_SIN:
  11473. dC = sin(dA);
  11474. break;
  11475. case JIM_EXPROP_FUNC_COS:
  11476. dC = cos(dA);
  11477. break;
  11478. case JIM_EXPROP_FUNC_TAN:
  11479. dC = tan(dA);
  11480. break;
  11481. case JIM_EXPROP_FUNC_ASIN:
  11482. dC = asin(dA);
  11483. break;
  11484. case JIM_EXPROP_FUNC_ACOS:
  11485. dC = acos(dA);
  11486. break;
  11487. case JIM_EXPROP_FUNC_ATAN:
  11488. dC = atan(dA);
  11489. break;
  11490. case JIM_EXPROP_FUNC_SINH:
  11491. dC = sinh(dA);
  11492. break;
  11493. case JIM_EXPROP_FUNC_COSH:
  11494. dC = cosh(dA);
  11495. break;
  11496. case JIM_EXPROP_FUNC_TANH:
  11497. dC = tanh(dA);
  11498. break;
  11499. case JIM_EXPROP_FUNC_CEIL:
  11500. dC = ceil(dA);
  11501. break;
  11502. case JIM_EXPROP_FUNC_FLOOR:
  11503. dC = floor(dA);
  11504. break;
  11505. case JIM_EXPROP_FUNC_EXP:
  11506. dC = exp(dA);
  11507. break;
  11508. case JIM_EXPROP_FUNC_LOG:
  11509. dC = log(dA);
  11510. break;
  11511. case JIM_EXPROP_FUNC_LOG10:
  11512. dC = log10(dA);
  11513. break;
  11514. case JIM_EXPROP_FUNC_SQRT:
  11515. dC = sqrt(dA);
  11516. break;
  11517. default:
  11518. abort();
  11519. }
  11520. Jim_SetResult(interp, Jim_NewDoubleObj(interp, dC));
  11521. }
  11522. Jim_DecrRefCount(interp, A);
  11523. return rc;
  11524. }
  11525. #endif
  11526. static int JimExprOpIntBin(Jim_Interp *interp, struct JimExprNode *node)
  11527. {
  11528. jim_wide wA, wB;
  11529. int rc;
  11530. Jim_Obj *A, *B;
  11531. if ((rc = JimExprGetTerm(interp, node->left, &A)) != JIM_OK) {
  11532. return rc;
  11533. }
  11534. if ((rc = JimExprGetTerm(interp, node->right, &B)) != JIM_OK) {
  11535. Jim_DecrRefCount(interp, A);
  11536. return rc;
  11537. }
  11538. rc = JIM_ERR;
  11539. if (Jim_GetWide(interp, A, &wA) == JIM_OK && Jim_GetWide(interp, B, &wB) == JIM_OK) {
  11540. jim_wide wC;
  11541. rc = JIM_OK;
  11542. switch (node->type) {
  11543. case JIM_EXPROP_LSHIFT:
  11544. wC = wA << wB;
  11545. break;
  11546. case JIM_EXPROP_RSHIFT:
  11547. wC = wA >> wB;
  11548. break;
  11549. case JIM_EXPROP_BITAND:
  11550. wC = wA & wB;
  11551. break;
  11552. case JIM_EXPROP_BITXOR:
  11553. wC = wA ^ wB;
  11554. break;
  11555. case JIM_EXPROP_BITOR:
  11556. wC = wA | wB;
  11557. break;
  11558. case JIM_EXPROP_MOD:
  11559. if (wB == 0) {
  11560. wC = 0;
  11561. Jim_SetResultString(interp, "Division by zero", -1);
  11562. rc = JIM_ERR;
  11563. }
  11564. else {
  11565. int negative = 0;
  11566. if (wB < 0) {
  11567. wB = -wB;
  11568. wA = -wA;
  11569. negative = 1;
  11570. }
  11571. wC = wA % wB;
  11572. if (wC < 0) {
  11573. wC += wB;
  11574. }
  11575. if (negative) {
  11576. wC = -wC;
  11577. }
  11578. }
  11579. break;
  11580. case JIM_EXPROP_ROTL:
  11581. case JIM_EXPROP_ROTR:{
  11582. unsigned long uA = (unsigned long)wA;
  11583. unsigned long uB = (unsigned long)wB;
  11584. const unsigned int S = sizeof(unsigned long) * 8;
  11585. uB %= S;
  11586. if (node->type == JIM_EXPROP_ROTR) {
  11587. uB = S - uB;
  11588. }
  11589. wC = (unsigned long)(uA << uB) | (uA >> (S - uB));
  11590. break;
  11591. }
  11592. default:
  11593. abort();
  11594. }
  11595. Jim_SetResultInt(interp, wC);
  11596. }
  11597. Jim_DecrRefCount(interp, A);
  11598. Jim_DecrRefCount(interp, B);
  11599. return rc;
  11600. }
  11601. static int JimExprOpBin(Jim_Interp *interp, struct JimExprNode *node)
  11602. {
  11603. int rc = JIM_OK;
  11604. double dA, dB, dC = 0;
  11605. jim_wide wA, wB, wC = 0;
  11606. Jim_Obj *A, *B;
  11607. if ((rc = JimExprGetTerm(interp, node->left, &A)) != JIM_OK) {
  11608. return rc;
  11609. }
  11610. if ((rc = JimExprGetTerm(interp, node->right, &B)) != JIM_OK) {
  11611. Jim_DecrRefCount(interp, A);
  11612. return rc;
  11613. }
  11614. if ((A->typePtr != &doubleObjType || A->bytes) &&
  11615. (B->typePtr != &doubleObjType || B->bytes) &&
  11616. JimGetWideNoErr(interp, A, &wA) == JIM_OK && JimGetWideNoErr(interp, B, &wB) == JIM_OK) {
  11617. switch (node->type) {
  11618. case JIM_EXPROP_POW:
  11619. case JIM_EXPROP_FUNC_POW:
  11620. if (wA == 0 && wB < 0) {
  11621. Jim_SetResultString(interp, "exponentiation of zero by negative power", -1);
  11622. rc = JIM_ERR;
  11623. goto done;
  11624. }
  11625. wC = JimPowWide(wA, wB);
  11626. goto intresult;
  11627. case JIM_EXPROP_ADD:
  11628. wC = wA + wB;
  11629. goto intresult;
  11630. case JIM_EXPROP_SUB:
  11631. wC = wA - wB;
  11632. goto intresult;
  11633. case JIM_EXPROP_MUL:
  11634. wC = wA * wB;
  11635. goto intresult;
  11636. case JIM_EXPROP_DIV:
  11637. if (wB == 0) {
  11638. Jim_SetResultString(interp, "Division by zero", -1);
  11639. rc = JIM_ERR;
  11640. goto done;
  11641. }
  11642. else {
  11643. if (wB < 0) {
  11644. wB = -wB;
  11645. wA = -wA;
  11646. }
  11647. wC = wA / wB;
  11648. if (wA % wB < 0) {
  11649. wC--;
  11650. }
  11651. goto intresult;
  11652. }
  11653. case JIM_EXPROP_LT:
  11654. wC = wA < wB;
  11655. goto intresult;
  11656. case JIM_EXPROP_GT:
  11657. wC = wA > wB;
  11658. goto intresult;
  11659. case JIM_EXPROP_LTE:
  11660. wC = wA <= wB;
  11661. goto intresult;
  11662. case JIM_EXPROP_GTE:
  11663. wC = wA >= wB;
  11664. goto intresult;
  11665. case JIM_EXPROP_NUMEQ:
  11666. wC = wA == wB;
  11667. goto intresult;
  11668. case JIM_EXPROP_NUMNE:
  11669. wC = wA != wB;
  11670. goto intresult;
  11671. }
  11672. }
  11673. if (Jim_GetDouble(interp, A, &dA) == JIM_OK && Jim_GetDouble(interp, B, &dB) == JIM_OK) {
  11674. switch (node->type) {
  11675. #ifndef JIM_MATH_FUNCTIONS
  11676. case JIM_EXPROP_POW:
  11677. case JIM_EXPROP_FUNC_POW:
  11678. case JIM_EXPROP_FUNC_ATAN2:
  11679. case JIM_EXPROP_FUNC_HYPOT:
  11680. case JIM_EXPROP_FUNC_FMOD:
  11681. Jim_SetResultString(interp, "unsupported", -1);
  11682. rc = JIM_ERR;
  11683. goto done;
  11684. #else
  11685. case JIM_EXPROP_POW:
  11686. case JIM_EXPROP_FUNC_POW:
  11687. dC = pow(dA, dB);
  11688. goto doubleresult;
  11689. case JIM_EXPROP_FUNC_ATAN2:
  11690. dC = atan2(dA, dB);
  11691. goto doubleresult;
  11692. case JIM_EXPROP_FUNC_HYPOT:
  11693. dC = hypot(dA, dB);
  11694. goto doubleresult;
  11695. case JIM_EXPROP_FUNC_FMOD:
  11696. dC = fmod(dA, dB);
  11697. goto doubleresult;
  11698. #endif
  11699. case JIM_EXPROP_ADD:
  11700. dC = dA + dB;
  11701. goto doubleresult;
  11702. case JIM_EXPROP_SUB:
  11703. dC = dA - dB;
  11704. goto doubleresult;
  11705. case JIM_EXPROP_MUL:
  11706. dC = dA * dB;
  11707. goto doubleresult;
  11708. case JIM_EXPROP_DIV:
  11709. if (dB == 0) {
  11710. #ifdef INFINITY
  11711. dC = dA < 0 ? -INFINITY : INFINITY;
  11712. #else
  11713. dC = (dA < 0 ? -1.0 : 1.0) * strtod("Inf", NULL);
  11714. #endif
  11715. }
  11716. else {
  11717. dC = dA / dB;
  11718. }
  11719. goto doubleresult;
  11720. case JIM_EXPROP_LT:
  11721. wC = dA < dB;
  11722. goto intresult;
  11723. case JIM_EXPROP_GT:
  11724. wC = dA > dB;
  11725. goto intresult;
  11726. case JIM_EXPROP_LTE:
  11727. wC = dA <= dB;
  11728. goto intresult;
  11729. case JIM_EXPROP_GTE:
  11730. wC = dA >= dB;
  11731. goto intresult;
  11732. case JIM_EXPROP_NUMEQ:
  11733. wC = dA == dB;
  11734. goto intresult;
  11735. case JIM_EXPROP_NUMNE:
  11736. wC = dA != dB;
  11737. goto intresult;
  11738. }
  11739. }
  11740. else {
  11741. int i = Jim_StringCompareObj(interp, A, B, 0);
  11742. switch (node->type) {
  11743. case JIM_EXPROP_LT:
  11744. wC = i < 0;
  11745. goto intresult;
  11746. case JIM_EXPROP_GT:
  11747. wC = i > 0;
  11748. goto intresult;
  11749. case JIM_EXPROP_LTE:
  11750. wC = i <= 0;
  11751. goto intresult;
  11752. case JIM_EXPROP_GTE:
  11753. wC = i >= 0;
  11754. goto intresult;
  11755. case JIM_EXPROP_NUMEQ:
  11756. wC = i == 0;
  11757. goto intresult;
  11758. case JIM_EXPROP_NUMNE:
  11759. wC = i != 0;
  11760. goto intresult;
  11761. }
  11762. }
  11763. rc = JIM_ERR;
  11764. done:
  11765. Jim_DecrRefCount(interp, A);
  11766. Jim_DecrRefCount(interp, B);
  11767. return rc;
  11768. intresult:
  11769. Jim_SetResultInt(interp, wC);
  11770. goto done;
  11771. doubleresult:
  11772. Jim_SetResult(interp, Jim_NewDoubleObj(interp, dC));
  11773. goto done;
  11774. }
  11775. static int JimSearchList(Jim_Interp *interp, Jim_Obj *listObjPtr, Jim_Obj *valObj)
  11776. {
  11777. int listlen;
  11778. int i;
  11779. listlen = Jim_ListLength(interp, listObjPtr);
  11780. for (i = 0; i < listlen; i++) {
  11781. if (Jim_StringEqObj(Jim_ListGetIndex(interp, listObjPtr, i), valObj)) {
  11782. return 1;
  11783. }
  11784. }
  11785. return 0;
  11786. }
  11787. static int JimExprOpStrBin(Jim_Interp *interp, struct JimExprNode *node)
  11788. {
  11789. Jim_Obj *A, *B;
  11790. jim_wide wC;
  11791. int comp, rc;
  11792. if ((rc = JimExprGetTerm(interp, node->left, &A)) != JIM_OK) {
  11793. return rc;
  11794. }
  11795. if ((rc = JimExprGetTerm(interp, node->right, &B)) != JIM_OK) {
  11796. Jim_DecrRefCount(interp, A);
  11797. return rc;
  11798. }
  11799. switch (node->type) {
  11800. case JIM_EXPROP_STREQ:
  11801. case JIM_EXPROP_STRNE:
  11802. wC = Jim_StringEqObj(A, B);
  11803. if (node->type == JIM_EXPROP_STRNE) {
  11804. wC = !wC;
  11805. }
  11806. break;
  11807. case JIM_EXPROP_STRLT:
  11808. case JIM_EXPROP_STRGT:
  11809. case JIM_EXPROP_STRLE:
  11810. case JIM_EXPROP_STRGE:
  11811. comp = Jim_StringCompareObj(interp, A, B, 0);
  11812. if (node->type == JIM_EXPROP_STRLT) {
  11813. wC = comp == -1;
  11814. } else if (node->type == JIM_EXPROP_STRGT) {
  11815. wC = comp == 1;
  11816. } else if (node->type == JIM_EXPROP_STRLE) {
  11817. wC = comp == -1 || comp == 0;
  11818. } else {
  11819. wC = comp == 0 || comp == 1;
  11820. }
  11821. break;
  11822. case JIM_EXPROP_STRIN:
  11823. wC = JimSearchList(interp, B, A);
  11824. break;
  11825. case JIM_EXPROP_STRNI:
  11826. wC = !JimSearchList(interp, B, A);
  11827. break;
  11828. default:
  11829. abort();
  11830. }
  11831. Jim_SetResultInt(interp, wC);
  11832. Jim_DecrRefCount(interp, A);
  11833. Jim_DecrRefCount(interp, B);
  11834. return rc;
  11835. }
  11836. static int ExprBool(Jim_Interp *interp, Jim_Obj *obj)
  11837. {
  11838. long l;
  11839. double d;
  11840. int b;
  11841. int ret = -1;
  11842. Jim_IncrRefCount(obj);
  11843. if (Jim_GetLong(interp, obj, &l) == JIM_OK) {
  11844. ret = (l != 0);
  11845. }
  11846. else if (Jim_GetDouble(interp, obj, &d) == JIM_OK) {
  11847. ret = (d != 0);
  11848. }
  11849. else if (Jim_GetBoolean(interp, obj, &b) == JIM_OK) {
  11850. ret = (b != 0);
  11851. }
  11852. Jim_DecrRefCount(interp, obj);
  11853. return ret;
  11854. }
  11855. static int JimExprOpAnd(Jim_Interp *interp, struct JimExprNode *node)
  11856. {
  11857. int result = JimExprGetTermBoolean(interp, node->left);
  11858. if (result == 1) {
  11859. result = JimExprGetTermBoolean(interp, node->right);
  11860. }
  11861. if (result == -1) {
  11862. return JIM_ERR;
  11863. }
  11864. Jim_SetResultInt(interp, result);
  11865. return JIM_OK;
  11866. }
  11867. static int JimExprOpOr(Jim_Interp *interp, struct JimExprNode *node)
  11868. {
  11869. int result = JimExprGetTermBoolean(interp, node->left);
  11870. if (result == 0) {
  11871. result = JimExprGetTermBoolean(interp, node->right);
  11872. }
  11873. if (result == -1) {
  11874. return JIM_ERR;
  11875. }
  11876. Jim_SetResultInt(interp, result);
  11877. return JIM_OK;
  11878. }
  11879. static int JimExprOpTernary(Jim_Interp *interp, struct JimExprNode *node)
  11880. {
  11881. int result = JimExprGetTermBoolean(interp, node->left);
  11882. if (result == 1) {
  11883. return JimExprEvalTermNode(interp, node->right);
  11884. }
  11885. else if (result == 0) {
  11886. return JimExprEvalTermNode(interp, node->ternary);
  11887. }
  11888. return JIM_ERR;
  11889. }
  11890. enum
  11891. {
  11892. OP_FUNC = 0x0001,
  11893. OP_RIGHT_ASSOC = 0x0002,
  11894. };
  11895. #define OPRINIT_ATTR(N, P, ARITY, F, ATTR) {N, F, P, ARITY, ATTR, sizeof(N) - 1}
  11896. #define OPRINIT(N, P, ARITY, F) OPRINIT_ATTR(N, P, ARITY, F, 0)
  11897. static const struct Jim_ExprOperator Jim_ExprOperators[] = {
  11898. OPRINIT("*", 110, 2, JimExprOpBin),
  11899. OPRINIT("/", 110, 2, JimExprOpBin),
  11900. OPRINIT("%", 110, 2, JimExprOpIntBin),
  11901. OPRINIT("-", 100, 2, JimExprOpBin),
  11902. OPRINIT("+", 100, 2, JimExprOpBin),
  11903. OPRINIT("<<", 90, 2, JimExprOpIntBin),
  11904. OPRINIT(">>", 90, 2, JimExprOpIntBin),
  11905. OPRINIT("<<<", 90, 2, JimExprOpIntBin),
  11906. OPRINIT(">>>", 90, 2, JimExprOpIntBin),
  11907. OPRINIT("<", 80, 2, JimExprOpBin),
  11908. OPRINIT(">", 80, 2, JimExprOpBin),
  11909. OPRINIT("<=", 80, 2, JimExprOpBin),
  11910. OPRINIT(">=", 80, 2, JimExprOpBin),
  11911. OPRINIT("==", 70, 2, JimExprOpBin),
  11912. OPRINIT("!=", 70, 2, JimExprOpBin),
  11913. OPRINIT("&", 50, 2, JimExprOpIntBin),
  11914. OPRINIT("^", 49, 2, JimExprOpIntBin),
  11915. OPRINIT("|", 48, 2, JimExprOpIntBin),
  11916. OPRINIT("&&", 10, 2, JimExprOpAnd),
  11917. OPRINIT("||", 9, 2, JimExprOpOr),
  11918. OPRINIT_ATTR("?", 5, 3, JimExprOpTernary, OP_RIGHT_ASSOC),
  11919. OPRINIT_ATTR(":", 5, 3, NULL, OP_RIGHT_ASSOC),
  11920. OPRINIT_ATTR("**", 120, 2, JimExprOpBin, OP_RIGHT_ASSOC),
  11921. OPRINIT("eq", 60, 2, JimExprOpStrBin),
  11922. OPRINIT("ne", 60, 2, JimExprOpStrBin),
  11923. OPRINIT("in", 55, 2, JimExprOpStrBin),
  11924. OPRINIT("ni", 55, 2, JimExprOpStrBin),
  11925. OPRINIT("lt", 75, 2, JimExprOpStrBin),
  11926. OPRINIT("gt", 75, 2, JimExprOpStrBin),
  11927. OPRINIT("le", 75, 2, JimExprOpStrBin),
  11928. OPRINIT("ge", 75, 2, JimExprOpStrBin),
  11929. OPRINIT_ATTR("!", 150, 1, JimExprOpNumUnary, OP_RIGHT_ASSOC),
  11930. OPRINIT_ATTR("~", 150, 1, JimExprOpIntUnary, OP_RIGHT_ASSOC),
  11931. OPRINIT_ATTR(" -", 150, 1, JimExprOpNumUnary, OP_RIGHT_ASSOC),
  11932. OPRINIT_ATTR(" +", 150, 1, JimExprOpNumUnary, OP_RIGHT_ASSOC),
  11933. OPRINIT_ATTR("int", 200, 1, JimExprOpNumUnary, OP_FUNC),
  11934. OPRINIT_ATTR("wide", 200, 1, JimExprOpNumUnary, OP_FUNC),
  11935. OPRINIT_ATTR("abs", 200, 1, JimExprOpNumUnary, OP_FUNC),
  11936. OPRINIT_ATTR("double", 200, 1, JimExprOpNumUnary, OP_FUNC),
  11937. OPRINIT_ATTR("round", 200, 1, JimExprOpNumUnary, OP_FUNC),
  11938. OPRINIT_ATTR("rand", 200, 0, JimExprOpNone, OP_FUNC),
  11939. OPRINIT_ATTR("srand", 200, 1, JimExprOpIntUnary, OP_FUNC),
  11940. #ifdef JIM_MATH_FUNCTIONS
  11941. OPRINIT_ATTR("sin", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
  11942. OPRINIT_ATTR("cos", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
  11943. OPRINIT_ATTR("tan", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
  11944. OPRINIT_ATTR("asin", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
  11945. OPRINIT_ATTR("acos", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
  11946. OPRINIT_ATTR("atan", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
  11947. OPRINIT_ATTR("atan2", 200, 2, JimExprOpBin, OP_FUNC),
  11948. OPRINIT_ATTR("sinh", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
  11949. OPRINIT_ATTR("cosh", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
  11950. OPRINIT_ATTR("tanh", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
  11951. OPRINIT_ATTR("ceil", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
  11952. OPRINIT_ATTR("floor", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
  11953. OPRINIT_ATTR("exp", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
  11954. OPRINIT_ATTR("log", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
  11955. OPRINIT_ATTR("log10", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
  11956. OPRINIT_ATTR("sqrt", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
  11957. OPRINIT_ATTR("pow", 200, 2, JimExprOpBin, OP_FUNC),
  11958. OPRINIT_ATTR("hypot", 200, 2, JimExprOpBin, OP_FUNC),
  11959. OPRINIT_ATTR("fmod", 200, 2, JimExprOpBin, OP_FUNC),
  11960. #endif
  11961. };
  11962. #undef OPRINIT
  11963. #undef OPRINIT_ATTR
  11964. #define JIM_EXPR_OPERATORS_NUM \
  11965. (sizeof(Jim_ExprOperators)/sizeof(struct Jim_ExprOperator))
  11966. static int JimParseExpression(struct JimParserCtx *pc)
  11967. {
  11968. pc->errmsg = NULL;
  11969. while (1) {
  11970. while (isspace(UCHAR(*pc->p)) || (*(pc->p) == '\\' && *(pc->p + 1) == '\n')) {
  11971. if (*pc->p == '\n') {
  11972. pc->linenr++;
  11973. }
  11974. pc->p++;
  11975. pc->len--;
  11976. }
  11977. if (*pc->p == '#') {
  11978. JimParseComment(pc);
  11979. continue;
  11980. }
  11981. break;
  11982. }
  11983. pc->tline = pc->linenr;
  11984. pc->tstart = pc->p;
  11985. if (pc->len == 0) {
  11986. pc->tend = pc->p;
  11987. pc->tt = JIM_TT_EOL;
  11988. pc->eof = 1;
  11989. return JIM_OK;
  11990. }
  11991. switch (*(pc->p)) {
  11992. case '(':
  11993. pc->tt = JIM_TT_SUBEXPR_START;
  11994. goto singlechar;
  11995. case ')':
  11996. pc->tt = JIM_TT_SUBEXPR_END;
  11997. goto singlechar;
  11998. case ',':
  11999. pc->tt = JIM_TT_SUBEXPR_COMMA;
  12000. singlechar:
  12001. pc->tend = pc->p;
  12002. pc->p++;
  12003. pc->len--;
  12004. break;
  12005. case '[':
  12006. return JimParseCmd(pc);
  12007. case '$':
  12008. if (JimParseVar(pc) == JIM_ERR)
  12009. return JimParseExprOperator(pc);
  12010. else {
  12011. if (pc->tt == JIM_TT_EXPRSUGAR) {
  12012. pc->errmsg = "nesting expr in expr is not allowed";
  12013. return JIM_ERR;
  12014. }
  12015. return JIM_OK;
  12016. }
  12017. break;
  12018. case '0':
  12019. case '1':
  12020. case '2':
  12021. case '3':
  12022. case '4':
  12023. case '5':
  12024. case '6':
  12025. case '7':
  12026. case '8':
  12027. case '9':
  12028. case '.':
  12029. return JimParseExprNumber(pc);
  12030. case '"':
  12031. return JimParseQuote(pc);
  12032. case '{':
  12033. return JimParseBrace(pc);
  12034. case 'N':
  12035. case 'I':
  12036. case 'n':
  12037. case 'i':
  12038. if (JimParseExprIrrational(pc) == JIM_ERR)
  12039. if (JimParseExprBoolean(pc) == JIM_ERR)
  12040. return JimParseExprOperator(pc);
  12041. break;
  12042. case 't':
  12043. case 'f':
  12044. case 'o':
  12045. case 'y':
  12046. if (JimParseExprBoolean(pc) == JIM_ERR)
  12047. return JimParseExprOperator(pc);
  12048. break;
  12049. default:
  12050. return JimParseExprOperator(pc);
  12051. break;
  12052. }
  12053. return JIM_OK;
  12054. }
  12055. static int JimParseExprNumber(struct JimParserCtx *pc)
  12056. {
  12057. char *end;
  12058. pc->tt = JIM_TT_EXPR_INT;
  12059. jim_strtoull(pc->p, (char **)&pc->p);
  12060. if (strchr("eENnIi.", *pc->p) || pc->p == pc->tstart) {
  12061. if (strtod(pc->tstart, &end)) { }
  12062. if (end == pc->tstart)
  12063. return JIM_ERR;
  12064. if (end > pc->p) {
  12065. pc->tt = JIM_TT_EXPR_DOUBLE;
  12066. pc->p = end;
  12067. }
  12068. }
  12069. pc->tend = pc->p - 1;
  12070. pc->len -= (pc->p - pc->tstart);
  12071. return JIM_OK;
  12072. }
  12073. static int JimParseExprIrrational(struct JimParserCtx *pc)
  12074. {
  12075. const char *irrationals[] = { "NaN", "nan", "NAN", "Inf", "inf", "INF", NULL };
  12076. int i;
  12077. for (i = 0; irrationals[i]; i++) {
  12078. const char *irr = irrationals[i];
  12079. if (strncmp(irr, pc->p, 3) == 0) {
  12080. pc->p += 3;
  12081. pc->len -= 3;
  12082. pc->tend = pc->p - 1;
  12083. pc->tt = JIM_TT_EXPR_DOUBLE;
  12084. return JIM_OK;
  12085. }
  12086. }
  12087. return JIM_ERR;
  12088. }
  12089. static int JimParseExprBoolean(struct JimParserCtx *pc)
  12090. {
  12091. int i;
  12092. for (i = 0; i < sizeof(jim_true_false_strings) / sizeof(*jim_true_false_strings); i++) {
  12093. if (strncmp(pc->p, jim_true_false_strings[i], jim_true_false_lens[i]) == 0) {
  12094. pc->p += jim_true_false_lens[i];
  12095. pc->len -= jim_true_false_lens[i];
  12096. pc->tend = pc->p - 1;
  12097. pc->tt = JIM_TT_EXPR_BOOLEAN;
  12098. return JIM_OK;
  12099. }
  12100. }
  12101. return JIM_ERR;
  12102. }
  12103. static const struct Jim_ExprOperator *JimExprOperatorInfoByOpcode(int opcode)
  12104. {
  12105. static Jim_ExprOperator dummy_op;
  12106. if (opcode < JIM_TT_EXPR_OP) {
  12107. return &dummy_op;
  12108. }
  12109. return &Jim_ExprOperators[opcode - JIM_TT_EXPR_OP];
  12110. }
  12111. static int JimParseExprOperator(struct JimParserCtx *pc)
  12112. {
  12113. int i;
  12114. const struct Jim_ExprOperator *bestOp = NULL;
  12115. int bestLen = 0;
  12116. for (i = 0; i < (signed)JIM_EXPR_OPERATORS_NUM; i++) {
  12117. const struct Jim_ExprOperator *op = &Jim_ExprOperators[i];
  12118. if (op->name[0] != pc->p[0]) {
  12119. continue;
  12120. }
  12121. if (op->namelen > bestLen && strncmp(op->name, pc->p, op->namelen) == 0) {
  12122. bestOp = op;
  12123. bestLen = op->namelen;
  12124. }
  12125. }
  12126. if (bestOp == NULL) {
  12127. return JIM_ERR;
  12128. }
  12129. if (bestOp->attr & OP_FUNC) {
  12130. const char *p = pc->p + bestLen;
  12131. int len = pc->len - bestLen;
  12132. while (len && isspace(UCHAR(*p))) {
  12133. len--;
  12134. p++;
  12135. }
  12136. if (*p != '(') {
  12137. pc->errmsg = "function requires parentheses";
  12138. return JIM_ERR;
  12139. }
  12140. }
  12141. pc->tend = pc->p + bestLen - 1;
  12142. pc->p += bestLen;
  12143. pc->len -= bestLen;
  12144. pc->tt = (bestOp - Jim_ExprOperators) + JIM_TT_EXPR_OP;
  12145. return JIM_OK;
  12146. }
  12147. static void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
  12148. static void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
  12149. static int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
  12150. static const Jim_ObjType exprObjType = {
  12151. "expression",
  12152. FreeExprInternalRep,
  12153. DupExprInternalRep,
  12154. NULL,
  12155. JIM_TYPE_NONE,
  12156. };
  12157. struct ExprTree
  12158. {
  12159. struct JimExprNode *expr;
  12160. struct JimExprNode *nodes;
  12161. int len;
  12162. int inUse;
  12163. };
  12164. static void ExprTreeFreeNodes(Jim_Interp *interp, struct JimExprNode *nodes, int num)
  12165. {
  12166. int i;
  12167. for (i = 0; i < num; i++) {
  12168. if (nodes[i].objPtr) {
  12169. Jim_DecrRefCount(interp, nodes[i].objPtr);
  12170. }
  12171. }
  12172. Jim_Free(nodes);
  12173. }
  12174. static void ExprTreeFree(Jim_Interp *interp, struct ExprTree *expr)
  12175. {
  12176. ExprTreeFreeNodes(interp, expr->nodes, expr->len);
  12177. Jim_Free(expr);
  12178. }
  12179. static void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
  12180. {
  12181. struct ExprTree *expr = (void *)objPtr->internalRep.ptr;
  12182. if (expr) {
  12183. if (--expr->inUse != 0) {
  12184. return;
  12185. }
  12186. ExprTreeFree(interp, expr);
  12187. }
  12188. }
  12189. static void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
  12190. {
  12191. JIM_NOTUSED(interp);
  12192. JIM_NOTUSED(srcPtr);
  12193. dupPtr->typePtr = NULL;
  12194. }
  12195. struct ExprBuilder {
  12196. int parencount;
  12197. int level;
  12198. ParseToken *token;
  12199. ParseToken *first_token;
  12200. Jim_Stack stack;
  12201. Jim_Obj *exprObjPtr;
  12202. Jim_Obj *fileNameObj;
  12203. struct JimExprNode *nodes;
  12204. struct JimExprNode *next;
  12205. };
  12206. #ifdef DEBUG_SHOW_EXPR
  12207. static void JimShowExprNode(struct JimExprNode *node, int level)
  12208. {
  12209. int i;
  12210. for (i = 0; i < level; i++) {
  12211. printf(" ");
  12212. }
  12213. if (TOKEN_IS_EXPR_OP(node->type)) {
  12214. printf("%s\n", jim_tt_name(node->type));
  12215. if (node->left) {
  12216. JimShowExprNode(node->left, level + 1);
  12217. }
  12218. if (node->right) {
  12219. JimShowExprNode(node->right, level + 1);
  12220. }
  12221. if (node->ternary) {
  12222. JimShowExprNode(node->ternary, level + 1);
  12223. }
  12224. }
  12225. else {
  12226. printf("[%s] %s\n", jim_tt_name(node->type), Jim_String(node->objPtr));
  12227. }
  12228. }
  12229. #endif
  12230. #define EXPR_UNTIL_CLOSE 0x0001
  12231. #define EXPR_FUNC_ARGS 0x0002
  12232. #define EXPR_TERNARY 0x0004
  12233. static int ExprTreeBuildTree(Jim_Interp *interp, struct ExprBuilder *builder, int precedence, int flags, int exp_numterms) {
  12234. int rc;
  12235. struct JimExprNode *node;
  12236. int exp_stacklen = builder->stack.len + exp_numterms;
  12237. if (builder->level++ > 200) {
  12238. Jim_SetResultString(interp, "Expression too complex", -1);
  12239. return JIM_ERR;
  12240. }
  12241. while (builder->token->type != JIM_TT_EOL) {
  12242. ParseToken *t = builder->token++;
  12243. int prevtt;
  12244. if (t == builder->first_token) {
  12245. prevtt = JIM_TT_NONE;
  12246. }
  12247. else {
  12248. prevtt = t[-1].type;
  12249. }
  12250. if (t->type == JIM_TT_SUBEXPR_START) {
  12251. if (builder->stack.len == exp_stacklen) {
  12252. Jim_SetResultFormatted(interp, "unexpected open parenthesis in expression: \"%#s\"", builder->exprObjPtr);
  12253. return JIM_ERR;
  12254. }
  12255. builder->parencount++;
  12256. rc = ExprTreeBuildTree(interp, builder, 0, EXPR_UNTIL_CLOSE, 1);
  12257. if (rc != JIM_OK) {
  12258. return rc;
  12259. }
  12260. }
  12261. else if (t->type == JIM_TT_SUBEXPR_END) {
  12262. if (!(flags & EXPR_UNTIL_CLOSE)) {
  12263. if (builder->stack.len == exp_stacklen && builder->level > 1) {
  12264. builder->token--;
  12265. builder->level--;
  12266. return JIM_OK;
  12267. }
  12268. Jim_SetResultFormatted(interp, "unexpected closing parenthesis in expression: \"%#s\"", builder->exprObjPtr);
  12269. return JIM_ERR;
  12270. }
  12271. builder->parencount--;
  12272. if (builder->stack.len == exp_stacklen) {
  12273. break;
  12274. }
  12275. }
  12276. else if (t->type == JIM_TT_SUBEXPR_COMMA) {
  12277. if (!(flags & EXPR_FUNC_ARGS)) {
  12278. if (builder->stack.len == exp_stacklen) {
  12279. builder->token--;
  12280. builder->level--;
  12281. return JIM_OK;
  12282. }
  12283. Jim_SetResultFormatted(interp, "unexpected comma in expression: \"%#s\"", builder->exprObjPtr);
  12284. return JIM_ERR;
  12285. }
  12286. else {
  12287. if (builder->stack.len > exp_stacklen) {
  12288. Jim_SetResultFormatted(interp, "too many arguments to math function");
  12289. return JIM_ERR;
  12290. }
  12291. }
  12292. }
  12293. else if (t->type == JIM_EXPROP_COLON) {
  12294. if (!(flags & EXPR_TERNARY)) {
  12295. if (builder->level != 1) {
  12296. builder->token--;
  12297. builder->level--;
  12298. return JIM_OK;
  12299. }
  12300. Jim_SetResultFormatted(interp, ": without ? in expression: \"%#s\"", builder->exprObjPtr);
  12301. return JIM_ERR;
  12302. }
  12303. if (builder->stack.len == exp_stacklen) {
  12304. builder->token--;
  12305. builder->level--;
  12306. return JIM_OK;
  12307. }
  12308. }
  12309. else if (TOKEN_IS_EXPR_OP(t->type)) {
  12310. const struct Jim_ExprOperator *op;
  12311. if (TOKEN_IS_EXPR_OP(prevtt) || TOKEN_IS_EXPR_START(prevtt)) {
  12312. if (t->type == JIM_EXPROP_SUB) {
  12313. t->type = JIM_EXPROP_UNARYMINUS;
  12314. }
  12315. else if (t->type == JIM_EXPROP_ADD) {
  12316. t->type = JIM_EXPROP_UNARYPLUS;
  12317. }
  12318. }
  12319. op = JimExprOperatorInfoByOpcode(t->type);
  12320. if (op->precedence < precedence || (!(op->attr & OP_RIGHT_ASSOC) && op->precedence == precedence)) {
  12321. builder->token--;
  12322. break;
  12323. }
  12324. if (op->attr & OP_FUNC) {
  12325. if (builder->token->type != JIM_TT_SUBEXPR_START) {
  12326. Jim_SetResultString(interp, "missing arguments for math function", -1);
  12327. return JIM_ERR;
  12328. }
  12329. builder->token++;
  12330. if (op->arity == 0) {
  12331. if (builder->token->type != JIM_TT_SUBEXPR_END) {
  12332. Jim_SetResultString(interp, "too many arguments for math function", -1);
  12333. return JIM_ERR;
  12334. }
  12335. builder->token++;
  12336. goto noargs;
  12337. }
  12338. builder->parencount++;
  12339. rc = ExprTreeBuildTree(interp, builder, 0, EXPR_FUNC_ARGS | EXPR_UNTIL_CLOSE, op->arity);
  12340. }
  12341. else if (t->type == JIM_EXPROP_TERNARY) {
  12342. rc = ExprTreeBuildTree(interp, builder, op->precedence, EXPR_TERNARY, 2);
  12343. }
  12344. else {
  12345. rc = ExprTreeBuildTree(interp, builder, op->precedence, 0, 1);
  12346. }
  12347. if (rc != JIM_OK) {
  12348. return rc;
  12349. }
  12350. noargs:
  12351. node = builder->next++;
  12352. node->type = t->type;
  12353. if (op->arity >= 3) {
  12354. node->ternary = Jim_StackPop(&builder->stack);
  12355. if (node->ternary == NULL) {
  12356. goto missingoperand;
  12357. }
  12358. }
  12359. if (op->arity >= 2) {
  12360. node->right = Jim_StackPop(&builder->stack);
  12361. if (node->right == NULL) {
  12362. goto missingoperand;
  12363. }
  12364. }
  12365. if (op->arity >= 1) {
  12366. node->left = Jim_StackPop(&builder->stack);
  12367. if (node->left == NULL) {
  12368. missingoperand:
  12369. Jim_SetResultFormatted(interp, "missing operand to %s in expression: \"%#s\"", op->name, builder->exprObjPtr);
  12370. builder->next--;
  12371. return JIM_ERR;
  12372. }
  12373. }
  12374. Jim_StackPush(&builder->stack, node);
  12375. }
  12376. else {
  12377. Jim_Obj *objPtr = NULL;
  12378. if (!TOKEN_IS_EXPR_START(prevtt) && !TOKEN_IS_EXPR_OP(prevtt)) {
  12379. Jim_SetResultFormatted(interp, "missing operator in expression: \"%#s\"", builder->exprObjPtr);
  12380. return JIM_ERR;
  12381. }
  12382. if (t->type == JIM_TT_EXPR_INT || t->type == JIM_TT_EXPR_DOUBLE) {
  12383. char *endptr;
  12384. if (t->type == JIM_TT_EXPR_INT) {
  12385. objPtr = Jim_NewIntObj(interp, jim_strtoull(t->token, &endptr));
  12386. }
  12387. else {
  12388. objPtr = Jim_NewDoubleObj(interp, strtod(t->token, &endptr));
  12389. }
  12390. if (endptr != t->token + t->len) {
  12391. Jim_FreeNewObj(interp, objPtr);
  12392. objPtr = NULL;
  12393. }
  12394. }
  12395. if (!objPtr) {
  12396. objPtr = Jim_NewStringObj(interp, t->token, t->len);
  12397. if (t->type == JIM_TT_CMD) {
  12398. Jim_SetSourceInfo(interp, objPtr, builder->fileNameObj, t->line);
  12399. }
  12400. }
  12401. node = builder->next++;
  12402. node->objPtr = objPtr;
  12403. Jim_IncrRefCount(node->objPtr);
  12404. node->type = t->type;
  12405. Jim_StackPush(&builder->stack, node);
  12406. }
  12407. }
  12408. if (builder->stack.len == exp_stacklen) {
  12409. builder->level--;
  12410. return JIM_OK;
  12411. }
  12412. if ((flags & EXPR_FUNC_ARGS)) {
  12413. Jim_SetResultFormatted(interp, "too %s arguments for math function", (builder->stack.len < exp_stacklen) ? "few" : "many");
  12414. }
  12415. else {
  12416. if (builder->stack.len < exp_stacklen) {
  12417. if (builder->level == 0) {
  12418. Jim_SetResultFormatted(interp, "empty expression");
  12419. }
  12420. else {
  12421. Jim_SetResultFormatted(interp, "syntax error in expression \"%#s\": premature end of expression", builder->exprObjPtr);
  12422. }
  12423. }
  12424. else {
  12425. Jim_SetResultFormatted(interp, "extra terms after expression");
  12426. }
  12427. }
  12428. return JIM_ERR;
  12429. }
  12430. static struct ExprTree *ExprTreeCreateTree(Jim_Interp *interp, const ParseTokenList *tokenlist, Jim_Obj *exprObjPtr, Jim_Obj *fileNameObj)
  12431. {
  12432. struct ExprTree *expr;
  12433. struct ExprBuilder builder;
  12434. int rc;
  12435. struct JimExprNode *top = NULL;
  12436. builder.parencount = 0;
  12437. builder.level = 0;
  12438. builder.token = builder.first_token = tokenlist->list;
  12439. builder.exprObjPtr = exprObjPtr;
  12440. builder.fileNameObj = fileNameObj;
  12441. builder.nodes = Jim_Alloc(sizeof(struct JimExprNode) * (tokenlist->count - 1));
  12442. memset(builder.nodes, 0, sizeof(struct JimExprNode) * (tokenlist->count - 1));
  12443. builder.next = builder.nodes;
  12444. Jim_InitStack(&builder.stack);
  12445. rc = ExprTreeBuildTree(interp, &builder, 0, 0, 1);
  12446. if (rc == JIM_OK) {
  12447. top = Jim_StackPop(&builder.stack);
  12448. if (builder.parencount) {
  12449. Jim_SetResultString(interp, "missing close parenthesis", -1);
  12450. rc = JIM_ERR;
  12451. }
  12452. }
  12453. Jim_FreeStack(&builder.stack);
  12454. if (rc != JIM_OK) {
  12455. ExprTreeFreeNodes(interp, builder.nodes, builder.next - builder.nodes);
  12456. return NULL;
  12457. }
  12458. expr = Jim_Alloc(sizeof(*expr));
  12459. expr->inUse = 1;
  12460. expr->expr = top;
  12461. expr->nodes = builder.nodes;
  12462. expr->len = builder.next - builder.nodes;
  12463. assert(expr->len <= tokenlist->count - 1);
  12464. return expr;
  12465. }
  12466. static int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
  12467. {
  12468. int exprTextLen;
  12469. const char *exprText;
  12470. struct JimParserCtx parser;
  12471. struct ExprTree *expr;
  12472. ParseTokenList tokenlist;
  12473. int line;
  12474. Jim_Obj *fileNameObj;
  12475. int rc = JIM_ERR;
  12476. fileNameObj = Jim_GetSourceInfo(interp, objPtr, &line);
  12477. Jim_IncrRefCount(fileNameObj);
  12478. exprText = Jim_GetString(objPtr, &exprTextLen);
  12479. ScriptTokenListInit(&tokenlist);
  12480. JimParserInit(&parser, exprText, exprTextLen, line);
  12481. while (!parser.eof) {
  12482. if (JimParseExpression(&parser) != JIM_OK) {
  12483. ScriptTokenListFree(&tokenlist);
  12484. Jim_SetResultFormatted(interp, "syntax error in expression: \"%#s\"", objPtr);
  12485. if (parser.errmsg) {
  12486. Jim_AppendStrings(interp, Jim_GetResult(interp), ": ", parser.errmsg, NULL);
  12487. }
  12488. expr = NULL;
  12489. goto err;
  12490. }
  12491. ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
  12492. parser.tline);
  12493. }
  12494. #ifdef DEBUG_SHOW_EXPR_TOKENS
  12495. {
  12496. int i;
  12497. printf("==== Expr Tokens (%s) ====\n", Jim_String(fileNameObj));
  12498. for (i = 0; i < tokenlist.count; i++) {
  12499. printf("[%2d]@%d %s '%.*s'\n", i, tokenlist.list[i].line, jim_tt_name(tokenlist.list[i].type),
  12500. tokenlist.list[i].len, tokenlist.list[i].token);
  12501. }
  12502. }
  12503. #endif
  12504. if (tokenlist.count <= 1) {
  12505. Jim_SetResultString(interp, "empty expression", -1);
  12506. rc = JIM_ERR;
  12507. }
  12508. else {
  12509. rc = JimParseCheckMissing(interp, parser.missing.ch);
  12510. }
  12511. if (rc != JIM_OK) {
  12512. ScriptTokenListFree(&tokenlist);
  12513. Jim_DecrRefCount(interp, fileNameObj);
  12514. return rc;
  12515. }
  12516. expr = ExprTreeCreateTree(interp, &tokenlist, objPtr, fileNameObj);
  12517. ScriptTokenListFree(&tokenlist);
  12518. if (!expr) {
  12519. goto err;
  12520. }
  12521. #ifdef DEBUG_SHOW_EXPR
  12522. printf("==== Expr ====\n");
  12523. JimShowExprNode(expr->expr, 0);
  12524. #endif
  12525. rc = JIM_OK;
  12526. err:
  12527. Jim_DecrRefCount(interp, fileNameObj);
  12528. Jim_FreeIntRep(interp, objPtr);
  12529. Jim_SetIntRepPtr(objPtr, expr);
  12530. objPtr->typePtr = &exprObjType;
  12531. return rc;
  12532. }
  12533. static struct ExprTree *JimGetExpression(Jim_Interp *interp, Jim_Obj *objPtr)
  12534. {
  12535. if (objPtr->typePtr != &exprObjType) {
  12536. if (SetExprFromAny(interp, objPtr) != JIM_OK) {
  12537. return NULL;
  12538. }
  12539. }
  12540. return (struct ExprTree *) Jim_GetIntRepPtr(objPtr);
  12541. }
  12542. #ifdef JIM_OPTIMIZATION
  12543. static Jim_Obj *JimExprIntValOrVar(Jim_Interp *interp, struct JimExprNode *node)
  12544. {
  12545. if (node->type == JIM_TT_EXPR_INT)
  12546. return node->objPtr;
  12547. else if (node->type == JIM_TT_VAR)
  12548. return Jim_GetVariable(interp, node->objPtr, JIM_NONE);
  12549. else if (node->type == JIM_TT_DICTSUGAR)
  12550. return JimExpandDictSugar(interp, node->objPtr);
  12551. else
  12552. return NULL;
  12553. }
  12554. #endif
  12555. static int JimExprEvalTermNode(Jim_Interp *interp, struct JimExprNode *node)
  12556. {
  12557. if (TOKEN_IS_EXPR_OP(node->type)) {
  12558. const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(node->type);
  12559. return op->funcop(interp, node);
  12560. }
  12561. else {
  12562. Jim_Obj *objPtr;
  12563. switch (node->type) {
  12564. case JIM_TT_EXPR_INT:
  12565. case JIM_TT_EXPR_DOUBLE:
  12566. case JIM_TT_EXPR_BOOLEAN:
  12567. case JIM_TT_STR:
  12568. Jim_SetResult(interp, node->objPtr);
  12569. return JIM_OK;
  12570. case JIM_TT_VAR:
  12571. objPtr = Jim_GetVariable(interp, node->objPtr, JIM_ERRMSG);
  12572. if (objPtr) {
  12573. Jim_SetResult(interp, objPtr);
  12574. return JIM_OK;
  12575. }
  12576. return JIM_ERR;
  12577. case JIM_TT_DICTSUGAR:
  12578. objPtr = JimExpandDictSugar(interp, node->objPtr);
  12579. if (objPtr) {
  12580. Jim_SetResult(interp, objPtr);
  12581. return JIM_OK;
  12582. }
  12583. return JIM_ERR;
  12584. case JIM_TT_ESC:
  12585. if (interp->safeexpr) {
  12586. return JIM_ERR;
  12587. }
  12588. if (Jim_SubstObj(interp, node->objPtr, &objPtr, JIM_NONE) == JIM_OK) {
  12589. Jim_SetResult(interp, objPtr);
  12590. return JIM_OK;
  12591. }
  12592. return JIM_ERR;
  12593. case JIM_TT_CMD:
  12594. if (interp->safeexpr) {
  12595. return JIM_ERR;
  12596. }
  12597. return Jim_EvalObj(interp, node->objPtr);
  12598. default:
  12599. return JIM_ERR;
  12600. }
  12601. }
  12602. }
  12603. static int JimExprGetTerm(Jim_Interp *interp, struct JimExprNode *node, Jim_Obj **objPtrPtr)
  12604. {
  12605. int rc = JimExprEvalTermNode(interp, node);
  12606. if (rc == JIM_OK) {
  12607. *objPtrPtr = Jim_GetResult(interp);
  12608. Jim_IncrRefCount(*objPtrPtr);
  12609. }
  12610. return rc;
  12611. }
  12612. static int JimExprGetTermBoolean(Jim_Interp *interp, struct JimExprNode *node)
  12613. {
  12614. if (JimExprEvalTermNode(interp, node) == JIM_OK) {
  12615. return ExprBool(interp, Jim_GetResult(interp));
  12616. }
  12617. return -1;
  12618. }
  12619. int Jim_EvalExpression(Jim_Interp *interp, Jim_Obj *exprObjPtr)
  12620. {
  12621. struct ExprTree *expr;
  12622. int retcode = JIM_OK;
  12623. Jim_IncrRefCount(exprObjPtr);
  12624. expr = JimGetExpression(interp, exprObjPtr);
  12625. if (!expr) {
  12626. retcode = JIM_ERR;
  12627. goto done;
  12628. }
  12629. #ifdef JIM_OPTIMIZATION
  12630. if (!interp->safeexpr) {
  12631. Jim_Obj *objPtr;
  12632. switch (expr->len) {
  12633. case 1:
  12634. objPtr = JimExprIntValOrVar(interp, expr->expr);
  12635. if (objPtr) {
  12636. Jim_SetResult(interp, objPtr);
  12637. goto done;
  12638. }
  12639. break;
  12640. case 2:
  12641. if (expr->expr->type == JIM_EXPROP_NOT) {
  12642. objPtr = JimExprIntValOrVar(interp, expr->expr->left);
  12643. if (objPtr && JimIsWide(objPtr)) {
  12644. Jim_SetResult(interp, JimWideValue(objPtr) ? interp->falseObj : interp->trueObj);
  12645. goto done;
  12646. }
  12647. }
  12648. break;
  12649. case 3:
  12650. objPtr = JimExprIntValOrVar(interp, expr->expr->left);
  12651. if (objPtr && JimIsWide(objPtr)) {
  12652. Jim_Obj *objPtr2 = JimExprIntValOrVar(interp, expr->expr->right);
  12653. if (objPtr2 && JimIsWide(objPtr2)) {
  12654. jim_wide wideValueA = JimWideValue(objPtr);
  12655. jim_wide wideValueB = JimWideValue(objPtr2);
  12656. int cmpRes;
  12657. switch (expr->expr->type) {
  12658. case JIM_EXPROP_LT:
  12659. cmpRes = wideValueA < wideValueB;
  12660. break;
  12661. case JIM_EXPROP_LTE:
  12662. cmpRes = wideValueA <= wideValueB;
  12663. break;
  12664. case JIM_EXPROP_GT:
  12665. cmpRes = wideValueA > wideValueB;
  12666. break;
  12667. case JIM_EXPROP_GTE:
  12668. cmpRes = wideValueA >= wideValueB;
  12669. break;
  12670. case JIM_EXPROP_NUMEQ:
  12671. cmpRes = wideValueA == wideValueB;
  12672. break;
  12673. case JIM_EXPROP_NUMNE:
  12674. cmpRes = wideValueA != wideValueB;
  12675. break;
  12676. default:
  12677. goto noopt;
  12678. }
  12679. Jim_SetResult(interp, cmpRes ? interp->trueObj : interp->falseObj);
  12680. goto done;
  12681. }
  12682. }
  12683. break;
  12684. }
  12685. }
  12686. noopt:
  12687. #endif
  12688. expr->inUse++;
  12689. retcode = JimExprEvalTermNode(interp, expr->expr);
  12690. Jim_FreeIntRep(interp, exprObjPtr);
  12691. exprObjPtr->typePtr = &exprObjType;
  12692. Jim_SetIntRepPtr(exprObjPtr, expr);
  12693. done:
  12694. Jim_DecrRefCount(interp, exprObjPtr);
  12695. return retcode;
  12696. }
  12697. int Jim_GetBoolFromExpr(Jim_Interp *interp, Jim_Obj *exprObjPtr, int *boolPtr)
  12698. {
  12699. int retcode = Jim_EvalExpression(interp, exprObjPtr);
  12700. if (retcode == JIM_OK) {
  12701. switch (ExprBool(interp, Jim_GetResult(interp))) {
  12702. case 0:
  12703. *boolPtr = 0;
  12704. break;
  12705. case 1:
  12706. *boolPtr = 1;
  12707. break;
  12708. case -1:
  12709. retcode = JIM_ERR;
  12710. break;
  12711. }
  12712. }
  12713. return retcode;
  12714. }
  12715. typedef struct ScanFmtPartDescr
  12716. {
  12717. const char *arg;
  12718. const char *prefix;
  12719. size_t width;
  12720. int pos;
  12721. char type;
  12722. char modifier;
  12723. } ScanFmtPartDescr;
  12724. typedef struct ScanFmtStringObj
  12725. {
  12726. jim_wide size;
  12727. char *stringRep;
  12728. size_t count;
  12729. size_t convCount;
  12730. size_t maxPos;
  12731. const char *error;
  12732. char *scratch;
  12733. ScanFmtPartDescr descr[1];
  12734. } ScanFmtStringObj;
  12735. static void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
  12736. static void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
  12737. static void UpdateStringOfScanFmt(Jim_Obj *objPtr);
  12738. static const Jim_ObjType scanFmtStringObjType = {
  12739. "scanformatstring",
  12740. FreeScanFmtInternalRep,
  12741. DupScanFmtInternalRep,
  12742. UpdateStringOfScanFmt,
  12743. JIM_TYPE_NONE,
  12744. };
  12745. void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
  12746. {
  12747. JIM_NOTUSED(interp);
  12748. Jim_Free((char *)objPtr->internalRep.ptr);
  12749. objPtr->internalRep.ptr = 0;
  12750. }
  12751. void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
  12752. {
  12753. size_t size = (size_t) ((ScanFmtStringObj *) srcPtr->internalRep.ptr)->size;
  12754. ScanFmtStringObj *newVec = (ScanFmtStringObj *) Jim_Alloc(size);
  12755. JIM_NOTUSED(interp);
  12756. memcpy(newVec, srcPtr->internalRep.ptr, size);
  12757. dupPtr->internalRep.ptr = newVec;
  12758. dupPtr->typePtr = &scanFmtStringObjType;
  12759. }
  12760. static void UpdateStringOfScanFmt(Jim_Obj *objPtr)
  12761. {
  12762. JimSetStringBytes(objPtr, ((ScanFmtStringObj *) objPtr->internalRep.ptr)->stringRep);
  12763. }
  12764. static int SetScanFmtFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
  12765. {
  12766. ScanFmtStringObj *fmtObj;
  12767. char *buffer;
  12768. int maxCount, i, approxSize, lastPos = -1;
  12769. const char *fmt = Jim_String(objPtr);
  12770. int maxFmtLen = Jim_Length(objPtr);
  12771. const char *fmtEnd = fmt + maxFmtLen;
  12772. int curr;
  12773. Jim_FreeIntRep(interp, objPtr);
  12774. for (i = 0, maxCount = 0; i < maxFmtLen; ++i)
  12775. if (fmt[i] == '%')
  12776. ++maxCount;
  12777. approxSize = sizeof(ScanFmtStringObj)
  12778. +(maxCount + 1) * sizeof(ScanFmtPartDescr)
  12779. +maxFmtLen * sizeof(char) + 3 + 1
  12780. + maxFmtLen * sizeof(char) + 1
  12781. + maxFmtLen * sizeof(char)
  12782. +(maxCount + 1) * sizeof(char)
  12783. +1;
  12784. fmtObj = (ScanFmtStringObj *) Jim_Alloc(approxSize);
  12785. memset(fmtObj, 0, approxSize);
  12786. fmtObj->size = approxSize;
  12787. fmtObj->maxPos = 0;
  12788. fmtObj->scratch = (char *)&fmtObj->descr[maxCount + 1];
  12789. fmtObj->stringRep = fmtObj->scratch + maxFmtLen + 3 + 1;
  12790. memcpy(fmtObj->stringRep, fmt, maxFmtLen);
  12791. buffer = fmtObj->stringRep + maxFmtLen + 1;
  12792. objPtr->internalRep.ptr = fmtObj;
  12793. objPtr->typePtr = &scanFmtStringObjType;
  12794. for (i = 0, curr = 0; fmt < fmtEnd; ++fmt) {
  12795. int width = 0, skip;
  12796. ScanFmtPartDescr *descr = &fmtObj->descr[curr];
  12797. fmtObj->count++;
  12798. descr->width = 0;
  12799. if (*fmt != '%' || fmt[1] == '%') {
  12800. descr->type = 0;
  12801. descr->prefix = &buffer[i];
  12802. for (; fmt < fmtEnd; ++fmt) {
  12803. if (*fmt == '%') {
  12804. if (fmt[1] != '%')
  12805. break;
  12806. ++fmt;
  12807. }
  12808. buffer[i++] = *fmt;
  12809. }
  12810. buffer[i++] = 0;
  12811. }
  12812. ++fmt;
  12813. if (fmt >= fmtEnd)
  12814. goto done;
  12815. descr->pos = 0;
  12816. if (*fmt == '*') {
  12817. descr->pos = -1;
  12818. ++fmt;
  12819. }
  12820. else
  12821. fmtObj->convCount++;
  12822. if (sscanf(fmt, "%d%n", &width, &skip) == 1) {
  12823. fmt += skip;
  12824. if (descr->pos != -1 && *fmt == '$') {
  12825. int prev;
  12826. ++fmt;
  12827. descr->pos = width;
  12828. width = 0;
  12829. if ((lastPos == 0 && descr->pos > 0)
  12830. || (lastPos > 0 && descr->pos == 0)) {
  12831. fmtObj->error = "cannot mix \"%\" and \"%n$\" conversion specifiers";
  12832. return JIM_ERR;
  12833. }
  12834. for (prev = 0; prev < curr; ++prev) {
  12835. if (fmtObj->descr[prev].pos == -1)
  12836. continue;
  12837. if (fmtObj->descr[prev].pos == descr->pos) {
  12838. fmtObj->error =
  12839. "variable is assigned by multiple \"%n$\" conversion specifiers";
  12840. return JIM_ERR;
  12841. }
  12842. }
  12843. if (descr->pos < 0) {
  12844. fmtObj->error =
  12845. "\"%n$\" conversion specifier is negative";
  12846. return JIM_ERR;
  12847. }
  12848. if (sscanf(fmt, "%d%n", &width, &skip) == 1) {
  12849. descr->width = width;
  12850. fmt += skip;
  12851. }
  12852. if (descr->pos > 0 && (size_t) descr->pos > fmtObj->maxPos)
  12853. fmtObj->maxPos = descr->pos;
  12854. }
  12855. else {
  12856. descr->width = width;
  12857. }
  12858. }
  12859. if (lastPos == -1)
  12860. lastPos = descr->pos;
  12861. if (*fmt == '[') {
  12862. int swapped = 1, beg = i, end, j;
  12863. descr->type = '[';
  12864. descr->arg = &buffer[i];
  12865. ++fmt;
  12866. if (*fmt == '^')
  12867. buffer[i++] = *fmt++;
  12868. if (*fmt == ']')
  12869. buffer[i++] = *fmt++;
  12870. while (*fmt && *fmt != ']')
  12871. buffer[i++] = *fmt++;
  12872. if (*fmt != ']') {
  12873. fmtObj->error = "unmatched [ in format string";
  12874. return JIM_ERR;
  12875. }
  12876. end = i;
  12877. buffer[i++] = 0;
  12878. while (swapped) {
  12879. swapped = 0;
  12880. for (j = beg + 1; j < end - 1; ++j) {
  12881. if (buffer[j] == '-' && buffer[j - 1] > buffer[j + 1]) {
  12882. char tmp = buffer[j - 1];
  12883. buffer[j - 1] = buffer[j + 1];
  12884. buffer[j + 1] = tmp;
  12885. swapped = 1;
  12886. }
  12887. }
  12888. }
  12889. }
  12890. else {
  12891. if (fmt < fmtEnd && strchr("hlL", *fmt))
  12892. descr->modifier = tolower((int)*fmt++);
  12893. if (fmt >= fmtEnd) {
  12894. fmtObj->error = "missing scan conversion character";
  12895. return JIM_ERR;
  12896. }
  12897. descr->type = *fmt;
  12898. if (strchr("efgcsndoxui", *fmt) == 0) {
  12899. fmtObj->error = "bad scan conversion character";
  12900. return JIM_ERR;
  12901. }
  12902. else if (*fmt == 'c' && descr->width != 0) {
  12903. fmtObj->error = "field width may not be specified in %c " "conversion";
  12904. return JIM_ERR;
  12905. }
  12906. else if (*fmt == 'u' && descr->modifier == 'l') {
  12907. fmtObj->error = "unsigned wide not supported";
  12908. return JIM_ERR;
  12909. }
  12910. }
  12911. curr++;
  12912. }
  12913. done:
  12914. return JIM_OK;
  12915. }
  12916. #define FormatGetCnvCount(_fo_) \
  12917. ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->convCount
  12918. #define FormatGetMaxPos(_fo_) \
  12919. ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->maxPos
  12920. #define FormatGetError(_fo_) \
  12921. ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->error
  12922. static Jim_Obj *JimScanAString(Jim_Interp *interp, const char *sdescr, const char *str)
  12923. {
  12924. char *buffer = Jim_StrDup(str);
  12925. char *p = buffer;
  12926. while (*str) {
  12927. int c;
  12928. int n;
  12929. if (!sdescr && isspace(UCHAR(*str)))
  12930. break;
  12931. n = utf8_tounicode(str, &c);
  12932. if (sdescr && !JimCharsetMatch(sdescr, strlen(sdescr), c, JIM_CHARSET_SCAN))
  12933. break;
  12934. while (n--)
  12935. *p++ = *str++;
  12936. }
  12937. *p = 0;
  12938. return Jim_NewStringObjNoAlloc(interp, buffer, p - buffer);
  12939. }
  12940. static int ScanOneEntry(Jim_Interp *interp, const char *str, int pos, int str_bytelen,
  12941. ScanFmtStringObj * fmtObj, long idx, Jim_Obj **valObjPtr)
  12942. {
  12943. const char *tok;
  12944. const ScanFmtPartDescr *descr = &fmtObj->descr[idx];
  12945. size_t scanned = 0;
  12946. size_t anchor = pos;
  12947. int i;
  12948. Jim_Obj *tmpObj = NULL;
  12949. *valObjPtr = 0;
  12950. if (descr->prefix) {
  12951. for (i = 0; pos < str_bytelen && descr->prefix[i]; ++i) {
  12952. if (isspace(UCHAR(descr->prefix[i])))
  12953. while (pos < str_bytelen && isspace(UCHAR(str[pos])))
  12954. ++pos;
  12955. else if (descr->prefix[i] != str[pos])
  12956. break;
  12957. else
  12958. ++pos;
  12959. }
  12960. if (pos >= str_bytelen) {
  12961. return -1;
  12962. }
  12963. else if (descr->prefix[i] != 0)
  12964. return 0;
  12965. }
  12966. if (descr->type != 'c' && descr->type != '[' && descr->type != 'n')
  12967. while (isspace(UCHAR(str[pos])))
  12968. ++pos;
  12969. scanned = pos - anchor;
  12970. if (descr->type == 'n') {
  12971. *valObjPtr = Jim_NewIntObj(interp, anchor + scanned);
  12972. }
  12973. else if (pos >= str_bytelen) {
  12974. return -1;
  12975. }
  12976. else if (descr->type == 'c') {
  12977. int c;
  12978. scanned += utf8_tounicode(&str[pos], &c);
  12979. *valObjPtr = Jim_NewIntObj(interp, c);
  12980. return scanned;
  12981. }
  12982. else {
  12983. if (descr->width > 0) {
  12984. size_t sLen = utf8_strlen(&str[pos], str_bytelen - pos);
  12985. size_t tLen = descr->width > sLen ? sLen : descr->width;
  12986. tmpObj = Jim_NewStringObjUtf8(interp, str + pos, tLen);
  12987. tok = tmpObj->bytes;
  12988. }
  12989. else {
  12990. tok = &str[pos];
  12991. }
  12992. switch (descr->type) {
  12993. case 'd':
  12994. case 'o':
  12995. case 'x':
  12996. case 'u':
  12997. case 'i':{
  12998. char *endp;
  12999. jim_wide w;
  13000. int base = descr->type == 'o' ? 8
  13001. : descr->type == 'x' ? 16 : descr->type == 'i' ? 0 : 10;
  13002. if (base == 0) {
  13003. w = jim_strtoull(tok, &endp);
  13004. }
  13005. else {
  13006. w = strtoull(tok, &endp, base);
  13007. }
  13008. if (endp != tok) {
  13009. *valObjPtr = Jim_NewIntObj(interp, w);
  13010. scanned += endp - tok;
  13011. }
  13012. else {
  13013. scanned = *tok ? 0 : -1;
  13014. }
  13015. break;
  13016. }
  13017. case 's':
  13018. case '[':{
  13019. *valObjPtr = JimScanAString(interp, descr->arg, tok);
  13020. scanned += Jim_Length(*valObjPtr);
  13021. break;
  13022. }
  13023. case 'e':
  13024. case 'f':
  13025. case 'g':{
  13026. char *endp;
  13027. double value = strtod(tok, &endp);
  13028. if (endp != tok) {
  13029. *valObjPtr = Jim_NewDoubleObj(interp, value);
  13030. scanned += endp - tok;
  13031. }
  13032. else {
  13033. scanned = *tok ? 0 : -1;
  13034. }
  13035. break;
  13036. }
  13037. }
  13038. if (tmpObj) {
  13039. Jim_FreeNewObj(interp, tmpObj);
  13040. }
  13041. }
  13042. return scanned;
  13043. }
  13044. Jim_Obj *Jim_ScanString(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *fmtObjPtr, int flags)
  13045. {
  13046. size_t i, pos;
  13047. int scanned = 1;
  13048. const char *str = Jim_String(strObjPtr);
  13049. int str_bytelen = Jim_Length(strObjPtr);
  13050. Jim_Obj *resultList = 0;
  13051. Jim_Obj **resultVec = 0;
  13052. int resultc;
  13053. Jim_Obj *emptyStr = 0;
  13054. ScanFmtStringObj *fmtObj;
  13055. JimPanic((fmtObjPtr->typePtr != &scanFmtStringObjType, "Jim_ScanString() for non-scan format"));
  13056. fmtObj = (ScanFmtStringObj *) fmtObjPtr->internalRep.ptr;
  13057. if (fmtObj->error != 0) {
  13058. if (flags & JIM_ERRMSG)
  13059. Jim_SetResultString(interp, fmtObj->error, -1);
  13060. return 0;
  13061. }
  13062. emptyStr = Jim_NewEmptyStringObj(interp);
  13063. Jim_IncrRefCount(emptyStr);
  13064. resultList = Jim_NewListObj(interp, NULL, 0);
  13065. if (fmtObj->maxPos > 0) {
  13066. for (i = 0; i < fmtObj->maxPos; ++i)
  13067. Jim_ListAppendElement(interp, resultList, emptyStr);
  13068. JimListGetElements(interp, resultList, &resultc, &resultVec);
  13069. }
  13070. for (i = 0, pos = 0; i < fmtObj->count; ++i) {
  13071. ScanFmtPartDescr *descr = &(fmtObj->descr[i]);
  13072. Jim_Obj *value = 0;
  13073. if (descr->type == 0)
  13074. continue;
  13075. if (scanned > 0)
  13076. scanned = ScanOneEntry(interp, str, pos, str_bytelen, fmtObj, i, &value);
  13077. if (scanned == -1 && i == 0)
  13078. goto eof;
  13079. pos += scanned;
  13080. if (value == 0)
  13081. value = Jim_NewEmptyStringObj(interp);
  13082. if (descr->pos == -1) {
  13083. Jim_FreeNewObj(interp, value);
  13084. }
  13085. else if (descr->pos == 0)
  13086. Jim_ListAppendElement(interp, resultList, value);
  13087. else if (resultVec[descr->pos - 1] == emptyStr) {
  13088. Jim_DecrRefCount(interp, resultVec[descr->pos - 1]);
  13089. Jim_IncrRefCount(value);
  13090. resultVec[descr->pos - 1] = value;
  13091. }
  13092. else {
  13093. Jim_FreeNewObj(interp, value);
  13094. goto err;
  13095. }
  13096. }
  13097. Jim_DecrRefCount(interp, emptyStr);
  13098. return resultList;
  13099. eof:
  13100. Jim_DecrRefCount(interp, emptyStr);
  13101. Jim_FreeNewObj(interp, resultList);
  13102. return (Jim_Obj *)EOF;
  13103. err:
  13104. Jim_DecrRefCount(interp, emptyStr);
  13105. Jim_FreeNewObj(interp, resultList);
  13106. return 0;
  13107. }
  13108. static void JimPrngInit(Jim_Interp *interp)
  13109. {
  13110. #define PRNG_SEED_SIZE 256
  13111. int i;
  13112. unsigned int *seed;
  13113. time_t t = time(NULL);
  13114. interp->prngState = Jim_Alloc(sizeof(Jim_PrngState));
  13115. seed = Jim_Alloc(PRNG_SEED_SIZE * sizeof(*seed));
  13116. for (i = 0; i < PRNG_SEED_SIZE; i++) {
  13117. seed[i] = (rand() ^ t ^ clock());
  13118. }
  13119. JimPrngSeed(interp, (unsigned char *)seed, PRNG_SEED_SIZE * sizeof(*seed));
  13120. Jim_Free(seed);
  13121. }
  13122. static void JimRandomBytes(Jim_Interp *interp, void *dest, unsigned int len)
  13123. {
  13124. Jim_PrngState *prng;
  13125. unsigned char *destByte = (unsigned char *)dest;
  13126. unsigned int si, sj, x;
  13127. if (interp->prngState == NULL)
  13128. JimPrngInit(interp);
  13129. prng = interp->prngState;
  13130. for (x = 0; x < len; x++) {
  13131. prng->i = (prng->i + 1) & 0xff;
  13132. si = prng->sbox[prng->i];
  13133. prng->j = (prng->j + si) & 0xff;
  13134. sj = prng->sbox[prng->j];
  13135. prng->sbox[prng->i] = sj;
  13136. prng->sbox[prng->j] = si;
  13137. *destByte++ = prng->sbox[(si + sj) & 0xff];
  13138. }
  13139. }
  13140. static void JimPrngSeed(Jim_Interp *interp, unsigned char *seed, int seedLen)
  13141. {
  13142. int i;
  13143. Jim_PrngState *prng;
  13144. if (interp->prngState == NULL)
  13145. JimPrngInit(interp);
  13146. prng = interp->prngState;
  13147. for (i = 0; i < 256; i++)
  13148. prng->sbox[i] = i;
  13149. for (i = 0; i < seedLen; i++) {
  13150. unsigned char t;
  13151. t = prng->sbox[i & 0xFF];
  13152. prng->sbox[i & 0xFF] = prng->sbox[seed[i]];
  13153. prng->sbox[seed[i]] = t;
  13154. }
  13155. prng->i = prng->j = 0;
  13156. for (i = 0; i < 256; i += seedLen) {
  13157. JimRandomBytes(interp, seed, seedLen);
  13158. }
  13159. }
  13160. static int Jim_IncrCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  13161. {
  13162. jim_wide wideValue, increment = 1;
  13163. Jim_Obj *intObjPtr;
  13164. if (argc != 2 && argc != 3) {
  13165. Jim_WrongNumArgs(interp, 1, argv, "varName ?increment?");
  13166. return JIM_ERR;
  13167. }
  13168. if (argc == 3) {
  13169. if (Jim_GetWideExpr(interp, argv[2], &increment) != JIM_OK)
  13170. return JIM_ERR;
  13171. }
  13172. intObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
  13173. if (!intObjPtr) {
  13174. wideValue = 0;
  13175. }
  13176. else if (Jim_GetWide(interp, intObjPtr, &wideValue) != JIM_OK) {
  13177. return JIM_ERR;
  13178. }
  13179. if (!intObjPtr || Jim_IsShared(intObjPtr)) {
  13180. intObjPtr = Jim_NewIntObj(interp, wideValue + increment);
  13181. if (Jim_SetVariable(interp, argv[1], intObjPtr) != JIM_OK) {
  13182. Jim_FreeNewObj(interp, intObjPtr);
  13183. return JIM_ERR;
  13184. }
  13185. }
  13186. else {
  13187. Jim_InvalidateStringRep(intObjPtr);
  13188. JimWideValue(intObjPtr) = wideValue + increment;
  13189. if (argv[1]->typePtr != &variableObjType) {
  13190. Jim_SetVariable(interp, argv[1], intObjPtr);
  13191. }
  13192. }
  13193. Jim_SetResult(interp, intObjPtr);
  13194. return JIM_OK;
  13195. }
  13196. #define JIM_EVAL_SARGV_LEN 8
  13197. #define JIM_EVAL_SINTV_LEN 8
  13198. static int JimTraceCallback(Jim_Interp *interp, const char *type, int argc, Jim_Obj *const *argv)
  13199. {
  13200. JimPanic((interp->traceCmdObj == NULL, "xtrace invoked with no object"));
  13201. int ret;
  13202. Jim_Obj *nargv[7];
  13203. Jim_Obj *traceCmdObj = interp->traceCmdObj;
  13204. Jim_Obj *resultObj = Jim_GetResult(interp);
  13205. ScriptObj *script = NULL;
  13206. if (interp->evalFrame->scriptObj) {
  13207. script = JimGetScript(interp, interp->evalFrame->scriptObj);
  13208. }
  13209. nargv[0] = traceCmdObj;
  13210. nargv[1] = Jim_NewStringObj(interp, type, -1);
  13211. nargv[2] = script ? script->fileNameObj : interp->emptyObj;
  13212. nargv[3] = Jim_NewIntObj(interp, script ? script->linenr : 1);
  13213. nargv[4] = resultObj;
  13214. nargv[5] = argv[0];
  13215. nargv[6] = Jim_NewListObj(interp, argv + 1, argc - 1);
  13216. interp->traceCmdObj = NULL;
  13217. Jim_IncrRefCount(resultObj);
  13218. ret = Jim_EvalObjVector(interp, 7, nargv);
  13219. Jim_DecrRefCount(interp, resultObj);
  13220. if (ret == JIM_OK || ret == JIM_RETURN) {
  13221. interp->traceCmdObj = traceCmdObj;
  13222. Jim_SetEmptyResult(interp);
  13223. ret = JIM_OK;
  13224. }
  13225. else {
  13226. Jim_DecrRefCount(interp, traceCmdObj);
  13227. }
  13228. return ret;
  13229. }
  13230. static int JimUnknown(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  13231. {
  13232. int retcode;
  13233. if (interp->unknown_called > 50) {
  13234. return JIM_ERR;
  13235. }
  13236. if (Jim_GetCommand(interp, interp->unknown, JIM_NONE) == NULL)
  13237. return JIM_ERR;
  13238. interp->unknown_called++;
  13239. retcode = Jim_EvalObjPrefix(interp, interp->unknown, argc, argv);
  13240. interp->unknown_called--;
  13241. return retcode;
  13242. }
  13243. static void JimPushEvalFrame(Jim_Interp *interp, Jim_EvalFrame *frame, Jim_Obj *scriptObj)
  13244. {
  13245. memset(frame, 0, sizeof(*frame));
  13246. frame->parent = interp->evalFrame;
  13247. frame->level = frame->parent->level + 1;
  13248. frame->procLevel = interp->procLevel;
  13249. frame->framePtr = interp->framePtr;
  13250. if (scriptObj) {
  13251. frame->scriptObj = scriptObj;
  13252. }
  13253. else {
  13254. frame->scriptObj = frame->parent->scriptObj;
  13255. }
  13256. interp->evalFrame = frame;
  13257. #if 0
  13258. if (frame->scriptObj) {
  13259. printf("script: %.*s\n", 20, Jim_String(frame->scriptObj));
  13260. }
  13261. #endif
  13262. }
  13263. static void JimPopEvalFrame(Jim_Interp *interp)
  13264. {
  13265. interp->evalFrame = interp->evalFrame->parent;
  13266. }
  13267. static int JimInvokeCommand(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
  13268. {
  13269. int retcode;
  13270. Jim_Cmd *cmdPtr;
  13271. void *prevPrivData;
  13272. Jim_Obj *tailcallObj = NULL;
  13273. #if 0
  13274. printf("invoke");
  13275. int j;
  13276. for (j = 0; j < objc; j++) {
  13277. printf(" '%s'", Jim_String(objv[j]));
  13278. }
  13279. printf("\n");
  13280. #endif
  13281. cmdPtr = Jim_GetCommand(interp, objv[0], JIM_ERRMSG);
  13282. if (cmdPtr == NULL) {
  13283. return JimUnknown(interp, objc, objv);
  13284. }
  13285. JimIncrCmdRefCount(cmdPtr);
  13286. if (interp->evalDepth == interp->maxEvalDepth) {
  13287. Jim_SetResultString(interp, "Infinite eval recursion", -1);
  13288. retcode = JIM_ERR;
  13289. goto out;
  13290. }
  13291. interp->evalDepth++;
  13292. prevPrivData = interp->cmdPrivData;
  13293. tailcall:
  13294. interp->evalFrame->argc = objc;
  13295. interp->evalFrame->argv = objv;
  13296. interp->evalFrame->cmd = cmdPtr;
  13297. if (!interp->traceCmdObj ||
  13298. (retcode = JimTraceCallback(interp, "cmd", objc, objv)) == JIM_OK) {
  13299. Jim_SetEmptyResult(interp);
  13300. if (cmdPtr->isproc) {
  13301. retcode = JimCallProcedure(interp, cmdPtr, objc, objv);
  13302. }
  13303. else {
  13304. interp->cmdPrivData = cmdPtr->u.native.privData;
  13305. retcode = cmdPtr->u.native.cmdProc(interp, objc, objv);
  13306. }
  13307. if (retcode == JIM_ERR) {
  13308. JimSetErrorStack(interp, NULL);
  13309. }
  13310. }
  13311. if (tailcallObj) {
  13312. Jim_DecrRefCount(interp, tailcallObj);
  13313. tailcallObj = NULL;
  13314. }
  13315. interp->evalFrame->argc = 0;
  13316. interp->evalFrame->argv = NULL;
  13317. if (retcode == JIM_EVAL && interp->framePtr->tailcallObj) {
  13318. JimDecrCmdRefCount(interp, cmdPtr);
  13319. cmdPtr = interp->framePtr->tailcallCmd;
  13320. interp->framePtr->tailcallCmd = NULL;
  13321. tailcallObj = interp->framePtr->tailcallObj;
  13322. interp->framePtr->tailcallObj = NULL;
  13323. objc = tailcallObj->internalRep.listValue.len;
  13324. objv = tailcallObj->internalRep.listValue.ele;
  13325. goto tailcall;
  13326. }
  13327. interp->cmdPrivData = prevPrivData;
  13328. interp->evalDepth--;
  13329. out:
  13330. JimDecrCmdRefCount(interp, cmdPtr);
  13331. if (retcode == JIM_ERR) {
  13332. JimSetErrorStack(interp, NULL);
  13333. }
  13334. if (interp->framePtr->tailcallObj) {
  13335. JimDecrCmdRefCount(interp, interp->framePtr->tailcallCmd);
  13336. Jim_DecrRefCount(interp, interp->framePtr->tailcallObj);
  13337. interp->framePtr->tailcallCmd = NULL;
  13338. interp->framePtr->tailcallObj = NULL;
  13339. }
  13340. return retcode;
  13341. }
  13342. int Jim_EvalObjVector(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
  13343. {
  13344. int i, retcode;
  13345. Jim_EvalFrame frame;
  13346. for (i = 0; i < objc; i++)
  13347. Jim_IncrRefCount(objv[i]);
  13348. JimPushEvalFrame(interp, &frame, NULL);
  13349. retcode = JimInvokeCommand(interp, objc, objv);
  13350. JimPopEvalFrame(interp);
  13351. for (i = 0; i < objc; i++)
  13352. Jim_DecrRefCount(interp, objv[i]);
  13353. return retcode;
  13354. }
  13355. int Jim_EvalObjPrefix(Jim_Interp *interp, Jim_Obj *prefix, int objc, Jim_Obj *const *objv)
  13356. {
  13357. int ret;
  13358. Jim_Obj **nargv = Jim_Alloc((objc + 1) * sizeof(*nargv));
  13359. nargv[0] = prefix;
  13360. memcpy(&nargv[1], &objv[0], sizeof(nargv[0]) * objc);
  13361. ret = Jim_EvalObjVector(interp, objc + 1, nargv);
  13362. Jim_Free(nargv);
  13363. return ret;
  13364. }
  13365. static int JimSubstOneToken(Jim_Interp *interp, const ScriptToken *token, Jim_Obj **objPtrPtr)
  13366. {
  13367. Jim_Obj *objPtr;
  13368. int ret = JIM_ERR;
  13369. switch (token->type) {
  13370. case JIM_TT_STR:
  13371. case JIM_TT_ESC:
  13372. objPtr = token->objPtr;
  13373. break;
  13374. case JIM_TT_VAR:
  13375. objPtr = Jim_GetVariable(interp, token->objPtr, JIM_ERRMSG);
  13376. break;
  13377. case JIM_TT_DICTSUGAR:
  13378. objPtr = JimExpandDictSugar(interp, token->objPtr);
  13379. break;
  13380. case JIM_TT_EXPRSUGAR:
  13381. ret = Jim_EvalExpression(interp, token->objPtr);
  13382. if (ret == JIM_OK) {
  13383. objPtr = Jim_GetResult(interp);
  13384. }
  13385. else {
  13386. objPtr = NULL;
  13387. }
  13388. break;
  13389. case JIM_TT_CMD:
  13390. ret = Jim_EvalObj(interp, token->objPtr);
  13391. if (ret == JIM_OK || ret == JIM_RETURN) {
  13392. objPtr = interp->result;
  13393. } else {
  13394. objPtr = NULL;
  13395. }
  13396. break;
  13397. default:
  13398. JimPanic((1,
  13399. "default token type (%d) reached " "in Jim_SubstObj().", token->type));
  13400. objPtr = NULL;
  13401. break;
  13402. }
  13403. if (objPtr) {
  13404. *objPtrPtr = objPtr;
  13405. return JIM_OK;
  13406. }
  13407. return ret;
  13408. }
  13409. static Jim_Obj *JimInterpolateTokens(Jim_Interp *interp, const ScriptToken * token, int tokens, int flags)
  13410. {
  13411. int totlen = 0, i;
  13412. Jim_Obj **intv;
  13413. Jim_Obj *sintv[JIM_EVAL_SINTV_LEN];
  13414. Jim_Obj *objPtr;
  13415. char *s;
  13416. if (tokens <= JIM_EVAL_SINTV_LEN)
  13417. intv = sintv;
  13418. else
  13419. intv = Jim_Alloc(sizeof(Jim_Obj *) * tokens);
  13420. for (i = 0; i < tokens; i++) {
  13421. switch (JimSubstOneToken(interp, &token[i], &intv[i])) {
  13422. case JIM_OK:
  13423. case JIM_RETURN:
  13424. break;
  13425. case JIM_BREAK:
  13426. if (flags & JIM_SUBST_FLAG) {
  13427. tokens = i;
  13428. continue;
  13429. }
  13430. case JIM_CONTINUE:
  13431. if (flags & JIM_SUBST_FLAG) {
  13432. intv[i] = NULL;
  13433. continue;
  13434. }
  13435. default:
  13436. while (i--) {
  13437. Jim_DecrRefCount(interp, intv[i]);
  13438. }
  13439. if (intv != sintv) {
  13440. Jim_Free(intv);
  13441. }
  13442. return NULL;
  13443. }
  13444. Jim_IncrRefCount(intv[i]);
  13445. Jim_String(intv[i]);
  13446. totlen += intv[i]->length;
  13447. }
  13448. if (tokens == 1 && intv[0] && intv == sintv) {
  13449. intv[0]->refCount--;
  13450. return intv[0];
  13451. }
  13452. objPtr = Jim_NewStringObjNoAlloc(interp, NULL, 0);
  13453. if (tokens == 4 && token[0].type == JIM_TT_ESC && token[1].type == JIM_TT_ESC
  13454. && token[2].type == JIM_TT_VAR) {
  13455. objPtr->typePtr = &interpolatedObjType;
  13456. objPtr->internalRep.dictSubstValue.varNameObjPtr = token[0].objPtr;
  13457. objPtr->internalRep.dictSubstValue.indexObjPtr = intv[2];
  13458. Jim_IncrRefCount(intv[2]);
  13459. }
  13460. else if (tokens && intv[0] && intv[0]->typePtr == &sourceObjType) {
  13461. int line;
  13462. Jim_Obj *fileNameObj = Jim_GetSourceInfo(interp, intv[0], &line);
  13463. Jim_SetSourceInfo(interp, objPtr, fileNameObj, line);
  13464. }
  13465. s = objPtr->bytes = Jim_Alloc(totlen + 1);
  13466. objPtr->length = totlen;
  13467. for (i = 0; i < tokens; i++) {
  13468. if (intv[i]) {
  13469. memcpy(s, intv[i]->bytes, intv[i]->length);
  13470. s += intv[i]->length;
  13471. Jim_DecrRefCount(interp, intv[i]);
  13472. }
  13473. }
  13474. objPtr->bytes[totlen] = '\0';
  13475. if (intv != sintv) {
  13476. Jim_Free(intv);
  13477. }
  13478. return objPtr;
  13479. }
  13480. static int JimEvalObjList(Jim_Interp *interp, Jim_Obj *listPtr)
  13481. {
  13482. int retcode = JIM_OK;
  13483. Jim_EvalFrame frame;
  13484. JimPanic((Jim_IsList(listPtr) == 0, "JimEvalObjList() invoked on non-list."));
  13485. JimPushEvalFrame(interp, &frame, NULL);
  13486. if (listPtr->internalRep.listValue.len) {
  13487. Jim_IncrRefCount(listPtr);
  13488. retcode = JimInvokeCommand(interp,
  13489. listPtr->internalRep.listValue.len,
  13490. listPtr->internalRep.listValue.ele);
  13491. Jim_DecrRefCount(interp, listPtr);
  13492. }
  13493. JimPopEvalFrame(interp);
  13494. return retcode;
  13495. }
  13496. int Jim_EvalObjList(Jim_Interp *interp, Jim_Obj *listPtr)
  13497. {
  13498. SetListFromAny(interp, listPtr);
  13499. return JimEvalObjList(interp, listPtr);
  13500. }
  13501. int Jim_EvalObj(Jim_Interp *interp, Jim_Obj *scriptObjPtr)
  13502. {
  13503. int i;
  13504. ScriptObj *script;
  13505. ScriptToken *token;
  13506. int retcode = JIM_OK;
  13507. Jim_Obj *sargv[JIM_EVAL_SARGV_LEN], **argv = NULL;
  13508. Jim_EvalFrame frame;
  13509. if (Jim_IsList(scriptObjPtr) && scriptObjPtr->bytes == NULL) {
  13510. return JimEvalObjList(interp, scriptObjPtr);
  13511. }
  13512. Jim_IncrRefCount(scriptObjPtr);
  13513. script = JimGetScript(interp, scriptObjPtr);
  13514. if (JimParseCheckMissing(interp, script->missing) == JIM_ERR) {
  13515. JimSetErrorStack(interp, script);
  13516. Jim_DecrRefCount(interp, scriptObjPtr);
  13517. return JIM_ERR;
  13518. }
  13519. Jim_SetEmptyResult(interp);
  13520. token = script->token;
  13521. #ifdef JIM_OPTIMIZATION
  13522. if (script->len == 0) {
  13523. Jim_DecrRefCount(interp, scriptObjPtr);
  13524. return JIM_OK;
  13525. }
  13526. if (script->len == 3
  13527. && token[1].objPtr->typePtr == &commandObjType
  13528. && token[1].objPtr->internalRep.cmdValue.cmdPtr->isproc == 0
  13529. && token[1].objPtr->internalRep.cmdValue.cmdPtr->u.native.cmdProc == Jim_IncrCoreCommand
  13530. && token[2].objPtr->typePtr == &variableObjType) {
  13531. Jim_Obj *objPtr = Jim_GetVariable(interp, token[2].objPtr, JIM_NONE);
  13532. if (objPtr && !Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
  13533. JimWideValue(objPtr)++;
  13534. Jim_InvalidateStringRep(objPtr);
  13535. Jim_DecrRefCount(interp, scriptObjPtr);
  13536. Jim_SetResult(interp, objPtr);
  13537. return JIM_OK;
  13538. }
  13539. }
  13540. #endif
  13541. script->inUse++;
  13542. JimPushEvalFrame(interp, &frame, scriptObjPtr);
  13543. interp->errorFlag = 0;
  13544. argv = sargv;
  13545. for (i = 0; i < script->len && retcode == JIM_OK; ) {
  13546. int argc;
  13547. int j;
  13548. argc = token[i].objPtr->internalRep.scriptLineValue.argc;
  13549. script->linenr = token[i].objPtr->internalRep.scriptLineValue.line;
  13550. if (argc > JIM_EVAL_SARGV_LEN)
  13551. argv = Jim_Alloc(sizeof(Jim_Obj *) * argc);
  13552. i++;
  13553. for (j = 0; j < argc; j++) {
  13554. long wordtokens = 1;
  13555. int expand = 0;
  13556. Jim_Obj *wordObjPtr = NULL;
  13557. if (token[i].type == JIM_TT_WORD) {
  13558. wordtokens = JimWideValue(token[i++].objPtr);
  13559. if (wordtokens < 0) {
  13560. expand = 1;
  13561. wordtokens = -wordtokens;
  13562. }
  13563. }
  13564. if (wordtokens == 1) {
  13565. switch (token[i].type) {
  13566. case JIM_TT_ESC:
  13567. case JIM_TT_STR:
  13568. wordObjPtr = token[i].objPtr;
  13569. break;
  13570. case JIM_TT_VAR:
  13571. wordObjPtr = Jim_GetVariable(interp, token[i].objPtr, JIM_ERRMSG);
  13572. break;
  13573. case JIM_TT_EXPRSUGAR:
  13574. retcode = Jim_EvalExpression(interp, token[i].objPtr);
  13575. if (retcode == JIM_OK) {
  13576. wordObjPtr = Jim_GetResult(interp);
  13577. }
  13578. else {
  13579. wordObjPtr = NULL;
  13580. }
  13581. break;
  13582. case JIM_TT_DICTSUGAR:
  13583. wordObjPtr = JimExpandDictSugar(interp, token[i].objPtr);
  13584. break;
  13585. case JIM_TT_CMD:
  13586. retcode = Jim_EvalObj(interp, token[i].objPtr);
  13587. if (retcode == JIM_OK) {
  13588. wordObjPtr = Jim_GetResult(interp);
  13589. }
  13590. break;
  13591. default:
  13592. JimPanic((1, "default token type reached " "in Jim_EvalObj()."));
  13593. }
  13594. }
  13595. else {
  13596. wordObjPtr = JimInterpolateTokens(interp, token + i, wordtokens, JIM_NONE);
  13597. }
  13598. if (!wordObjPtr) {
  13599. if (retcode == JIM_OK) {
  13600. retcode = JIM_ERR;
  13601. }
  13602. break;
  13603. }
  13604. Jim_IncrRefCount(wordObjPtr);
  13605. i += wordtokens;
  13606. if (!expand) {
  13607. argv[j] = wordObjPtr;
  13608. }
  13609. else {
  13610. int len = Jim_ListLength(interp, wordObjPtr);
  13611. int newargc = argc + len - 1;
  13612. int k;
  13613. if (len > 1) {
  13614. if (argv == sargv) {
  13615. if (newargc > JIM_EVAL_SARGV_LEN) {
  13616. argv = Jim_Alloc(sizeof(*argv) * newargc);
  13617. memcpy(argv, sargv, sizeof(*argv) * j);
  13618. }
  13619. }
  13620. else {
  13621. argv = Jim_Realloc(argv, sizeof(*argv) * newargc);
  13622. }
  13623. }
  13624. for (k = 0; k < len; k++) {
  13625. argv[j++] = wordObjPtr->internalRep.listValue.ele[k];
  13626. Jim_IncrRefCount(wordObjPtr->internalRep.listValue.ele[k]);
  13627. }
  13628. Jim_DecrRefCount(interp, wordObjPtr);
  13629. j--;
  13630. argc += len - 1;
  13631. }
  13632. }
  13633. if (retcode == JIM_OK && argc) {
  13634. retcode = JimInvokeCommand(interp, argc, argv);
  13635. if (Jim_CheckSignal(interp)) {
  13636. retcode = JIM_SIGNAL;
  13637. }
  13638. }
  13639. while (j-- > 0) {
  13640. Jim_DecrRefCount(interp, argv[j]);
  13641. }
  13642. if (argv != sargv) {
  13643. Jim_Free(argv);
  13644. argv = sargv;
  13645. }
  13646. }
  13647. if (retcode == JIM_ERR) {
  13648. JimSetErrorStack(interp, NULL);
  13649. }
  13650. JimPopEvalFrame(interp);
  13651. Jim_FreeIntRep(interp, scriptObjPtr);
  13652. scriptObjPtr->typePtr = &scriptObjType;
  13653. Jim_SetIntRepPtr(scriptObjPtr, script);
  13654. Jim_DecrRefCount(interp, scriptObjPtr);
  13655. return retcode;
  13656. }
  13657. static int JimSetProcArg(Jim_Interp *interp, Jim_Obj *argNameObj, Jim_Obj *argValObj)
  13658. {
  13659. int retcode;
  13660. const char *varname = Jim_String(argNameObj);
  13661. if (*varname == '&') {
  13662. Jim_Obj *objPtr;
  13663. Jim_CallFrame *savedCallFrame = interp->framePtr;
  13664. interp->framePtr = interp->framePtr->parent;
  13665. objPtr = Jim_GetVariable(interp, argValObj, JIM_ERRMSG);
  13666. interp->framePtr = savedCallFrame;
  13667. if (!objPtr) {
  13668. return JIM_ERR;
  13669. }
  13670. objPtr = Jim_NewStringObj(interp, varname + 1, -1);
  13671. Jim_IncrRefCount(objPtr);
  13672. retcode = Jim_SetVariableLink(interp, objPtr, argValObj, interp->framePtr->parent);
  13673. Jim_DecrRefCount(interp, objPtr);
  13674. }
  13675. else {
  13676. retcode = Jim_SetVariable(interp, argNameObj, argValObj);
  13677. }
  13678. return retcode;
  13679. }
  13680. static void JimSetProcWrongArgs(Jim_Interp *interp, Jim_Obj *procNameObj, Jim_Cmd *cmd)
  13681. {
  13682. Jim_Obj *argmsg = Jim_NewStringObj(interp, "", 0);
  13683. int i;
  13684. for (i = 0; i < cmd->u.proc.argListLen; i++) {
  13685. Jim_AppendString(interp, argmsg, " ", 1);
  13686. if (i == cmd->u.proc.argsPos) {
  13687. if (cmd->u.proc.arglist[i].defaultObjPtr) {
  13688. Jim_AppendString(interp, argmsg, "?", 1);
  13689. Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].defaultObjPtr);
  13690. Jim_AppendString(interp, argmsg, " ...?", -1);
  13691. }
  13692. else {
  13693. Jim_AppendString(interp, argmsg, "?arg ...?", -1);
  13694. }
  13695. }
  13696. else {
  13697. if (cmd->u.proc.arglist[i].defaultObjPtr) {
  13698. Jim_AppendString(interp, argmsg, "?", 1);
  13699. Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].nameObjPtr);
  13700. Jim_AppendString(interp, argmsg, "?", 1);
  13701. }
  13702. else {
  13703. const char *arg = Jim_String(cmd->u.proc.arglist[i].nameObjPtr);
  13704. if (*arg == '&') {
  13705. arg++;
  13706. }
  13707. Jim_AppendString(interp, argmsg, arg, -1);
  13708. }
  13709. }
  13710. }
  13711. Jim_SetResultFormatted(interp, "wrong # args: should be \"%#s%#s\"", procNameObj, argmsg);
  13712. }
  13713. #ifdef jim_ext_namespace
  13714. int Jim_EvalNamespace(Jim_Interp *interp, Jim_Obj *scriptObj, Jim_Obj *nsObj)
  13715. {
  13716. Jim_CallFrame *callFramePtr;
  13717. int retcode;
  13718. callFramePtr = JimCreateCallFrame(interp, interp->framePtr, nsObj);
  13719. callFramePtr->argv = interp->evalFrame->argv;
  13720. callFramePtr->argc = interp->evalFrame->argc;
  13721. callFramePtr->procArgsObjPtr = NULL;
  13722. callFramePtr->procBodyObjPtr = scriptObj;
  13723. callFramePtr->staticVars = NULL;
  13724. Jim_IncrRefCount(scriptObj);
  13725. interp->framePtr = callFramePtr;
  13726. if (interp->framePtr->level == interp->maxCallFrameDepth) {
  13727. Jim_SetResultString(interp, "Too many nested calls. Infinite recursion?", -1);
  13728. retcode = JIM_ERR;
  13729. }
  13730. else {
  13731. retcode = Jim_EvalObj(interp, scriptObj);
  13732. }
  13733. interp->framePtr = interp->framePtr->parent;
  13734. JimFreeCallFrame(interp, callFramePtr, JIM_FCF_REUSE);
  13735. return retcode;
  13736. }
  13737. #endif
  13738. static int JimCallProcedure(Jim_Interp *interp, Jim_Cmd *cmd, int argc, Jim_Obj *const *argv)
  13739. {
  13740. Jim_CallFrame *callFramePtr;
  13741. int i, d, retcode, optargs;
  13742. if (argc - 1 < cmd->u.proc.reqArity ||
  13743. (cmd->u.proc.argsPos < 0 && argc - 1 > cmd->u.proc.reqArity + cmd->u.proc.optArity)) {
  13744. JimSetProcWrongArgs(interp, argv[0], cmd);
  13745. return JIM_ERR;
  13746. }
  13747. if (Jim_Length(cmd->u.proc.bodyObjPtr) == 0) {
  13748. return JIM_OK;
  13749. }
  13750. if (interp->framePtr->level == interp->maxCallFrameDepth) {
  13751. Jim_SetResultString(interp, "Too many nested calls. Infinite recursion?", -1);
  13752. return JIM_ERR;
  13753. }
  13754. callFramePtr = JimCreateCallFrame(interp, interp->framePtr, cmd->u.proc.nsObj);
  13755. callFramePtr->argv = argv;
  13756. callFramePtr->argc = argc;
  13757. callFramePtr->procArgsObjPtr = cmd->u.proc.argListObjPtr;
  13758. callFramePtr->procBodyObjPtr = cmd->u.proc.bodyObjPtr;
  13759. callFramePtr->staticVars = cmd->u.proc.staticVars;
  13760. interp->procLevel++;
  13761. Jim_IncrRefCount(cmd->u.proc.argListObjPtr);
  13762. Jim_IncrRefCount(cmd->u.proc.bodyObjPtr);
  13763. interp->framePtr = callFramePtr;
  13764. optargs = (argc - 1 - cmd->u.proc.reqArity);
  13765. i = 1;
  13766. for (d = 0; d < cmd->u.proc.argListLen; d++) {
  13767. Jim_Obj *nameObjPtr = cmd->u.proc.arglist[d].nameObjPtr;
  13768. if (d == cmd->u.proc.argsPos) {
  13769. Jim_Obj *listObjPtr;
  13770. int argsLen = 0;
  13771. if (cmd->u.proc.reqArity + cmd->u.proc.optArity < argc - 1) {
  13772. argsLen = argc - 1 - (cmd->u.proc.reqArity + cmd->u.proc.optArity);
  13773. }
  13774. listObjPtr = Jim_NewListObj(interp, &argv[i], argsLen);
  13775. if (cmd->u.proc.arglist[d].defaultObjPtr) {
  13776. nameObjPtr =cmd->u.proc.arglist[d].defaultObjPtr;
  13777. }
  13778. retcode = Jim_SetVariable(interp, nameObjPtr, listObjPtr);
  13779. if (retcode != JIM_OK) {
  13780. goto badargset;
  13781. }
  13782. i += argsLen;
  13783. continue;
  13784. }
  13785. if (cmd->u.proc.arglist[d].defaultObjPtr == NULL || optargs-- > 0) {
  13786. retcode = JimSetProcArg(interp, nameObjPtr, argv[i++]);
  13787. }
  13788. else {
  13789. retcode = Jim_SetVariable(interp, nameObjPtr, cmd->u.proc.arglist[d].defaultObjPtr);
  13790. }
  13791. if (retcode != JIM_OK) {
  13792. goto badargset;
  13793. }
  13794. }
  13795. if (interp->traceCmdObj == NULL ||
  13796. (retcode = JimTraceCallback(interp, "proc", argc, argv)) == JIM_OK) {
  13797. retcode = Jim_EvalObj(interp, cmd->u.proc.bodyObjPtr);
  13798. }
  13799. badargset:
  13800. retcode = JimInvokeDefer(interp, retcode);
  13801. interp->framePtr = interp->framePtr->parent;
  13802. JimFreeCallFrame(interp, callFramePtr, JIM_FCF_REUSE);
  13803. if (retcode == JIM_RETURN) {
  13804. if (--interp->returnLevel <= 0) {
  13805. retcode = interp->returnCode;
  13806. interp->returnCode = JIM_OK;
  13807. interp->returnLevel = 0;
  13808. }
  13809. }
  13810. interp->procLevel--;
  13811. return retcode;
  13812. }
  13813. int Jim_EvalSource(Jim_Interp *interp, const char *filename, int lineno, const char *script)
  13814. {
  13815. int retval;
  13816. Jim_Obj *scriptObjPtr;
  13817. scriptObjPtr = Jim_NewStringObj(interp, script, -1);
  13818. Jim_IncrRefCount(scriptObjPtr);
  13819. if (filename) {
  13820. Jim_SetSourceInfo(interp, scriptObjPtr, Jim_NewStringObj(interp, filename, -1), lineno);
  13821. }
  13822. retval = Jim_EvalObj(interp, scriptObjPtr);
  13823. Jim_DecrRefCount(interp, scriptObjPtr);
  13824. return retval;
  13825. }
  13826. int Jim_Eval(Jim_Interp *interp, const char *script)
  13827. {
  13828. return Jim_EvalObj(interp, Jim_NewStringObj(interp, script, -1));
  13829. }
  13830. int Jim_EvalGlobal(Jim_Interp *interp, const char *script)
  13831. {
  13832. int retval;
  13833. Jim_CallFrame *savedFramePtr = interp->framePtr;
  13834. interp->framePtr = interp->topFramePtr;
  13835. retval = Jim_Eval(interp, script);
  13836. interp->framePtr = savedFramePtr;
  13837. return retval;
  13838. }
  13839. int Jim_EvalFileGlobal(Jim_Interp *interp, const char *filename)
  13840. {
  13841. int retval;
  13842. Jim_CallFrame *savedFramePtr = interp->framePtr;
  13843. interp->framePtr = interp->topFramePtr;
  13844. retval = Jim_EvalFile(interp, filename);
  13845. interp->framePtr = savedFramePtr;
  13846. return retval;
  13847. }
  13848. #include <sys/stat.h>
  13849. static Jim_Obj *JimReadTextFile(Jim_Interp *interp, const char *filename)
  13850. {
  13851. jim_stat_t sb;
  13852. int fd;
  13853. char *buf;
  13854. int readlen;
  13855. if (Jim_Stat(filename, &sb) == -1 || (fd = open(filename, O_RDONLY | O_TEXT, 0666)) < 0) {
  13856. Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", filename, strerror(errno));
  13857. return NULL;
  13858. }
  13859. buf = Jim_Alloc(sb.st_size + 1);
  13860. readlen = read(fd, buf, sb.st_size);
  13861. close(fd);
  13862. if (readlen < 0) {
  13863. Jim_Free(buf);
  13864. Jim_SetResultFormatted(interp, "failed to load file \"%s\": %s", filename, strerror(errno));
  13865. return NULL;
  13866. }
  13867. else {
  13868. Jim_Obj *objPtr;
  13869. buf[readlen] = 0;
  13870. objPtr = Jim_NewStringObjNoAlloc(interp, buf, readlen);
  13871. return objPtr;
  13872. }
  13873. }
  13874. int Jim_EvalFile(Jim_Interp *interp, const char *filename)
  13875. {
  13876. Jim_Obj *filenameObj;
  13877. Jim_Obj *oldFilenameObj;
  13878. Jim_Obj *scriptObjPtr;
  13879. int retcode;
  13880. scriptObjPtr = JimReadTextFile(interp, filename);
  13881. if (!scriptObjPtr) {
  13882. return JIM_ERR;
  13883. }
  13884. filenameObj = Jim_NewStringObj(interp, filename, -1);
  13885. Jim_SetSourceInfo(interp, scriptObjPtr, filenameObj, 1);
  13886. oldFilenameObj = JimPushInterpObj(interp->currentFilenameObj, filenameObj);
  13887. retcode = Jim_EvalObj(interp, scriptObjPtr);
  13888. JimPopInterpObj(interp, interp->currentFilenameObj, oldFilenameObj);
  13889. if (retcode == JIM_RETURN) {
  13890. if (--interp->returnLevel <= 0) {
  13891. retcode = interp->returnCode;
  13892. interp->returnCode = JIM_OK;
  13893. interp->returnLevel = 0;
  13894. }
  13895. }
  13896. return retcode;
  13897. }
  13898. static void JimParseSubst(struct JimParserCtx *pc, int flags)
  13899. {
  13900. pc->tstart = pc->p;
  13901. pc->tline = pc->linenr;
  13902. if (pc->len == 0) {
  13903. pc->tend = pc->p;
  13904. pc->tt = JIM_TT_EOL;
  13905. pc->eof = 1;
  13906. return;
  13907. }
  13908. if (*pc->p == '[' && !(flags & JIM_SUBST_NOCMD)) {
  13909. JimParseCmd(pc);
  13910. return;
  13911. }
  13912. if (*pc->p == '$' && !(flags & JIM_SUBST_NOVAR)) {
  13913. if (JimParseVar(pc) == JIM_OK) {
  13914. return;
  13915. }
  13916. pc->tstart = pc->p;
  13917. pc->p++;
  13918. pc->len--;
  13919. }
  13920. while (pc->len) {
  13921. if (*pc->p == '$' && !(flags & JIM_SUBST_NOVAR)) {
  13922. break;
  13923. }
  13924. if (*pc->p == '[' && !(flags & JIM_SUBST_NOCMD)) {
  13925. break;
  13926. }
  13927. if (*pc->p == '\\' && pc->len > 1) {
  13928. pc->p++;
  13929. pc->len--;
  13930. }
  13931. pc->p++;
  13932. pc->len--;
  13933. }
  13934. pc->tend = pc->p - 1;
  13935. pc->tt = (flags & JIM_SUBST_NOESC) ? JIM_TT_STR : JIM_TT_ESC;
  13936. }
  13937. static int SetSubstFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr, int flags)
  13938. {
  13939. int scriptTextLen;
  13940. const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);
  13941. struct JimParserCtx parser;
  13942. struct ScriptObj *script = Jim_Alloc(sizeof(*script));
  13943. ParseTokenList tokenlist;
  13944. ScriptTokenListInit(&tokenlist);
  13945. JimParserInit(&parser, scriptText, scriptTextLen, 1);
  13946. while (1) {
  13947. JimParseSubst(&parser, flags);
  13948. if (parser.eof) {
  13949. break;
  13950. }
  13951. ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
  13952. parser.tline);
  13953. }
  13954. script->inUse = 1;
  13955. script->substFlags = flags;
  13956. script->fileNameObj = interp->emptyObj;
  13957. Jim_IncrRefCount(script->fileNameObj);
  13958. SubstObjAddTokens(interp, script, &tokenlist);
  13959. ScriptTokenListFree(&tokenlist);
  13960. #ifdef DEBUG_SHOW_SUBST
  13961. {
  13962. int i;
  13963. printf("==== Subst ====\n");
  13964. for (i = 0; i < script->len; i++) {
  13965. printf("[%2d] %s '%s'\n", i, jim_tt_name(script->token[i].type),
  13966. Jim_String(script->token[i].objPtr));
  13967. }
  13968. }
  13969. #endif
  13970. Jim_FreeIntRep(interp, objPtr);
  13971. Jim_SetIntRepPtr(objPtr, script);
  13972. objPtr->typePtr = &scriptObjType;
  13973. return JIM_OK;
  13974. }
  13975. static ScriptObj *Jim_GetSubst(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
  13976. {
  13977. if (objPtr->typePtr != &scriptObjType || ((ScriptObj *)Jim_GetIntRepPtr(objPtr))->substFlags != flags)
  13978. SetSubstFromAny(interp, objPtr, flags);
  13979. return (ScriptObj *) Jim_GetIntRepPtr(objPtr);
  13980. }
  13981. int Jim_SubstObj(Jim_Interp *interp, Jim_Obj *substObjPtr, Jim_Obj **resObjPtrPtr, int flags)
  13982. {
  13983. ScriptObj *script;
  13984. JimPanic((substObjPtr->refCount == 0, "Jim_SubstObj() called with zero refcount object"));
  13985. script = Jim_GetSubst(interp, substObjPtr, flags);
  13986. Jim_IncrRefCount(substObjPtr);
  13987. script->inUse++;
  13988. *resObjPtrPtr = JimInterpolateTokens(interp, script->token, script->len, flags);
  13989. script->inUse--;
  13990. Jim_DecrRefCount(interp, substObjPtr);
  13991. if (*resObjPtrPtr == NULL) {
  13992. return JIM_ERR;
  13993. }
  13994. return JIM_OK;
  13995. }
  13996. void Jim_WrongNumArgs(Jim_Interp *interp, int argc, Jim_Obj *const *argv, const char *msg)
  13997. {
  13998. Jim_Obj *objPtr;
  13999. Jim_Obj *listObjPtr;
  14000. JimPanic((argc == 0, "Jim_WrongNumArgs() called with argc=0"));
  14001. listObjPtr = Jim_NewListObj(interp, argv, argc);
  14002. if (msg && *msg) {
  14003. Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, msg, -1));
  14004. }
  14005. Jim_IncrRefCount(listObjPtr);
  14006. objPtr = Jim_ListJoin(interp, listObjPtr, " ", 1);
  14007. Jim_DecrRefCount(interp, listObjPtr);
  14008. Jim_SetResultFormatted(interp, "wrong # args: should be \"%#s\"", objPtr);
  14009. }
  14010. typedef void JimHashtableIteratorCallbackType(Jim_Interp *interp, Jim_Obj *listObjPtr,
  14011. Jim_Obj *keyObjPtr, void *value, Jim_Obj *patternObjPtr, int type);
  14012. #define JimTrivialMatch(pattern) (strpbrk((pattern), "*[?\\") == NULL)
  14013. static Jim_Obj *JimHashtablePatternMatch(Jim_Interp *interp, Jim_HashTable *ht, Jim_Obj *patternObjPtr,
  14014. JimHashtableIteratorCallbackType *callback, int type)
  14015. {
  14016. Jim_HashEntry *he;
  14017. Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
  14018. if (patternObjPtr && JimTrivialMatch(Jim_String(patternObjPtr))) {
  14019. he = Jim_FindHashEntry(ht, patternObjPtr);
  14020. if (he) {
  14021. callback(interp, listObjPtr, Jim_GetHashEntryKey(he), Jim_GetHashEntryVal(he),
  14022. patternObjPtr, type);
  14023. }
  14024. }
  14025. else {
  14026. Jim_HashTableIterator htiter;
  14027. JimInitHashTableIterator(ht, &htiter);
  14028. while ((he = Jim_NextHashEntry(&htiter)) != NULL) {
  14029. callback(interp, listObjPtr, Jim_GetHashEntryKey(he), Jim_GetHashEntryVal(he),
  14030. patternObjPtr, type);
  14031. }
  14032. }
  14033. return listObjPtr;
  14034. }
  14035. #define JIM_CMDLIST_COMMANDS 0
  14036. #define JIM_CMDLIST_PROCS 1
  14037. #define JIM_CMDLIST_CHANNELS 2
  14038. static void JimCommandMatch(Jim_Interp *interp, Jim_Obj *listObjPtr,
  14039. Jim_Obj *keyObj, void *value, Jim_Obj *patternObj, int type)
  14040. {
  14041. Jim_Cmd *cmdPtr = (Jim_Cmd *)value;
  14042. if (type == JIM_CMDLIST_PROCS && !cmdPtr->isproc) {
  14043. return;
  14044. }
  14045. Jim_IncrRefCount(keyObj);
  14046. if (type != JIM_CMDLIST_CHANNELS || Jim_AioFilehandle(interp, keyObj) >= 0) {
  14047. int match = 1;
  14048. if (patternObj) {
  14049. int plen, slen;
  14050. const char *pattern = Jim_GetStringNoQualifier(patternObj, &plen);
  14051. const char *str = Jim_GetStringNoQualifier(keyObj, &slen);
  14052. #ifdef JIM_NO_INTROSPECTION
  14053. match = (JimStringCompareUtf8(pattern, plen, str, slen, 0) == 0);
  14054. #else
  14055. match = JimGlobMatch(pattern, plen, str, slen, 0);
  14056. #endif
  14057. }
  14058. if (match) {
  14059. Jim_ListAppendElement(interp, listObjPtr, keyObj);
  14060. }
  14061. }
  14062. Jim_DecrRefCount(interp, keyObj);
  14063. }
  14064. static Jim_Obj *JimCommandsList(Jim_Interp *interp, Jim_Obj *patternObjPtr, int type)
  14065. {
  14066. return JimHashtablePatternMatch(interp, &interp->commands, patternObjPtr, JimCommandMatch, type);
  14067. }
  14068. #define JIM_VARLIST_GLOBALS 0
  14069. #define JIM_VARLIST_LOCALS 1
  14070. #define JIM_VARLIST_VARS 2
  14071. #define JIM_VARLIST_MASK 0x000f
  14072. #define JIM_VARLIST_VALUES 0x1000
  14073. static void JimVariablesMatch(Jim_Interp *interp, Jim_Obj *listObjPtr,
  14074. Jim_Obj *keyObj, void *value, Jim_Obj *patternObj, int type)
  14075. {
  14076. Jim_VarVal *vv = (Jim_VarVal *)value;
  14077. if ((type & JIM_VARLIST_MASK) != JIM_VARLIST_LOCALS || vv->linkFramePtr == NULL) {
  14078. if (patternObj == NULL || Jim_StringMatchObj(interp, patternObj, keyObj, 0)) {
  14079. Jim_ListAppendElement(interp, listObjPtr, keyObj);
  14080. if (type & JIM_VARLIST_VALUES) {
  14081. Jim_ListAppendElement(interp, listObjPtr, vv->objPtr);
  14082. }
  14083. }
  14084. }
  14085. }
  14086. static Jim_Obj *JimVariablesList(Jim_Interp *interp, Jim_Obj *patternObjPtr, int mode)
  14087. {
  14088. if (mode == JIM_VARLIST_LOCALS && interp->framePtr == interp->topFramePtr) {
  14089. return interp->emptyObj;
  14090. }
  14091. else {
  14092. Jim_CallFrame *framePtr = (mode == JIM_VARLIST_GLOBALS) ? interp->topFramePtr : interp->framePtr;
  14093. return JimHashtablePatternMatch(interp, &framePtr->vars, patternObjPtr, JimVariablesMatch,
  14094. mode);
  14095. }
  14096. }
  14097. static int JimInfoLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr, Jim_Obj **objPtrPtr)
  14098. {
  14099. long level;
  14100. if (Jim_GetLong(interp, levelObjPtr, &level) == JIM_OK) {
  14101. Jim_CallFrame *targetCallFrame = JimGetCallFrameByInteger(interp, level);
  14102. if (targetCallFrame && targetCallFrame != interp->topFramePtr) {
  14103. #ifdef JIM_NO_INTROSPECTION
  14104. *objPtrPtr = Jim_NewListObj(interp, targetCallFrame->argv, 1);
  14105. #else
  14106. *objPtrPtr = Jim_NewListObj(interp, targetCallFrame->argv, targetCallFrame->argc);
  14107. #endif
  14108. return JIM_OK;
  14109. }
  14110. }
  14111. Jim_SetResultFormatted(interp, "bad level \"%#s\"", levelObjPtr);
  14112. return JIM_ERR;
  14113. }
  14114. static int JimInfoFrame(Jim_Interp *interp, Jim_Obj *levelObjPtr, Jim_Obj **objPtrPtr)
  14115. {
  14116. long level;
  14117. if (Jim_GetLong(interp, levelObjPtr, &level) == JIM_OK) {
  14118. Jim_EvalFrame *frame = JimGetEvalFrameByProcLevel(interp, level);
  14119. if (frame) {
  14120. Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
  14121. Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "type", -1));
  14122. Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "source", -1));
  14123. if (frame->scriptObj) {
  14124. ScriptObj *script = JimGetScript(interp, frame->scriptObj);
  14125. Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "line", -1));
  14126. Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, script->linenr));
  14127. Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "file", -1));
  14128. Jim_ListAppendElement(interp, listObj, script->fileNameObj);
  14129. }
  14130. #ifndef JIM_NO_INTROSPECTION
  14131. {
  14132. Jim_Obj *cmdObj = Jim_NewListObj(interp, frame->argv, frame->argc);
  14133. Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "cmd", -1));
  14134. Jim_ListAppendElement(interp, listObj, cmdObj);
  14135. }
  14136. #endif
  14137. {
  14138. Jim_Obj *procNameObj = JimProcForEvalFrame(interp, frame);
  14139. if (procNameObj) {
  14140. Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "proc", -1));
  14141. Jim_ListAppendElement(interp, listObj, procNameObj);
  14142. }
  14143. }
  14144. Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "level", -1));
  14145. Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, interp->framePtr->level - frame->framePtr->level));
  14146. *objPtrPtr = listObj;
  14147. return JIM_OK;
  14148. }
  14149. }
  14150. Jim_SetResultFormatted(interp, "bad level \"%#s\"", levelObjPtr);
  14151. return JIM_ERR;
  14152. }
  14153. static int Jim_PutsCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14154. {
  14155. if (argc != 2 && argc != 3) {
  14156. Jim_WrongNumArgs(interp, 1, argv, "?-nonewline? string");
  14157. return JIM_ERR;
  14158. }
  14159. if (argc == 3) {
  14160. if (!Jim_CompareStringImmediate(interp, argv[1], "-nonewline")) {
  14161. Jim_SetResultString(interp, "The second argument must " "be -nonewline", -1);
  14162. return JIM_ERR;
  14163. }
  14164. else {
  14165. fputs(Jim_String(argv[2]), stdout);
  14166. }
  14167. }
  14168. else {
  14169. puts(Jim_String(argv[1]));
  14170. }
  14171. return JIM_OK;
  14172. }
  14173. static int JimAddMulHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int op)
  14174. {
  14175. jim_wide wideValue, res;
  14176. double doubleValue, doubleRes;
  14177. int i;
  14178. res = (op == JIM_EXPROP_ADD) ? 0 : 1;
  14179. for (i = 1; i < argc; i++) {
  14180. if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK)
  14181. goto trydouble;
  14182. if (op == JIM_EXPROP_ADD)
  14183. res += wideValue;
  14184. else
  14185. res *= wideValue;
  14186. }
  14187. Jim_SetResultInt(interp, res);
  14188. return JIM_OK;
  14189. trydouble:
  14190. doubleRes = (double)res;
  14191. for (; i < argc; i++) {
  14192. if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)
  14193. return JIM_ERR;
  14194. if (op == JIM_EXPROP_ADD)
  14195. doubleRes += doubleValue;
  14196. else
  14197. doubleRes *= doubleValue;
  14198. }
  14199. Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
  14200. return JIM_OK;
  14201. }
  14202. static int JimSubDivHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int op)
  14203. {
  14204. jim_wide wideValue, res = 0;
  14205. double doubleValue, doubleRes = 0;
  14206. int i = 2;
  14207. if (argc < 2) {
  14208. Jim_WrongNumArgs(interp, 1, argv, "number ?number ... number?");
  14209. return JIM_ERR;
  14210. }
  14211. else if (argc == 2) {
  14212. if (Jim_GetWide(interp, argv[1], &wideValue) != JIM_OK) {
  14213. if (Jim_GetDouble(interp, argv[1], &doubleValue) != JIM_OK) {
  14214. return JIM_ERR;
  14215. }
  14216. else {
  14217. if (op == JIM_EXPROP_SUB)
  14218. doubleRes = -doubleValue;
  14219. else
  14220. doubleRes = 1.0 / doubleValue;
  14221. Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
  14222. return JIM_OK;
  14223. }
  14224. }
  14225. if (op == JIM_EXPROP_SUB) {
  14226. res = -wideValue;
  14227. Jim_SetResultInt(interp, res);
  14228. }
  14229. else {
  14230. doubleRes = 1.0 / wideValue;
  14231. Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
  14232. }
  14233. return JIM_OK;
  14234. }
  14235. else {
  14236. if (Jim_GetWide(interp, argv[1], &res) != JIM_OK) {
  14237. if (Jim_GetDouble(interp, argv[1], &doubleRes)
  14238. != JIM_OK) {
  14239. return JIM_ERR;
  14240. }
  14241. else {
  14242. goto trydouble;
  14243. }
  14244. }
  14245. }
  14246. for (i = 2; i < argc; i++) {
  14247. if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK) {
  14248. doubleRes = (double)res;
  14249. goto trydouble;
  14250. }
  14251. if (op == JIM_EXPROP_SUB)
  14252. res -= wideValue;
  14253. else {
  14254. if (wideValue == 0) {
  14255. Jim_SetResultString(interp, "Division by zero", -1);
  14256. return JIM_ERR;
  14257. }
  14258. res /= wideValue;
  14259. }
  14260. }
  14261. Jim_SetResultInt(interp, res);
  14262. return JIM_OK;
  14263. trydouble:
  14264. for (; i < argc; i++) {
  14265. if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)
  14266. return JIM_ERR;
  14267. if (op == JIM_EXPROP_SUB)
  14268. doubleRes -= doubleValue;
  14269. else
  14270. doubleRes /= doubleValue;
  14271. }
  14272. Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
  14273. return JIM_OK;
  14274. }
  14275. static int Jim_AddCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14276. {
  14277. return JimAddMulHelper(interp, argc, argv, JIM_EXPROP_ADD);
  14278. }
  14279. static int Jim_MulCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14280. {
  14281. return JimAddMulHelper(interp, argc, argv, JIM_EXPROP_MUL);
  14282. }
  14283. static int Jim_SubCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14284. {
  14285. return JimSubDivHelper(interp, argc, argv, JIM_EXPROP_SUB);
  14286. }
  14287. static int Jim_DivCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14288. {
  14289. return JimSubDivHelper(interp, argc, argv, JIM_EXPROP_DIV);
  14290. }
  14291. static int Jim_SetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14292. {
  14293. if (argc != 2 && argc != 3) {
  14294. Jim_WrongNumArgs(interp, 1, argv, "varName ?newValue?");
  14295. return JIM_ERR;
  14296. }
  14297. if (argc == 2) {
  14298. Jim_Obj *objPtr;
  14299. objPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
  14300. if (!objPtr)
  14301. return JIM_ERR;
  14302. Jim_SetResult(interp, objPtr);
  14303. return JIM_OK;
  14304. }
  14305. if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)
  14306. return JIM_ERR;
  14307. Jim_SetResult(interp, argv[2]);
  14308. return JIM_OK;
  14309. }
  14310. static int Jim_UnsetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14311. {
  14312. int i = 1;
  14313. int complain = 1;
  14314. while (i < argc) {
  14315. if (Jim_CompareStringImmediate(interp, argv[i], "--")) {
  14316. i++;
  14317. break;
  14318. }
  14319. if (Jim_CompareStringImmediate(interp, argv[i], "-nocomplain")) {
  14320. complain = 0;
  14321. i++;
  14322. continue;
  14323. }
  14324. break;
  14325. }
  14326. while (i < argc) {
  14327. if (Jim_UnsetVariable(interp, argv[i], complain ? JIM_ERRMSG : JIM_NONE) != JIM_OK
  14328. && complain) {
  14329. return JIM_ERR;
  14330. }
  14331. i++;
  14332. }
  14333. Jim_SetEmptyResult(interp);
  14334. return JIM_OK;
  14335. }
  14336. static int JimCheckLoopRetcode(Jim_Interp *interp, int retval)
  14337. {
  14338. if (retval == JIM_BREAK || retval == JIM_CONTINUE) {
  14339. if (--interp->break_level > 0) {
  14340. return 1;
  14341. }
  14342. }
  14343. return 0;
  14344. }
  14345. static int Jim_WhileCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14346. {
  14347. if (argc != 3) {
  14348. Jim_WrongNumArgs(interp, 1, argv, "condition body");
  14349. return JIM_ERR;
  14350. }
  14351. while (1) {
  14352. int boolean = 0, retval;
  14353. if ((retval = Jim_GetBoolFromExpr(interp, argv[1], &boolean)) != JIM_OK)
  14354. return retval;
  14355. if (!boolean)
  14356. break;
  14357. if ((retval = Jim_EvalObj(interp, argv[2])) != JIM_OK) {
  14358. if (JimCheckLoopRetcode(interp, retval)) {
  14359. return retval;
  14360. }
  14361. switch (retval) {
  14362. case JIM_BREAK:
  14363. goto out;
  14364. case JIM_CONTINUE:
  14365. continue;
  14366. default:
  14367. return retval;
  14368. }
  14369. }
  14370. }
  14371. out:
  14372. Jim_SetEmptyResult(interp);
  14373. return JIM_OK;
  14374. }
  14375. static int Jim_ForCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14376. {
  14377. int retval;
  14378. int boolean = 1;
  14379. int immediate = 0;
  14380. Jim_Obj *varNamePtr = NULL;
  14381. Jim_Obj *stopVarNamePtr = NULL;
  14382. if (argc != 5) {
  14383. Jim_WrongNumArgs(interp, 1, argv, "start test next body");
  14384. return JIM_ERR;
  14385. }
  14386. if ((retval = Jim_EvalObj(interp, argv[1])) != JIM_OK) {
  14387. return retval;
  14388. }
  14389. retval = Jim_GetBoolFromExpr(interp, argv[2], &boolean);
  14390. #ifdef JIM_OPTIMIZATION
  14391. if (retval == JIM_OK && boolean) {
  14392. ScriptObj *incrScript;
  14393. struct ExprTree *expr;
  14394. jim_wide stop, currentVal;
  14395. Jim_Obj *objPtr;
  14396. int cmpOffset;
  14397. expr = JimGetExpression(interp, argv[2]);
  14398. incrScript = JimGetScript(interp, argv[3]);
  14399. if (incrScript == NULL || incrScript->len != 3 || !expr || expr->len != 3) {
  14400. goto evalstart;
  14401. }
  14402. if (incrScript->token[1].type != JIM_TT_ESC) {
  14403. goto evalstart;
  14404. }
  14405. if (expr->expr->type == JIM_EXPROP_LT) {
  14406. cmpOffset = 0;
  14407. }
  14408. else if (expr->expr->type == JIM_EXPROP_LTE) {
  14409. cmpOffset = 1;
  14410. }
  14411. else {
  14412. goto evalstart;
  14413. }
  14414. if (expr->expr->left->type != JIM_TT_VAR) {
  14415. goto evalstart;
  14416. }
  14417. if (expr->expr->right->type != JIM_TT_VAR && expr->expr->right->type != JIM_TT_EXPR_INT) {
  14418. goto evalstart;
  14419. }
  14420. if (!Jim_CompareStringImmediate(interp, incrScript->token[1].objPtr, "incr")) {
  14421. goto evalstart;
  14422. }
  14423. if (!Jim_StringEqObj(incrScript->token[2].objPtr, expr->expr->left->objPtr)) {
  14424. goto evalstart;
  14425. }
  14426. if (expr->expr->right->type == JIM_TT_EXPR_INT) {
  14427. if (Jim_GetWideExpr(interp, expr->expr->right->objPtr, &stop) == JIM_ERR) {
  14428. goto evalstart;
  14429. }
  14430. }
  14431. else {
  14432. stopVarNamePtr = expr->expr->right->objPtr;
  14433. Jim_IncrRefCount(stopVarNamePtr);
  14434. stop = 0;
  14435. }
  14436. varNamePtr = expr->expr->left->objPtr;
  14437. Jim_IncrRefCount(varNamePtr);
  14438. objPtr = Jim_GetVariable(interp, varNamePtr, JIM_NONE);
  14439. if (objPtr == NULL || Jim_GetWide(interp, objPtr, &currentVal) != JIM_OK) {
  14440. goto testcond;
  14441. }
  14442. while (retval == JIM_OK) {
  14443. if (stopVarNamePtr) {
  14444. objPtr = Jim_GetVariable(interp, stopVarNamePtr, JIM_NONE);
  14445. if (objPtr == NULL || Jim_GetWide(interp, objPtr, &stop) != JIM_OK) {
  14446. goto testcond;
  14447. }
  14448. }
  14449. if (currentVal >= stop + cmpOffset) {
  14450. break;
  14451. }
  14452. retval = Jim_EvalObj(interp, argv[4]);
  14453. if (JimCheckLoopRetcode(interp, retval)) {
  14454. immediate++;
  14455. goto out;
  14456. }
  14457. if (retval == JIM_OK || retval == JIM_CONTINUE) {
  14458. retval = JIM_OK;
  14459. objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG);
  14460. if (objPtr == NULL) {
  14461. retval = JIM_ERR;
  14462. goto out;
  14463. }
  14464. if (!Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
  14465. currentVal = ++JimWideValue(objPtr);
  14466. Jim_InvalidateStringRep(objPtr);
  14467. }
  14468. else {
  14469. if (Jim_GetWide(interp, objPtr, &currentVal) != JIM_OK ||
  14470. Jim_SetVariable(interp, varNamePtr, Jim_NewIntObj(interp,
  14471. ++currentVal)) != JIM_OK) {
  14472. goto evalnext;
  14473. }
  14474. }
  14475. }
  14476. }
  14477. goto out;
  14478. }
  14479. evalstart:
  14480. #endif
  14481. while (boolean && (retval == JIM_OK || retval == JIM_CONTINUE)) {
  14482. retval = Jim_EvalObj(interp, argv[4]);
  14483. if (JimCheckLoopRetcode(interp, retval)) {
  14484. immediate++;
  14485. break;
  14486. }
  14487. if (retval == JIM_OK || retval == JIM_CONTINUE) {
  14488. JIM_IF_OPTIM(evalnext:)
  14489. retval = Jim_EvalObj(interp, argv[3]);
  14490. if (retval == JIM_OK || retval == JIM_CONTINUE) {
  14491. JIM_IF_OPTIM(testcond:)
  14492. retval = Jim_GetBoolFromExpr(interp, argv[2], &boolean);
  14493. }
  14494. }
  14495. }
  14496. JIM_IF_OPTIM(out:)
  14497. if (stopVarNamePtr) {
  14498. Jim_DecrRefCount(interp, stopVarNamePtr);
  14499. }
  14500. if (varNamePtr) {
  14501. Jim_DecrRefCount(interp, varNamePtr);
  14502. }
  14503. if (!immediate) {
  14504. if (retval == JIM_CONTINUE || retval == JIM_BREAK || retval == JIM_OK) {
  14505. Jim_SetEmptyResult(interp);
  14506. return JIM_OK;
  14507. }
  14508. }
  14509. return retval;
  14510. }
  14511. static int Jim_LoopCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14512. {
  14513. int retval;
  14514. jim_wide i;
  14515. jim_wide limit = 0;
  14516. jim_wide incr = 1;
  14517. Jim_Obj *bodyObjPtr;
  14518. if (argc < 4 || argc > 6) {
  14519. Jim_WrongNumArgs(interp, 1, argv, "var ?first? limit ?incr? body");
  14520. return JIM_ERR;
  14521. }
  14522. retval = Jim_GetWideExpr(interp, argv[2], &i);
  14523. if (argc > 4 && retval == JIM_OK) {
  14524. retval = Jim_GetWideExpr(interp, argv[3], &limit);
  14525. }
  14526. if (argc > 5 && retval == JIM_OK) {
  14527. Jim_GetWideExpr(interp, argv[4], &incr);
  14528. }
  14529. if (retval != JIM_OK) {
  14530. return retval;
  14531. }
  14532. if (argc == 4) {
  14533. limit = i;
  14534. i = 0;
  14535. }
  14536. bodyObjPtr = argv[argc - 1];
  14537. retval = Jim_SetVariable(interp, argv[1], Jim_NewIntObj(interp, i));
  14538. while (((i < limit && incr > 0) || (i > limit && incr < 0)) && retval == JIM_OK) {
  14539. retval = Jim_EvalObj(interp, bodyObjPtr);
  14540. if (JimCheckLoopRetcode(interp, retval)) {
  14541. return retval;
  14542. }
  14543. if (retval == JIM_OK || retval == JIM_CONTINUE) {
  14544. Jim_Obj *objPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
  14545. retval = JIM_OK;
  14546. i += incr;
  14547. if (objPtr && !Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
  14548. if (argv[1]->typePtr != &variableObjType) {
  14549. if (Jim_SetVariable(interp, argv[1], objPtr) != JIM_OK) {
  14550. return JIM_ERR;
  14551. }
  14552. }
  14553. JimWideValue(objPtr) = i;
  14554. Jim_InvalidateStringRep(objPtr);
  14555. if (argv[1]->typePtr != &variableObjType) {
  14556. if (Jim_SetVariable(interp, argv[1], objPtr) != JIM_OK) {
  14557. retval = JIM_ERR;
  14558. break;
  14559. }
  14560. }
  14561. }
  14562. else {
  14563. objPtr = Jim_NewIntObj(interp, i);
  14564. retval = Jim_SetVariable(interp, argv[1], objPtr);
  14565. if (retval != JIM_OK) {
  14566. Jim_FreeNewObj(interp, objPtr);
  14567. }
  14568. }
  14569. }
  14570. }
  14571. if (retval == JIM_OK || retval == JIM_CONTINUE || retval == JIM_BREAK) {
  14572. Jim_SetEmptyResult(interp);
  14573. return JIM_OK;
  14574. }
  14575. return retval;
  14576. }
  14577. typedef struct {
  14578. Jim_Obj *objPtr;
  14579. int idx;
  14580. } Jim_ListIter;
  14581. static void JimListIterInit(Jim_ListIter *iter, Jim_Obj *objPtr)
  14582. {
  14583. iter->objPtr = objPtr;
  14584. iter->idx = 0;
  14585. }
  14586. static Jim_Obj *JimListIterNext(Jim_Interp *interp, Jim_ListIter *iter)
  14587. {
  14588. if (iter->idx >= Jim_ListLength(interp, iter->objPtr)) {
  14589. return NULL;
  14590. }
  14591. return iter->objPtr->internalRep.listValue.ele[iter->idx++];
  14592. }
  14593. static int JimListIterDone(Jim_Interp *interp, Jim_ListIter *iter)
  14594. {
  14595. return iter->idx >= Jim_ListLength(interp, iter->objPtr);
  14596. }
  14597. static int JimForeachMapHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int doMap)
  14598. {
  14599. int result = JIM_OK;
  14600. int i, numargs;
  14601. Jim_ListIter twoiters[2];
  14602. Jim_ListIter *iters;
  14603. Jim_Obj *script;
  14604. Jim_Obj *resultObj;
  14605. if (argc < 4 || argc % 2 != 0) {
  14606. Jim_WrongNumArgs(interp, 1, argv, "varList list ?varList list ...? script");
  14607. return JIM_ERR;
  14608. }
  14609. script = argv[argc - 1];
  14610. numargs = (argc - 1 - 1);
  14611. if (numargs == 2) {
  14612. iters = twoiters;
  14613. }
  14614. else {
  14615. iters = Jim_Alloc(numargs * sizeof(*iters));
  14616. }
  14617. for (i = 0; i < numargs; i++) {
  14618. JimListIterInit(&iters[i], argv[i + 1]);
  14619. if (i % 2 == 0 && JimListIterDone(interp, &iters[i])) {
  14620. result = JIM_ERR;
  14621. }
  14622. }
  14623. if (result != JIM_OK) {
  14624. Jim_SetResultString(interp, "foreach varlist is empty", -1);
  14625. goto empty_varlist;
  14626. }
  14627. if (doMap) {
  14628. resultObj = Jim_NewListObj(interp, NULL, 0);
  14629. }
  14630. else {
  14631. resultObj = interp->emptyObj;
  14632. }
  14633. Jim_IncrRefCount(resultObj);
  14634. while (1) {
  14635. for (i = 0; i < numargs; i += 2) {
  14636. if (!JimListIterDone(interp, &iters[i + 1])) {
  14637. break;
  14638. }
  14639. }
  14640. if (i == numargs) {
  14641. break;
  14642. }
  14643. for (i = 0; i < numargs; i += 2) {
  14644. Jim_Obj *varName;
  14645. JimListIterInit(&iters[i], argv[i + 1]);
  14646. while ((varName = JimListIterNext(interp, &iters[i])) != NULL) {
  14647. Jim_Obj *valObj = JimListIterNext(interp, &iters[i + 1]);
  14648. if (!valObj) {
  14649. valObj = interp->emptyObj;
  14650. }
  14651. Jim_IncrRefCount(valObj);
  14652. result = Jim_SetVariable(interp, varName, valObj);
  14653. Jim_DecrRefCount(interp, valObj);
  14654. if (result != JIM_OK) {
  14655. goto err;
  14656. }
  14657. }
  14658. }
  14659. result = Jim_EvalObj(interp, script);
  14660. if (JimCheckLoopRetcode(interp, result)) {
  14661. goto err;
  14662. }
  14663. switch (result) {
  14664. case JIM_OK:
  14665. if (doMap) {
  14666. Jim_ListAppendElement(interp, resultObj, interp->result);
  14667. }
  14668. break;
  14669. case JIM_CONTINUE:
  14670. break;
  14671. case JIM_BREAK:
  14672. goto out;
  14673. default:
  14674. goto err;
  14675. }
  14676. }
  14677. out:
  14678. result = JIM_OK;
  14679. Jim_SetResult(interp, resultObj);
  14680. err:
  14681. Jim_DecrRefCount(interp, resultObj);
  14682. empty_varlist:
  14683. if (numargs > 2) {
  14684. Jim_Free(iters);
  14685. }
  14686. return result;
  14687. }
  14688. static int Jim_ForeachCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14689. {
  14690. return JimForeachMapHelper(interp, argc, argv, 0);
  14691. }
  14692. static int Jim_LmapCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14693. {
  14694. return JimForeachMapHelper(interp, argc, argv, 1);
  14695. }
  14696. static int Jim_LassignCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14697. {
  14698. int result = JIM_ERR;
  14699. int i;
  14700. Jim_ListIter iter;
  14701. Jim_Obj *resultObj;
  14702. if (argc < 2) {
  14703. Jim_WrongNumArgs(interp, 1, argv, "varList list ?varName ...?");
  14704. return JIM_ERR;
  14705. }
  14706. JimListIterInit(&iter, argv[1]);
  14707. for (i = 2; i < argc; i++) {
  14708. Jim_Obj *valObj = JimListIterNext(interp, &iter);
  14709. result = Jim_SetVariable(interp, argv[i], valObj ? valObj : interp->emptyObj);
  14710. if (result != JIM_OK) {
  14711. return result;
  14712. }
  14713. }
  14714. resultObj = Jim_NewListObj(interp, NULL, 0);
  14715. while (!JimListIterDone(interp, &iter)) {
  14716. Jim_ListAppendElement(interp, resultObj, JimListIterNext(interp, &iter));
  14717. }
  14718. Jim_SetResult(interp, resultObj);
  14719. return JIM_OK;
  14720. }
  14721. static int Jim_IfCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14722. {
  14723. int boolean, retval, current = 1, falsebody = 0;
  14724. if (argc >= 3) {
  14725. while (1) {
  14726. if (current >= argc)
  14727. goto err;
  14728. if ((retval = Jim_GetBoolFromExpr(interp, argv[current++], &boolean))
  14729. != JIM_OK)
  14730. return retval;
  14731. if (current >= argc)
  14732. goto err;
  14733. if (Jim_CompareStringImmediate(interp, argv[current], "then"))
  14734. current++;
  14735. if (current >= argc)
  14736. goto err;
  14737. if (boolean)
  14738. return Jim_EvalObj(interp, argv[current]);
  14739. if (++current >= argc) {
  14740. Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
  14741. return JIM_OK;
  14742. }
  14743. falsebody = current++;
  14744. if (Jim_CompareStringImmediate(interp, argv[falsebody], "else")) {
  14745. if (current != argc - 1)
  14746. goto err;
  14747. return Jim_EvalObj(interp, argv[current]);
  14748. }
  14749. else if (Jim_CompareStringImmediate(interp, argv[falsebody], "elseif"))
  14750. continue;
  14751. else if (falsebody != argc - 1)
  14752. goto err;
  14753. return Jim_EvalObj(interp, argv[falsebody]);
  14754. }
  14755. return JIM_OK;
  14756. }
  14757. err:
  14758. Jim_WrongNumArgs(interp, 1, argv, "condition ?then? trueBody ?elseif ...? ?else? falseBody");
  14759. return JIM_ERR;
  14760. }
  14761. int Jim_CommandMatchObj(Jim_Interp *interp, Jim_Obj *commandObj, Jim_Obj *patternObj,
  14762. Jim_Obj *stringObj, int flags)
  14763. {
  14764. Jim_Obj *parms[5];
  14765. int argc = 0;
  14766. long eq;
  14767. int rc;
  14768. parms[argc++] = commandObj;
  14769. if (flags & JIM_NOCASE) {
  14770. parms[argc++] = Jim_NewStringObj(interp, "-nocase", -1);
  14771. }
  14772. if (flags & JIM_OPT_END) {
  14773. parms[argc++] = Jim_NewStringObj(interp, "--", -1);
  14774. }
  14775. parms[argc++] = patternObj;
  14776. parms[argc++] = stringObj;
  14777. rc = Jim_EvalObjVector(interp, argc, parms);
  14778. if (rc != JIM_OK || Jim_GetLong(interp, Jim_GetResult(interp), &eq) != JIM_OK) {
  14779. eq = -rc;
  14780. }
  14781. return eq;
  14782. }
  14783. static int Jim_SwitchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14784. {
  14785. enum { SWITCH_EXACT, SWITCH_GLOB, SWITCH_RE, SWITCH_CMD };
  14786. int matchOpt = SWITCH_EXACT, opt = 1, patCount, i;
  14787. int match_flags = 0;
  14788. Jim_Obj *command = NULL, *scriptObj = NULL, *strObj;
  14789. Jim_Obj **caseList;
  14790. if (argc < 3) {
  14791. wrongnumargs:
  14792. Jim_WrongNumArgs(interp, 1, argv, "?options? string "
  14793. "pattern body ... ?default body? or " "{pattern body ?pattern body ...?}");
  14794. return JIM_ERR;
  14795. }
  14796. for (opt = 1; opt < argc; ++opt) {
  14797. const char *option = Jim_String(argv[opt]);
  14798. if (*option != '-')
  14799. break;
  14800. else if (strncmp(option, "--", 2) == 0) {
  14801. ++opt;
  14802. break;
  14803. }
  14804. else if (strncmp(option, "-exact", 2) == 0)
  14805. matchOpt = SWITCH_EXACT;
  14806. else if (strncmp(option, "-glob", 2) == 0)
  14807. matchOpt = SWITCH_GLOB;
  14808. else if (strncmp(option, "-regexp", 2) == 0) {
  14809. matchOpt = SWITCH_RE;
  14810. match_flags |= JIM_OPT_END;
  14811. }
  14812. else if (strncmp(option, "-command", 2) == 0) {
  14813. matchOpt = SWITCH_CMD;
  14814. if ((argc - opt) < 2)
  14815. goto wrongnumargs;
  14816. command = argv[++opt];
  14817. }
  14818. else {
  14819. Jim_SetResultFormatted(interp,
  14820. "bad option \"%#s\": must be -exact, -glob, -regexp, -command procname or --",
  14821. argv[opt]);
  14822. return JIM_ERR;
  14823. }
  14824. if ((argc - opt) < 2)
  14825. goto wrongnumargs;
  14826. }
  14827. strObj = argv[opt++];
  14828. patCount = argc - opt;
  14829. if (patCount == 1) {
  14830. JimListGetElements(interp, argv[opt], &patCount, &caseList);
  14831. }
  14832. else
  14833. caseList = (Jim_Obj **)&argv[opt];
  14834. if (patCount == 0 || patCount % 2 != 0)
  14835. goto wrongnumargs;
  14836. for (i = 0; scriptObj == NULL && i < patCount; i += 2) {
  14837. Jim_Obj *patObj = caseList[i];
  14838. if (!Jim_CompareStringImmediate(interp, patObj, "default")
  14839. || i < (patCount - 2)) {
  14840. switch (matchOpt) {
  14841. case SWITCH_EXACT:
  14842. if (Jim_StringEqObj(strObj, patObj))
  14843. scriptObj = caseList[i + 1];
  14844. break;
  14845. case SWITCH_GLOB:
  14846. if (Jim_StringMatchObj(interp, patObj, strObj, 0))
  14847. scriptObj = caseList[i + 1];
  14848. break;
  14849. case SWITCH_RE:
  14850. command = Jim_NewStringObj(interp, "regexp", -1);
  14851. case SWITCH_CMD:{
  14852. int rc = Jim_CommandMatchObj(interp, command, patObj, strObj, match_flags);
  14853. if (argc - opt == 1) {
  14854. JimListGetElements(interp, argv[opt], &patCount, &caseList);
  14855. }
  14856. if (rc < 0) {
  14857. return -rc;
  14858. }
  14859. if (rc)
  14860. scriptObj = caseList[i + 1];
  14861. break;
  14862. }
  14863. }
  14864. }
  14865. else {
  14866. scriptObj = caseList[i + 1];
  14867. }
  14868. }
  14869. for (; i < patCount && Jim_CompareStringImmediate(interp, scriptObj, "-"); i += 2)
  14870. scriptObj = caseList[i + 1];
  14871. if (scriptObj && Jim_CompareStringImmediate(interp, scriptObj, "-")) {
  14872. Jim_SetResultFormatted(interp, "no body specified for pattern \"%#s\"", caseList[i - 2]);
  14873. return JIM_ERR;
  14874. }
  14875. Jim_SetEmptyResult(interp);
  14876. if (scriptObj) {
  14877. return Jim_EvalObj(interp, scriptObj);
  14878. }
  14879. return JIM_OK;
  14880. }
  14881. static int Jim_ListCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14882. {
  14883. Jim_Obj *listObjPtr;
  14884. listObjPtr = Jim_NewListObj(interp, argv + 1, argc - 1);
  14885. Jim_SetResult(interp, listObjPtr);
  14886. return JIM_OK;
  14887. }
  14888. static int Jim_LindexCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14889. {
  14890. Jim_Obj *objPtr;
  14891. int ret;
  14892. if (argc < 2) {
  14893. Jim_WrongNumArgs(interp, 1, argv, "list ?index ...?");
  14894. return JIM_ERR;
  14895. }
  14896. ret = Jim_ListIndices(interp, argv[1], argv + 2, argc - 2, &objPtr, JIM_NONE);
  14897. if (ret < 0) {
  14898. ret = JIM_OK;
  14899. Jim_SetEmptyResult(interp);
  14900. }
  14901. else if (ret == JIM_OK) {
  14902. Jim_SetResult(interp, objPtr);
  14903. }
  14904. return ret;
  14905. }
  14906. static int Jim_LlengthCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14907. {
  14908. if (argc != 2) {
  14909. Jim_WrongNumArgs(interp, 1, argv, "list");
  14910. return JIM_ERR;
  14911. }
  14912. Jim_SetResultInt(interp, Jim_ListLength(interp, argv[1]));
  14913. return JIM_OK;
  14914. }
  14915. static int Jim_LsearchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  14916. {
  14917. static const char * const options[] = {
  14918. "-bool", "-not", "-nocase", "-exact", "-glob", "-regexp", "-all", "-inline", "-command",
  14919. "-stride", "-index", NULL
  14920. };
  14921. enum
  14922. { OPT_BOOL, OPT_NOT, OPT_NOCASE, OPT_EXACT, OPT_GLOB, OPT_REGEXP, OPT_ALL, OPT_INLINE,
  14923. OPT_COMMAND, OPT_STRIDE, OPT_INDEX };
  14924. int i;
  14925. int opt_bool = 0;
  14926. int opt_not = 0;
  14927. int opt_all = 0;
  14928. int opt_inline = 0;
  14929. int opt_match = OPT_EXACT;
  14930. int listlen;
  14931. int rc = JIM_OK;
  14932. Jim_Obj *listObjPtr = NULL;
  14933. Jim_Obj *commandObj = NULL;
  14934. Jim_Obj *indexObj = NULL;
  14935. int match_flags = 0;
  14936. long stride = 1;
  14937. if (argc < 3) {
  14938. wrongargs:
  14939. Jim_WrongNumArgs(interp, 1, argv,
  14940. "?-exact|-glob|-regexp|-command 'command'? ?-bool|-inline? ?-not? ?-nocase? ?-all? ?-stride len? ?-index val? list value");
  14941. return JIM_ERR;
  14942. }
  14943. for (i = 1; i < argc - 2; i++) {
  14944. int option;
  14945. if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ERRMSG) != JIM_OK) {
  14946. return JIM_ERR;
  14947. }
  14948. switch (option) {
  14949. case OPT_BOOL:
  14950. opt_bool = 1;
  14951. opt_inline = 0;
  14952. break;
  14953. case OPT_NOT:
  14954. opt_not = 1;
  14955. break;
  14956. case OPT_NOCASE:
  14957. match_flags |= JIM_NOCASE;
  14958. break;
  14959. case OPT_INLINE:
  14960. opt_inline = 1;
  14961. opt_bool = 0;
  14962. break;
  14963. case OPT_ALL:
  14964. opt_all = 1;
  14965. break;
  14966. case OPT_REGEXP:
  14967. opt_match = option;
  14968. match_flags |= JIM_OPT_END;
  14969. break;
  14970. case OPT_COMMAND:
  14971. if (i >= argc - 2) {
  14972. goto wrongargs;
  14973. }
  14974. commandObj = argv[++i];
  14975. case OPT_EXACT:
  14976. case OPT_GLOB:
  14977. opt_match = option;
  14978. break;
  14979. case OPT_INDEX:
  14980. if (i >= argc - 2) {
  14981. goto wrongargs;
  14982. }
  14983. indexObj = argv[++i];
  14984. break;
  14985. case OPT_STRIDE:
  14986. if (i >= argc - 2) {
  14987. goto wrongargs;
  14988. }
  14989. if (Jim_GetLong(interp, argv[++i], &stride) != JIM_OK) {
  14990. return JIM_ERR;
  14991. }
  14992. if (stride < 1) {
  14993. Jim_SetResultString(interp, "stride length must be at least 1", -1);
  14994. return JIM_ERR;
  14995. }
  14996. break;
  14997. }
  14998. }
  14999. argc -= i;
  15000. if (argc < 2) {
  15001. goto wrongargs;
  15002. }
  15003. argv += i;
  15004. listlen = Jim_ListLength(interp, argv[0]);
  15005. if (listlen % stride) {
  15006. Jim_SetResultString(interp, "list size must be a multiple of the stride length", -1);
  15007. return JIM_ERR;
  15008. }
  15009. if (opt_all) {
  15010. listObjPtr = Jim_NewListObj(interp, NULL, 0);
  15011. }
  15012. if (opt_match == OPT_REGEXP) {
  15013. commandObj = Jim_NewStringObj(interp, "regexp", -1);
  15014. }
  15015. if (commandObj) {
  15016. Jim_IncrRefCount(commandObj);
  15017. }
  15018. for (i = 0; i < listlen; i += stride) {
  15019. int eq = 0;
  15020. Jim_Obj *searchListObj;
  15021. Jim_Obj *objPtr;
  15022. int offset;
  15023. if (indexObj) {
  15024. int indexlen = Jim_ListLength(interp, indexObj);
  15025. if (stride == 1) {
  15026. searchListObj = Jim_ListGetIndex(interp, argv[0], i);
  15027. }
  15028. else {
  15029. searchListObj = Jim_NewListObj(interp, argv[0]->internalRep.listValue.ele + i, stride);
  15030. }
  15031. Jim_IncrRefCount(searchListObj);
  15032. rc = Jim_ListIndices(interp, searchListObj, indexObj->internalRep.listValue.ele, indexlen, &objPtr, JIM_ERRMSG);
  15033. if (rc != JIM_OK) {
  15034. Jim_DecrRefCount(interp, searchListObj);
  15035. rc = JIM_ERR;
  15036. goto done;
  15037. }
  15038. offset = 0;
  15039. }
  15040. else {
  15041. searchListObj = argv[0];
  15042. offset = i;
  15043. objPtr = Jim_ListGetIndex(interp, searchListObj, i);
  15044. Jim_IncrRefCount(searchListObj);
  15045. }
  15046. switch (opt_match) {
  15047. case OPT_EXACT:
  15048. eq = Jim_StringCompareObj(interp, argv[1], objPtr, match_flags) == 0;
  15049. break;
  15050. case OPT_GLOB:
  15051. eq = Jim_StringMatchObj(interp, argv[1], objPtr, match_flags);
  15052. break;
  15053. case OPT_REGEXP:
  15054. case OPT_COMMAND:
  15055. eq = Jim_CommandMatchObj(interp, commandObj, argv[1], objPtr, match_flags);
  15056. if (eq < 0) {
  15057. Jim_DecrRefCount(interp, searchListObj);
  15058. rc = JIM_ERR;
  15059. goto done;
  15060. }
  15061. break;
  15062. }
  15063. if ((!opt_bool && eq == !opt_not) || (opt_bool && (eq || opt_all))) {
  15064. Jim_Obj *resultObj;
  15065. if (opt_bool) {
  15066. resultObj = Jim_NewIntObj(interp, eq ^ opt_not);
  15067. }
  15068. else if (!opt_inline) {
  15069. resultObj = Jim_NewIntObj(interp, i);
  15070. }
  15071. else if (stride == 1) {
  15072. resultObj = objPtr;
  15073. }
  15074. else if (opt_all) {
  15075. ListInsertElements(listObjPtr, -1, stride,
  15076. searchListObj->internalRep.listValue.ele + offset);
  15077. resultObj = NULL;
  15078. }
  15079. else {
  15080. resultObj = Jim_NewListObj(interp, searchListObj->internalRep.listValue.ele + offset, stride);
  15081. }
  15082. if (opt_all) {
  15083. if (stride == 1) {
  15084. Jim_ListAppendElement(interp, listObjPtr, resultObj);
  15085. }
  15086. }
  15087. else {
  15088. Jim_SetResult(interp, resultObj);
  15089. Jim_DecrRefCount(interp, searchListObj);
  15090. goto done;
  15091. }
  15092. }
  15093. Jim_DecrRefCount(interp, searchListObj);
  15094. }
  15095. if (opt_all) {
  15096. Jim_SetResult(interp, listObjPtr);
  15097. listObjPtr = NULL;
  15098. }
  15099. else {
  15100. if (opt_bool) {
  15101. Jim_SetResultBool(interp, opt_not);
  15102. }
  15103. else if (!opt_inline) {
  15104. Jim_SetResultInt(interp, -1);
  15105. }
  15106. }
  15107. done:
  15108. if (listObjPtr) {
  15109. Jim_FreeNewObj(interp, listObjPtr);
  15110. }
  15111. if (commandObj) {
  15112. Jim_DecrRefCount(interp, commandObj);
  15113. }
  15114. return rc;
  15115. }
  15116. static int Jim_LappendCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15117. {
  15118. Jim_Obj *listObjPtr;
  15119. int new_obj = 0;
  15120. int i;
  15121. if (argc < 2) {
  15122. Jim_WrongNumArgs(interp, 1, argv, "varName ?value value ...?");
  15123. return JIM_ERR;
  15124. }
  15125. listObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
  15126. if (!listObjPtr) {
  15127. listObjPtr = Jim_NewListObj(interp, NULL, 0);
  15128. new_obj = 1;
  15129. }
  15130. else if (Jim_IsShared(listObjPtr)) {
  15131. listObjPtr = Jim_DuplicateObj(interp, listObjPtr);
  15132. new_obj = 1;
  15133. }
  15134. for (i = 2; i < argc; i++)
  15135. Jim_ListAppendElement(interp, listObjPtr, argv[i]);
  15136. if (Jim_SetVariable(interp, argv[1], listObjPtr) != JIM_OK) {
  15137. if (new_obj)
  15138. Jim_FreeNewObj(interp, listObjPtr);
  15139. return JIM_ERR;
  15140. }
  15141. Jim_SetResult(interp, listObjPtr);
  15142. return JIM_OK;
  15143. }
  15144. static int Jim_LinsertCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15145. {
  15146. int idx, len;
  15147. Jim_Obj *listPtr;
  15148. if (argc < 3) {
  15149. Jim_WrongNumArgs(interp, 1, argv, "list index ?element ...?");
  15150. return JIM_ERR;
  15151. }
  15152. listPtr = argv[1];
  15153. if (Jim_IsShared(listPtr))
  15154. listPtr = Jim_DuplicateObj(interp, listPtr);
  15155. if (Jim_GetIndex(interp, argv[2], &idx) != JIM_OK)
  15156. goto err;
  15157. len = Jim_ListLength(interp, listPtr);
  15158. if (idx >= len)
  15159. idx = len;
  15160. else if (idx < 0)
  15161. idx = len + idx + 1;
  15162. Jim_ListInsertElements(interp, listPtr, idx, argc - 3, &argv[3]);
  15163. Jim_SetResult(interp, listPtr);
  15164. return JIM_OK;
  15165. err:
  15166. if (listPtr != argv[1]) {
  15167. Jim_FreeNewObj(interp, listPtr);
  15168. }
  15169. return JIM_ERR;
  15170. }
  15171. static int Jim_LreplaceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15172. {
  15173. int first, last, len, rangeLen;
  15174. Jim_Obj *listObj;
  15175. Jim_Obj *newListObj;
  15176. if (argc < 4) {
  15177. Jim_WrongNumArgs(interp, 1, argv, "list first last ?element ...?");
  15178. return JIM_ERR;
  15179. }
  15180. if (Jim_GetIndex(interp, argv[2], &first) != JIM_OK ||
  15181. Jim_GetIndex(interp, argv[3], &last) != JIM_OK) {
  15182. return JIM_ERR;
  15183. }
  15184. listObj = argv[1];
  15185. len = Jim_ListLength(interp, listObj);
  15186. first = JimRelToAbsIndex(len, first);
  15187. last = JimRelToAbsIndex(len, last);
  15188. JimRelToAbsRange(len, &first, &last, &rangeLen);
  15189. if (first > len) {
  15190. first = len;
  15191. }
  15192. newListObj = Jim_NewListObj(interp, listObj->internalRep.listValue.ele, first);
  15193. ListInsertElements(newListObj, -1, argc - 4, argv + 4);
  15194. ListInsertElements(newListObj, -1, len - first - rangeLen, listObj->internalRep.listValue.ele + first + rangeLen);
  15195. Jim_SetResult(interp, newListObj);
  15196. return JIM_OK;
  15197. }
  15198. static int Jim_LsetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15199. {
  15200. if (argc < 3) {
  15201. Jim_WrongNumArgs(interp, 1, argv, "listVar ?index ...? value");
  15202. return JIM_ERR;
  15203. }
  15204. else if (argc == 3) {
  15205. if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)
  15206. return JIM_ERR;
  15207. Jim_SetResult(interp, argv[2]);
  15208. return JIM_OK;
  15209. }
  15210. return Jim_ListSetIndex(interp, argv[1], argv + 2, argc - 3, argv[argc - 1]);
  15211. }
  15212. static int Jim_LsortCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const argv[])
  15213. {
  15214. static const char * const options[] = {
  15215. "-ascii", "-nocase", "-increasing", "-decreasing", "-command", "-integer", "-real", "-index", "-unique",
  15216. "-stride", "-dictionary", NULL
  15217. };
  15218. enum {
  15219. OPT_ASCII, OPT_NOCASE, OPT_INCREASING, OPT_DECREASING, OPT_COMMAND, OPT_INTEGER, OPT_REAL, OPT_INDEX, OPT_UNIQUE,
  15220. OPT_STRIDE, OPT_DICT
  15221. };
  15222. Jim_Obj *resObj;
  15223. int i;
  15224. int retCode;
  15225. int shared;
  15226. long stride = 1;
  15227. Jim_Obj **elements;
  15228. int listlen;
  15229. struct lsort_info info;
  15230. if (argc < 2) {
  15231. wrongargs:
  15232. Jim_WrongNumArgs(interp, 1, argv, "?options? list");
  15233. return JIM_ERR;
  15234. }
  15235. info.type = JIM_LSORT_ASCII;
  15236. info.order = 1;
  15237. info.indexc = 0;
  15238. info.unique = 0;
  15239. info.command = NULL;
  15240. info.interp = interp;
  15241. for (i = 1; i < (argc - 1); i++) {
  15242. int option;
  15243. if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ENUM_ABBREV | JIM_ERRMSG)
  15244. != JIM_OK)
  15245. return JIM_ERR;
  15246. switch (option) {
  15247. case OPT_ASCII:
  15248. info.type = JIM_LSORT_ASCII;
  15249. break;
  15250. case OPT_DICT:
  15251. info.type = JIM_LSORT_DICT;
  15252. break;
  15253. case OPT_NOCASE:
  15254. info.type = JIM_LSORT_NOCASE;
  15255. break;
  15256. case OPT_INTEGER:
  15257. info.type = JIM_LSORT_INTEGER;
  15258. break;
  15259. case OPT_REAL:
  15260. info.type = JIM_LSORT_REAL;
  15261. break;
  15262. case OPT_INCREASING:
  15263. info.order = 1;
  15264. break;
  15265. case OPT_DECREASING:
  15266. info.order = -1;
  15267. break;
  15268. case OPT_UNIQUE:
  15269. info.unique = 1;
  15270. break;
  15271. case OPT_COMMAND:
  15272. if (i >= (argc - 2)) {
  15273. Jim_SetResultString(interp, "\"-command\" option must be followed by comparison command", -1);
  15274. return JIM_ERR;
  15275. }
  15276. info.type = JIM_LSORT_COMMAND;
  15277. info.command = argv[i + 1];
  15278. i++;
  15279. break;
  15280. case OPT_STRIDE:
  15281. if (i >= argc - 2) {
  15282. goto wrongargs;
  15283. }
  15284. if (Jim_GetLong(interp, argv[++i], &stride) != JIM_OK) {
  15285. return JIM_ERR;
  15286. }
  15287. if (stride < 2) {
  15288. Jim_SetResultString(interp, "stride length must be at least 2", -1);
  15289. return JIM_ERR;
  15290. }
  15291. break;
  15292. case OPT_INDEX:
  15293. if (i >= (argc - 2)) {
  15294. badindex:
  15295. Jim_SetResultString(interp, "\"-index\" option must be followed by list index", -1);
  15296. return JIM_ERR;
  15297. }
  15298. JimListGetElements(interp, argv[i + 1], &info.indexc, &info.indexv);
  15299. if (info.indexc == 0) {
  15300. goto badindex;
  15301. }
  15302. i++;
  15303. break;
  15304. }
  15305. }
  15306. resObj = argv[argc - 1];
  15307. JimListGetElements(interp, resObj, &listlen, &elements);
  15308. if (listlen <= 1) {
  15309. Jim_SetResult(interp, resObj);
  15310. return JIM_OK;
  15311. }
  15312. if (stride > 1) {
  15313. Jim_Obj *tmpListObj;
  15314. int i;
  15315. if (listlen % stride) {
  15316. Jim_SetResultString(interp, "list size must be a multiple of the stride length", -1);
  15317. return JIM_ERR;
  15318. }
  15319. tmpListObj = Jim_NewListObj(interp, NULL, 0);
  15320. Jim_IncrRefCount(tmpListObj);
  15321. for (i = 0; i < listlen; i += stride) {
  15322. Jim_ListAppendElement(interp, tmpListObj, Jim_NewListObj(interp, elements + i, stride));
  15323. }
  15324. retCode = ListSortElements(interp, tmpListObj, &info);
  15325. if (retCode == JIM_OK) {
  15326. resObj = Jim_NewListObj(interp, NULL, 0);
  15327. for (i = 0; i < listlen; i += stride) {
  15328. Jim_ListAppendList(interp, resObj, Jim_ListGetIndex(interp, tmpListObj, i / stride));
  15329. }
  15330. Jim_SetResult(interp, resObj);
  15331. }
  15332. Jim_DecrRefCount(interp, tmpListObj);
  15333. }
  15334. else {
  15335. if ((shared = Jim_IsShared(resObj))) {
  15336. resObj = Jim_DuplicateObj(interp, resObj);
  15337. }
  15338. retCode = ListSortElements(interp, resObj, &info);
  15339. if (retCode == JIM_OK) {
  15340. Jim_SetResult(interp, resObj);
  15341. }
  15342. else if (shared) {
  15343. Jim_FreeNewObj(interp, resObj);
  15344. }
  15345. }
  15346. return retCode;
  15347. }
  15348. static int Jim_AppendCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15349. {
  15350. Jim_Obj *stringObjPtr;
  15351. int i;
  15352. if (argc < 2) {
  15353. Jim_WrongNumArgs(interp, 1, argv, "varName ?value ...?");
  15354. return JIM_ERR;
  15355. }
  15356. if (argc == 2) {
  15357. stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
  15358. if (!stringObjPtr)
  15359. return JIM_ERR;
  15360. }
  15361. else {
  15362. int new_obj = 0;
  15363. stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
  15364. if (!stringObjPtr) {
  15365. stringObjPtr = Jim_NewEmptyStringObj(interp);
  15366. new_obj = 1;
  15367. }
  15368. else if (Jim_IsShared(stringObjPtr)) {
  15369. new_obj = 1;
  15370. stringObjPtr = Jim_DuplicateObj(interp, stringObjPtr);
  15371. }
  15372. for (i = 2; i < argc; i++) {
  15373. Jim_AppendObj(interp, stringObjPtr, argv[i]);
  15374. }
  15375. if (Jim_SetVariable(interp, argv[1], stringObjPtr) != JIM_OK) {
  15376. if (new_obj) {
  15377. Jim_FreeNewObj(interp, stringObjPtr);
  15378. }
  15379. return JIM_ERR;
  15380. }
  15381. }
  15382. Jim_SetResult(interp, stringObjPtr);
  15383. return JIM_OK;
  15384. }
  15385. static int Jim_EvalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15386. {
  15387. int rc;
  15388. if (argc < 2) {
  15389. Jim_WrongNumArgs(interp, 1, argv, "arg ?arg ...?");
  15390. return JIM_ERR;
  15391. }
  15392. if (argc == 2) {
  15393. rc = Jim_EvalObj(interp, argv[1]);
  15394. }
  15395. else {
  15396. rc = Jim_EvalObj(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
  15397. }
  15398. return rc;
  15399. }
  15400. static int Jim_UplevelCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15401. {
  15402. if (argc >= 2) {
  15403. int retcode;
  15404. Jim_CallFrame *savedCallFrame, *targetCallFrame;
  15405. const char *str;
  15406. savedCallFrame = interp->framePtr;
  15407. str = Jim_String(argv[1]);
  15408. if ((str[0] >= '0' && str[0] <= '9') || str[0] == '#') {
  15409. targetCallFrame = Jim_GetCallFrameByLevel(interp, argv[1]);
  15410. argc--;
  15411. argv++;
  15412. }
  15413. else {
  15414. targetCallFrame = Jim_GetCallFrameByLevel(interp, NULL);
  15415. }
  15416. if (targetCallFrame == NULL) {
  15417. return JIM_ERR;
  15418. }
  15419. if (argc < 2) {
  15420. Jim_WrongNumArgs(interp, 1, argv - 1, "?level? command ?arg ...?");
  15421. return JIM_ERR;
  15422. }
  15423. interp->framePtr = targetCallFrame;
  15424. if (argc == 2) {
  15425. retcode = Jim_EvalObj(interp, argv[1]);
  15426. }
  15427. else {
  15428. retcode = Jim_EvalObj(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
  15429. }
  15430. interp->framePtr = savedCallFrame;
  15431. return retcode;
  15432. }
  15433. else {
  15434. Jim_WrongNumArgs(interp, 1, argv, "?level? command ?arg ...?");
  15435. return JIM_ERR;
  15436. }
  15437. }
  15438. static int Jim_ExprCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15439. {
  15440. int retcode;
  15441. if (argc == 2) {
  15442. retcode = Jim_EvalExpression(interp, argv[1]);
  15443. }
  15444. #ifndef JIM_COMPAT
  15445. else {
  15446. Jim_WrongNumArgs(interp, 1, argv, "expression");
  15447. retcode = JIM_ERR;
  15448. }
  15449. #else
  15450. else if (argc > 2) {
  15451. Jim_Obj *objPtr;
  15452. objPtr = Jim_ConcatObj(interp, argc - 1, argv + 1);
  15453. Jim_IncrRefCount(objPtr);
  15454. retcode = Jim_EvalExpression(interp, objPtr);
  15455. Jim_DecrRefCount(interp, objPtr);
  15456. }
  15457. else {
  15458. Jim_WrongNumArgs(interp, 1, argv, "expression ?...?");
  15459. return JIM_ERR;
  15460. }
  15461. #endif
  15462. return retcode;
  15463. }
  15464. static int JimBreakContinueHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int retcode)
  15465. {
  15466. if (argc != 1 && argc != 2) {
  15467. Jim_WrongNumArgs(interp, 1, argv, "?level?");
  15468. return JIM_ERR;
  15469. }
  15470. if (argc == 2) {
  15471. long level;
  15472. int ret = Jim_GetLong(interp, argv[1], &level);
  15473. if (ret != JIM_OK) {
  15474. return ret;
  15475. }
  15476. interp->break_level = level;
  15477. }
  15478. return retcode;
  15479. }
  15480. static int Jim_BreakCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15481. {
  15482. return JimBreakContinueHelper(interp, argc, argv, JIM_BREAK);
  15483. }
  15484. static int Jim_ContinueCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15485. {
  15486. return JimBreakContinueHelper(interp, argc, argv, JIM_CONTINUE);
  15487. }
  15488. static int Jim_StacktraceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15489. {
  15490. Jim_Obj *listObj;
  15491. int i;
  15492. jim_wide skip = 0;
  15493. jim_wide last = 0;
  15494. if (argc > 1) {
  15495. if (Jim_GetWideExpr(interp, argv[1], &skip) != JIM_OK) {
  15496. return JIM_ERR;
  15497. }
  15498. }
  15499. if (argc > 2) {
  15500. if (Jim_GetWideExpr(interp, argv[2], &last) != JIM_OK) {
  15501. return JIM_ERR;
  15502. }
  15503. }
  15504. listObj = Jim_NewListObj(interp, NULL, 0);
  15505. for (i = skip; i <= interp->procLevel; i++) {
  15506. Jim_EvalFrame *frame = JimGetEvalFrameByProcLevel(interp, -i);
  15507. if (frame->procLevel < last) {
  15508. break;
  15509. }
  15510. JimAddStackFrame(interp, frame, listObj);
  15511. }
  15512. Jim_SetResult(interp, listObj);
  15513. return JIM_OK;
  15514. }
  15515. static int Jim_ReturnCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15516. {
  15517. int i;
  15518. Jim_Obj *stackTraceObj = NULL;
  15519. Jim_Obj *errorCodeObj = NULL;
  15520. int returnCode = JIM_OK;
  15521. long level = 1;
  15522. for (i = 1; i < argc - 1; i += 2) {
  15523. if (Jim_CompareStringImmediate(interp, argv[i], "-code")) {
  15524. if (Jim_GetReturnCode(interp, argv[i + 1], &returnCode) == JIM_ERR) {
  15525. return JIM_ERR;
  15526. }
  15527. }
  15528. else if (Jim_CompareStringImmediate(interp, argv[i], "-errorinfo")) {
  15529. stackTraceObj = argv[i + 1];
  15530. }
  15531. else if (Jim_CompareStringImmediate(interp, argv[i], "-errorcode")) {
  15532. errorCodeObj = argv[i + 1];
  15533. }
  15534. else if (Jim_CompareStringImmediate(interp, argv[i], "-level")) {
  15535. if (Jim_GetLong(interp, argv[i + 1], &level) != JIM_OK || level < 0) {
  15536. Jim_SetResultFormatted(interp, "bad level \"%#s\"", argv[i + 1]);
  15537. return JIM_ERR;
  15538. }
  15539. }
  15540. else {
  15541. break;
  15542. }
  15543. }
  15544. if (i != argc - 1 && i != argc) {
  15545. Jim_WrongNumArgs(interp, 1, argv,
  15546. "?-code code? ?-errorinfo stacktrace? ?-level level? ?result?");
  15547. }
  15548. if (stackTraceObj && returnCode == JIM_ERR) {
  15549. JimSetStackTrace(interp, stackTraceObj);
  15550. }
  15551. if (errorCodeObj && returnCode == JIM_ERR) {
  15552. Jim_SetGlobalVariableStr(interp, "errorCode", errorCodeObj);
  15553. }
  15554. interp->returnCode = returnCode;
  15555. interp->returnLevel = level;
  15556. if (i == argc - 1) {
  15557. Jim_SetResult(interp, argv[i]);
  15558. }
  15559. return level == 0 ? returnCode : JIM_RETURN;
  15560. }
  15561. static int Jim_TailcallCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15562. {
  15563. if (interp->framePtr->level == 0) {
  15564. Jim_SetResultString(interp, "tailcall can only be called from a proc or lambda", -1);
  15565. return JIM_ERR;
  15566. }
  15567. else if (argc >= 2) {
  15568. Jim_CallFrame *cf = interp->framePtr->parent;
  15569. Jim_Cmd *cmdPtr = Jim_GetCommand(interp, argv[1], JIM_ERRMSG);
  15570. if (cmdPtr == NULL) {
  15571. return JIM_ERR;
  15572. }
  15573. JimPanic((cf->tailcallCmd != NULL, "Already have a tailcallCmd"));
  15574. JimIncrCmdRefCount(cmdPtr);
  15575. cf->tailcallCmd = cmdPtr;
  15576. JimPanic((cf->tailcallObj != NULL, "Already have a tailcallobj"));
  15577. cf->tailcallObj = Jim_NewListObj(interp, argv + 1, argc - 1);
  15578. Jim_IncrRefCount(cf->tailcallObj);
  15579. return JIM_EVAL;
  15580. }
  15581. return JIM_OK;
  15582. }
  15583. static int JimAliasCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15584. {
  15585. Jim_Obj *cmdList;
  15586. Jim_Obj *prefixListObj = Jim_CmdPrivData(interp);
  15587. cmdList = Jim_DuplicateObj(interp, prefixListObj);
  15588. Jim_ListInsertElements(interp, cmdList, Jim_ListLength(interp, cmdList), argc - 1, argv + 1);
  15589. return JimEvalObjList(interp, cmdList);
  15590. }
  15591. static void JimAliasCmdDelete(Jim_Interp *interp, void *privData)
  15592. {
  15593. Jim_Obj *prefixListObj = privData;
  15594. Jim_DecrRefCount(interp, prefixListObj);
  15595. }
  15596. static int Jim_AliasCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15597. {
  15598. Jim_Obj *prefixListObj;
  15599. if (argc < 3) {
  15600. Jim_WrongNumArgs(interp, 1, argv, "newname command ?args ...?");
  15601. return JIM_ERR;
  15602. }
  15603. prefixListObj = Jim_NewListObj(interp, argv + 2, argc - 2);
  15604. Jim_IncrRefCount(prefixListObj);
  15605. Jim_SetResult(interp, argv[1]);
  15606. return Jim_CreateCommandObj(interp, argv[1], JimAliasCmd, prefixListObj, JimAliasCmdDelete);
  15607. }
  15608. static int Jim_ProcCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15609. {
  15610. Jim_Cmd *cmd;
  15611. if (argc != 4 && argc != 5) {
  15612. Jim_WrongNumArgs(interp, 1, argv, "name arglist ?statics? body");
  15613. return JIM_ERR;
  15614. }
  15615. if (argc == 4) {
  15616. cmd = JimCreateProcedureCmd(interp, argv[2], NULL, argv[3], NULL);
  15617. }
  15618. else {
  15619. cmd = JimCreateProcedureCmd(interp, argv[2], argv[3], argv[4], NULL);
  15620. }
  15621. if (cmd) {
  15622. Jim_Obj *nameObjPtr = JimQualifyName(interp, argv[1]);
  15623. JimCreateCommand(interp, nameObjPtr, cmd);
  15624. JimUpdateProcNamespace(interp, cmd, nameObjPtr);
  15625. Jim_DecrRefCount(interp, nameObjPtr);
  15626. Jim_SetResult(interp, argv[1]);
  15627. return JIM_OK;
  15628. }
  15629. return JIM_ERR;
  15630. }
  15631. static int Jim_XtraceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15632. {
  15633. if (argc != 2) {
  15634. Jim_WrongNumArgs(interp, 1, argv, "callback");
  15635. return JIM_ERR;
  15636. }
  15637. if (interp->traceCmdObj) {
  15638. Jim_DecrRefCount(interp, interp->traceCmdObj);
  15639. interp->traceCmdObj = NULL;
  15640. }
  15641. if (Jim_Length(argv[1])) {
  15642. interp->traceCmdObj = argv[1];
  15643. Jim_IncrRefCount(interp->traceCmdObj);
  15644. }
  15645. return JIM_OK;
  15646. }
  15647. static int Jim_LocalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15648. {
  15649. int retcode;
  15650. if (argc < 2) {
  15651. Jim_WrongNumArgs(interp, 1, argv, "cmd ?args ...?");
  15652. return JIM_ERR;
  15653. }
  15654. interp->local++;
  15655. retcode = Jim_EvalObjVector(interp, argc - 1, argv + 1);
  15656. interp->local--;
  15657. if (retcode == 0) {
  15658. Jim_Obj *cmdNameObj = Jim_GetResult(interp);
  15659. if (Jim_GetCommand(interp, cmdNameObj, JIM_ERRMSG) == NULL) {
  15660. return JIM_ERR;
  15661. }
  15662. if (interp->framePtr->localCommands == NULL) {
  15663. interp->framePtr->localCommands = Jim_Alloc(sizeof(*interp->framePtr->localCommands));
  15664. Jim_InitStack(interp->framePtr->localCommands);
  15665. }
  15666. Jim_IncrRefCount(cmdNameObj);
  15667. Jim_StackPush(interp->framePtr->localCommands, cmdNameObj);
  15668. }
  15669. return retcode;
  15670. }
  15671. static int Jim_UpcallCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15672. {
  15673. if (argc < 2) {
  15674. Jim_WrongNumArgs(interp, 1, argv, "cmd ?args ...?");
  15675. return JIM_ERR;
  15676. }
  15677. else {
  15678. int retcode;
  15679. Jim_Cmd *cmdPtr = Jim_GetCommand(interp, argv[1], JIM_ERRMSG);
  15680. if (cmdPtr == NULL || !cmdPtr->isproc || !cmdPtr->prevCmd) {
  15681. Jim_SetResultFormatted(interp, "no previous command: \"%#s\"", argv[1]);
  15682. return JIM_ERR;
  15683. }
  15684. cmdPtr->u.proc.upcall++;
  15685. JimIncrCmdRefCount(cmdPtr);
  15686. retcode = Jim_EvalObjVector(interp, argc - 1, argv + 1);
  15687. cmdPtr->u.proc.upcall--;
  15688. JimDecrCmdRefCount(interp, cmdPtr);
  15689. return retcode;
  15690. }
  15691. }
  15692. static int Jim_ApplyCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15693. {
  15694. if (argc < 2) {
  15695. Jim_WrongNumArgs(interp, 1, argv, "lambdaExpr ?arg ...?");
  15696. return JIM_ERR;
  15697. }
  15698. else {
  15699. int ret;
  15700. Jim_Cmd *cmd;
  15701. Jim_Obj *argListObjPtr;
  15702. Jim_Obj *bodyObjPtr;
  15703. Jim_Obj *nsObj = NULL;
  15704. Jim_Obj **nargv;
  15705. int len = Jim_ListLength(interp, argv[1]);
  15706. if (len != 2 && len != 3) {
  15707. Jim_SetResultFormatted(interp, "can't interpret \"%#s\" as a lambda expression", argv[1]);
  15708. return JIM_ERR;
  15709. }
  15710. if (len == 3) {
  15711. #ifdef jim_ext_namespace
  15712. nsObj = Jim_ListGetIndex(interp, argv[1], 2);
  15713. #else
  15714. Jim_SetResultString(interp, "namespaces not enabled", -1);
  15715. return JIM_ERR;
  15716. #endif
  15717. }
  15718. argListObjPtr = Jim_ListGetIndex(interp, argv[1], 0);
  15719. bodyObjPtr = Jim_ListGetIndex(interp, argv[1], 1);
  15720. cmd = JimCreateProcedureCmd(interp, argListObjPtr, NULL, bodyObjPtr, nsObj);
  15721. if (cmd) {
  15722. nargv = Jim_Alloc((argc - 2 + 1) * sizeof(*nargv));
  15723. nargv[0] = Jim_NewStringObj(interp, "apply lambdaExpr", -1);
  15724. Jim_IncrRefCount(nargv[0]);
  15725. memcpy(&nargv[1], argv + 2, (argc - 2) * sizeof(*nargv));
  15726. ret = JimCallProcedure(interp, cmd, argc - 2 + 1, nargv);
  15727. Jim_DecrRefCount(interp, nargv[0]);
  15728. Jim_Free(nargv);
  15729. JimDecrCmdRefCount(interp, cmd);
  15730. return ret;
  15731. }
  15732. return JIM_ERR;
  15733. }
  15734. }
  15735. static int Jim_ConcatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15736. {
  15737. Jim_SetResult(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
  15738. return JIM_OK;
  15739. }
  15740. static int Jim_UpvarCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15741. {
  15742. int i;
  15743. Jim_CallFrame *targetCallFrame;
  15744. if (argc > 3 && (argc % 2 == 0)) {
  15745. targetCallFrame = Jim_GetCallFrameByLevel(interp, argv[1]);
  15746. argc--;
  15747. argv++;
  15748. }
  15749. else {
  15750. targetCallFrame = Jim_GetCallFrameByLevel(interp, NULL);
  15751. }
  15752. if (targetCallFrame == NULL) {
  15753. return JIM_ERR;
  15754. }
  15755. if (argc < 3) {
  15756. Jim_WrongNumArgs(interp, 1, argv, "?level? otherVar localVar ?otherVar localVar ...?");
  15757. return JIM_ERR;
  15758. }
  15759. for (i = 1; i < argc; i += 2) {
  15760. if (Jim_SetVariableLink(interp, argv[i + 1], argv[i], targetCallFrame) != JIM_OK)
  15761. return JIM_ERR;
  15762. }
  15763. return JIM_OK;
  15764. }
  15765. static int Jim_GlobalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15766. {
  15767. int i;
  15768. if (argc < 2) {
  15769. Jim_WrongNumArgs(interp, 1, argv, "varName ?varName ...?");
  15770. return JIM_ERR;
  15771. }
  15772. if (interp->framePtr->level == 0)
  15773. return JIM_OK;
  15774. for (i = 1; i < argc; i++) {
  15775. const char *name = Jim_String(argv[i]);
  15776. if (name[0] != ':' || name[1] != ':') {
  15777. if (Jim_SetVariableLink(interp, argv[i], argv[i], interp->topFramePtr) != JIM_OK)
  15778. return JIM_ERR;
  15779. }
  15780. }
  15781. return JIM_OK;
  15782. }
  15783. static Jim_Obj *JimStringMap(Jim_Interp *interp, Jim_Obj *mapListObjPtr,
  15784. Jim_Obj *objPtr, int nocase)
  15785. {
  15786. int numMaps;
  15787. const char *str, *noMatchStart = NULL;
  15788. int strLen, i;
  15789. Jim_Obj *resultObjPtr;
  15790. numMaps = Jim_ListLength(interp, mapListObjPtr);
  15791. if (numMaps % 2) {
  15792. Jim_SetResultString(interp, "list must contain an even number of elements", -1);
  15793. return NULL;
  15794. }
  15795. str = Jim_String(objPtr);
  15796. strLen = Jim_Utf8Length(interp, objPtr);
  15797. resultObjPtr = Jim_NewStringObj(interp, "", 0);
  15798. while (strLen) {
  15799. for (i = 0; i < numMaps; i += 2) {
  15800. Jim_Obj *eachObjPtr;
  15801. const char *k;
  15802. int kl;
  15803. eachObjPtr = Jim_ListGetIndex(interp, mapListObjPtr, i);
  15804. k = Jim_String(eachObjPtr);
  15805. kl = Jim_Utf8Length(interp, eachObjPtr);
  15806. if (strLen >= kl && kl) {
  15807. int rc;
  15808. rc = JimStringCompareUtf8(str, kl, k, kl, nocase);
  15809. if (rc == 0) {
  15810. if (noMatchStart) {
  15811. Jim_AppendString(interp, resultObjPtr, noMatchStart, str - noMatchStart);
  15812. noMatchStart = NULL;
  15813. }
  15814. Jim_AppendObj(interp, resultObjPtr, Jim_ListGetIndex(interp, mapListObjPtr, i + 1));
  15815. str += utf8_index(str, kl);
  15816. strLen -= kl;
  15817. break;
  15818. }
  15819. }
  15820. }
  15821. if (i == numMaps) {
  15822. int c;
  15823. if (noMatchStart == NULL)
  15824. noMatchStart = str;
  15825. str += utf8_tounicode(str, &c);
  15826. strLen--;
  15827. }
  15828. }
  15829. if (noMatchStart) {
  15830. Jim_AppendString(interp, resultObjPtr, noMatchStart, str - noMatchStart);
  15831. }
  15832. return resultObjPtr;
  15833. }
  15834. static int Jim_StringCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  15835. {
  15836. int len;
  15837. int opt_case = 1;
  15838. int option;
  15839. static const char * const nocase_options[] = {
  15840. "-nocase", NULL
  15841. };
  15842. static const char * const nocase_length_options[] = {
  15843. "-nocase", "-length", NULL
  15844. };
  15845. enum {
  15846. OPT_BYTELENGTH,
  15847. OPT_BYTERANGE,
  15848. OPT_CAT,
  15849. OPT_COMPARE,
  15850. OPT_EQUAL,
  15851. OPT_FIRST,
  15852. OPT_INDEX,
  15853. OPT_IS,
  15854. OPT_LAST,
  15855. OPT_LENGTH,
  15856. OPT_MAP,
  15857. OPT_MATCH,
  15858. OPT_RANGE,
  15859. OPT_REPEAT,
  15860. OPT_REPLACE,
  15861. OPT_REVERSE,
  15862. OPT_TOLOWER,
  15863. OPT_TOTITLE,
  15864. OPT_TOUPPER,
  15865. OPT_TRIM,
  15866. OPT_TRIMLEFT,
  15867. OPT_TRIMRIGHT,
  15868. OPT_COUNT
  15869. };
  15870. static const jim_subcmd_type cmds[OPT_COUNT + 1] = {
  15871. JIM_DEF_SUBCMD("bytelength", "string", 1, 1),
  15872. JIM_DEF_SUBCMD("byterange", "string first last", 3, 3),
  15873. JIM_DEF_SUBCMD("cat", "?...?", 0, -1),
  15874. JIM_DEF_SUBCMD("compare", "?-nocase? ?-length int? string1 string2", 2, 5),
  15875. JIM_DEF_SUBCMD("equal", "?-nocase? ?-length int? string1 string2", 2, 5),
  15876. JIM_DEF_SUBCMD("first", "subString string ?index?", 2, 3),
  15877. JIM_DEF_SUBCMD("index", "string index", 2, 2),
  15878. JIM_DEF_SUBCMD("is", "class ?-strict? str", 2, 3),
  15879. JIM_DEF_SUBCMD("last", "subString string ?index?", 2, 3),
  15880. JIM_DEF_SUBCMD("length","string", 1, 1),
  15881. JIM_DEF_SUBCMD("map", "?-nocase? mapList string", 2, 3),
  15882. JIM_DEF_SUBCMD("match", "?-nocase? pattern string", 2, 3),
  15883. JIM_DEF_SUBCMD("range", "string first last", 3, 3),
  15884. JIM_DEF_SUBCMD("repeat", "string count", 2, 2),
  15885. JIM_DEF_SUBCMD("replace", "string first last ?string?", 3, 4),
  15886. JIM_DEF_SUBCMD("reverse", "string", 1, 1),
  15887. JIM_DEF_SUBCMD("tolower", "string", 1, 1),
  15888. JIM_DEF_SUBCMD("totitle", "string", 1, 1),
  15889. JIM_DEF_SUBCMD("toupper", "string", 1, 1),
  15890. JIM_DEF_SUBCMD("trim", "string ?trimchars?", 1, 2),
  15891. JIM_DEF_SUBCMD("trimleft", "string ?trimchars?", 1, 2),
  15892. JIM_DEF_SUBCMD("trimright", "string ?trimchars?", 1, 2),
  15893. { NULL }
  15894. };
  15895. const jim_subcmd_type *ct = Jim_ParseSubCmd(interp, cmds, argc, argv);
  15896. if (!ct) {
  15897. return JIM_ERR;
  15898. }
  15899. if (ct->function) {
  15900. return ct->function(interp, argc, argv);
  15901. }
  15902. option = ct - cmds;
  15903. switch (option) {
  15904. case OPT_LENGTH:
  15905. Jim_SetResultInt(interp, Jim_Utf8Length(interp, argv[2]));
  15906. return JIM_OK;
  15907. case OPT_BYTELENGTH:
  15908. Jim_SetResultInt(interp, Jim_Length(argv[2]));
  15909. return JIM_OK;
  15910. case OPT_CAT:{
  15911. Jim_Obj *objPtr;
  15912. if (argc == 3) {
  15913. objPtr = argv[2];
  15914. }
  15915. else {
  15916. int i;
  15917. objPtr = Jim_NewStringObj(interp, "", 0);
  15918. for (i = 2; i < argc; i++) {
  15919. Jim_AppendObj(interp, objPtr, argv[i]);
  15920. }
  15921. }
  15922. Jim_SetResult(interp, objPtr);
  15923. return JIM_OK;
  15924. }
  15925. case OPT_COMPARE:
  15926. case OPT_EQUAL:
  15927. {
  15928. long opt_length = -1;
  15929. int n = argc - 4;
  15930. int i = 2;
  15931. while (n > 0) {
  15932. int subopt;
  15933. if (Jim_GetEnum(interp, argv[i++], nocase_length_options, &subopt, NULL,
  15934. JIM_ENUM_ABBREV) != JIM_OK) {
  15935. badcompareargs:
  15936. Jim_SubCmdArgError(interp, ct, argv[0]);
  15937. return JIM_ERR;
  15938. }
  15939. if (subopt == 0) {
  15940. opt_case = 0;
  15941. n--;
  15942. }
  15943. else {
  15944. if (n < 2) {
  15945. goto badcompareargs;
  15946. }
  15947. if (Jim_GetLong(interp, argv[i++], &opt_length) != JIM_OK) {
  15948. return JIM_ERR;
  15949. }
  15950. n -= 2;
  15951. }
  15952. }
  15953. if (n) {
  15954. goto badcompareargs;
  15955. }
  15956. argv += argc - 2;
  15957. if (opt_length < 0 && option != OPT_COMPARE && opt_case) {
  15958. Jim_SetResultBool(interp, Jim_StringEqObj(argv[0], argv[1]));
  15959. }
  15960. else {
  15961. const char *s1 = Jim_String(argv[0]);
  15962. int l1 = Jim_Utf8Length(interp, argv[0]);
  15963. const char *s2 = Jim_String(argv[1]);
  15964. int l2 = Jim_Utf8Length(interp, argv[1]);
  15965. if (opt_length >= 0) {
  15966. if (l1 > opt_length) {
  15967. l1 = opt_length;
  15968. }
  15969. if (l2 > opt_length) {
  15970. l2 = opt_length;
  15971. }
  15972. }
  15973. n = JimStringCompareUtf8(s1, l1, s2, l2, !opt_case);
  15974. Jim_SetResultInt(interp, option == OPT_COMPARE ? n : n == 0);
  15975. }
  15976. return JIM_OK;
  15977. }
  15978. case OPT_MATCH:
  15979. if (argc != 4 &&
  15980. (argc != 5 ||
  15981. Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
  15982. JIM_ENUM_ABBREV) != JIM_OK)) {
  15983. Jim_WrongNumArgs(interp, 2, argv, "?-nocase? pattern string");
  15984. return JIM_ERR;
  15985. }
  15986. if (opt_case == 0) {
  15987. argv++;
  15988. }
  15989. Jim_SetResultBool(interp, Jim_StringMatchObj(interp, argv[2], argv[3], !opt_case));
  15990. return JIM_OK;
  15991. case OPT_MAP:{
  15992. Jim_Obj *objPtr;
  15993. if (argc != 4 &&
  15994. (argc != 5 ||
  15995. Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
  15996. JIM_ENUM_ABBREV) != JIM_OK)) {
  15997. Jim_WrongNumArgs(interp, 2, argv, "?-nocase? mapList string");
  15998. return JIM_ERR;
  15999. }
  16000. if (opt_case == 0) {
  16001. argv++;
  16002. }
  16003. objPtr = JimStringMap(interp, argv[2], argv[3], !opt_case);
  16004. if (objPtr == NULL) {
  16005. return JIM_ERR;
  16006. }
  16007. Jim_SetResult(interp, objPtr);
  16008. return JIM_OK;
  16009. }
  16010. case OPT_RANGE:{
  16011. Jim_Obj *objPtr = Jim_StringRangeObj(interp, argv[2], argv[3], argv[4]);
  16012. if (objPtr == NULL) {
  16013. return JIM_ERR;
  16014. }
  16015. Jim_SetResult(interp, objPtr);
  16016. return JIM_OK;
  16017. }
  16018. case OPT_BYTERANGE:{
  16019. Jim_Obj *objPtr = Jim_StringByteRangeObj(interp, argv[2], argv[3], argv[4]);
  16020. if (objPtr == NULL) {
  16021. return JIM_ERR;
  16022. }
  16023. Jim_SetResult(interp, objPtr);
  16024. return JIM_OK;
  16025. }
  16026. case OPT_REPLACE:{
  16027. Jim_Obj *objPtr = JimStringReplaceObj(interp, argv[2], argv[3], argv[4], argc == 6 ? argv[5] : NULL);
  16028. if (objPtr == NULL) {
  16029. return JIM_ERR;
  16030. }
  16031. Jim_SetResult(interp, objPtr);
  16032. return JIM_OK;
  16033. }
  16034. case OPT_REPEAT:{
  16035. Jim_Obj *objPtr;
  16036. jim_wide count;
  16037. if (Jim_GetWideExpr(interp, argv[3], &count) != JIM_OK) {
  16038. return JIM_ERR;
  16039. }
  16040. objPtr = Jim_NewStringObj(interp, "", 0);
  16041. if (count > 0) {
  16042. while (count--) {
  16043. Jim_AppendObj(interp, objPtr, argv[2]);
  16044. }
  16045. }
  16046. Jim_SetResult(interp, objPtr);
  16047. return JIM_OK;
  16048. }
  16049. case OPT_REVERSE:{
  16050. char *buf, *p;
  16051. const char *str;
  16052. int i;
  16053. str = Jim_GetString(argv[2], &len);
  16054. buf = Jim_Alloc(len + 1);
  16055. assert(buf);
  16056. p = buf + len;
  16057. *p = 0;
  16058. for (i = 0; i < len; ) {
  16059. int c;
  16060. int l = utf8_tounicode(str, &c);
  16061. memcpy(p - l, str, l);
  16062. p -= l;
  16063. i += l;
  16064. str += l;
  16065. }
  16066. Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, buf, len));
  16067. return JIM_OK;
  16068. }
  16069. case OPT_INDEX:{
  16070. int idx;
  16071. const char *str;
  16072. if (Jim_GetIndex(interp, argv[3], &idx) != JIM_OK) {
  16073. return JIM_ERR;
  16074. }
  16075. str = Jim_String(argv[2]);
  16076. len = Jim_Utf8Length(interp, argv[2]);
  16077. idx = JimRelToAbsIndex(len, idx);
  16078. if (idx < 0 || idx >= len || str == NULL) {
  16079. Jim_SetResultString(interp, "", 0);
  16080. }
  16081. else if (len == Jim_Length(argv[2])) {
  16082. Jim_SetResultString(interp, str + idx, 1);
  16083. }
  16084. else {
  16085. int c;
  16086. int i = utf8_index(str, idx);
  16087. Jim_SetResultString(interp, str + i, utf8_tounicode(str + i, &c));
  16088. }
  16089. return JIM_OK;
  16090. }
  16091. case OPT_FIRST:
  16092. case OPT_LAST:{
  16093. int idx = 0, l1, l2;
  16094. const char *s1, *s2;
  16095. s1 = Jim_String(argv[2]);
  16096. s2 = Jim_String(argv[3]);
  16097. l1 = Jim_Utf8Length(interp, argv[2]);
  16098. l2 = Jim_Utf8Length(interp, argv[3]);
  16099. if (argc == 5) {
  16100. if (Jim_GetIndex(interp, argv[4], &idx) != JIM_OK) {
  16101. return JIM_ERR;
  16102. }
  16103. idx = JimRelToAbsIndex(l2, idx);
  16104. if (idx < 0) {
  16105. idx = 0;
  16106. }
  16107. }
  16108. else if (option == OPT_LAST) {
  16109. idx = l2;
  16110. }
  16111. if (option == OPT_FIRST) {
  16112. Jim_SetResultInt(interp, JimStringFirst(s1, l1, s2, l2, idx));
  16113. }
  16114. else {
  16115. #ifdef JIM_UTF8
  16116. Jim_SetResultInt(interp, JimStringLastUtf8(s1, l1, s2, idx));
  16117. #else
  16118. Jim_SetResultInt(interp, JimStringLast(s1, l1, s2, idx));
  16119. #endif
  16120. }
  16121. return JIM_OK;
  16122. }
  16123. case OPT_TRIM:
  16124. Jim_SetResult(interp, JimStringTrim(interp, argv[2], argc == 4 ? argv[3] : NULL));
  16125. return JIM_OK;
  16126. case OPT_TRIMLEFT:
  16127. Jim_SetResult(interp, JimStringTrimLeft(interp, argv[2], argc == 4 ? argv[3] : NULL));
  16128. return JIM_OK;
  16129. case OPT_TRIMRIGHT:{
  16130. Jim_SetResult(interp, JimStringTrimRight(interp, argv[2], argc == 4 ? argv[3] : NULL));
  16131. return JIM_OK;
  16132. }
  16133. case OPT_TOLOWER:
  16134. Jim_SetResult(interp, JimStringToLower(interp, argv[2]));
  16135. return JIM_OK;
  16136. case OPT_TOUPPER:
  16137. Jim_SetResult(interp, JimStringToUpper(interp, argv[2]));
  16138. return JIM_OK;
  16139. case OPT_TOTITLE:
  16140. Jim_SetResult(interp, JimStringToTitle(interp, argv[2]));
  16141. return JIM_OK;
  16142. case OPT_IS:
  16143. if (argc == 5 && !Jim_CompareStringImmediate(interp, argv[3], "-strict")) {
  16144. Jim_SubCmdArgError(interp, ct, argv[0]);
  16145. return JIM_ERR;
  16146. }
  16147. return JimStringIs(interp, argv[argc - 1], argv[2], argc == 5);
  16148. }
  16149. return JIM_OK;
  16150. }
  16151. static int Jim_TimeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  16152. {
  16153. long i, count = 1;
  16154. jim_wide start, elapsed;
  16155. if (argc < 2) {
  16156. Jim_WrongNumArgs(interp, 1, argv, "script ?count?");
  16157. return JIM_ERR;
  16158. }
  16159. if (argc == 3) {
  16160. if (Jim_GetLong(interp, argv[2], &count) != JIM_OK)
  16161. return JIM_ERR;
  16162. }
  16163. if (count < 0)
  16164. return JIM_OK;
  16165. i = count;
  16166. start = Jim_GetTimeUsec(CLOCK_MONOTONIC_RAW);
  16167. while (i-- > 0) {
  16168. int retval;
  16169. retval = Jim_EvalObj(interp, argv[1]);
  16170. if (retval != JIM_OK) {
  16171. return retval;
  16172. }
  16173. }
  16174. elapsed = Jim_GetTimeUsec(CLOCK_MONOTONIC_RAW) - start;
  16175. if (elapsed < count * 10) {
  16176. Jim_SetResult(interp, Jim_NewDoubleObj(interp, elapsed * 1.0 / count));
  16177. }
  16178. else {
  16179. Jim_SetResultInt(interp, count == 0 ? 0 : elapsed / count);
  16180. }
  16181. Jim_AppendString(interp, Jim_GetResult(interp)," microseconds per iteration", -1);
  16182. return JIM_OK;
  16183. }
  16184. static int Jim_TimeRateCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  16185. {
  16186. long us = 0;
  16187. jim_wide start, delta, overhead;
  16188. Jim_Obj *objPtr;
  16189. double us_per_iter;
  16190. int count;
  16191. int n;
  16192. if (argc < 2) {
  16193. Jim_WrongNumArgs(interp, 1, argv, "script ?milliseconds?");
  16194. return JIM_ERR;
  16195. }
  16196. if (argc == 3) {
  16197. if (Jim_GetLong(interp, argv[2], &us) != JIM_OK)
  16198. return JIM_ERR;
  16199. us *= 1000;
  16200. }
  16201. if (us < 1) {
  16202. us = 1000 * 1000;
  16203. }
  16204. start = Jim_GetTimeUsec(CLOCK_MONOTONIC_RAW);
  16205. count = 0;
  16206. do {
  16207. int retval = Jim_EvalObj(interp, argv[1]);
  16208. delta = Jim_GetTimeUsec(CLOCK_MONOTONIC_RAW) - start;
  16209. if (retval != JIM_OK) {
  16210. return retval;
  16211. }
  16212. count++;
  16213. } while (delta < us);
  16214. start = Jim_GetTimeUsec(CLOCK_MONOTONIC_RAW);
  16215. n = 0;
  16216. do {
  16217. int retval = Jim_EvalObj(interp, interp->nullScriptObj);
  16218. overhead = Jim_GetTimeUsec(CLOCK_MONOTONIC_RAW) - start;
  16219. if (retval != JIM_OK) {
  16220. return retval;
  16221. }
  16222. n++;
  16223. } while (n < count);
  16224. delta -= overhead;
  16225. us_per_iter = (double)delta / count;
  16226. objPtr = Jim_NewListObj(interp, NULL, 0);
  16227. Jim_ListAppendElement(interp, objPtr, Jim_NewStringObj(interp, "us_per_iter", -1));
  16228. Jim_ListAppendElement(interp, objPtr, Jim_NewDoubleObj(interp, us_per_iter));
  16229. Jim_ListAppendElement(interp, objPtr, Jim_NewStringObj(interp, "iters_per_sec", -1));
  16230. Jim_ListAppendElement(interp, objPtr, Jim_NewDoubleObj(interp, 1e6 / us_per_iter));
  16231. Jim_ListAppendElement(interp, objPtr, Jim_NewStringObj(interp, "count", -1));
  16232. Jim_ListAppendElement(interp, objPtr, Jim_NewIntObj(interp, count));
  16233. Jim_ListAppendElement(interp, objPtr, Jim_NewStringObj(interp, "elapsed_us", -1));
  16234. Jim_ListAppendElement(interp, objPtr, Jim_NewIntObj(interp, delta));
  16235. Jim_SetResult(interp, objPtr);
  16236. return JIM_OK;
  16237. }
  16238. static int Jim_ExitCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  16239. {
  16240. long exitCode = 0;
  16241. if (argc > 2) {
  16242. Jim_WrongNumArgs(interp, 1, argv, "?exitCode?");
  16243. return JIM_ERR;
  16244. }
  16245. if (argc == 2) {
  16246. if (Jim_GetLong(interp, argv[1], &exitCode) != JIM_OK)
  16247. return JIM_ERR;
  16248. Jim_SetResult(interp, argv[1]);
  16249. }
  16250. interp->exitCode = exitCode;
  16251. return JIM_EXIT;
  16252. }
  16253. static int JimMatchReturnCodes(Jim_Interp *interp, Jim_Obj *retcodeListObj, int rc)
  16254. {
  16255. int len = Jim_ListLength(interp, retcodeListObj);
  16256. int i;
  16257. for (i = 0; i < len; i++) {
  16258. int returncode;
  16259. if (Jim_GetReturnCode(interp, Jim_ListGetIndex(interp, retcodeListObj, i), &returncode) != JIM_OK) {
  16260. return JIM_ERR;
  16261. }
  16262. if (rc == returncode) {
  16263. return JIM_OK;
  16264. }
  16265. }
  16266. return -1;
  16267. }
  16268. static int JimCatchTryHelper(Jim_Interp *interp, int istry, int argc, Jim_Obj *const *argv)
  16269. {
  16270. static const char * const wrongargs_catchtry[2] = {
  16271. "?-?no?code ... --? script ?resultVarName? ?optionVarName?",
  16272. "?-?no?code ... --? script ?on|trap codes vars script? ... ?finally script?"
  16273. };
  16274. int exitCode = 0;
  16275. int i;
  16276. int sig = 0;
  16277. int ok;
  16278. Jim_Obj *finallyScriptObj = NULL;
  16279. Jim_Obj *msgVarObj = NULL;
  16280. Jim_Obj *optsVarObj = NULL;
  16281. Jim_Obj *handlerScriptObj = NULL;
  16282. Jim_Obj *errorCodeObj;
  16283. int idx;
  16284. jim_wide ignore_mask = (1 << JIM_EXIT) | (1 << JIM_EVAL) | (1 << JIM_SIGNAL);
  16285. static const int max_ignore_code = sizeof(ignore_mask) * 8;
  16286. JimPanic((istry != 0 && istry != 1, "wrong args to JimCatchTryHelper"));
  16287. Jim_SetGlobalVariableStr(interp, "errorCode", Jim_NewStringObj(interp, "NONE", -1));
  16288. for (i = 1; i < argc - 1; i++) {
  16289. const char *arg = Jim_String(argv[i]);
  16290. jim_wide option;
  16291. int ignore;
  16292. if (strcmp(arg, "--") == 0) {
  16293. i++;
  16294. break;
  16295. }
  16296. if (*arg != '-') {
  16297. break;
  16298. }
  16299. if (strncmp(arg, "-no", 3) == 0) {
  16300. arg += 3;
  16301. ignore = 1;
  16302. }
  16303. else {
  16304. arg++;
  16305. ignore = 0;
  16306. }
  16307. if (Jim_StringToWide(arg, &option, 10) != JIM_OK) {
  16308. option = -1;
  16309. }
  16310. if (option < 0) {
  16311. option = Jim_FindByName(arg, jimReturnCodes, jimReturnCodesSize);
  16312. }
  16313. if (option < 0) {
  16314. goto wrongargs;
  16315. }
  16316. if (ignore) {
  16317. ignore_mask |= ((jim_wide)1 << option);
  16318. }
  16319. else {
  16320. ignore_mask &= (~((jim_wide)1 << option));
  16321. }
  16322. }
  16323. idx = i;
  16324. if (argc - idx < 1) {
  16325. wrongargs:
  16326. Jim_WrongNumArgs(interp, 1, argv, wrongargs_catchtry[istry]);
  16327. return JIM_ERR;
  16328. }
  16329. if ((ignore_mask & (1 << JIM_SIGNAL)) == 0) {
  16330. sig++;
  16331. }
  16332. interp->signal_level += sig;
  16333. if (Jim_CheckSignal(interp)) {
  16334. exitCode = JIM_SIGNAL;
  16335. }
  16336. else {
  16337. exitCode = Jim_EvalObj(interp, argv[idx]);
  16338. interp->errorFlag = 0;
  16339. }
  16340. interp->signal_level -= sig;
  16341. errorCodeObj = Jim_GetGlobalVariableStr(interp, "errorCode", JIM_NONE);
  16342. idx++;
  16343. if (istry) {
  16344. while (idx < argc) {
  16345. int option;
  16346. int ret;
  16347. static const char * const try_options[] = { "on", "trap", "finally", NULL };
  16348. enum { TRY_ON, TRY_TRAP, TRY_FINALLY, };
  16349. if (Jim_GetEnum(interp, argv[idx], try_options, &option, "handler", JIM_ERRMSG) != JIM_OK) {
  16350. return JIM_ERR;
  16351. }
  16352. switch (option) {
  16353. case TRY_ON:
  16354. case TRY_TRAP:
  16355. if (idx + 4 > argc) {
  16356. goto wrongargs;
  16357. }
  16358. if (option == TRY_ON) {
  16359. ret = JimMatchReturnCodes(interp, argv[idx + 1], exitCode);
  16360. if (ret > JIM_OK) {
  16361. goto wrongargs;
  16362. }
  16363. }
  16364. else if (errorCodeObj) {
  16365. int len = Jim_ListLength(interp, argv[idx + 1]);
  16366. int i;
  16367. ret = JIM_OK;
  16368. for (i = 0; i < len; i++) {
  16369. Jim_Obj *matchObj = Jim_ListGetIndex(interp, argv[idx + 1], i);
  16370. Jim_Obj *objPtr = Jim_ListGetIndex(interp, errorCodeObj, i);
  16371. if (Jim_StringCompareObj(interp, matchObj, objPtr, 0) != 0) {
  16372. ret = -1;
  16373. break;
  16374. }
  16375. }
  16376. }
  16377. else {
  16378. ret = -1;
  16379. }
  16380. if (ret == JIM_OK && handlerScriptObj == NULL) {
  16381. msgVarObj = Jim_ListGetIndex(interp, argv[idx + 2], 0);
  16382. optsVarObj = Jim_ListGetIndex(interp, argv[idx + 2], 1);
  16383. handlerScriptObj = argv[idx + 3];
  16384. }
  16385. idx += 4;
  16386. break;
  16387. case TRY_FINALLY:
  16388. if (idx + 2 != argc) {
  16389. goto wrongargs;
  16390. }
  16391. finallyScriptObj = argv[idx + 1];
  16392. idx += 2;
  16393. break;
  16394. }
  16395. }
  16396. }
  16397. else {
  16398. if (argc - idx >= 1) {
  16399. msgVarObj = argv[idx];
  16400. idx++;
  16401. if (argc - idx >= 1) {
  16402. optsVarObj = argv[idx];
  16403. idx++;
  16404. }
  16405. }
  16406. }
  16407. if (exitCode >= 0 && exitCode < max_ignore_code && (((unsigned jim_wide)1 << exitCode) & ignore_mask)) {
  16408. if (finallyScriptObj) {
  16409. Jim_EvalObj(interp, finallyScriptObj);
  16410. }
  16411. return exitCode;
  16412. }
  16413. if (sig && exitCode == JIM_SIGNAL) {
  16414. if (interp->signal_set_result) {
  16415. interp->signal_set_result(interp, interp->sigmask);
  16416. }
  16417. else if (!istry) {
  16418. Jim_SetResultInt(interp, interp->sigmask);
  16419. }
  16420. interp->sigmask = 0;
  16421. }
  16422. ok = 1;
  16423. if (msgVarObj && Jim_Length(msgVarObj)) {
  16424. if (Jim_SetVariable(interp, msgVarObj, Jim_GetResult(interp)) != JIM_OK) {
  16425. ok = 0;
  16426. }
  16427. }
  16428. if (ok && optsVarObj && Jim_Length(optsVarObj)) {
  16429. Jim_Obj *optListObj = Jim_NewListObj(interp, NULL, 0);
  16430. Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-code", -1));
  16431. Jim_ListAppendElement(interp, optListObj,
  16432. Jim_NewIntObj(interp, exitCode == JIM_RETURN ? interp->returnCode : exitCode));
  16433. Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-level", -1));
  16434. Jim_ListAppendElement(interp, optListObj, Jim_NewIntObj(interp, interp->returnLevel));
  16435. if (exitCode == JIM_ERR) {
  16436. Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-errorinfo",
  16437. -1));
  16438. Jim_ListAppendElement(interp, optListObj, interp->stackTrace);
  16439. if (errorCodeObj) {
  16440. Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-errorcode", -1));
  16441. Jim_ListAppendElement(interp, optListObj, errorCodeObj);
  16442. }
  16443. }
  16444. if (Jim_SetVariable(interp, optsVarObj, optListObj) != JIM_OK) {
  16445. ok = 0;
  16446. }
  16447. }
  16448. if (ok && handlerScriptObj) {
  16449. exitCode = Jim_EvalObj(interp, handlerScriptObj);
  16450. }
  16451. if (finallyScriptObj) {
  16452. Jim_Obj *prevResultObj = Jim_GetResult(interp);
  16453. Jim_IncrRefCount(prevResultObj);
  16454. int ret = Jim_EvalObj(interp, finallyScriptObj);
  16455. if (ret == JIM_OK) {
  16456. Jim_SetResult(interp, prevResultObj);
  16457. }
  16458. else {
  16459. exitCode = ret;
  16460. }
  16461. Jim_DecrRefCount(interp, prevResultObj);
  16462. }
  16463. if (!istry) {
  16464. Jim_SetResultInt(interp, exitCode);
  16465. exitCode = JIM_OK;
  16466. }
  16467. return exitCode;
  16468. }
  16469. static int Jim_CatchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  16470. {
  16471. return JimCatchTryHelper(interp, 0, argc, argv);
  16472. }
  16473. static int Jim_TryCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  16474. {
  16475. return JimCatchTryHelper(interp, 1, argc, argv);
  16476. }
  16477. static int Jim_RenameCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  16478. {
  16479. if (argc != 3) {
  16480. Jim_WrongNumArgs(interp, 1, argv, "oldName newName");
  16481. return JIM_ERR;
  16482. }
  16483. return Jim_RenameCommand(interp, argv[1], argv[2]);
  16484. }
  16485. #define JIM_DICTMATCH_KEYS 0x0001
  16486. #define JIM_DICTMATCH_VALUES 0x002
  16487. int Jim_DictMatchTypes(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *patternObj, int match_type, int return_types)
  16488. {
  16489. Jim_Obj *listObjPtr;
  16490. Jim_Dict *dict;
  16491. int i;
  16492. if (SetDictFromAny(interp, objPtr) != JIM_OK) {
  16493. return JIM_ERR;
  16494. }
  16495. dict = objPtr->internalRep.dictValue;
  16496. listObjPtr = Jim_NewListObj(interp, NULL, 0);
  16497. for (i = 0; i < dict->len; i += 2 ) {
  16498. Jim_Obj *keyObj = dict->table[i];
  16499. Jim_Obj *valObj = dict->table[i + 1];
  16500. if (patternObj) {
  16501. Jim_Obj *matchObj = (match_type == JIM_DICTMATCH_KEYS) ? keyObj : valObj;
  16502. if (!Jim_StringMatchObj(interp, patternObj, matchObj, 0)) {
  16503. continue;
  16504. }
  16505. }
  16506. if (return_types & JIM_DICTMATCH_KEYS) {
  16507. Jim_ListAppendElement(interp, listObjPtr, keyObj);
  16508. }
  16509. if (return_types & JIM_DICTMATCH_VALUES) {
  16510. Jim_ListAppendElement(interp, listObjPtr, valObj);
  16511. }
  16512. }
  16513. Jim_SetResult(interp, listObjPtr);
  16514. return JIM_OK;
  16515. }
  16516. int Jim_DictSize(Jim_Interp *interp, Jim_Obj *objPtr)
  16517. {
  16518. if (SetDictFromAny(interp, objPtr) != JIM_OK) {
  16519. return -1;
  16520. }
  16521. return objPtr->internalRep.dictValue->len / 2;
  16522. }
  16523. Jim_Obj *Jim_DictMerge(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
  16524. {
  16525. Jim_Obj *objPtr = Jim_NewDictObj(interp, NULL, 0);
  16526. int i;
  16527. JimPanic((objc == 0, "Jim_DictMerge called with objc=0"));
  16528. for (i = 0; i < objc; i++) {
  16529. Jim_Obj **table;
  16530. int tablelen;
  16531. int j;
  16532. table = Jim_DictPairs(interp, objv[i], &tablelen);
  16533. if (tablelen && !table) {
  16534. Jim_FreeNewObj(interp, objPtr);
  16535. return NULL;
  16536. }
  16537. for (j = 0; j < tablelen; j += 2) {
  16538. DictAddElement(interp, objPtr, table[j], table[j + 1]);
  16539. }
  16540. }
  16541. return objPtr;
  16542. }
  16543. int Jim_DictInfo(Jim_Interp *interp, Jim_Obj *objPtr)
  16544. {
  16545. char buffer[100];
  16546. Jim_Obj *output;
  16547. Jim_Dict *dict;
  16548. if (SetDictFromAny(interp, objPtr) != JIM_OK) {
  16549. return JIM_ERR;
  16550. }
  16551. dict = objPtr->internalRep.dictValue;
  16552. snprintf(buffer, sizeof(buffer), "%d entries in table, %d buckets", dict->len, dict->size);
  16553. output = Jim_NewStringObj(interp, buffer, -1);
  16554. Jim_SetResult(interp, output);
  16555. return JIM_OK;
  16556. }
  16557. static int Jim_EvalEnsemble(Jim_Interp *interp, const char *basecmd, const char *subcmd, int argc, Jim_Obj *const *argv)
  16558. {
  16559. Jim_Obj *prefixObj = Jim_NewStringObj(interp, basecmd, -1);
  16560. Jim_AppendString(interp, prefixObj, " ", 1);
  16561. Jim_AppendString(interp, prefixObj, subcmd, -1);
  16562. return Jim_EvalObjPrefix(interp, prefixObj, argc, argv);
  16563. }
  16564. static int JimDictWith(Jim_Interp *interp, Jim_Obj *dictVarName, Jim_Obj *const *keyv, int keyc, Jim_Obj *scriptObj)
  16565. {
  16566. int i;
  16567. Jim_Obj *objPtr;
  16568. Jim_Obj *dictObj;
  16569. Jim_Obj **dictValues;
  16570. int len;
  16571. int ret = JIM_OK;
  16572. dictObj = Jim_GetVariable(interp, dictVarName, JIM_ERRMSG);
  16573. if (dictObj == NULL || Jim_DictKeysVector(interp, dictObj, keyv, keyc, &objPtr, JIM_ERRMSG) != JIM_OK) {
  16574. return JIM_ERR;
  16575. }
  16576. dictValues = Jim_DictPairs(interp, objPtr, &len);
  16577. if (len && dictValues == NULL) {
  16578. return JIM_ERR;
  16579. }
  16580. for (i = 0; i < len; i += 2) {
  16581. if (Jim_SetVariable(interp, dictValues[i], dictValues[i + 1]) == JIM_ERR) {
  16582. return JIM_ERR;
  16583. }
  16584. }
  16585. if (Jim_Length(scriptObj)) {
  16586. ret = Jim_EvalObj(interp, scriptObj);
  16587. if (ret == JIM_OK && Jim_GetVariable(interp, dictVarName, 0) != NULL) {
  16588. Jim_Obj **newkeyv = Jim_Alloc(sizeof(*newkeyv) * (keyc + 1));
  16589. for (i = 0; i < keyc; i++) {
  16590. newkeyv[i] = keyv[i];
  16591. }
  16592. for (i = 0; i < len; i += 2) {
  16593. if (Jim_StringCompareObj(interp, dictVarName, dictValues[i], 0) != 0) {
  16594. objPtr = Jim_GetVariable(interp, dictValues[i], 0);
  16595. newkeyv[keyc] = dictValues[i];
  16596. Jim_SetDictKeysVector(interp, dictVarName, newkeyv, keyc + 1, objPtr, JIM_NORESULT);
  16597. }
  16598. }
  16599. Jim_Free(newkeyv);
  16600. }
  16601. }
  16602. return ret;
  16603. }
  16604. static int Jim_DictCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  16605. {
  16606. Jim_Obj *objPtr;
  16607. int types = JIM_DICTMATCH_KEYS;
  16608. enum {
  16609. OPT_CREATE,
  16610. OPT_GET,
  16611. OPT_GETDEF,
  16612. OPT_GETWITHDEFAULT,
  16613. OPT_SET,
  16614. OPT_UNSET,
  16615. OPT_EXISTS,
  16616. OPT_KEYS,
  16617. OPT_SIZE,
  16618. OPT_INFO,
  16619. OPT_MERGE,
  16620. OPT_WITH,
  16621. OPT_APPEND,
  16622. OPT_LAPPEND,
  16623. OPT_INCR,
  16624. OPT_REMOVE,
  16625. OPT_VALUES,
  16626. OPT_FOR,
  16627. OPT_REPLACE,
  16628. OPT_UPDATE,
  16629. OPT_COUNT
  16630. };
  16631. static const jim_subcmd_type cmds[OPT_COUNT + 1] = {
  16632. JIM_DEF_SUBCMD("create", "?key value ...?", 0, -2),
  16633. JIM_DEF_SUBCMD("get", "dictionary ?key ...?", 1, -1),
  16634. JIM_DEF_SUBCMD_HIDDEN("getdef", "dictionary ?key ...? key default", 3, -1),
  16635. JIM_DEF_SUBCMD("getwithdefault", "dictionary ?key ...? key default", 3, -1),
  16636. JIM_DEF_SUBCMD("set", "varName key ?key ...? value", 3, -1),
  16637. JIM_DEF_SUBCMD("unset", "varName key ?key ...?", 2, -1),
  16638. JIM_DEF_SUBCMD("exists", "dictionary key ?key ...?", 2, -1),
  16639. JIM_DEF_SUBCMD("keys", "dictionary ?pattern?", 1, 2),
  16640. JIM_DEF_SUBCMD("size", "dictionary", 1, 1),
  16641. JIM_DEF_SUBCMD("info", "dictionary", 1, 1),
  16642. JIM_DEF_SUBCMD("merge", "?...?", 0, -1),
  16643. JIM_DEF_SUBCMD("with", "dictVar ?key ...? script", 2, -1),
  16644. JIM_DEF_SUBCMD("append", "varName key ?value ...?", 2, -1),
  16645. JIM_DEF_SUBCMD("lappend", "varName key ?value ...?", 2, -1),
  16646. JIM_DEF_SUBCMD("incr", "varName key ?increment?", 2, 3),
  16647. JIM_DEF_SUBCMD("remove", "dictionary ?key ...?", 1, -1),
  16648. JIM_DEF_SUBCMD("values", "dictionary ?pattern?", 1, 2),
  16649. JIM_DEF_SUBCMD("for", "vars dictionary script", 3, 3),
  16650. JIM_DEF_SUBCMD("replace", "dictionary ?key value ...?", 1, -1),
  16651. JIM_DEF_SUBCMD("update", "varName ?arg ...? script", 2, -1),
  16652. { NULL }
  16653. };
  16654. const jim_subcmd_type *ct = Jim_ParseSubCmd(interp, cmds, argc, argv);
  16655. if (!ct) {
  16656. return JIM_ERR;
  16657. }
  16658. if (ct->function) {
  16659. return ct->function(interp, argc, argv);
  16660. }
  16661. switch (ct - cmds) {
  16662. case OPT_GET:
  16663. if (Jim_DictKeysVector(interp, argv[2], argv + 3, argc - 3, &objPtr,
  16664. JIM_ERRMSG) != JIM_OK) {
  16665. return JIM_ERR;
  16666. }
  16667. Jim_SetResult(interp, objPtr);
  16668. return JIM_OK;
  16669. case OPT_GETDEF:
  16670. case OPT_GETWITHDEFAULT:{
  16671. int rc = Jim_DictKeysVector(interp, argv[2], argv + 3, argc - 4, &objPtr, JIM_ERRMSG);
  16672. if (rc == -1) {
  16673. return JIM_ERR;
  16674. }
  16675. if (rc == JIM_ERR) {
  16676. Jim_SetResult(interp, argv[argc - 1]);
  16677. }
  16678. else {
  16679. Jim_SetResult(interp, objPtr);
  16680. }
  16681. return JIM_OK;
  16682. }
  16683. case OPT_SET:
  16684. return Jim_SetDictKeysVector(interp, argv[2], argv + 3, argc - 4, argv[argc - 1], JIM_ERRMSG);
  16685. case OPT_EXISTS:{
  16686. int rc = Jim_DictKeysVector(interp, argv[2], argv + 3, argc - 3, &objPtr, JIM_NONE);
  16687. if (rc < 0) {
  16688. return JIM_ERR;
  16689. }
  16690. Jim_SetResultBool(interp, rc == JIM_OK);
  16691. return JIM_OK;
  16692. }
  16693. case OPT_UNSET:
  16694. if (Jim_SetDictKeysVector(interp, argv[2], argv + 3, argc - 3, NULL, JIM_NONE) != JIM_OK) {
  16695. return JIM_ERR;
  16696. }
  16697. return JIM_OK;
  16698. case OPT_VALUES:
  16699. types = JIM_DICTMATCH_VALUES;
  16700. case OPT_KEYS:
  16701. return Jim_DictMatchTypes(interp, argv[2], argc == 4 ? argv[3] : NULL, types, types);
  16702. case OPT_SIZE:
  16703. if (Jim_DictSize(interp, argv[2]) < 0) {
  16704. return JIM_ERR;
  16705. }
  16706. Jim_SetResultInt(interp, Jim_DictSize(interp, argv[2]));
  16707. return JIM_OK;
  16708. case OPT_MERGE:
  16709. if (argc == 2) {
  16710. return JIM_OK;
  16711. }
  16712. objPtr = Jim_DictMerge(interp, argc - 2, argv + 2);
  16713. if (objPtr == NULL) {
  16714. return JIM_ERR;
  16715. }
  16716. Jim_SetResult(interp, objPtr);
  16717. return JIM_OK;
  16718. case OPT_CREATE:
  16719. objPtr = Jim_NewDictObj(interp, argv + 2, argc - 2);
  16720. Jim_SetResult(interp, objPtr);
  16721. return JIM_OK;
  16722. case OPT_INFO:
  16723. return Jim_DictInfo(interp, argv[2]);
  16724. case OPT_WITH:
  16725. return JimDictWith(interp, argv[2], argv + 3, argc - 4, argv[argc - 1]);
  16726. case OPT_UPDATE:
  16727. if (argc < 6 || argc % 2) {
  16728. argc = 2;
  16729. }
  16730. default:
  16731. return Jim_EvalEnsemble(interp, "dict", Jim_String(argv[1]), argc - 2, argv + 2);
  16732. }
  16733. }
  16734. static int Jim_SubstCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  16735. {
  16736. static const char * const options[] = {
  16737. "-nobackslashes", "-nocommands", "-novariables", NULL
  16738. };
  16739. enum
  16740. { OPT_NOBACKSLASHES, OPT_NOCOMMANDS, OPT_NOVARIABLES };
  16741. int i;
  16742. int flags = JIM_SUBST_FLAG;
  16743. Jim_Obj *objPtr;
  16744. if (argc < 2) {
  16745. Jim_WrongNumArgs(interp, 1, argv, "?options? string");
  16746. return JIM_ERR;
  16747. }
  16748. for (i = 1; i < (argc - 1); i++) {
  16749. int option;
  16750. if (Jim_GetEnum(interp, argv[i], options, &option, NULL,
  16751. JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
  16752. return JIM_ERR;
  16753. }
  16754. switch (option) {
  16755. case OPT_NOBACKSLASHES:
  16756. flags |= JIM_SUBST_NOESC;
  16757. break;
  16758. case OPT_NOCOMMANDS:
  16759. flags |= JIM_SUBST_NOCMD;
  16760. break;
  16761. case OPT_NOVARIABLES:
  16762. flags |= JIM_SUBST_NOVAR;
  16763. break;
  16764. }
  16765. }
  16766. if (Jim_SubstObj(interp, argv[argc - 1], &objPtr, flags) != JIM_OK) {
  16767. return JIM_ERR;
  16768. }
  16769. Jim_SetResult(interp, objPtr);
  16770. return JIM_OK;
  16771. }
  16772. #ifdef jim_ext_namespace
  16773. static int JimIsGlobalNamespace(Jim_Obj *objPtr)
  16774. {
  16775. int len;
  16776. const char *str = Jim_GetString(objPtr, &len);
  16777. return len >= 2 && str[0] == ':' && str[1] == ':';
  16778. }
  16779. #endif
  16780. static int Jim_InfoCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  16781. {
  16782. Jim_Obj *objPtr;
  16783. int mode = 0;
  16784. enum {
  16785. INFO_ALIAS,
  16786. INFO_ARGS,
  16787. INFO_BODY,
  16788. INFO_CHANNELS,
  16789. INFO_COMMANDS,
  16790. INFO_COMPLETE,
  16791. INFO_EXISTS,
  16792. INFO_FRAME,
  16793. INFO_GLOBALS,
  16794. INFO_HOSTNAME,
  16795. INFO_LEVEL,
  16796. INFO_LOCALS,
  16797. INFO_NAMEOFEXECUTABLE,
  16798. INFO_PATCHLEVEL,
  16799. INFO_PROCS,
  16800. INFO_REFERENCES,
  16801. INFO_RETURNCODES,
  16802. INFO_SCRIPT,
  16803. INFO_SOURCE,
  16804. INFO_STACKTRACE,
  16805. INFO_STATICS,
  16806. INFO_VARS,
  16807. INFO_VERSION,
  16808. INFO_COUNT
  16809. };
  16810. static const jim_subcmd_type cmds[INFO_COUNT + 1] = {
  16811. JIM_DEF_SUBCMD("alias", "command", 1, 1),
  16812. JIM_DEF_SUBCMD("args", "procname", 1, 1),
  16813. JIM_DEF_SUBCMD("body", "procname", 1, 1),
  16814. JIM_DEF_SUBCMD("channels", "?pattern?", 0, 1),
  16815. JIM_DEF_SUBCMD("commands", "?pattern?", 0, 1),
  16816. JIM_DEF_SUBCMD("complete", "script ?missing?", 1, 2),
  16817. JIM_DEF_SUBCMD("exists", "varName", 1, 1),
  16818. JIM_DEF_SUBCMD("frame", "?levelNum?", 0, 1),
  16819. JIM_DEF_SUBCMD("globals", "?pattern?", 0, 1),
  16820. JIM_DEF_SUBCMD("hostname", NULL, 0, 0),
  16821. JIM_DEF_SUBCMD("level", "?levelNum?", 0, 1),
  16822. JIM_DEF_SUBCMD("locals", "?pattern?", 0, 1),
  16823. JIM_DEF_SUBCMD("nameofexecutable", NULL, 0, 0),
  16824. JIM_DEF_SUBCMD("patchlevel", NULL, 0, 0),
  16825. JIM_DEF_SUBCMD("procs", "?pattern?", 0, 1),
  16826. JIM_DEF_SUBCMD("references", NULL, 0, 0),
  16827. JIM_DEF_SUBCMD("returncodes", "?code?", 0, 1),
  16828. JIM_DEF_SUBCMD("script", "?filename?", 0, 1),
  16829. JIM_DEF_SUBCMD("source", "source ?filename line?", 1, 3),
  16830. JIM_DEF_SUBCMD("stacktrace", NULL, 0, 0),
  16831. JIM_DEF_SUBCMD("statics", "procname", 1, 1),
  16832. JIM_DEF_SUBCMD("vars", "?pattern?", 0, 1),
  16833. JIM_DEF_SUBCMD("version", NULL, 0, 0),
  16834. { NULL }
  16835. };
  16836. const jim_subcmd_type *ct;
  16837. #ifdef jim_ext_namespace
  16838. int nons = 0;
  16839. if (argc > 2 && Jim_CompareStringImmediate(interp, argv[1], "-nons")) {
  16840. argc--;
  16841. argv++;
  16842. nons = 1;
  16843. }
  16844. #endif
  16845. ct = Jim_ParseSubCmd(interp, cmds, argc, argv);
  16846. if (!ct) {
  16847. return JIM_ERR;
  16848. }
  16849. if (ct->function) {
  16850. return ct->function(interp, argc, argv);
  16851. }
  16852. int option = ct - cmds;
  16853. switch (option) {
  16854. case INFO_EXISTS:
  16855. Jim_SetResultBool(interp, Jim_GetVariable(interp, argv[2], 0) != NULL);
  16856. return JIM_OK;
  16857. case INFO_ALIAS:{
  16858. Jim_Cmd *cmdPtr;
  16859. if ((cmdPtr = Jim_GetCommand(interp, argv[2], JIM_ERRMSG)) == NULL) {
  16860. return JIM_ERR;
  16861. }
  16862. if (cmdPtr->isproc || cmdPtr->u.native.cmdProc != JimAliasCmd) {
  16863. Jim_SetResultFormatted(interp, "command \"%#s\" is not an alias", argv[2]);
  16864. return JIM_ERR;
  16865. }
  16866. Jim_SetResult(interp, (Jim_Obj *)cmdPtr->u.native.privData);
  16867. return JIM_OK;
  16868. }
  16869. case INFO_CHANNELS:
  16870. mode++;
  16871. #ifndef jim_ext_aio
  16872. Jim_SetResultString(interp, "aio not enabled", -1);
  16873. return JIM_ERR;
  16874. #endif
  16875. case INFO_PROCS:
  16876. mode++;
  16877. case INFO_COMMANDS:
  16878. #ifdef jim_ext_namespace
  16879. if (!nons) {
  16880. if (Jim_Length(interp->framePtr->nsObj) || (argc == 3 && JimIsGlobalNamespace(argv[2]))) {
  16881. return Jim_EvalPrefix(interp, "namespace info", argc - 1, argv + 1);
  16882. }
  16883. }
  16884. #endif
  16885. Jim_SetResult(interp, JimCommandsList(interp, (argc == 3) ? argv[2] : NULL, mode));
  16886. return JIM_OK;
  16887. case INFO_VARS:
  16888. mode++;
  16889. case INFO_LOCALS:
  16890. mode++;
  16891. case INFO_GLOBALS:
  16892. #ifdef jim_ext_namespace
  16893. if (!nons) {
  16894. if (Jim_Length(interp->framePtr->nsObj) || (argc == 3 && JimIsGlobalNamespace(argv[2]))) {
  16895. return Jim_EvalPrefix(interp, "namespace info", argc - 1, argv + 1);
  16896. }
  16897. }
  16898. #endif
  16899. Jim_SetResult(interp, JimVariablesList(interp, argc == 3 ? argv[2] : NULL, mode));
  16900. return JIM_OK;
  16901. case INFO_SCRIPT:
  16902. if (argc == 3) {
  16903. Jim_IncrRefCount(argv[2]);
  16904. Jim_DecrRefCount(interp, interp->currentFilenameObj);
  16905. interp->currentFilenameObj = argv[2];
  16906. }
  16907. Jim_SetResult(interp, interp->currentFilenameObj);
  16908. return JIM_OK;
  16909. case INFO_SOURCE:{
  16910. Jim_Obj *resObjPtr;
  16911. Jim_Obj *fileNameObj;
  16912. if (argc == 4) {
  16913. Jim_SubCmdArgError(interp, ct, argv[0]);
  16914. return JIM_ERR;
  16915. }
  16916. if (argc == 5) {
  16917. jim_wide line;
  16918. if (Jim_GetWide(interp, argv[4], &line) != JIM_OK) {
  16919. return JIM_ERR;
  16920. }
  16921. resObjPtr = Jim_NewStringObj(interp, Jim_String(argv[2]), Jim_Length(argv[2]));
  16922. Jim_SetSourceInfo(interp, resObjPtr, argv[3], line);
  16923. }
  16924. else {
  16925. int line;
  16926. fileNameObj = Jim_GetSourceInfo(interp, argv[2], &line);
  16927. resObjPtr = Jim_NewListObj(interp, NULL, 0);
  16928. Jim_ListAppendElement(interp, resObjPtr, fileNameObj);
  16929. Jim_ListAppendElement(interp, resObjPtr, Jim_NewIntObj(interp, line));
  16930. }
  16931. Jim_SetResult(interp, resObjPtr);
  16932. return JIM_OK;
  16933. }
  16934. case INFO_STACKTRACE:
  16935. Jim_SetResult(interp, interp->stackTrace);
  16936. return JIM_OK;
  16937. case INFO_LEVEL:
  16938. if (argc == 2) {
  16939. Jim_SetResultInt(interp, interp->framePtr->level);
  16940. }
  16941. else {
  16942. if (JimInfoLevel(interp, argv[2], &objPtr) != JIM_OK) {
  16943. return JIM_ERR;
  16944. }
  16945. Jim_SetResult(interp, objPtr);
  16946. }
  16947. return JIM_OK;
  16948. case INFO_FRAME:
  16949. if (argc == 2) {
  16950. Jim_SetResultInt(interp, interp->procLevel + 1);
  16951. }
  16952. else {
  16953. if (JimInfoFrame(interp, argv[2], &objPtr) != JIM_OK) {
  16954. return JIM_ERR;
  16955. }
  16956. Jim_SetResult(interp, objPtr);
  16957. }
  16958. return JIM_OK;
  16959. case INFO_BODY:
  16960. case INFO_STATICS:
  16961. case INFO_ARGS:{
  16962. Jim_Cmd *cmdPtr;
  16963. if ((cmdPtr = Jim_GetCommand(interp, argv[2], JIM_ERRMSG)) == NULL) {
  16964. return JIM_ERR;
  16965. }
  16966. if (!cmdPtr->isproc) {
  16967. Jim_SetResultFormatted(interp, "command \"%#s\" is not a procedure", argv[2]);
  16968. return JIM_ERR;
  16969. }
  16970. switch (option) {
  16971. #ifdef JIM_NO_INTROSPECTION
  16972. default:
  16973. Jim_SetResultString(interp, "unsupported", -1);
  16974. return JIM_ERR;
  16975. #else
  16976. case INFO_BODY:
  16977. Jim_SetResult(interp, cmdPtr->u.proc.bodyObjPtr);
  16978. break;
  16979. case INFO_ARGS:
  16980. Jim_SetResult(interp, cmdPtr->u.proc.argListObjPtr);
  16981. break;
  16982. #endif
  16983. case INFO_STATICS:
  16984. if (cmdPtr->u.proc.staticVars) {
  16985. Jim_SetResult(interp, JimHashtablePatternMatch(interp, cmdPtr->u.proc.staticVars,
  16986. NULL, JimVariablesMatch, JIM_VARLIST_LOCALS | JIM_VARLIST_VALUES));
  16987. }
  16988. break;
  16989. }
  16990. return JIM_OK;
  16991. }
  16992. case INFO_VERSION:
  16993. case INFO_PATCHLEVEL:{
  16994. char buf[(JIM_INTEGER_SPACE * 2) + 1];
  16995. sprintf(buf, "%d.%d", JIM_VERSION / 100, JIM_VERSION % 100);
  16996. Jim_SetResultString(interp, buf, -1);
  16997. return JIM_OK;
  16998. }
  16999. case INFO_COMPLETE: {
  17000. char missing;
  17001. Jim_SetResultBool(interp, Jim_ScriptIsComplete(interp, argv[2], &missing));
  17002. if (missing != ' ' && argc == 4) {
  17003. Jim_SetVariable(interp, argv[3], Jim_NewStringObj(interp, &missing, 1));
  17004. }
  17005. return JIM_OK;
  17006. }
  17007. case INFO_HOSTNAME:
  17008. return Jim_Eval(interp, "os.gethostname");
  17009. case INFO_NAMEOFEXECUTABLE:
  17010. return Jim_Eval(interp, "{info nameofexecutable}");
  17011. case INFO_RETURNCODES:
  17012. if (argc == 2) {
  17013. int i;
  17014. Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
  17015. for (i = 0; jimReturnCodes[i]; i++) {
  17016. Jim_ListAppendElement(interp, listObjPtr, Jim_NewIntObj(interp, i));
  17017. Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp,
  17018. jimReturnCodes[i], -1));
  17019. }
  17020. Jim_SetResult(interp, listObjPtr);
  17021. }
  17022. else if (argc == 3) {
  17023. long code;
  17024. const char *name;
  17025. if (Jim_GetLong(interp, argv[2], &code) != JIM_OK) {
  17026. return JIM_ERR;
  17027. }
  17028. name = Jim_ReturnCode(code);
  17029. if (*name == '?') {
  17030. Jim_SetResultInt(interp, code);
  17031. }
  17032. else {
  17033. Jim_SetResultString(interp, name, -1);
  17034. }
  17035. }
  17036. return JIM_OK;
  17037. case INFO_REFERENCES:
  17038. #ifdef JIM_REFERENCES
  17039. return JimInfoReferences(interp, argc, argv);
  17040. #else
  17041. Jim_SetResultString(interp, "not supported", -1);
  17042. return JIM_ERR;
  17043. #endif
  17044. default:
  17045. abort();
  17046. }
  17047. }
  17048. static int Jim_ExistsCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  17049. {
  17050. Jim_Obj *objPtr;
  17051. int result = 0;
  17052. static const char * const options[] = {
  17053. "-command", "-proc", "-alias", "-var", NULL
  17054. };
  17055. enum
  17056. {
  17057. OPT_COMMAND, OPT_PROC, OPT_ALIAS, OPT_VAR
  17058. };
  17059. int option;
  17060. if (argc == 2) {
  17061. option = OPT_VAR;
  17062. objPtr = argv[1];
  17063. }
  17064. else if (argc == 3) {
  17065. if (Jim_GetEnum(interp, argv[1], options, &option, NULL, JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
  17066. return JIM_ERR;
  17067. }
  17068. objPtr = argv[2];
  17069. }
  17070. else {
  17071. Jim_WrongNumArgs(interp, 1, argv, "?option? name");
  17072. return JIM_ERR;
  17073. }
  17074. if (option == OPT_VAR) {
  17075. result = Jim_GetVariable(interp, objPtr, 0) != NULL;
  17076. }
  17077. else {
  17078. Jim_Cmd *cmd = Jim_GetCommand(interp, objPtr, JIM_NONE);
  17079. if (cmd) {
  17080. switch (option) {
  17081. case OPT_COMMAND:
  17082. result = 1;
  17083. break;
  17084. case OPT_ALIAS:
  17085. result = cmd->isproc == 0 && cmd->u.native.cmdProc == JimAliasCmd;
  17086. break;
  17087. case OPT_PROC:
  17088. result = cmd->isproc;
  17089. break;
  17090. }
  17091. }
  17092. }
  17093. Jim_SetResultBool(interp, result);
  17094. return JIM_OK;
  17095. }
  17096. static int Jim_SplitCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  17097. {
  17098. const char *str, *splitChars, *noMatchStart;
  17099. int splitLen, strLen;
  17100. Jim_Obj *resObjPtr;
  17101. int c;
  17102. int len;
  17103. if (argc != 2 && argc != 3) {
  17104. Jim_WrongNumArgs(interp, 1, argv, "string ?splitChars?");
  17105. return JIM_ERR;
  17106. }
  17107. str = Jim_GetString(argv[1], &len);
  17108. if (len == 0) {
  17109. return JIM_OK;
  17110. }
  17111. strLen = Jim_Utf8Length(interp, argv[1]);
  17112. if (argc == 2) {
  17113. splitChars = " \n\t\r";
  17114. splitLen = 4;
  17115. }
  17116. else {
  17117. splitChars = Jim_String(argv[2]);
  17118. splitLen = Jim_Utf8Length(interp, argv[2]);
  17119. }
  17120. noMatchStart = str;
  17121. resObjPtr = Jim_NewListObj(interp, NULL, 0);
  17122. if (splitLen) {
  17123. Jim_Obj *objPtr;
  17124. while (strLen--) {
  17125. const char *sc = splitChars;
  17126. int scLen = splitLen;
  17127. int sl = utf8_tounicode(str, &c);
  17128. while (scLen--) {
  17129. int pc;
  17130. sc += utf8_tounicode(sc, &pc);
  17131. if (c == pc) {
  17132. objPtr = Jim_NewStringObj(interp, noMatchStart, (str - noMatchStart));
  17133. Jim_ListAppendElement(interp, resObjPtr, objPtr);
  17134. noMatchStart = str + sl;
  17135. break;
  17136. }
  17137. }
  17138. str += sl;
  17139. }
  17140. objPtr = Jim_NewStringObj(interp, noMatchStart, (str - noMatchStart));
  17141. Jim_ListAppendElement(interp, resObjPtr, objPtr);
  17142. }
  17143. else {
  17144. Jim_Obj **commonObj = NULL;
  17145. #define NUM_COMMON (128 - 9)
  17146. while (strLen--) {
  17147. int n = utf8_tounicode(str, &c);
  17148. #ifdef JIM_OPTIMIZATION
  17149. if (c >= 9 && c < 128) {
  17150. c -= 9;
  17151. if (!commonObj) {
  17152. commonObj = Jim_Alloc(sizeof(*commonObj) * NUM_COMMON);
  17153. memset(commonObj, 0, sizeof(*commonObj) * NUM_COMMON);
  17154. }
  17155. if (!commonObj[c]) {
  17156. commonObj[c] = Jim_NewStringObj(interp, str, 1);
  17157. }
  17158. Jim_ListAppendElement(interp, resObjPtr, commonObj[c]);
  17159. str++;
  17160. continue;
  17161. }
  17162. #endif
  17163. Jim_ListAppendElement(interp, resObjPtr, Jim_NewStringObjUtf8(interp, str, 1));
  17164. str += n;
  17165. }
  17166. Jim_Free(commonObj);
  17167. }
  17168. Jim_SetResult(interp, resObjPtr);
  17169. return JIM_OK;
  17170. }
  17171. static int Jim_JoinCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  17172. {
  17173. const char *joinStr;
  17174. int joinStrLen;
  17175. if (argc != 2 && argc != 3) {
  17176. Jim_WrongNumArgs(interp, 1, argv, "list ?joinString?");
  17177. return JIM_ERR;
  17178. }
  17179. if (argc == 2) {
  17180. joinStr = " ";
  17181. joinStrLen = 1;
  17182. }
  17183. else {
  17184. joinStr = Jim_GetString(argv[2], &joinStrLen);
  17185. }
  17186. Jim_SetResult(interp, Jim_ListJoin(interp, argv[1], joinStr, joinStrLen));
  17187. return JIM_OK;
  17188. }
  17189. static int Jim_FormatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  17190. {
  17191. Jim_Obj *objPtr;
  17192. if (argc < 2) {
  17193. Jim_WrongNumArgs(interp, 1, argv, "formatString ?arg arg ...?");
  17194. return JIM_ERR;
  17195. }
  17196. objPtr = Jim_FormatString(interp, argv[1], argc - 2, argv + 2);
  17197. if (objPtr == NULL)
  17198. return JIM_ERR;
  17199. Jim_SetResult(interp, objPtr);
  17200. return JIM_OK;
  17201. }
  17202. static int Jim_ScanCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  17203. {
  17204. Jim_Obj *listPtr, **outVec;
  17205. int outc, i;
  17206. if (argc < 3) {
  17207. Jim_WrongNumArgs(interp, 1, argv, "string format ?varName varName ...?");
  17208. return JIM_ERR;
  17209. }
  17210. if (argv[2]->typePtr != &scanFmtStringObjType)
  17211. SetScanFmtFromAny(interp, argv[2]);
  17212. if (FormatGetError(argv[2]) != 0) {
  17213. Jim_SetResultString(interp, FormatGetError(argv[2]), -1);
  17214. return JIM_ERR;
  17215. }
  17216. if (argc > 3) {
  17217. int maxPos = FormatGetMaxPos(argv[2]);
  17218. int count = FormatGetCnvCount(argv[2]);
  17219. if (maxPos > argc - 3) {
  17220. Jim_SetResultString(interp, "\"%n$\" argument index out of range", -1);
  17221. return JIM_ERR;
  17222. }
  17223. else if (count > argc - 3) {
  17224. Jim_SetResultString(interp, "different numbers of variable names and "
  17225. "field specifiers", -1);
  17226. return JIM_ERR;
  17227. }
  17228. else if (count < argc - 3) {
  17229. Jim_SetResultString(interp, "variable is not assigned by any "
  17230. "conversion specifiers", -1);
  17231. return JIM_ERR;
  17232. }
  17233. }
  17234. listPtr = Jim_ScanString(interp, argv[1], argv[2], JIM_ERRMSG);
  17235. if (listPtr == 0)
  17236. return JIM_ERR;
  17237. if (argc > 3) {
  17238. int rc = JIM_OK;
  17239. int count = 0;
  17240. if (listPtr != 0 && listPtr != (Jim_Obj *)EOF) {
  17241. int len = Jim_ListLength(interp, listPtr);
  17242. if (len != 0) {
  17243. JimListGetElements(interp, listPtr, &outc, &outVec);
  17244. for (i = 0; i < outc; ++i) {
  17245. if (Jim_Length(outVec[i]) > 0) {
  17246. ++count;
  17247. if (Jim_SetVariable(interp, argv[3 + i], outVec[i]) != JIM_OK) {
  17248. rc = JIM_ERR;
  17249. }
  17250. }
  17251. }
  17252. }
  17253. Jim_FreeNewObj(interp, listPtr);
  17254. }
  17255. else {
  17256. count = -1;
  17257. }
  17258. if (rc == JIM_OK) {
  17259. Jim_SetResultInt(interp, count);
  17260. }
  17261. return rc;
  17262. }
  17263. else {
  17264. if (listPtr == (Jim_Obj *)EOF) {
  17265. Jim_SetResult(interp, Jim_NewListObj(interp, 0, 0));
  17266. return JIM_OK;
  17267. }
  17268. Jim_SetResult(interp, listPtr);
  17269. }
  17270. return JIM_OK;
  17271. }
  17272. static int Jim_ErrorCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  17273. {
  17274. if (argc != 2 && argc != 3) {
  17275. Jim_WrongNumArgs(interp, 1, argv, "message ?stacktrace?");
  17276. return JIM_ERR;
  17277. }
  17278. Jim_SetResult(interp, argv[1]);
  17279. if (argc == 3) {
  17280. JimSetStackTrace(interp, argv[2]);
  17281. return JIM_ERR;
  17282. }
  17283. return JIM_ERR;
  17284. }
  17285. static int Jim_LrangeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  17286. {
  17287. Jim_Obj *objPtr;
  17288. if (argc != 4) {
  17289. Jim_WrongNumArgs(interp, 1, argv, "list first last");
  17290. return JIM_ERR;
  17291. }
  17292. if ((objPtr = Jim_ListRange(interp, argv[1], argv[2], argv[3])) == NULL)
  17293. return JIM_ERR;
  17294. Jim_SetResult(interp, objPtr);
  17295. return JIM_OK;
  17296. }
  17297. static int Jim_LrepeatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  17298. {
  17299. Jim_Obj *objPtr;
  17300. jim_wide count;
  17301. if (argc < 2 || Jim_GetWideExpr(interp, argv[1], &count) != JIM_OK || count < 0) {
  17302. Jim_WrongNumArgs(interp, 1, argv, "count ?value ...?");
  17303. return JIM_ERR;
  17304. }
  17305. if (count == 0 || argc == 2) {
  17306. Jim_SetEmptyResult(interp);
  17307. return JIM_OK;
  17308. }
  17309. argc -= 2;
  17310. argv += 2;
  17311. objPtr = Jim_NewListObj(interp, NULL, 0);
  17312. ListEnsureLength(objPtr, argc * count);
  17313. while (count--) {
  17314. ListInsertElements(objPtr, -1, argc, argv);
  17315. }
  17316. Jim_SetResult(interp, objPtr);
  17317. return JIM_OK;
  17318. }
  17319. char **Jim_GetEnviron(void)
  17320. {
  17321. #if defined(HAVE__NSGETENVIRON)
  17322. return *_NSGetEnviron();
  17323. #elif defined(_environ)
  17324. return _environ;
  17325. #else
  17326. #if !defined(NO_ENVIRON_EXTERN)
  17327. extern char **environ;
  17328. #endif
  17329. return environ;
  17330. #endif
  17331. }
  17332. void Jim_SetEnviron(char **env)
  17333. {
  17334. #if defined(HAVE__NSGETENVIRON)
  17335. *_NSGetEnviron() = env;
  17336. #elif defined(_environ)
  17337. _environ = env;
  17338. #else
  17339. #if !defined(NO_ENVIRON_EXTERN)
  17340. extern char **environ;
  17341. #endif
  17342. environ = env;
  17343. #endif
  17344. }
  17345. static int Jim_EnvCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  17346. {
  17347. const char *key;
  17348. const char *val;
  17349. if (argc == 1) {
  17350. char **e = Jim_GetEnviron();
  17351. int i;
  17352. Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
  17353. for (i = 0; e[i]; i++) {
  17354. const char *equals = strchr(e[i], '=');
  17355. if (equals) {
  17356. Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, e[i],
  17357. equals - e[i]));
  17358. Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, equals + 1, -1));
  17359. }
  17360. }
  17361. Jim_SetResult(interp, listObjPtr);
  17362. return JIM_OK;
  17363. }
  17364. if (argc > 3) {
  17365. Jim_WrongNumArgs(interp, 1, argv, "varName ?default?");
  17366. return JIM_ERR;
  17367. }
  17368. key = Jim_String(argv[1]);
  17369. val = getenv(key);
  17370. if (val == NULL) {
  17371. if (argc < 3) {
  17372. Jim_SetResultFormatted(interp, "environment variable \"%#s\" does not exist", argv[1]);
  17373. return JIM_ERR;
  17374. }
  17375. val = Jim_String(argv[2]);
  17376. }
  17377. Jim_SetResult(interp, Jim_NewStringObj(interp, val, -1));
  17378. return JIM_OK;
  17379. }
  17380. static int Jim_SourceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  17381. {
  17382. int retval;
  17383. if (argc != 2) {
  17384. Jim_WrongNumArgs(interp, 1, argv, "fileName");
  17385. return JIM_ERR;
  17386. }
  17387. retval = Jim_EvalFile(interp, Jim_String(argv[1]));
  17388. if (retval == JIM_RETURN)
  17389. return JIM_OK;
  17390. return retval;
  17391. }
  17392. static int Jim_LreverseCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  17393. {
  17394. Jim_Obj *revObjPtr, **ele;
  17395. int len;
  17396. if (argc != 2) {
  17397. Jim_WrongNumArgs(interp, 1, argv, "list");
  17398. return JIM_ERR;
  17399. }
  17400. JimListGetElements(interp, argv[1], &len, &ele);
  17401. revObjPtr = Jim_NewListObj(interp, NULL, 0);
  17402. ListEnsureLength(revObjPtr, len);
  17403. len--;
  17404. while (len >= 0)
  17405. ListAppendElement(revObjPtr, ele[len--]);
  17406. Jim_SetResult(interp, revObjPtr);
  17407. return JIM_OK;
  17408. }
  17409. static int JimRangeLen(jim_wide start, jim_wide end, jim_wide step)
  17410. {
  17411. jim_wide len;
  17412. if (step == 0)
  17413. return -1;
  17414. if (start == end)
  17415. return 0;
  17416. else if (step > 0 && start > end)
  17417. return -1;
  17418. else if (step < 0 && end > start)
  17419. return -1;
  17420. len = end - start;
  17421. if (len < 0)
  17422. len = -len;
  17423. if (step < 0)
  17424. step = -step;
  17425. len = 1 + ((len - 1) / step);
  17426. if (len > INT_MAX)
  17427. len = INT_MAX;
  17428. return (int)((len < 0) ? -1 : len);
  17429. }
  17430. static int Jim_RangeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  17431. {
  17432. jim_wide start = 0, end, step = 1;
  17433. int len, i;
  17434. Jim_Obj *objPtr;
  17435. if (argc < 2 || argc > 4) {
  17436. Jim_WrongNumArgs(interp, 1, argv, "?start? end ?step?");
  17437. return JIM_ERR;
  17438. }
  17439. if (argc == 2) {
  17440. if (Jim_GetWideExpr(interp, argv[1], &end) != JIM_OK)
  17441. return JIM_ERR;
  17442. }
  17443. else {
  17444. if (Jim_GetWideExpr(interp, argv[1], &start) != JIM_OK ||
  17445. Jim_GetWideExpr(interp, argv[2], &end) != JIM_OK)
  17446. return JIM_ERR;
  17447. if (argc == 4 && Jim_GetWideExpr(interp, argv[3], &step) != JIM_OK)
  17448. return JIM_ERR;
  17449. }
  17450. if ((len = JimRangeLen(start, end, step)) == -1) {
  17451. Jim_SetResultString(interp, "Invalid (infinite?) range specified", -1);
  17452. return JIM_ERR;
  17453. }
  17454. objPtr = Jim_NewListObj(interp, NULL, 0);
  17455. ListEnsureLength(objPtr, len);
  17456. for (i = 0; i < len; i++)
  17457. ListAppendElement(objPtr, Jim_NewIntObj(interp, start + i * step));
  17458. Jim_SetResult(interp, objPtr);
  17459. return JIM_OK;
  17460. }
  17461. static int Jim_RandCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  17462. {
  17463. jim_wide min = 0, max = 0, len, maxMul;
  17464. if (argc < 1 || argc > 3) {
  17465. Jim_WrongNumArgs(interp, 1, argv, "?min? max");
  17466. return JIM_ERR;
  17467. }
  17468. if (argc == 1) {
  17469. max = JIM_WIDE_MAX;
  17470. } else if (argc == 2) {
  17471. if (Jim_GetWideExpr(interp, argv[1], &max) != JIM_OK)
  17472. return JIM_ERR;
  17473. } else if (argc == 3) {
  17474. if (Jim_GetWideExpr(interp, argv[1], &min) != JIM_OK ||
  17475. Jim_GetWideExpr(interp, argv[2], &max) != JIM_OK)
  17476. return JIM_ERR;
  17477. }
  17478. len = max-min;
  17479. if (len < 0) {
  17480. Jim_SetResultString(interp, "Invalid arguments (max < min)", -1);
  17481. return JIM_ERR;
  17482. }
  17483. maxMul = JIM_WIDE_MAX - (len ? (JIM_WIDE_MAX%len) : 0);
  17484. while (1) {
  17485. jim_wide r;
  17486. JimRandomBytes(interp, &r, sizeof(jim_wide));
  17487. if (r < 0 || r >= maxMul) continue;
  17488. r = (len == 0) ? 0 : r%len;
  17489. Jim_SetResultInt(interp, min+r);
  17490. return JIM_OK;
  17491. }
  17492. }
  17493. static const struct {
  17494. const char *name;
  17495. Jim_CmdProc *cmdProc;
  17496. } Jim_CoreCommandsTable[] = {
  17497. {"alias", Jim_AliasCoreCommand},
  17498. {"set", Jim_SetCoreCommand},
  17499. {"unset", Jim_UnsetCoreCommand},
  17500. {"puts", Jim_PutsCoreCommand},
  17501. {"+", Jim_AddCoreCommand},
  17502. {"*", Jim_MulCoreCommand},
  17503. {"-", Jim_SubCoreCommand},
  17504. {"/", Jim_DivCoreCommand},
  17505. {"incr", Jim_IncrCoreCommand},
  17506. {"while", Jim_WhileCoreCommand},
  17507. {"loop", Jim_LoopCoreCommand},
  17508. {"for", Jim_ForCoreCommand},
  17509. {"foreach", Jim_ForeachCoreCommand},
  17510. {"lmap", Jim_LmapCoreCommand},
  17511. {"lassign", Jim_LassignCoreCommand},
  17512. {"if", Jim_IfCoreCommand},
  17513. {"switch", Jim_SwitchCoreCommand},
  17514. {"list", Jim_ListCoreCommand},
  17515. {"lindex", Jim_LindexCoreCommand},
  17516. {"lset", Jim_LsetCoreCommand},
  17517. {"lsearch", Jim_LsearchCoreCommand},
  17518. {"llength", Jim_LlengthCoreCommand},
  17519. {"lappend", Jim_LappendCoreCommand},
  17520. {"linsert", Jim_LinsertCoreCommand},
  17521. {"lreplace", Jim_LreplaceCoreCommand},
  17522. {"lsort", Jim_LsortCoreCommand},
  17523. {"append", Jim_AppendCoreCommand},
  17524. {"eval", Jim_EvalCoreCommand},
  17525. {"uplevel", Jim_UplevelCoreCommand},
  17526. {"expr", Jim_ExprCoreCommand},
  17527. {"break", Jim_BreakCoreCommand},
  17528. {"continue", Jim_ContinueCoreCommand},
  17529. {"proc", Jim_ProcCoreCommand},
  17530. {"xtrace", Jim_XtraceCoreCommand},
  17531. {"concat", Jim_ConcatCoreCommand},
  17532. {"return", Jim_ReturnCoreCommand},
  17533. {"upvar", Jim_UpvarCoreCommand},
  17534. {"global", Jim_GlobalCoreCommand},
  17535. {"string", Jim_StringCoreCommand},
  17536. {"time", Jim_TimeCoreCommand},
  17537. {"timerate", Jim_TimeRateCoreCommand},
  17538. {"exit", Jim_ExitCoreCommand},
  17539. {"catch", Jim_CatchCoreCommand},
  17540. {"try", Jim_TryCoreCommand},
  17541. #ifdef JIM_REFERENCES
  17542. {"ref", Jim_RefCoreCommand},
  17543. {"getref", Jim_GetrefCoreCommand},
  17544. {"setref", Jim_SetrefCoreCommand},
  17545. {"finalize", Jim_FinalizeCoreCommand},
  17546. {"collect", Jim_CollectCoreCommand},
  17547. #endif
  17548. {"rename", Jim_RenameCoreCommand},
  17549. {"dict", Jim_DictCoreCommand},
  17550. {"subst", Jim_SubstCoreCommand},
  17551. {"info", Jim_InfoCoreCommand},
  17552. {"exists", Jim_ExistsCoreCommand},
  17553. {"split", Jim_SplitCoreCommand},
  17554. {"join", Jim_JoinCoreCommand},
  17555. {"format", Jim_FormatCoreCommand},
  17556. {"scan", Jim_ScanCoreCommand},
  17557. {"error", Jim_ErrorCoreCommand},
  17558. {"lrange", Jim_LrangeCoreCommand},
  17559. {"lrepeat", Jim_LrepeatCoreCommand},
  17560. {"env", Jim_EnvCoreCommand},
  17561. {"source", Jim_SourceCoreCommand},
  17562. {"lreverse", Jim_LreverseCoreCommand},
  17563. {"range", Jim_RangeCoreCommand},
  17564. {"rand", Jim_RandCoreCommand},
  17565. {"tailcall", Jim_TailcallCoreCommand},
  17566. {"local", Jim_LocalCoreCommand},
  17567. {"upcall", Jim_UpcallCoreCommand},
  17568. {"apply", Jim_ApplyCoreCommand},
  17569. {"stacktrace", Jim_StacktraceCoreCommand},
  17570. {NULL, NULL},
  17571. };
  17572. void Jim_RegisterCoreCommands(Jim_Interp *interp)
  17573. {
  17574. int i = 0;
  17575. while (Jim_CoreCommandsTable[i].name != NULL) {
  17576. Jim_CreateCommand(interp,
  17577. Jim_CoreCommandsTable[i].name, Jim_CoreCommandsTable[i].cmdProc, NULL, NULL);
  17578. i++;
  17579. }
  17580. }
  17581. void Jim_MakeErrorMessage(Jim_Interp *interp)
  17582. {
  17583. Jim_Obj *argv[2];
  17584. argv[0] = Jim_NewStringObj(interp, "errorInfo", -1);
  17585. argv[1] = interp->result;
  17586. Jim_EvalObjVector(interp, 2, argv);
  17587. }
  17588. static char **JimSortStringTable(const char *const *tablePtr)
  17589. {
  17590. int count;
  17591. char **tablePtrSorted;
  17592. for (count = 0; tablePtr[count]; count++) {
  17593. }
  17594. tablePtrSorted = Jim_Alloc(sizeof(char *) * (count + 1));
  17595. memcpy(tablePtrSorted, tablePtr, sizeof(char *) * count);
  17596. qsort(tablePtrSorted, count, sizeof(char *), qsortCompareStringPointers);
  17597. tablePtrSorted[count] = NULL;
  17598. return tablePtrSorted;
  17599. }
  17600. static void JimSetFailedEnumResult(Jim_Interp *interp, const char *arg, const char *badtype,
  17601. const char *prefix, const char *const *tablePtr, const char *name)
  17602. {
  17603. char **tablePtrSorted;
  17604. int i;
  17605. if (name == NULL) {
  17606. name = "option";
  17607. }
  17608. Jim_SetResultFormatted(interp, "%s%s \"%s\": must be ", badtype, name, arg);
  17609. tablePtrSorted = JimSortStringTable(tablePtr);
  17610. for (i = 0; tablePtrSorted[i]; i++) {
  17611. if (tablePtrSorted[i + 1] == NULL && i > 0) {
  17612. Jim_AppendString(interp, Jim_GetResult(interp), "or ", -1);
  17613. }
  17614. Jim_AppendStrings(interp, Jim_GetResult(interp), prefix, tablePtrSorted[i], NULL);
  17615. if (tablePtrSorted[i + 1]) {
  17616. Jim_AppendString(interp, Jim_GetResult(interp), ", ", -1);
  17617. }
  17618. }
  17619. Jim_Free(tablePtrSorted);
  17620. }
  17621. int Jim_CheckShowCommands(Jim_Interp *interp, Jim_Obj *objPtr, const char *const *tablePtr)
  17622. {
  17623. if (Jim_CompareStringImmediate(interp, objPtr, "-commands")) {
  17624. int i;
  17625. char **tablePtrSorted = JimSortStringTable(tablePtr);
  17626. Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
  17627. for (i = 0; tablePtrSorted[i]; i++) {
  17628. Jim_ListAppendElement(interp, Jim_GetResult(interp), Jim_NewStringObj(interp, tablePtrSorted[i], -1));
  17629. }
  17630. Jim_Free(tablePtrSorted);
  17631. return JIM_OK;
  17632. }
  17633. return JIM_ERR;
  17634. }
  17635. static const Jim_ObjType getEnumObjType = {
  17636. "get-enum",
  17637. NULL,
  17638. NULL,
  17639. NULL,
  17640. JIM_TYPE_REFERENCES
  17641. };
  17642. int Jim_GetEnum(Jim_Interp *interp, Jim_Obj *objPtr,
  17643. const char *const *tablePtr, int *indexPtr, const char *name, int flags)
  17644. {
  17645. const char *bad = "bad ";
  17646. const char *const *entryPtr = NULL;
  17647. int i;
  17648. int match = -1;
  17649. int arglen;
  17650. const char *arg;
  17651. if (objPtr->typePtr == &getEnumObjType) {
  17652. if (objPtr->internalRep.ptrIntValue.ptr == tablePtr && objPtr->internalRep.ptrIntValue.int1 == flags) {
  17653. *indexPtr = objPtr->internalRep.ptrIntValue.int2;
  17654. return JIM_OK;
  17655. }
  17656. }
  17657. arg = Jim_GetString(objPtr, &arglen);
  17658. *indexPtr = -1;
  17659. for (entryPtr = tablePtr, i = 0; *entryPtr != NULL; entryPtr++, i++) {
  17660. if (Jim_CompareStringImmediate(interp, objPtr, *entryPtr)) {
  17661. match = i;
  17662. goto found;
  17663. }
  17664. if (flags & JIM_ENUM_ABBREV) {
  17665. if (strncmp(arg, *entryPtr, arglen) == 0) {
  17666. if (*arg == '-' && arglen == 1) {
  17667. break;
  17668. }
  17669. if (match >= 0) {
  17670. bad = "ambiguous ";
  17671. goto ambiguous;
  17672. }
  17673. match = i;
  17674. }
  17675. }
  17676. }
  17677. if (match >= 0) {
  17678. found:
  17679. Jim_FreeIntRep(interp, objPtr);
  17680. objPtr->typePtr = &getEnumObjType;
  17681. objPtr->internalRep.ptrIntValue.ptr = (void *)tablePtr;
  17682. objPtr->internalRep.ptrIntValue.int1 = flags;
  17683. objPtr->internalRep.ptrIntValue.int2 = match;
  17684. *indexPtr = match;
  17685. return JIM_OK;
  17686. }
  17687. ambiguous:
  17688. if (flags & JIM_ERRMSG) {
  17689. JimSetFailedEnumResult(interp, arg, bad, "", tablePtr, name);
  17690. }
  17691. return JIM_ERR;
  17692. }
  17693. int Jim_FindByName(const char *name, const char * const array[], size_t len)
  17694. {
  17695. int i;
  17696. for (i = 0; i < (int)len; i++) {
  17697. if (array[i] && strcmp(array[i], name) == 0) {
  17698. return i;
  17699. }
  17700. }
  17701. return -1;
  17702. }
  17703. int Jim_IsDict(Jim_Obj *objPtr)
  17704. {
  17705. return objPtr->typePtr == &dictObjType;
  17706. }
  17707. int Jim_IsList(Jim_Obj *objPtr)
  17708. {
  17709. return objPtr->typePtr == &listObjType;
  17710. }
  17711. void Jim_SetResultFormatted(Jim_Interp *interp, const char *format, ...)
  17712. {
  17713. int len = strlen(format);
  17714. int extra = 0;
  17715. int n = 0;
  17716. const char *params[5];
  17717. int nobjparam = 0;
  17718. Jim_Obj *objparam[5];
  17719. char *buf;
  17720. va_list args;
  17721. int i;
  17722. va_start(args, format);
  17723. for (i = 0; i < len && n < 5; i++) {
  17724. int l;
  17725. if (strncmp(format + i, "%s", 2) == 0) {
  17726. params[n] = va_arg(args, char *);
  17727. l = strlen(params[n]);
  17728. }
  17729. else if (strncmp(format + i, "%#s", 3) == 0) {
  17730. Jim_Obj *objPtr = va_arg(args, Jim_Obj *);
  17731. params[n] = Jim_GetString(objPtr, &l);
  17732. objparam[nobjparam++] = objPtr;
  17733. Jim_IncrRefCount(objPtr);
  17734. }
  17735. else {
  17736. if (format[i] == '%') {
  17737. i++;
  17738. }
  17739. continue;
  17740. }
  17741. n++;
  17742. extra += l;
  17743. }
  17744. len += extra;
  17745. buf = Jim_Alloc(len + 1);
  17746. len = snprintf(buf, len + 1, format, params[0], params[1], params[2], params[3], params[4]);
  17747. va_end(args);
  17748. Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, buf, len));
  17749. for (i = 0; i < nobjparam; i++) {
  17750. Jim_DecrRefCount(interp, objparam[i]);
  17751. }
  17752. }
  17753. int Jim_CheckAbiVersion(Jim_Interp *interp, int abi_version)
  17754. {
  17755. if (abi_version != JIM_ABI_VERSION) {
  17756. Jim_SetResultString(interp, "ABI version mismatch", -1);
  17757. return JIM_ERR;
  17758. }
  17759. return JIM_OK;
  17760. }
  17761. #ifndef jim_ext_package
  17762. int Jim_PackageProvide(Jim_Interp *interp, const char *name, const char *ver, int flags)
  17763. {
  17764. return JIM_OK;
  17765. }
  17766. #endif
  17767. #ifndef jim_ext_aio
  17768. int Jim_AioFilehandle(Jim_Interp *interp, Jim_Obj *fhObj)
  17769. {
  17770. return -1;
  17771. }
  17772. #endif
  17773. #include <stdio.h>
  17774. #include <string.h>
  17775. static int subcmd_null(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  17776. {
  17777. return JIM_OK;
  17778. }
  17779. static const jim_subcmd_type dummy_subcmd = {
  17780. "dummy", NULL, subcmd_null, 0, 0, JIM_MODFLAG_HIDDEN
  17781. };
  17782. static Jim_Obj *subcmd_cmd_list(Jim_Interp *interp, const jim_subcmd_type * ct, const char *sep)
  17783. {
  17784. Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
  17785. Jim_Obj *sortCmd[2];
  17786. for (; ct->cmd; ct++) {
  17787. if (!(ct->flags & JIM_MODFLAG_HIDDEN)) {
  17788. Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, ct->cmd, -1));
  17789. }
  17790. }
  17791. sortCmd[0] = Jim_NewStringObj(interp, "lsort", -1);
  17792. sortCmd[1] = listObj;
  17793. if (Jim_EvalObjVector(interp, 2, sortCmd) == JIM_OK) {
  17794. return Jim_ListJoin(interp, Jim_GetResult(interp), sep, strlen(sep));
  17795. }
  17796. return Jim_GetResult(interp);
  17797. }
  17798. static void bad_subcmd(Jim_Interp *interp, const jim_subcmd_type * command_table, const char *type,
  17799. Jim_Obj *cmd, Jim_Obj *subcmd)
  17800. {
  17801. Jim_SetResultFormatted(interp, "%#s, %s command \"%#s\": should be %#s", cmd, type,
  17802. subcmd, subcmd_cmd_list(interp, command_table, ", "));
  17803. }
  17804. static void show_cmd_usage(Jim_Interp *interp, const jim_subcmd_type * command_table, int argc,
  17805. Jim_Obj *const *argv)
  17806. {
  17807. Jim_SetResultFormatted(interp, "Usage: \"%#s command ... \", where command is one of: %#s",
  17808. argv[0], subcmd_cmd_list(interp, command_table, ", "));
  17809. }
  17810. static void add_cmd_usage(Jim_Interp *interp, const jim_subcmd_type * ct, Jim_Obj *cmd)
  17811. {
  17812. if (cmd) {
  17813. Jim_AppendStrings(interp, Jim_GetResult(interp), Jim_String(cmd), " ", NULL);
  17814. }
  17815. Jim_AppendStrings(interp, Jim_GetResult(interp), ct->cmd, NULL);
  17816. if (ct->args && *ct->args) {
  17817. Jim_AppendStrings(interp, Jim_GetResult(interp), " ", ct->args, NULL);
  17818. }
  17819. }
  17820. void Jim_SubCmdArgError(Jim_Interp *interp, const jim_subcmd_type * ct, Jim_Obj *subcmd)
  17821. {
  17822. Jim_SetResultString(interp, "wrong # args: should be \"", -1);
  17823. add_cmd_usage(interp, ct, subcmd);
  17824. Jim_AppendStrings(interp, Jim_GetResult(interp), "\"", NULL);
  17825. }
  17826. static const Jim_ObjType subcmdLookupObjType = {
  17827. "subcmd-lookup",
  17828. NULL,
  17829. NULL,
  17830. NULL,
  17831. JIM_TYPE_REFERENCES
  17832. };
  17833. const jim_subcmd_type *Jim_ParseSubCmd(Jim_Interp *interp, const jim_subcmd_type * command_table,
  17834. int argc, Jim_Obj *const *argv)
  17835. {
  17836. const jim_subcmd_type *ct;
  17837. const jim_subcmd_type *partial = 0;
  17838. int cmdlen;
  17839. Jim_Obj *cmd;
  17840. const char *cmdstr;
  17841. int help = 0;
  17842. int argsok = 1;
  17843. if (argc < 2) {
  17844. Jim_SetResultFormatted(interp, "wrong # args: should be \"%#s command ...\"\n"
  17845. "Use \"%#s -help ?command?\" for help", argv[0], argv[0]);
  17846. return 0;
  17847. }
  17848. cmd = argv[1];
  17849. if (cmd->typePtr == &subcmdLookupObjType) {
  17850. if (cmd->internalRep.ptrIntValue.ptr == command_table) {
  17851. ct = command_table + cmd->internalRep.ptrIntValue.int1;
  17852. goto found;
  17853. }
  17854. }
  17855. if (Jim_CompareStringImmediate(interp, cmd, "-help")) {
  17856. if (argc == 2) {
  17857. show_cmd_usage(interp, command_table, argc, argv);
  17858. return &dummy_subcmd;
  17859. }
  17860. help = 1;
  17861. cmd = argv[2];
  17862. }
  17863. if (Jim_CompareStringImmediate(interp, cmd, "-commands")) {
  17864. Jim_SetResult(interp, subcmd_cmd_list(interp, command_table, " "));
  17865. return &dummy_subcmd;
  17866. }
  17867. cmdstr = Jim_GetString(cmd, &cmdlen);
  17868. for (ct = command_table; ct->cmd; ct++) {
  17869. if (Jim_CompareStringImmediate(interp, cmd, ct->cmd)) {
  17870. break;
  17871. }
  17872. if (strncmp(cmdstr, ct->cmd, cmdlen) == 0) {
  17873. if (partial) {
  17874. if (help) {
  17875. show_cmd_usage(interp, command_table, argc, argv);
  17876. return &dummy_subcmd;
  17877. }
  17878. bad_subcmd(interp, command_table, "ambiguous", argv[0], argv[1 + help]);
  17879. return 0;
  17880. }
  17881. partial = ct;
  17882. }
  17883. continue;
  17884. }
  17885. if (partial && !ct->cmd) {
  17886. ct = partial;
  17887. }
  17888. if (!ct->cmd) {
  17889. if (help) {
  17890. show_cmd_usage(interp, command_table, argc, argv);
  17891. return &dummy_subcmd;
  17892. }
  17893. bad_subcmd(interp, command_table, "unknown", argv[0], argv[1 + help]);
  17894. return 0;
  17895. }
  17896. if (help) {
  17897. Jim_SetResultString(interp, "Usage: ", -1);
  17898. add_cmd_usage(interp, ct, argv[0]);
  17899. return &dummy_subcmd;
  17900. }
  17901. Jim_FreeIntRep(interp, cmd);
  17902. cmd->typePtr = &subcmdLookupObjType;
  17903. cmd->internalRep.ptrIntValue.ptr = (void *)command_table;
  17904. cmd->internalRep.ptrIntValue.int1 = ct - command_table;
  17905. found:
  17906. if (argc - 2 < ct->minargs) {
  17907. argsok = 0;
  17908. }
  17909. else if (ct->maxargs >= 0 && argc - 2 > ct->maxargs) {
  17910. argsok = 0;
  17911. }
  17912. else if (ct->maxargs < -1 && (argc - 2) % -ct->maxargs != 0) {
  17913. argsok = 0;
  17914. }
  17915. if (!argsok) {
  17916. Jim_SetResultString(interp, "wrong # args: should be \"", -1);
  17917. add_cmd_usage(interp, ct, argv[0]);
  17918. Jim_AppendStrings(interp, Jim_GetResult(interp), "\"", NULL);
  17919. return 0;
  17920. }
  17921. return ct;
  17922. }
  17923. int Jim_CallSubCmd(Jim_Interp *interp, const jim_subcmd_type * ct, int argc, Jim_Obj *const *argv)
  17924. {
  17925. int ret = JIM_ERR;
  17926. if (ct) {
  17927. if (ct->flags & JIM_MODFLAG_FULLARGV) {
  17928. ret = ct->function(interp, argc, argv);
  17929. }
  17930. else {
  17931. ret = ct->function(interp, argc - 2, argv + 2);
  17932. }
  17933. if (ret < 0) {
  17934. Jim_SubCmdArgError(interp, ct, argv[0]);
  17935. ret = JIM_ERR;
  17936. }
  17937. }
  17938. return ret;
  17939. }
  17940. int Jim_SubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
  17941. {
  17942. const jim_subcmd_type *ct =
  17943. Jim_ParseSubCmd(interp, (const jim_subcmd_type *)Jim_CmdPrivData(interp), argc, argv);
  17944. return Jim_CallSubCmd(interp, ct, argc, argv);
  17945. }
  17946. #include <ctype.h>
  17947. #include <stdlib.h>
  17948. #include <string.h>
  17949. #include <stdio.h>
  17950. #include <assert.h>
  17951. int utf8_fromunicode(char *p, unsigned uc)
  17952. {
  17953. if (uc <= 0x7f) {
  17954. *p = uc;
  17955. return 1;
  17956. }
  17957. else if (uc <= 0x7ff) {
  17958. *p++ = 0xc0 | ((uc & 0x7c0) >> 6);
  17959. *p = 0x80 | (uc & 0x3f);
  17960. return 2;
  17961. }
  17962. else if (uc <= 0xffff) {
  17963. *p++ = 0xe0 | ((uc & 0xf000) >> 12);
  17964. *p++ = 0x80 | ((uc & 0xfc0) >> 6);
  17965. *p = 0x80 | (uc & 0x3f);
  17966. return 3;
  17967. }
  17968. else {
  17969. *p++ = 0xf0 | ((uc & 0x1c0000) >> 18);
  17970. *p++ = 0x80 | ((uc & 0x3f000) >> 12);
  17971. *p++ = 0x80 | ((uc & 0xfc0) >> 6);
  17972. *p = 0x80 | (uc & 0x3f);
  17973. return 4;
  17974. }
  17975. }
  17976. #include <ctype.h>
  17977. #include <string.h>
  17978. #include <stdio.h>
  17979. #define JIM_INTEGER_SPACE 24
  17980. #define MAX_FLOAT_WIDTH 320
  17981. Jim_Obj *Jim_FormatString(Jim_Interp *interp, Jim_Obj *fmtObjPtr, int objc, Jim_Obj *const *objv)
  17982. {
  17983. const char *span, *format, *formatEnd, *msg;
  17984. int numBytes = 0, objIndex = 0, gotXpg = 0, gotSequential = 0;
  17985. static const char * const mixedXPG =
  17986. "cannot mix \"%\" and \"%n$\" conversion specifiers";
  17987. static const char * const badIndex[2] = {
  17988. "not enough arguments for all format specifiers",
  17989. "\"%n$\" argument index out of range"
  17990. };
  17991. int formatLen;
  17992. Jim_Obj *resultPtr;
  17993. char *num_buffer = NULL;
  17994. int num_buffer_size = 0;
  17995. span = format = Jim_GetString(fmtObjPtr, &formatLen);
  17996. formatEnd = format + formatLen;
  17997. resultPtr = Jim_NewEmptyStringObj(interp);
  17998. while (format != formatEnd) {
  17999. char *end;
  18000. int gotMinus, sawFlag;
  18001. int gotPrecision, useShort;
  18002. long width, precision;
  18003. int newXpg;
  18004. int ch;
  18005. int step;
  18006. int doubleType;
  18007. char pad = ' ';
  18008. char spec[2*JIM_INTEGER_SPACE + 12];
  18009. char *p;
  18010. int formatted_chars;
  18011. int formatted_bytes;
  18012. const char *formatted_buf;
  18013. step = utf8_tounicode(format, &ch);
  18014. format += step;
  18015. if (ch != '%') {
  18016. numBytes += step;
  18017. continue;
  18018. }
  18019. if (numBytes) {
  18020. Jim_AppendString(interp, resultPtr, span, numBytes);
  18021. numBytes = 0;
  18022. }
  18023. step = utf8_tounicode(format, &ch);
  18024. if (ch == '%') {
  18025. span = format;
  18026. numBytes = step;
  18027. format += step;
  18028. continue;
  18029. }
  18030. newXpg = 0;
  18031. if (isdigit(ch)) {
  18032. int position = strtoul(format, &end, 10);
  18033. if (*end == '$') {
  18034. newXpg = 1;
  18035. objIndex = position - 1;
  18036. format = end + 1;
  18037. step = utf8_tounicode(format, &ch);
  18038. }
  18039. }
  18040. if (newXpg) {
  18041. if (gotSequential) {
  18042. msg = mixedXPG;
  18043. goto errorMsg;
  18044. }
  18045. gotXpg = 1;
  18046. } else {
  18047. if (gotXpg) {
  18048. msg = mixedXPG;
  18049. goto errorMsg;
  18050. }
  18051. gotSequential = 1;
  18052. }
  18053. if ((objIndex < 0) || (objIndex >= objc)) {
  18054. msg = badIndex[gotXpg];
  18055. goto errorMsg;
  18056. }
  18057. p = spec;
  18058. *p++ = '%';
  18059. gotMinus = 0;
  18060. sawFlag = 1;
  18061. do {
  18062. switch (ch) {
  18063. case '-':
  18064. gotMinus = 1;
  18065. break;
  18066. case '0':
  18067. pad = ch;
  18068. break;
  18069. case ' ':
  18070. case '+':
  18071. case '#':
  18072. break;
  18073. default:
  18074. sawFlag = 0;
  18075. continue;
  18076. }
  18077. *p++ = ch;
  18078. format += step;
  18079. step = utf8_tounicode(format, &ch);
  18080. } while (sawFlag && (p - spec <= 5));
  18081. width = 0;
  18082. if (isdigit(ch)) {
  18083. width = strtoul(format, &end, 10);
  18084. format = end;
  18085. step = utf8_tounicode(format, &ch);
  18086. } else if (ch == '*') {
  18087. if (objIndex >= objc - 1) {
  18088. msg = badIndex[gotXpg];
  18089. goto errorMsg;
  18090. }
  18091. if (Jim_GetLong(interp, objv[objIndex], &width) != JIM_OK) {
  18092. goto error;
  18093. }
  18094. if (width < 0) {
  18095. width = -width;
  18096. if (!gotMinus) {
  18097. *p++ = '-';
  18098. gotMinus = 1;
  18099. }
  18100. }
  18101. objIndex++;
  18102. format += step;
  18103. step = utf8_tounicode(format, &ch);
  18104. }
  18105. gotPrecision = precision = 0;
  18106. if (ch == '.') {
  18107. gotPrecision = 1;
  18108. format += step;
  18109. step = utf8_tounicode(format, &ch);
  18110. }
  18111. if (isdigit(ch)) {
  18112. precision = strtoul(format, &end, 10);
  18113. format = end;
  18114. step = utf8_tounicode(format, &ch);
  18115. } else if (ch == '*') {
  18116. if (objIndex >= objc - 1) {
  18117. msg = badIndex[gotXpg];
  18118. goto errorMsg;
  18119. }
  18120. if (Jim_GetLong(interp, objv[objIndex], &precision) != JIM_OK) {
  18121. goto error;
  18122. }
  18123. if (precision < 0) {
  18124. precision = 0;
  18125. }
  18126. objIndex++;
  18127. format += step;
  18128. step = utf8_tounicode(format, &ch);
  18129. }
  18130. useShort = 0;
  18131. if (ch == 'h') {
  18132. useShort = 1;
  18133. format += step;
  18134. step = utf8_tounicode(format, &ch);
  18135. } else if (ch == 'l') {
  18136. format += step;
  18137. step = utf8_tounicode(format, &ch);
  18138. if (ch == 'l') {
  18139. format += step;
  18140. step = utf8_tounicode(format, &ch);
  18141. }
  18142. }
  18143. format += step;
  18144. span = format;
  18145. if (ch == 'i') {
  18146. ch = 'd';
  18147. }
  18148. doubleType = 0;
  18149. switch (ch) {
  18150. case '\0':
  18151. msg = "format string ended in middle of field specifier";
  18152. goto errorMsg;
  18153. case 's': {
  18154. formatted_buf = Jim_GetString(objv[objIndex], &formatted_bytes);
  18155. formatted_chars = Jim_Utf8Length(interp, objv[objIndex]);
  18156. if (gotPrecision && (precision < formatted_chars)) {
  18157. formatted_chars = precision;
  18158. formatted_bytes = utf8_index(formatted_buf, precision);
  18159. }
  18160. break;
  18161. }
  18162. case 'c': {
  18163. jim_wide code;
  18164. if (Jim_GetWide(interp, objv[objIndex], &code) != JIM_OK) {
  18165. goto error;
  18166. }
  18167. formatted_bytes = utf8_getchars(spec, code);
  18168. formatted_buf = spec;
  18169. formatted_chars = 1;
  18170. break;
  18171. }
  18172. case 'b': {
  18173. unsigned jim_wide w;
  18174. int length;
  18175. int i;
  18176. int j;
  18177. if (Jim_GetWide(interp, objv[objIndex], (jim_wide *)&w) != JIM_OK) {
  18178. goto error;
  18179. }
  18180. length = sizeof(w) * 8;
  18181. if (num_buffer_size < length + 1) {
  18182. num_buffer_size = length + 1;
  18183. num_buffer = Jim_Realloc(num_buffer, num_buffer_size);
  18184. }
  18185. j = 0;
  18186. for (i = length; i > 0; ) {
  18187. i--;
  18188. if (w & ((unsigned jim_wide)1 << i)) {
  18189. num_buffer[j++] = '1';
  18190. }
  18191. else if (j || i == 0) {
  18192. num_buffer[j++] = '0';
  18193. }
  18194. }
  18195. num_buffer[j] = 0;
  18196. formatted_chars = formatted_bytes = j;
  18197. formatted_buf = num_buffer;
  18198. break;
  18199. }
  18200. case 'e':
  18201. case 'E':
  18202. case 'f':
  18203. case 'g':
  18204. case 'G':
  18205. doubleType = 1;
  18206. case 'd':
  18207. case 'u':
  18208. case 'o':
  18209. case 'x':
  18210. case 'X': {
  18211. jim_wide w;
  18212. double d;
  18213. int length;
  18214. if (width) {
  18215. p += sprintf(p, "%ld", width);
  18216. }
  18217. if (gotPrecision) {
  18218. p += sprintf(p, ".%ld", precision);
  18219. }
  18220. if (doubleType) {
  18221. if (Jim_GetDouble(interp, objv[objIndex], &d) != JIM_OK) {
  18222. goto error;
  18223. }
  18224. length = MAX_FLOAT_WIDTH;
  18225. }
  18226. else {
  18227. if (Jim_GetWide(interp, objv[objIndex], &w) != JIM_OK) {
  18228. goto error;
  18229. }
  18230. length = JIM_INTEGER_SPACE;
  18231. if (useShort) {
  18232. if (ch == 'd') {
  18233. w = (short)w;
  18234. }
  18235. else {
  18236. w = (unsigned short)w;
  18237. }
  18238. }
  18239. *p++ = 'l';
  18240. #ifdef HAVE_LONG_LONG
  18241. if (sizeof(long long) == sizeof(jim_wide)) {
  18242. *p++ = 'l';
  18243. }
  18244. #endif
  18245. }
  18246. *p++ = (char) ch;
  18247. *p = '\0';
  18248. if (width > 10000 || length > 10000 || precision > 10000) {
  18249. Jim_SetResultString(interp, "format too long", -1);
  18250. goto error;
  18251. }
  18252. if (width > length) {
  18253. length = width;
  18254. }
  18255. if (gotPrecision) {
  18256. length += precision;
  18257. }
  18258. if (num_buffer_size < length + 1) {
  18259. num_buffer_size = length + 1;
  18260. num_buffer = Jim_Realloc(num_buffer, num_buffer_size);
  18261. }
  18262. if (doubleType) {
  18263. snprintf(num_buffer, length + 1, spec, d);
  18264. }
  18265. else {
  18266. formatted_bytes = snprintf(num_buffer, length + 1, spec, w);
  18267. }
  18268. formatted_chars = formatted_bytes = strlen(num_buffer);
  18269. formatted_buf = num_buffer;
  18270. break;
  18271. }
  18272. default: {
  18273. spec[0] = ch;
  18274. spec[1] = '\0';
  18275. Jim_SetResultFormatted(interp, "bad field specifier \"%s\"", spec);
  18276. goto error;
  18277. }
  18278. }
  18279. if (!gotMinus) {
  18280. while (formatted_chars < width) {
  18281. Jim_AppendString(interp, resultPtr, &pad, 1);
  18282. formatted_chars++;
  18283. }
  18284. }
  18285. Jim_AppendString(interp, resultPtr, formatted_buf, formatted_bytes);
  18286. while (formatted_chars < width) {
  18287. Jim_AppendString(interp, resultPtr, &pad, 1);
  18288. formatted_chars++;
  18289. }
  18290. objIndex += gotSequential;
  18291. }
  18292. if (numBytes) {
  18293. Jim_AppendString(interp, resultPtr, span, numBytes);
  18294. }
  18295. Jim_Free(num_buffer);
  18296. return resultPtr;
  18297. errorMsg:
  18298. Jim_SetResultString(interp, msg, -1);
  18299. error:
  18300. Jim_FreeNewObj(interp, resultPtr);
  18301. Jim_Free(num_buffer);
  18302. return NULL;
  18303. }
  18304. #if defined(JIM_REGEXP)
  18305. #include <stdio.h>
  18306. #include <ctype.h>
  18307. #include <stdlib.h>
  18308. #include <string.h>
  18309. #define REG_MAX_PAREN 100
  18310. #define END 0
  18311. #define BOL 1
  18312. #define EOL 2
  18313. #define ANY 3
  18314. #define ANYOF 4
  18315. #define ANYBUT 5
  18316. #define BRANCH 6
  18317. #define BACK 7
  18318. #define EXACTLY 8
  18319. #define NOTHING 9
  18320. #define REP 10
  18321. #define REPMIN 11
  18322. #define REPX 12
  18323. #define REPXMIN 13
  18324. #define BOLX 14
  18325. #define EOLX 15
  18326. #define WORDA 16
  18327. #define WORDZ 17
  18328. #define OPENNC 1000
  18329. #define OPEN 1001
  18330. #define CLOSENC 2000
  18331. #define CLOSE 2001
  18332. #define CLOSE_END (CLOSE+REG_MAX_PAREN)
  18333. #define REG_MAGIC 0xFADED00D
  18334. #define OP(preg, p) (preg->program[p])
  18335. #define NEXT(preg, p) (preg->program[p + 1])
  18336. #define OPERAND(p) ((p) + 2)
  18337. #define FAIL(R,M) { (R)->err = (M); return (M); }
  18338. #define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?' || (c) == '{')
  18339. #define META "^$.[()|?{+*"
  18340. #define HASWIDTH 1
  18341. #define SIMPLE 2
  18342. #define SPSTART 4
  18343. #define WORST 0
  18344. #define MAX_REP_COUNT 1000000
  18345. static int reg(regex_t *preg, int paren, int *flagp );
  18346. static int regpiece(regex_t *preg, int *flagp );
  18347. static int regbranch(regex_t *preg, int *flagp );
  18348. static int regatom(regex_t *preg, int *flagp );
  18349. static int regnode(regex_t *preg, int op );
  18350. static int regnext(regex_t *preg, int p );
  18351. static void regc(regex_t *preg, int b );
  18352. static int reginsert(regex_t *preg, int op, int size, int opnd );
  18353. static void regtail(regex_t *preg, int p, int val);
  18354. static void regoptail(regex_t *preg, int p, int val );
  18355. static int regopsize(regex_t *preg, int p );
  18356. static int reg_range_find(const int *string, int c);
  18357. static const char *str_find(const char *string, int c, int nocase);
  18358. static int prefix_cmp(const int *prog, int proglen, const char *string, int nocase);
  18359. #ifdef DEBUG
  18360. static int regnarrate = 0;
  18361. static void regdump(regex_t *preg);
  18362. static const char *regprop( int op );
  18363. #endif
  18364. static int str_int_len(const int *seq)
  18365. {
  18366. int n = 0;
  18367. while (*seq++) {
  18368. n++;
  18369. }
  18370. return n;
  18371. }
  18372. int jim_regcomp(regex_t *preg, const char *exp, int cflags)
  18373. {
  18374. int scan;
  18375. int longest;
  18376. unsigned len;
  18377. int flags;
  18378. #ifdef DEBUG
  18379. fprintf(stderr, "Compiling: '%s'\n", exp);
  18380. #endif
  18381. memset(preg, 0, sizeof(*preg));
  18382. if (exp == NULL)
  18383. FAIL(preg, REG_ERR_NULL_ARGUMENT);
  18384. preg->cflags = cflags;
  18385. preg->regparse = exp;
  18386. preg->proglen = (strlen(exp) + 1) * 5;
  18387. preg->program = malloc(preg->proglen * sizeof(int));
  18388. if (preg->program == NULL)
  18389. FAIL(preg, REG_ERR_NOMEM);
  18390. regc(preg, REG_MAGIC);
  18391. if (reg(preg, 0, &flags) == 0) {
  18392. return preg->err;
  18393. }
  18394. if (preg->re_nsub >= REG_MAX_PAREN)
  18395. FAIL(preg,REG_ERR_TOO_BIG);
  18396. preg->regstart = 0;
  18397. preg->reganch = 0;
  18398. preg->regmust = 0;
  18399. preg->regmlen = 0;
  18400. scan = 1;
  18401. if (OP(preg, regnext(preg, scan)) == END) {
  18402. scan = OPERAND(scan);
  18403. if (OP(preg, scan) == EXACTLY) {
  18404. preg->regstart = preg->program[OPERAND(scan)];
  18405. }
  18406. else if (OP(preg, scan) == BOL)
  18407. preg->reganch++;
  18408. if (flags&SPSTART) {
  18409. longest = 0;
  18410. len = 0;
  18411. for (; scan != 0; scan = regnext(preg, scan)) {
  18412. if (OP(preg, scan) == EXACTLY) {
  18413. int plen = str_int_len(preg->program + OPERAND(scan));
  18414. if (plen >= len) {
  18415. longest = OPERAND(scan);
  18416. len = plen;
  18417. }
  18418. }
  18419. }
  18420. preg->regmust = longest;
  18421. preg->regmlen = len;
  18422. }
  18423. }
  18424. #ifdef DEBUG
  18425. regdump(preg);
  18426. #endif
  18427. return 0;
  18428. }
  18429. static int reg(regex_t *preg, int paren, int *flagp )
  18430. {
  18431. int ret;
  18432. int br;
  18433. int ender;
  18434. int parno = 0;
  18435. int flags;
  18436. *flagp = HASWIDTH;
  18437. if (paren) {
  18438. if (preg->regparse[0] == '?' && preg->regparse[1] == ':') {
  18439. preg->regparse += 2;
  18440. parno = -1;
  18441. }
  18442. else {
  18443. parno = ++preg->re_nsub;
  18444. }
  18445. ret = regnode(preg, OPEN+parno);
  18446. } else
  18447. ret = 0;
  18448. br = regbranch(preg, &flags);
  18449. if (br == 0)
  18450. return 0;
  18451. if (ret != 0)
  18452. regtail(preg, ret, br);
  18453. else
  18454. ret = br;
  18455. if (!(flags&HASWIDTH))
  18456. *flagp &= ~HASWIDTH;
  18457. *flagp |= flags&SPSTART;
  18458. while (*preg->regparse == '|') {
  18459. preg->regparse++;
  18460. br = regbranch(preg, &flags);
  18461. if (br == 0)
  18462. return 0;
  18463. regtail(preg, ret, br);
  18464. if (!(flags&HASWIDTH))
  18465. *flagp &= ~HASWIDTH;
  18466. *flagp |= flags&SPSTART;
  18467. }
  18468. ender = regnode(preg, (paren) ? CLOSE+parno : END);
  18469. regtail(preg, ret, ender);
  18470. for (br = ret; br != 0; br = regnext(preg, br))
  18471. regoptail(preg, br, ender);
  18472. if (paren && *preg->regparse++ != ')') {
  18473. preg->err = REG_ERR_UNMATCHED_PAREN;
  18474. return 0;
  18475. } else if (!paren && *preg->regparse != '\0') {
  18476. if (*preg->regparse == ')') {
  18477. preg->err = REG_ERR_UNMATCHED_PAREN;
  18478. return 0;
  18479. } else {
  18480. preg->err = REG_ERR_JUNK_ON_END;
  18481. return 0;
  18482. }
  18483. }
  18484. return(ret);
  18485. }
  18486. static int regbranch(regex_t *preg, int *flagp )
  18487. {
  18488. int ret;
  18489. int chain;
  18490. int latest;
  18491. int flags;
  18492. *flagp = WORST;
  18493. ret = regnode(preg, BRANCH);
  18494. chain = 0;
  18495. while (*preg->regparse != '\0' && *preg->regparse != ')' &&
  18496. *preg->regparse != '|') {
  18497. latest = regpiece(preg, &flags);
  18498. if (latest == 0)
  18499. return 0;
  18500. *flagp |= flags&HASWIDTH;
  18501. if (chain == 0) {
  18502. *flagp |= flags&SPSTART;
  18503. }
  18504. else {
  18505. regtail(preg, chain, latest);
  18506. }
  18507. chain = latest;
  18508. }
  18509. if (chain == 0)
  18510. (void) regnode(preg, NOTHING);
  18511. return(ret);
  18512. }
  18513. static int regpiece(regex_t *preg, int *flagp)
  18514. {
  18515. int ret;
  18516. char op;
  18517. int next;
  18518. int flags;
  18519. int min;
  18520. int max;
  18521. ret = regatom(preg, &flags);
  18522. if (ret == 0)
  18523. return 0;
  18524. op = *preg->regparse;
  18525. if (!ISMULT(op)) {
  18526. *flagp = flags;
  18527. return(ret);
  18528. }
  18529. if (!(flags&HASWIDTH) && op != '?') {
  18530. preg->err = REG_ERR_OPERAND_COULD_BE_EMPTY;
  18531. return 0;
  18532. }
  18533. if (op == '{') {
  18534. char *end;
  18535. min = strtoul(preg->regparse + 1, &end, 10);
  18536. if (end == preg->regparse + 1) {
  18537. preg->err = REG_ERR_BAD_COUNT;
  18538. return 0;
  18539. }
  18540. if (*end == '}') {
  18541. max = min;
  18542. }
  18543. else if (*end == '\0') {
  18544. preg->err = REG_ERR_UNMATCHED_BRACES;
  18545. return 0;
  18546. }
  18547. else {
  18548. preg->regparse = end;
  18549. max = strtoul(preg->regparse + 1, &end, 10);
  18550. if (*end != '}') {
  18551. preg->err = REG_ERR_UNMATCHED_BRACES;
  18552. return 0;
  18553. }
  18554. }
  18555. if (end == preg->regparse + 1) {
  18556. max = MAX_REP_COUNT;
  18557. }
  18558. else if (max < min || max >= 100) {
  18559. preg->err = REG_ERR_BAD_COUNT;
  18560. return 0;
  18561. }
  18562. if (min >= 100) {
  18563. preg->err = REG_ERR_BAD_COUNT;
  18564. return 0;
  18565. }
  18566. preg->regparse = strchr(preg->regparse, '}');
  18567. }
  18568. else {
  18569. min = (op == '+');
  18570. max = (op == '?' ? 1 : MAX_REP_COUNT);
  18571. }
  18572. if (preg->regparse[1] == '?') {
  18573. preg->regparse++;
  18574. next = reginsert(preg, flags & SIMPLE ? REPMIN : REPXMIN, 5, ret);
  18575. }
  18576. else {
  18577. next = reginsert(preg, flags & SIMPLE ? REP: REPX, 5, ret);
  18578. }
  18579. preg->program[ret + 2] = max;
  18580. preg->program[ret + 3] = min;
  18581. preg->program[ret + 4] = 0;
  18582. *flagp = (min) ? (WORST|HASWIDTH) : (WORST|SPSTART);
  18583. if (!(flags & SIMPLE)) {
  18584. int back = regnode(preg, BACK);
  18585. regtail(preg, back, ret);
  18586. regtail(preg, next, back);
  18587. }
  18588. preg->regparse++;
  18589. if (ISMULT(*preg->regparse)) {
  18590. preg->err = REG_ERR_NESTED_COUNT;
  18591. return 0;
  18592. }
  18593. return ret;
  18594. }
  18595. static void reg_addrange(regex_t *preg, int lower, int upper)
  18596. {
  18597. if (lower > upper) {
  18598. reg_addrange(preg, upper, lower);
  18599. }
  18600. regc(preg, upper - lower + 1);
  18601. regc(preg, lower);
  18602. }
  18603. static void reg_addrange_str(regex_t *preg, const char *str)
  18604. {
  18605. while (*str) {
  18606. reg_addrange(preg, *str, *str);
  18607. str++;
  18608. }
  18609. }
  18610. static int reg_utf8_tounicode_case(const char *s, int *uc, int upper)
  18611. {
  18612. int l = utf8_tounicode(s, uc);
  18613. if (upper) {
  18614. *uc = utf8_upper(*uc);
  18615. }
  18616. return l;
  18617. }
  18618. static int hexdigitval(int c)
  18619. {
  18620. if (c >= '0' && c <= '9')
  18621. return c - '0';
  18622. if (c >= 'a' && c <= 'f')
  18623. return c - 'a' + 10;
  18624. if (c >= 'A' && c <= 'F')
  18625. return c - 'A' + 10;
  18626. return -1;
  18627. }
  18628. static int parse_hex(const char *s, int n, int *uc)
  18629. {
  18630. int val = 0;
  18631. int k;
  18632. for (k = 0; k < n; k++) {
  18633. int c = hexdigitval(*s++);
  18634. if (c == -1) {
  18635. break;
  18636. }
  18637. val = (val << 4) | c;
  18638. }
  18639. if (k) {
  18640. *uc = val;
  18641. }
  18642. return k;
  18643. }
  18644. static int reg_decode_escape(const char *s, int *ch)
  18645. {
  18646. int n;
  18647. const char *s0 = s;
  18648. *ch = *s++;
  18649. switch (*ch) {
  18650. case 'b': *ch = '\b'; break;
  18651. case 'e': *ch = 27; break;
  18652. case 'f': *ch = '\f'; break;
  18653. case 'n': *ch = '\n'; break;
  18654. case 'r': *ch = '\r'; break;
  18655. case 't': *ch = '\t'; break;
  18656. case 'v': *ch = '\v'; break;
  18657. case 'u':
  18658. if (*s == '{') {
  18659. n = parse_hex(s + 1, 6, ch);
  18660. if (n > 0 && s[n + 1] == '}' && *ch >= 0 && *ch <= 0x1fffff) {
  18661. s += n + 2;
  18662. }
  18663. else {
  18664. *ch = 'u';
  18665. }
  18666. }
  18667. else if ((n = parse_hex(s, 4, ch)) > 0) {
  18668. s += n;
  18669. }
  18670. break;
  18671. case 'U':
  18672. if ((n = parse_hex(s, 8, ch)) > 0) {
  18673. s += n;
  18674. }
  18675. break;
  18676. case 'x':
  18677. if ((n = parse_hex(s, 2, ch)) > 0) {
  18678. s += n;
  18679. }
  18680. break;
  18681. case '\0':
  18682. s--;
  18683. *ch = '\\';
  18684. break;
  18685. }
  18686. return s - s0;
  18687. }
  18688. static int regatom(regex_t *preg, int *flagp)
  18689. {
  18690. int ret;
  18691. int flags;
  18692. int nocase = (preg->cflags & REG_ICASE);
  18693. int ch;
  18694. int n = reg_utf8_tounicode_case(preg->regparse, &ch, nocase);
  18695. *flagp = WORST;
  18696. preg->regparse += n;
  18697. switch (ch) {
  18698. case '^':
  18699. ret = regnode(preg, BOL);
  18700. break;
  18701. case '$':
  18702. ret = regnode(preg, EOL);
  18703. break;
  18704. case '.':
  18705. ret = regnode(preg, ANY);
  18706. *flagp |= HASWIDTH|SIMPLE;
  18707. break;
  18708. case '[': {
  18709. const char *pattern = preg->regparse;
  18710. if (*pattern == '^') {
  18711. ret = regnode(preg, ANYBUT);
  18712. pattern++;
  18713. } else
  18714. ret = regnode(preg, ANYOF);
  18715. if (*pattern == ']' || *pattern == '-') {
  18716. reg_addrange(preg, *pattern, *pattern);
  18717. pattern++;
  18718. }
  18719. while (*pattern != ']') {
  18720. int start;
  18721. int end;
  18722. enum {
  18723. CC_ALPHA, CC_ALNUM, CC_SPACE, CC_BLANK, CC_UPPER, CC_LOWER,
  18724. CC_DIGIT, CC_XDIGIT, CC_CNTRL, CC_GRAPH, CC_PRINT, CC_PUNCT,
  18725. CC_NUM
  18726. };
  18727. int cc;
  18728. if (!*pattern) {
  18729. preg->err = REG_ERR_UNMATCHED_BRACKET;
  18730. return 0;
  18731. }
  18732. pattern += reg_utf8_tounicode_case(pattern, &start, nocase);
  18733. if (start == '\\') {
  18734. switch (*pattern) {
  18735. case 's':
  18736. pattern++;
  18737. cc = CC_SPACE;
  18738. goto cc_switch;
  18739. case 'd':
  18740. pattern++;
  18741. cc = CC_DIGIT;
  18742. goto cc_switch;
  18743. case 'w':
  18744. pattern++;
  18745. reg_addrange(preg, '_', '_');
  18746. cc = CC_ALNUM;
  18747. goto cc_switch;
  18748. }
  18749. pattern += reg_decode_escape(pattern, &start);
  18750. if (start == 0) {
  18751. preg->err = REG_ERR_NULL_CHAR;
  18752. return 0;
  18753. }
  18754. if (start == '\\' && *pattern == 0) {
  18755. preg->err = REG_ERR_INVALID_ESCAPE;
  18756. return 0;
  18757. }
  18758. }
  18759. if (pattern[0] == '-' && pattern[1] && pattern[1] != ']') {
  18760. pattern += utf8_tounicode(pattern, &end);
  18761. pattern += reg_utf8_tounicode_case(pattern, &end, nocase);
  18762. if (end == '\\') {
  18763. pattern += reg_decode_escape(pattern, &end);
  18764. if (end == 0) {
  18765. preg->err = REG_ERR_NULL_CHAR;
  18766. return 0;
  18767. }
  18768. if (end == '\\' && *pattern == 0) {
  18769. preg->err = REG_ERR_INVALID_ESCAPE;
  18770. return 0;
  18771. }
  18772. }
  18773. reg_addrange(preg, start, end);
  18774. continue;
  18775. }
  18776. if (start == '[' && pattern[0] == ':') {
  18777. static const char *character_class[] = {
  18778. ":alpha:", ":alnum:", ":space:", ":blank:", ":upper:", ":lower:",
  18779. ":digit:", ":xdigit:", ":cntrl:", ":graph:", ":print:", ":punct:",
  18780. };
  18781. for (cc = 0; cc < CC_NUM; cc++) {
  18782. n = strlen(character_class[cc]);
  18783. if (strncmp(pattern, character_class[cc], n) == 0) {
  18784. if (pattern[n] != ']') {
  18785. preg->err = REG_ERR_UNMATCHED_BRACKET;
  18786. return 0;
  18787. }
  18788. pattern += n + 1;
  18789. break;
  18790. }
  18791. }
  18792. if (cc != CC_NUM) {
  18793. cc_switch:
  18794. switch (cc) {
  18795. case CC_ALNUM:
  18796. reg_addrange(preg, '0', '9');
  18797. case CC_ALPHA:
  18798. if ((preg->cflags & REG_ICASE) == 0) {
  18799. reg_addrange(preg, 'a', 'z');
  18800. }
  18801. reg_addrange(preg, 'A', 'Z');
  18802. break;
  18803. case CC_SPACE:
  18804. reg_addrange_str(preg, " \t\r\n\f\v");
  18805. break;
  18806. case CC_BLANK:
  18807. reg_addrange_str(preg, " \t");
  18808. break;
  18809. case CC_UPPER:
  18810. reg_addrange(preg, 'A', 'Z');
  18811. break;
  18812. case CC_LOWER:
  18813. reg_addrange(preg, 'a', 'z');
  18814. break;
  18815. case CC_XDIGIT:
  18816. reg_addrange(preg, 'a', 'f');
  18817. reg_addrange(preg, 'A', 'F');
  18818. case CC_DIGIT:
  18819. reg_addrange(preg, '0', '9');
  18820. break;
  18821. case CC_CNTRL:
  18822. reg_addrange(preg, 0, 31);
  18823. reg_addrange(preg, 127, 127);
  18824. break;
  18825. case CC_PRINT:
  18826. reg_addrange(preg, ' ', '~');
  18827. break;
  18828. case CC_GRAPH:
  18829. reg_addrange(preg, '!', '~');
  18830. break;
  18831. case CC_PUNCT:
  18832. reg_addrange(preg, '!', '/');
  18833. reg_addrange(preg, ':', '@');
  18834. reg_addrange(preg, '[', '`');
  18835. reg_addrange(preg, '{', '~');
  18836. break;
  18837. }
  18838. continue;
  18839. }
  18840. }
  18841. reg_addrange(preg, start, start);
  18842. }
  18843. regc(preg, '\0');
  18844. if (*pattern) {
  18845. pattern++;
  18846. }
  18847. preg->regparse = pattern;
  18848. *flagp |= HASWIDTH|SIMPLE;
  18849. }
  18850. break;
  18851. case '(':
  18852. ret = reg(preg, 1, &flags);
  18853. if (ret == 0)
  18854. return 0;
  18855. *flagp |= flags&(HASWIDTH|SPSTART);
  18856. break;
  18857. case '\0':
  18858. case '|':
  18859. case ')':
  18860. preg->err = REG_ERR_INTERNAL;
  18861. return 0;
  18862. case '?':
  18863. case '+':
  18864. case '*':
  18865. case '{':
  18866. preg->err = REG_ERR_COUNT_FOLLOWS_NOTHING;
  18867. return 0;
  18868. case '\\':
  18869. ch = *preg->regparse++;
  18870. switch (ch) {
  18871. case '\0':
  18872. preg->err = REG_ERR_INVALID_ESCAPE;
  18873. return 0;
  18874. case 'A':
  18875. ret = regnode(preg, BOLX);
  18876. break;
  18877. case 'Z':
  18878. ret = regnode(preg, EOLX);
  18879. break;
  18880. case '<':
  18881. case 'm':
  18882. ret = regnode(preg, WORDA);
  18883. break;
  18884. case '>':
  18885. case 'M':
  18886. ret = regnode(preg, WORDZ);
  18887. break;
  18888. case 'd':
  18889. case 'D':
  18890. ret = regnode(preg, ch == 'd' ? ANYOF : ANYBUT);
  18891. reg_addrange(preg, '0', '9');
  18892. regc(preg, '\0');
  18893. *flagp |= HASWIDTH|SIMPLE;
  18894. break;
  18895. case 'w':
  18896. case 'W':
  18897. ret = regnode(preg, ch == 'w' ? ANYOF : ANYBUT);
  18898. if ((preg->cflags & REG_ICASE) == 0) {
  18899. reg_addrange(preg, 'a', 'z');
  18900. }
  18901. reg_addrange(preg, 'A', 'Z');
  18902. reg_addrange(preg, '0', '9');
  18903. reg_addrange(preg, '_', '_');
  18904. regc(preg, '\0');
  18905. *flagp |= HASWIDTH|SIMPLE;
  18906. break;
  18907. case 's':
  18908. case 'S':
  18909. ret = regnode(preg, ch == 's' ? ANYOF : ANYBUT);
  18910. reg_addrange_str(preg," \t\r\n\f\v");
  18911. regc(preg, '\0');
  18912. *flagp |= HASWIDTH|SIMPLE;
  18913. break;
  18914. default:
  18915. preg->regparse--;
  18916. goto de_fault;
  18917. }
  18918. break;
  18919. de_fault:
  18920. default: {
  18921. int added = 0;
  18922. preg->regparse -= n;
  18923. ret = regnode(preg, EXACTLY);
  18924. while (*preg->regparse && strchr(META, *preg->regparse) == NULL) {
  18925. n = reg_utf8_tounicode_case(preg->regparse, &ch, (preg->cflags & REG_ICASE));
  18926. if (ch == '\\' && preg->regparse[n]) {
  18927. if (strchr("<>mMwWdDsSAZ", preg->regparse[n])) {
  18928. break;
  18929. }
  18930. n += reg_decode_escape(preg->regparse + n, &ch);
  18931. if (ch == 0) {
  18932. preg->err = REG_ERR_NULL_CHAR;
  18933. return 0;
  18934. }
  18935. }
  18936. if (ISMULT(preg->regparse[n])) {
  18937. if (added) {
  18938. break;
  18939. }
  18940. regc(preg, ch);
  18941. added++;
  18942. preg->regparse += n;
  18943. break;
  18944. }
  18945. regc(preg, ch);
  18946. added++;
  18947. preg->regparse += n;
  18948. }
  18949. regc(preg, '\0');
  18950. *flagp |= HASWIDTH;
  18951. if (added == 1)
  18952. *flagp |= SIMPLE;
  18953. break;
  18954. }
  18955. break;
  18956. }
  18957. return(ret);
  18958. }
  18959. static void reg_grow(regex_t *preg, int n)
  18960. {
  18961. if (preg->p + n >= preg->proglen) {
  18962. preg->proglen = (preg->p + n) * 2;
  18963. preg->program = realloc(preg->program, preg->proglen * sizeof(int));
  18964. }
  18965. }
  18966. static int regnode(regex_t *preg, int op)
  18967. {
  18968. reg_grow(preg, 2);
  18969. preg->program[preg->p++] = op;
  18970. preg->program[preg->p++] = 0;
  18971. return preg->p - 2;
  18972. }
  18973. static void regc(regex_t *preg, int b )
  18974. {
  18975. reg_grow(preg, 1);
  18976. preg->program[preg->p++] = b;
  18977. }
  18978. static int reginsert(regex_t *preg, int op, int size, int opnd )
  18979. {
  18980. reg_grow(preg, size);
  18981. memmove(preg->program + opnd + size, preg->program + opnd, sizeof(int) * (preg->p - opnd));
  18982. memset(preg->program + opnd, 0, sizeof(int) * size);
  18983. preg->program[opnd] = op;
  18984. preg->p += size;
  18985. return opnd + size;
  18986. }
  18987. static void regtail(regex_t *preg, int p, int val)
  18988. {
  18989. int scan;
  18990. int temp;
  18991. int offset;
  18992. scan = p;
  18993. for (;;) {
  18994. temp = regnext(preg, scan);
  18995. if (temp == 0)
  18996. break;
  18997. scan = temp;
  18998. }
  18999. if (OP(preg, scan) == BACK)
  19000. offset = scan - val;
  19001. else
  19002. offset = val - scan;
  19003. preg->program[scan + 1] = offset;
  19004. }
  19005. static void regoptail(regex_t *preg, int p, int val )
  19006. {
  19007. if (p != 0 && OP(preg, p) == BRANCH) {
  19008. regtail(preg, OPERAND(p), val);
  19009. }
  19010. }
  19011. static int regtry(regex_t *preg, const char *string );
  19012. static int regmatch(regex_t *preg, int prog);
  19013. static int regrepeat(regex_t *preg, int p, int max);
  19014. int jim_regexec(regex_t *preg, const char *string, size_t nmatch, regmatch_t pmatch[], int eflags)
  19015. {
  19016. const char *s;
  19017. int scan;
  19018. if (preg == NULL || preg->program == NULL || string == NULL) {
  19019. return REG_ERR_NULL_ARGUMENT;
  19020. }
  19021. if (*preg->program != REG_MAGIC) {
  19022. return REG_ERR_CORRUPTED;
  19023. }
  19024. #ifdef DEBUG
  19025. fprintf(stderr, "regexec: %s\n", string);
  19026. regdump(preg);
  19027. #endif
  19028. preg->eflags = eflags;
  19029. preg->pmatch = pmatch;
  19030. preg->nmatch = nmatch;
  19031. preg->start = string;
  19032. for (scan = OPERAND(1); scan != 0; scan += regopsize(preg, scan)) {
  19033. int op = OP(preg, scan);
  19034. if (op == END)
  19035. break;
  19036. if (op == REPX || op == REPXMIN)
  19037. preg->program[scan + 4] = 0;
  19038. }
  19039. if (preg->regmust != 0) {
  19040. s = string;
  19041. while ((s = str_find(s, preg->program[preg->regmust], preg->cflags & REG_ICASE)) != NULL) {
  19042. if (prefix_cmp(preg->program + preg->regmust, preg->regmlen, s, preg->cflags & REG_ICASE) >= 0) {
  19043. break;
  19044. }
  19045. s++;
  19046. }
  19047. if (s == NULL)
  19048. return REG_NOMATCH;
  19049. }
  19050. preg->regbol = string;
  19051. if (preg->reganch) {
  19052. if (eflags & REG_NOTBOL) {
  19053. goto nextline;
  19054. }
  19055. while (1) {
  19056. if (regtry(preg, string)) {
  19057. return REG_NOERROR;
  19058. }
  19059. if (*string) {
  19060. nextline:
  19061. if (preg->cflags & REG_NEWLINE) {
  19062. string = strchr(string, '\n');
  19063. if (string) {
  19064. preg->regbol = ++string;
  19065. continue;
  19066. }
  19067. }
  19068. }
  19069. return REG_NOMATCH;
  19070. }
  19071. }
  19072. s = string;
  19073. if (preg->regstart != '\0') {
  19074. while ((s = str_find(s, preg->regstart, preg->cflags & REG_ICASE)) != NULL) {
  19075. if (regtry(preg, s))
  19076. return REG_NOERROR;
  19077. s++;
  19078. }
  19079. }
  19080. else
  19081. while (1) {
  19082. if (regtry(preg, s))
  19083. return REG_NOERROR;
  19084. if (*s == '\0') {
  19085. break;
  19086. }
  19087. else {
  19088. int c;
  19089. s += utf8_tounicode(s, &c);
  19090. }
  19091. }
  19092. return REG_NOMATCH;
  19093. }
  19094. static int regtry( regex_t *preg, const char *string )
  19095. {
  19096. int i;
  19097. preg->reginput = string;
  19098. for (i = 0; i < preg->nmatch; i++) {
  19099. preg->pmatch[i].rm_so = -1;
  19100. preg->pmatch[i].rm_eo = -1;
  19101. }
  19102. if (regmatch(preg, 1)) {
  19103. preg->pmatch[0].rm_so = string - preg->start;
  19104. preg->pmatch[0].rm_eo = preg->reginput - preg->start;
  19105. return(1);
  19106. } else
  19107. return(0);
  19108. }
  19109. static int prefix_cmp(const int *prog, int proglen, const char *string, int nocase)
  19110. {
  19111. const char *s = string;
  19112. while (proglen && *s) {
  19113. int ch;
  19114. int n = reg_utf8_tounicode_case(s, &ch, nocase);
  19115. if (ch != *prog) {
  19116. return -1;
  19117. }
  19118. prog++;
  19119. s += n;
  19120. proglen--;
  19121. }
  19122. if (proglen == 0) {
  19123. return s - string;
  19124. }
  19125. return -1;
  19126. }
  19127. static int reg_range_find(const int *range, int c)
  19128. {
  19129. while (*range) {
  19130. if (c >= range[1] && c <= (range[0] + range[1] - 1)) {
  19131. return 1;
  19132. }
  19133. range += 2;
  19134. }
  19135. return 0;
  19136. }
  19137. static const char *str_find(const char *string, int c, int nocase)
  19138. {
  19139. if (nocase) {
  19140. c = utf8_upper(c);
  19141. }
  19142. while (*string) {
  19143. int ch;
  19144. int n = reg_utf8_tounicode_case(string, &ch, nocase);
  19145. if (c == ch) {
  19146. return string;
  19147. }
  19148. string += n;
  19149. }
  19150. return NULL;
  19151. }
  19152. static int reg_iseol(regex_t *preg, int ch)
  19153. {
  19154. if (preg->cflags & REG_NEWLINE) {
  19155. return ch == '\0' || ch == '\n';
  19156. }
  19157. else {
  19158. return ch == '\0';
  19159. }
  19160. }
  19161. static int regmatchsimplerepeat(regex_t *preg, int scan, int matchmin)
  19162. {
  19163. int nextch = '\0';
  19164. const char *save;
  19165. int no;
  19166. int c;
  19167. int max = preg->program[scan + 2];
  19168. int min = preg->program[scan + 3];
  19169. int next = regnext(preg, scan);
  19170. if (OP(preg, next) == EXACTLY) {
  19171. nextch = preg->program[OPERAND(next)];
  19172. }
  19173. save = preg->reginput;
  19174. no = regrepeat(preg, scan + 5, max);
  19175. if (no < min) {
  19176. return 0;
  19177. }
  19178. if (matchmin) {
  19179. max = no;
  19180. no = min;
  19181. }
  19182. while (1) {
  19183. if (matchmin) {
  19184. if (no > max) {
  19185. break;
  19186. }
  19187. }
  19188. else {
  19189. if (no < min) {
  19190. break;
  19191. }
  19192. }
  19193. preg->reginput = save + utf8_index(save, no);
  19194. reg_utf8_tounicode_case(preg->reginput, &c, (preg->cflags & REG_ICASE));
  19195. if (reg_iseol(preg, nextch) || c == nextch) {
  19196. if (regmatch(preg, next)) {
  19197. return(1);
  19198. }
  19199. }
  19200. if (matchmin) {
  19201. no++;
  19202. }
  19203. else {
  19204. no--;
  19205. }
  19206. }
  19207. return(0);
  19208. }
  19209. static int regmatchrepeat(regex_t *preg, int scan, int matchmin)
  19210. {
  19211. int *scanpt = preg->program + scan;
  19212. int max = scanpt[2];
  19213. int min = scanpt[3];
  19214. if (scanpt[4] < min) {
  19215. scanpt[4]++;
  19216. if (regmatch(preg, scan + 5)) {
  19217. return 1;
  19218. }
  19219. scanpt[4]--;
  19220. return 0;
  19221. }
  19222. if (scanpt[4] > max) {
  19223. return 0;
  19224. }
  19225. if (matchmin) {
  19226. if (regmatch(preg, regnext(preg, scan))) {
  19227. return 1;
  19228. }
  19229. scanpt[4]++;
  19230. if (regmatch(preg, scan + 5)) {
  19231. return 1;
  19232. }
  19233. scanpt[4]--;
  19234. return 0;
  19235. }
  19236. if (scanpt[4] < max) {
  19237. scanpt[4]++;
  19238. if (regmatch(preg, scan + 5)) {
  19239. return 1;
  19240. }
  19241. scanpt[4]--;
  19242. }
  19243. return regmatch(preg, regnext(preg, scan));
  19244. }
  19245. static int regmatch(regex_t *preg, int prog)
  19246. {
  19247. int scan;
  19248. int next;
  19249. const char *save;
  19250. scan = prog;
  19251. #ifdef DEBUG
  19252. if (scan != 0 && regnarrate)
  19253. fprintf(stderr, "%s(\n", regprop(scan));
  19254. #endif
  19255. while (scan != 0) {
  19256. int n;
  19257. int c;
  19258. #ifdef DEBUG
  19259. if (regnarrate) {
  19260. fprintf(stderr, "%3d: %s...\n", scan, regprop(OP(preg, scan)));
  19261. }
  19262. #endif
  19263. next = regnext(preg, scan);
  19264. n = reg_utf8_tounicode_case(preg->reginput, &c, (preg->cflags & REG_ICASE));
  19265. switch (OP(preg, scan)) {
  19266. case BOLX:
  19267. if ((preg->eflags & REG_NOTBOL)) {
  19268. return(0);
  19269. }
  19270. case BOL:
  19271. if (preg->reginput != preg->regbol) {
  19272. return(0);
  19273. }
  19274. break;
  19275. case EOLX:
  19276. if (c != 0) {
  19277. return 0;
  19278. }
  19279. break;
  19280. case EOL:
  19281. if (!reg_iseol(preg, c)) {
  19282. return(0);
  19283. }
  19284. break;
  19285. case WORDA:
  19286. if ((!isalnum(UCHAR(c))) && c != '_')
  19287. return(0);
  19288. if (preg->reginput > preg->regbol &&
  19289. (isalnum(UCHAR(preg->reginput[-1])) || preg->reginput[-1] == '_'))
  19290. return(0);
  19291. break;
  19292. case WORDZ:
  19293. if (preg->reginput > preg->regbol) {
  19294. if (reg_iseol(preg, c) || !(isalnum(UCHAR(c)) || c == '_')) {
  19295. c = preg->reginput[-1];
  19296. if (isalnum(UCHAR(c)) || c == '_') {
  19297. break;
  19298. }
  19299. }
  19300. }
  19301. return(0);
  19302. case ANY:
  19303. if (reg_iseol(preg, c))
  19304. return 0;
  19305. preg->reginput += n;
  19306. break;
  19307. case EXACTLY: {
  19308. int opnd;
  19309. int len;
  19310. int slen;
  19311. opnd = OPERAND(scan);
  19312. len = str_int_len(preg->program + opnd);
  19313. slen = prefix_cmp(preg->program + opnd, len, preg->reginput, preg->cflags & REG_ICASE);
  19314. if (slen < 0) {
  19315. return(0);
  19316. }
  19317. preg->reginput += slen;
  19318. }
  19319. break;
  19320. case ANYOF:
  19321. if (reg_iseol(preg, c) || reg_range_find(preg->program + OPERAND(scan), c) == 0) {
  19322. return(0);
  19323. }
  19324. preg->reginput += n;
  19325. break;
  19326. case ANYBUT:
  19327. if (reg_iseol(preg, c) || reg_range_find(preg->program + OPERAND(scan), c) != 0) {
  19328. return(0);
  19329. }
  19330. preg->reginput += n;
  19331. break;
  19332. case NOTHING:
  19333. break;
  19334. case BACK:
  19335. break;
  19336. case BRANCH:
  19337. if (OP(preg, next) != BRANCH)
  19338. next = OPERAND(scan);
  19339. else {
  19340. do {
  19341. save = preg->reginput;
  19342. if (regmatch(preg, OPERAND(scan))) {
  19343. return(1);
  19344. }
  19345. preg->reginput = save;
  19346. scan = regnext(preg, scan);
  19347. } while (scan != 0 && OP(preg, scan) == BRANCH);
  19348. return(0);
  19349. }
  19350. break;
  19351. case REP:
  19352. case REPMIN:
  19353. return regmatchsimplerepeat(preg, scan, OP(preg, scan) == REPMIN);
  19354. case REPX:
  19355. case REPXMIN:
  19356. return regmatchrepeat(preg, scan, OP(preg, scan) == REPXMIN);
  19357. case END:
  19358. return 1;
  19359. case OPENNC:
  19360. case CLOSENC:
  19361. return regmatch(preg, next);
  19362. default:
  19363. if (OP(preg, scan) >= OPEN+1 && OP(preg, scan) < CLOSE_END) {
  19364. save = preg->reginput;
  19365. if (regmatch(preg, next)) {
  19366. if (OP(preg, scan) < CLOSE) {
  19367. int no = OP(preg, scan) - OPEN;
  19368. if (no < preg->nmatch && preg->pmatch[no].rm_so == -1) {
  19369. preg->pmatch[no].rm_so = save - preg->start;
  19370. }
  19371. }
  19372. else {
  19373. int no = OP(preg, scan) - CLOSE;
  19374. if (no < preg->nmatch && preg->pmatch[no].rm_eo == -1) {
  19375. preg->pmatch[no].rm_eo = save - preg->start;
  19376. }
  19377. }
  19378. return(1);
  19379. }
  19380. preg->reginput = save;
  19381. return(0);
  19382. }
  19383. return REG_ERR_INTERNAL;
  19384. }
  19385. scan = next;
  19386. }
  19387. return REG_ERR_INTERNAL;
  19388. }
  19389. static int regrepeat(regex_t *preg, int p, int max)
  19390. {
  19391. int count = 0;
  19392. const char *scan;
  19393. int opnd;
  19394. int ch;
  19395. int n;
  19396. scan = preg->reginput;
  19397. opnd = OPERAND(p);
  19398. switch (OP(preg, p)) {
  19399. case ANY:
  19400. while (!reg_iseol(preg, *scan) && count < max) {
  19401. count++;
  19402. scan += utf8_charlen(*scan);
  19403. }
  19404. break;
  19405. case EXACTLY:
  19406. while (count < max) {
  19407. n = reg_utf8_tounicode_case(scan, &ch, preg->cflags & REG_ICASE);
  19408. if (preg->program[opnd] != ch) {
  19409. break;
  19410. }
  19411. count++;
  19412. scan += n;
  19413. }
  19414. break;
  19415. case ANYOF:
  19416. while (count < max) {
  19417. n = reg_utf8_tounicode_case(scan, &ch, preg->cflags & REG_ICASE);
  19418. if (reg_iseol(preg, ch) || reg_range_find(preg->program + opnd, ch) == 0) {
  19419. break;
  19420. }
  19421. count++;
  19422. scan += n;
  19423. }
  19424. break;
  19425. case ANYBUT:
  19426. while (count < max) {
  19427. n = reg_utf8_tounicode_case(scan, &ch, preg->cflags & REG_ICASE);
  19428. if (reg_iseol(preg, ch) || reg_range_find(preg->program + opnd, ch) != 0) {
  19429. break;
  19430. }
  19431. count++;
  19432. scan += n;
  19433. }
  19434. break;
  19435. default:
  19436. preg->err = REG_ERR_INTERNAL;
  19437. count = 0;
  19438. break;
  19439. }
  19440. preg->reginput = scan;
  19441. return(count);
  19442. }
  19443. static int regnext(regex_t *preg, int p )
  19444. {
  19445. int offset;
  19446. offset = NEXT(preg, p);
  19447. if (offset == 0)
  19448. return 0;
  19449. if (OP(preg, p) == BACK)
  19450. return(p-offset);
  19451. else
  19452. return(p+offset);
  19453. }
  19454. static int regopsize(regex_t *preg, int p )
  19455. {
  19456. switch (OP(preg, p)) {
  19457. case REP:
  19458. case REPMIN:
  19459. case REPX:
  19460. case REPXMIN:
  19461. return 5;
  19462. case ANYOF:
  19463. case ANYBUT:
  19464. case EXACTLY: {
  19465. int s = p + 2;
  19466. while (preg->program[s++]) {
  19467. }
  19468. return s - p;
  19469. }
  19470. }
  19471. return 2;
  19472. }
  19473. size_t jim_regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
  19474. {
  19475. static const char *error_strings[] = {
  19476. "success",
  19477. "no match",
  19478. "bad pattern",
  19479. "null argument",
  19480. "unknown error",
  19481. "too big",
  19482. "out of memory",
  19483. "too many ()",
  19484. "parentheses () not balanced",
  19485. "braces {} not balanced",
  19486. "invalid repetition count(s)",
  19487. "extra characters",
  19488. "*+ of empty atom",
  19489. "nested count",
  19490. "internal error",
  19491. "count follows nothing",
  19492. "invalid escape \\ sequence",
  19493. "corrupted program",
  19494. "contains null char",
  19495. "brackets [] not balanced",
  19496. };
  19497. const char *err;
  19498. if (errcode < 0 || errcode >= REG_ERR_NUM) {
  19499. err = "Bad error code";
  19500. }
  19501. else {
  19502. err = error_strings[errcode];
  19503. }
  19504. return snprintf(errbuf, errbuf_size, "%s", err);
  19505. }
  19506. void jim_regfree(regex_t *preg)
  19507. {
  19508. free(preg->program);
  19509. }
  19510. #endif
  19511. #include <string.h>
  19512. void Jim_SetResultErrno(Jim_Interp *interp, const char *msg)
  19513. {
  19514. Jim_SetResultFormatted(interp, "%s: %s", msg, strerror(Jim_Errno()));
  19515. }
  19516. #if defined(_WIN32) || defined(WIN32)
  19517. #include <sys/stat.h>
  19518. int Jim_Errno(void)
  19519. {
  19520. switch (GetLastError()) {
  19521. case ERROR_FILE_NOT_FOUND: return ENOENT;
  19522. case ERROR_PATH_NOT_FOUND: return ENOENT;
  19523. case ERROR_TOO_MANY_OPEN_FILES: return EMFILE;
  19524. case ERROR_ACCESS_DENIED: return EACCES;
  19525. case ERROR_INVALID_HANDLE: return EBADF;
  19526. case ERROR_BAD_ENVIRONMENT: return E2BIG;
  19527. case ERROR_BAD_FORMAT: return ENOEXEC;
  19528. case ERROR_INVALID_ACCESS: return EACCES;
  19529. case ERROR_INVALID_DRIVE: return ENOENT;
  19530. case ERROR_CURRENT_DIRECTORY: return EACCES;
  19531. case ERROR_NOT_SAME_DEVICE: return EXDEV;
  19532. case ERROR_NO_MORE_FILES: return ENOENT;
  19533. case ERROR_WRITE_PROTECT: return EROFS;
  19534. case ERROR_BAD_UNIT: return ENXIO;
  19535. case ERROR_NOT_READY: return EBUSY;
  19536. case ERROR_BAD_COMMAND: return EIO;
  19537. case ERROR_CRC: return EIO;
  19538. case ERROR_BAD_LENGTH: return EIO;
  19539. case ERROR_SEEK: return EIO;
  19540. case ERROR_WRITE_FAULT: return EIO;
  19541. case ERROR_READ_FAULT: return EIO;
  19542. case ERROR_GEN_FAILURE: return EIO;
  19543. case ERROR_SHARING_VIOLATION: return EACCES;
  19544. case ERROR_LOCK_VIOLATION: return EACCES;
  19545. case ERROR_SHARING_BUFFER_EXCEEDED: return ENFILE;
  19546. case ERROR_HANDLE_DISK_FULL: return ENOSPC;
  19547. case ERROR_NOT_SUPPORTED: return ENODEV;
  19548. case ERROR_REM_NOT_LIST: return EBUSY;
  19549. case ERROR_DUP_NAME: return EEXIST;
  19550. case ERROR_BAD_NETPATH: return ENOENT;
  19551. case ERROR_NETWORK_BUSY: return EBUSY;
  19552. case ERROR_DEV_NOT_EXIST: return ENODEV;
  19553. case ERROR_TOO_MANY_CMDS: return EAGAIN;
  19554. case ERROR_ADAP_HDW_ERR: return EIO;
  19555. case ERROR_BAD_NET_RESP: return EIO;
  19556. case ERROR_UNEXP_NET_ERR: return EIO;
  19557. case ERROR_NETNAME_DELETED: return ENOENT;
  19558. case ERROR_NETWORK_ACCESS_DENIED: return EACCES;
  19559. case ERROR_BAD_DEV_TYPE: return ENODEV;
  19560. case ERROR_BAD_NET_NAME: return ENOENT;
  19561. case ERROR_TOO_MANY_NAMES: return ENFILE;
  19562. case ERROR_TOO_MANY_SESS: return EIO;
  19563. case ERROR_SHARING_PAUSED: return EAGAIN;
  19564. case ERROR_REDIR_PAUSED: return EAGAIN;
  19565. case ERROR_FILE_EXISTS: return EEXIST;
  19566. case ERROR_CANNOT_MAKE: return ENOSPC;
  19567. case ERROR_OUT_OF_STRUCTURES: return ENFILE;
  19568. case ERROR_ALREADY_ASSIGNED: return EEXIST;
  19569. case ERROR_INVALID_PASSWORD: return EPERM;
  19570. case ERROR_NET_WRITE_FAULT: return EIO;
  19571. case ERROR_NO_PROC_SLOTS: return EAGAIN;
  19572. case ERROR_DISK_CHANGE: return EXDEV;
  19573. case ERROR_BROKEN_PIPE: return EPIPE;
  19574. case ERROR_OPEN_FAILED: return ENOENT;
  19575. case ERROR_DISK_FULL: return ENOSPC;
  19576. case ERROR_NO_MORE_SEARCH_HANDLES: return EMFILE;
  19577. case ERROR_INVALID_TARGET_HANDLE: return EBADF;
  19578. case ERROR_INVALID_NAME: return ENOENT;
  19579. case ERROR_PROC_NOT_FOUND: return ESRCH;
  19580. case ERROR_WAIT_NO_CHILDREN: return ECHILD;
  19581. case ERROR_CHILD_NOT_COMPLETE: return ECHILD;
  19582. case ERROR_DIRECT_ACCESS_HANDLE: return EBADF;
  19583. case ERROR_SEEK_ON_DEVICE: return ESPIPE;
  19584. case ERROR_BUSY_DRIVE: return EAGAIN;
  19585. case ERROR_DIR_NOT_EMPTY: return EEXIST;
  19586. case ERROR_NOT_LOCKED: return EACCES;
  19587. case ERROR_BAD_PATHNAME: return ENOENT;
  19588. case ERROR_LOCK_FAILED: return EACCES;
  19589. case ERROR_ALREADY_EXISTS: return EEXIST;
  19590. case ERROR_FILENAME_EXCED_RANGE: return ENAMETOOLONG;
  19591. case ERROR_BAD_PIPE: return EPIPE;
  19592. case ERROR_PIPE_BUSY: return EAGAIN;
  19593. case ERROR_PIPE_NOT_CONNECTED: return EPIPE;
  19594. case ERROR_DIRECTORY: return ENOTDIR;
  19595. }
  19596. return EINVAL;
  19597. }
  19598. long JimProcessPid(phandle_t pid)
  19599. {
  19600. if (pid == INVALID_HANDLE_VALUE) {
  19601. return -1;
  19602. }
  19603. return GetProcessId(pid);
  19604. }
  19605. phandle_t JimWaitPid(long pid, int *status, int nohang)
  19606. {
  19607. if (pid > 0) {
  19608. HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION | SYNCHRONIZE, FALSE, pid);
  19609. if (h) {
  19610. long pid = waitpid(h, status, nohang);
  19611. CloseHandle(h);
  19612. if (pid > 0) {
  19613. return h;
  19614. }
  19615. }
  19616. }
  19617. return JIM_BAD_PHANDLE;
  19618. }
  19619. long waitpid(phandle_t phandle, int *status, int nohang)
  19620. {
  19621. long pid;
  19622. DWORD ret = WaitForSingleObject(phandle, nohang ? 0 : INFINITE);
  19623. if (ret == WAIT_TIMEOUT || ret == WAIT_FAILED) {
  19624. return -1;
  19625. }
  19626. GetExitCodeProcess(phandle, &ret);
  19627. *status = ret;
  19628. pid = GetProcessId(phandle);
  19629. CloseHandle(phandle);
  19630. return pid;
  19631. }
  19632. int Jim_MakeTempFile(Jim_Interp *interp, const char *filename_template, int unlink_file)
  19633. {
  19634. char name[MAX_PATH];
  19635. HANDLE handle;
  19636. if (!GetTempPath(MAX_PATH, name) || !GetTempFileName(name, filename_template ? filename_template : "JIM", 0, name)) {
  19637. return -1;
  19638. }
  19639. handle = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, NULL,
  19640. CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | (unlink_file ? FILE_FLAG_DELETE_ON_CLOSE : 0),
  19641. NULL);
  19642. if (handle == INVALID_HANDLE_VALUE) {
  19643. goto error;
  19644. }
  19645. Jim_SetResultString(interp, name, -1);
  19646. return _open_osfhandle((intptr_t)handle, _O_RDWR | _O_TEXT);
  19647. error:
  19648. Jim_SetResultErrno(interp, name);
  19649. DeleteFile(name);
  19650. return -1;
  19651. }
  19652. int Jim_OpenForWrite(const char *filename, int append)
  19653. {
  19654. if (strcmp(filename, "/dev/null") == 0) {
  19655. filename = "nul:";
  19656. }
  19657. int fd = _open(filename, _O_WRONLY | _O_CREAT | _O_TEXT | (append ? _O_APPEND : _O_TRUNC), _S_IREAD | _S_IWRITE);
  19658. if (fd >= 0 && append) {
  19659. _lseek(fd, 0L, SEEK_END);
  19660. }
  19661. return fd;
  19662. }
  19663. int Jim_OpenForRead(const char *filename)
  19664. {
  19665. if (strcmp(filename, "/dev/null") == 0) {
  19666. filename = "nul:";
  19667. }
  19668. return _open(filename, _O_RDONLY | _O_TEXT, 0);
  19669. }
  19670. #elif defined(HAVE_UNISTD_H)
  19671. int Jim_MakeTempFile(Jim_Interp *interp, const char *filename_template, int unlink_file)
  19672. {
  19673. int fd;
  19674. mode_t mask;
  19675. Jim_Obj *filenameObj;
  19676. if (filename_template == NULL) {
  19677. const char *tmpdir = getenv("TMPDIR");
  19678. if (tmpdir == NULL || *tmpdir == '\0' || access(tmpdir, W_OK) != 0) {
  19679. tmpdir = "/tmp/";
  19680. }
  19681. filenameObj = Jim_NewStringObj(interp, tmpdir, -1);
  19682. if (tmpdir[0] && tmpdir[strlen(tmpdir) - 1] != '/') {
  19683. Jim_AppendString(interp, filenameObj, "/", 1);
  19684. }
  19685. Jim_AppendString(interp, filenameObj, "tcl.tmp.XXXXXX", -1);
  19686. }
  19687. else {
  19688. filenameObj = Jim_NewStringObj(interp, filename_template, -1);
  19689. }
  19690. #ifdef HAVE_UMASK
  19691. mask = umask(S_IXUSR | S_IRWXG | S_IRWXO);
  19692. #endif
  19693. #ifdef HAVE_MKSTEMP
  19694. fd = mkstemp(filenameObj->bytes);
  19695. #else
  19696. if (mktemp(filenameObj->bytes) == NULL) {
  19697. fd = -1;
  19698. }
  19699. else {
  19700. fd = open(filenameObj->bytes, O_RDWR | O_CREAT | O_TRUNC);
  19701. }
  19702. #endif
  19703. #ifdef HAVE_UMASK
  19704. umask(mask);
  19705. #endif
  19706. if (fd < 0) {
  19707. Jim_SetResultErrno(interp, Jim_String(filenameObj));
  19708. Jim_FreeNewObj(interp, filenameObj);
  19709. return -1;
  19710. }
  19711. if (unlink_file) {
  19712. remove(Jim_String(filenameObj));
  19713. }
  19714. Jim_SetResult(interp, filenameObj);
  19715. return fd;
  19716. }
  19717. int Jim_OpenForWrite(const char *filename, int append)
  19718. {
  19719. return open(filename, O_WRONLY | O_CREAT | (append ? O_APPEND : O_TRUNC), 0666);
  19720. }
  19721. int Jim_OpenForRead(const char *filename)
  19722. {
  19723. return open(filename, O_RDONLY, 0);
  19724. }
  19725. #endif
  19726. #if defined(_WIN32) || defined(WIN32)
  19727. #ifndef STRICT
  19728. #define STRICT
  19729. #endif
  19730. #define WIN32_LEAN_AND_MEAN
  19731. #include <windows.h>
  19732. #if defined(HAVE_DLOPEN_COMPAT)
  19733. void *dlopen(const char *path, int mode)
  19734. {
  19735. JIM_NOTUSED(mode);
  19736. return (void *)LoadLibraryA(path);
  19737. }
  19738. int dlclose(void *handle)
  19739. {
  19740. FreeLibrary((HANDLE)handle);
  19741. return 0;
  19742. }
  19743. void *dlsym(void *handle, const char *symbol)
  19744. {
  19745. return GetProcAddress((HMODULE)handle, symbol);
  19746. }
  19747. char *dlerror(void)
  19748. {
  19749. static char msg[121];
  19750. FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),
  19751. LANG_NEUTRAL, msg, sizeof(msg) - 1, NULL);
  19752. return msg;
  19753. }
  19754. #endif
  19755. #ifdef _MSC_VER
  19756. #include <sys/timeb.h>
  19757. int gettimeofday(struct timeval *tv, void *unused)
  19758. {
  19759. struct _timeb tb;
  19760. _ftime(&tb);
  19761. tv->tv_sec = tb.time;
  19762. tv->tv_usec = tb.millitm * 1000;
  19763. return 0;
  19764. }
  19765. DIR *opendir(const char *name)
  19766. {
  19767. DIR *dir = 0;
  19768. if (name && name[0]) {
  19769. size_t base_length = strlen(name);
  19770. const char *all =
  19771. strchr("/\\", name[base_length - 1]) ? "*" : "/*";
  19772. if ((dir = (DIR *) Jim_Alloc(sizeof *dir)) != 0 &&
  19773. (dir->name = (char *)Jim_Alloc(base_length + strlen(all) + 1)) != 0) {
  19774. strcat(strcpy(dir->name, name), all);
  19775. if ((dir->handle = (long)_findfirst(dir->name, &dir->info)) != -1)
  19776. dir->result.d_name = 0;
  19777. else {
  19778. Jim_Free(dir->name);
  19779. Jim_Free(dir);
  19780. dir = 0;
  19781. }
  19782. }
  19783. else {
  19784. Jim_Free(dir);
  19785. dir = 0;
  19786. errno = ENOMEM;
  19787. }
  19788. }
  19789. else {
  19790. errno = EINVAL;
  19791. }
  19792. return dir;
  19793. }
  19794. int closedir(DIR * dir)
  19795. {
  19796. int result = -1;
  19797. if (dir) {
  19798. if (dir->handle != -1)
  19799. result = _findclose(dir->handle);
  19800. Jim_Free(dir->name);
  19801. Jim_Free(dir);
  19802. }
  19803. if (result == -1)
  19804. errno = EBADF;
  19805. return result;
  19806. }
  19807. struct dirent *readdir(DIR * dir)
  19808. {
  19809. struct dirent *result = 0;
  19810. if (dir && dir->handle != -1) {
  19811. if (!dir->result.d_name || _findnext(dir->handle, &dir->info) != -1) {
  19812. result = &dir->result;
  19813. result->d_name = dir->info.name;
  19814. }
  19815. }
  19816. else {
  19817. errno = EBADF;
  19818. }
  19819. return result;
  19820. }
  19821. #endif
  19822. #endif
  19823. #include <stdio.h>
  19824. #include <signal.h>
  19825. #ifndef SIGPIPE
  19826. #define SIGPIPE 13
  19827. #endif
  19828. #ifndef SIGINT
  19829. #define SIGINT 2
  19830. #endif
  19831. const char *Jim_SignalId(int sig)
  19832. {
  19833. static char buf[10];
  19834. switch (sig) {
  19835. case SIGINT: return "SIGINT";
  19836. case SIGPIPE: return "SIGPIPE";
  19837. }
  19838. snprintf(buf, sizeof(buf), "%d", sig);
  19839. return buf;
  19840. }
  19841. #ifndef JIM_BOOTSTRAP_LIB_ONLY
  19842. #include <errno.h>
  19843. #include <string.h>
  19844. #include <stdio.h>
  19845. #ifdef USE_LINENOISE
  19846. #ifdef HAVE_UNISTD_H
  19847. #include <unistd.h>
  19848. #endif
  19849. #ifdef HAVE_SYS_STAT_H
  19850. #include <sys/stat.h>
  19851. #endif
  19852. #include "linenoise.h"
  19853. #else
  19854. #define MAX_LINE_LEN 512
  19855. #endif
  19856. #ifdef USE_LINENOISE
  19857. struct JimCompletionInfo {
  19858. Jim_Interp *interp;
  19859. Jim_Obj *completion_command;
  19860. Jim_Obj *hints_command;
  19861. };
  19862. static struct JimCompletionInfo *JimGetCompletionInfo(Jim_Interp *interp);
  19863. static void JimCompletionCallback(const char *prefix, linenoiseCompletions *comp, void *userdata);
  19864. static const char completion_callback_assoc_key[] = "interactive-completion";
  19865. static char *JimHintsCallback(const char *prefix, int *color, int *bold, void *userdata);
  19866. static void JimFreeHintsCallback(void *hint, void *userdata);
  19867. #endif
  19868. char *Jim_HistoryGetline(Jim_Interp *interp, const char *prompt)
  19869. {
  19870. #ifdef USE_LINENOISE
  19871. struct JimCompletionInfo *compinfo = JimGetCompletionInfo(interp);
  19872. char *result;
  19873. Jim_Obj *objPtr;
  19874. long mlmode = 0;
  19875. if (compinfo->completion_command) {
  19876. linenoiseSetCompletionCallback(JimCompletionCallback, compinfo);
  19877. }
  19878. if (compinfo->hints_command) {
  19879. linenoiseSetHintsCallback(JimHintsCallback, compinfo);
  19880. linenoiseSetFreeHintsCallback(JimFreeHintsCallback);
  19881. }
  19882. objPtr = Jim_GetVariableStr(interp, "history::multiline", JIM_NONE);
  19883. if (objPtr && Jim_GetLong(interp, objPtr, &mlmode) == JIM_NONE) {
  19884. linenoiseSetMultiLine(mlmode);
  19885. }
  19886. result = linenoise(prompt);
  19887. linenoiseSetCompletionCallback(NULL, NULL);
  19888. linenoiseSetHintsCallback(NULL, NULL);
  19889. linenoiseSetFreeHintsCallback(NULL);
  19890. return result;
  19891. #else
  19892. int len;
  19893. char *line = Jim_Alloc(MAX_LINE_LEN);
  19894. fputs(prompt, stdout);
  19895. fflush(stdout);
  19896. if (fgets(line, MAX_LINE_LEN, stdin) == NULL) {
  19897. Jim_Free(line);
  19898. return NULL;
  19899. }
  19900. len = strlen(line);
  19901. if (len && line[len - 1] == '\n') {
  19902. line[len - 1] = '\0';
  19903. }
  19904. return line;
  19905. #endif
  19906. }
  19907. void Jim_HistoryLoad(const char *filename)
  19908. {
  19909. #ifdef USE_LINENOISE
  19910. linenoiseHistoryLoad(filename);
  19911. #endif
  19912. }
  19913. void Jim_HistoryAdd(const char *line)
  19914. {
  19915. #ifdef USE_LINENOISE
  19916. linenoiseHistoryAdd(line);
  19917. #endif
  19918. }
  19919. void Jim_HistorySave(const char *filename)
  19920. {
  19921. #ifdef USE_LINENOISE
  19922. #ifdef HAVE_UMASK
  19923. mode_t mask;
  19924. mask = umask(S_IXUSR | S_IRWXG | S_IRWXO);
  19925. #endif
  19926. linenoiseHistorySave(filename);
  19927. #ifdef HAVE_UMASK
  19928. umask(mask);
  19929. #endif
  19930. #endif
  19931. }
  19932. void Jim_HistoryShow(void)
  19933. {
  19934. #ifdef USE_LINENOISE
  19935. int i;
  19936. int len;
  19937. char **history = linenoiseHistory(&len);
  19938. for (i = 0; i < len; i++) {
  19939. printf("%4d %s\n", i + 1, history[i]);
  19940. }
  19941. #endif
  19942. }
  19943. void Jim_HistorySetMaxLen(int length)
  19944. {
  19945. #ifdef USE_LINENOISE
  19946. linenoiseHistorySetMaxLen(length);
  19947. #endif
  19948. }
  19949. int Jim_HistoryGetMaxLen(void)
  19950. {
  19951. #ifdef USE_LINENOISE
  19952. return linenoiseHistoryGetMaxLen();
  19953. #endif
  19954. return 0;
  19955. }
  19956. #ifdef USE_LINENOISE
  19957. static void JimCompletionCallback(const char *prefix, linenoiseCompletions *comp, void *userdata)
  19958. {
  19959. struct JimCompletionInfo *info = (struct JimCompletionInfo *)userdata;
  19960. Jim_Obj *objv[2];
  19961. int ret;
  19962. objv[0] = info->completion_command;
  19963. objv[1] = Jim_NewStringObj(info->interp, prefix, -1);
  19964. ret = Jim_EvalObjVector(info->interp, 2, objv);
  19965. if (ret == JIM_OK) {
  19966. int i;
  19967. Jim_Obj *listObj = Jim_GetResult(info->interp);
  19968. int len = Jim_ListLength(info->interp, listObj);
  19969. for (i = 0; i < len; i++) {
  19970. linenoiseAddCompletion(comp, Jim_String(Jim_ListGetIndex(info->interp, listObj, i)));
  19971. }
  19972. }
  19973. }
  19974. static char *JimHintsCallback(const char *prefix, int *color, int *bold, void *userdata)
  19975. {
  19976. struct JimCompletionInfo *info = (struct JimCompletionInfo *)userdata;
  19977. Jim_Obj *objv[2];
  19978. int ret;
  19979. char *result = NULL;
  19980. objv[0] = info->hints_command;
  19981. objv[1] = Jim_NewStringObj(info->interp, prefix, -1);
  19982. ret = Jim_EvalObjVector(info->interp, 2, objv);
  19983. if (ret == JIM_OK) {
  19984. Jim_Obj *listObj = Jim_GetResult(info->interp);
  19985. Jim_IncrRefCount(listObj);
  19986. int len = Jim_ListLength(info->interp, listObj);
  19987. if (len >= 1) {
  19988. long x;
  19989. result = Jim_StrDup(Jim_String(Jim_ListGetIndex(info->interp, listObj, 0)));
  19990. if (len >= 2 && Jim_GetLong(info->interp, Jim_ListGetIndex(info->interp, listObj, 1), &x) == JIM_OK) {
  19991. *color = x;
  19992. }
  19993. if (len >= 3 && Jim_GetLong(info->interp, Jim_ListGetIndex(info->interp, listObj, 2), &x) == JIM_OK) {
  19994. *bold = x;
  19995. }
  19996. }
  19997. Jim_DecrRefCount(info->interp, listObj);
  19998. }
  19999. return result;
  20000. }
  20001. static void JimFreeHintsCallback(void *hint, void *userdata)
  20002. {
  20003. Jim_Free(hint);
  20004. }
  20005. static void JimHistoryFreeCompletion(Jim_Interp *interp, void *data)
  20006. {
  20007. struct JimCompletionInfo *compinfo = data;
  20008. if (compinfo->completion_command) {
  20009. Jim_DecrRefCount(interp, compinfo->completion_command);
  20010. }
  20011. if (compinfo->hints_command) {
  20012. Jim_DecrRefCount(interp, compinfo->hints_command);
  20013. }
  20014. Jim_Free(compinfo);
  20015. }
  20016. static struct JimCompletionInfo *JimGetCompletionInfo(Jim_Interp *interp)
  20017. {
  20018. struct JimCompletionInfo *compinfo = Jim_GetAssocData(interp, completion_callback_assoc_key);
  20019. if (compinfo == NULL) {
  20020. compinfo = Jim_Alloc(sizeof(*compinfo));
  20021. compinfo->interp = interp;
  20022. compinfo->completion_command = NULL;
  20023. compinfo->hints_command = NULL;
  20024. Jim_SetAssocData(interp, completion_callback_assoc_key, JimHistoryFreeCompletion, compinfo);
  20025. }
  20026. return compinfo;
  20027. }
  20028. #endif
  20029. void Jim_HistorySetCompletion(Jim_Interp *interp, Jim_Obj *completionCommandObj)
  20030. {
  20031. #ifdef USE_LINENOISE
  20032. struct JimCompletionInfo *compinfo = JimGetCompletionInfo(interp);
  20033. if (completionCommandObj) {
  20034. Jim_IncrRefCount(completionCommandObj);
  20035. }
  20036. if (compinfo->completion_command) {
  20037. Jim_DecrRefCount(interp, compinfo->completion_command);
  20038. }
  20039. compinfo->completion_command = completionCommandObj;
  20040. #endif
  20041. }
  20042. void Jim_HistorySetHints(Jim_Interp *interp, Jim_Obj *hintsCommandObj)
  20043. {
  20044. #ifdef USE_LINENOISE
  20045. struct JimCompletionInfo *compinfo = JimGetCompletionInfo(interp);
  20046. if (hintsCommandObj) {
  20047. Jim_IncrRefCount(hintsCommandObj);
  20048. }
  20049. if (compinfo->hints_command) {
  20050. Jim_DecrRefCount(interp, compinfo->hints_command);
  20051. }
  20052. compinfo->hints_command = hintsCommandObj;
  20053. #endif
  20054. }
  20055. int Jim_InteractivePrompt(Jim_Interp *interp)
  20056. {
  20057. int retcode = JIM_OK;
  20058. char *history_file = NULL;
  20059. #ifdef USE_LINENOISE
  20060. const char *home;
  20061. home = getenv("HOME");
  20062. if (home && isatty(STDIN_FILENO)) {
  20063. int history_len = strlen(home) + sizeof("/.jim_history");
  20064. history_file = Jim_Alloc(history_len);
  20065. snprintf(history_file, history_len, "%s/.jim_history", home);
  20066. Jim_HistoryLoad(history_file);
  20067. }
  20068. Jim_HistorySetCompletion(interp, Jim_NewStringObj(interp, "tcl::autocomplete", -1));
  20069. Jim_HistorySetHints(interp, Jim_NewStringObj(interp, "tcl::stdhint", -1));
  20070. #endif
  20071. printf("Welcome to Jim version %d.%d\n",
  20072. JIM_VERSION / 100, JIM_VERSION % 100);
  20073. Jim_SetVariableStrWithStr(interp, JIM_INTERACTIVE, "1");
  20074. while (1) {
  20075. Jim_Obj *scriptObjPtr;
  20076. const char *result;
  20077. int reslen;
  20078. char prompt[20];
  20079. if (retcode != JIM_OK) {
  20080. const char *retcodestr = Jim_ReturnCode(retcode);
  20081. if (*retcodestr == '?') {
  20082. snprintf(prompt, sizeof(prompt) - 3, "[%d] . ", retcode);
  20083. }
  20084. else {
  20085. snprintf(prompt, sizeof(prompt) - 3, "[%s] . ", retcodestr);
  20086. }
  20087. }
  20088. else {
  20089. strcpy(prompt, ". ");
  20090. }
  20091. scriptObjPtr = Jim_NewStringObj(interp, "", 0);
  20092. Jim_IncrRefCount(scriptObjPtr);
  20093. while (1) {
  20094. char state;
  20095. char *line;
  20096. line = Jim_HistoryGetline(interp, prompt);
  20097. if (line == NULL) {
  20098. if (errno == EINTR) {
  20099. continue;
  20100. }
  20101. Jim_DecrRefCount(interp, scriptObjPtr);
  20102. retcode = JIM_OK;
  20103. goto out;
  20104. }
  20105. if (Jim_Length(scriptObjPtr) != 0) {
  20106. Jim_AppendString(interp, scriptObjPtr, "\n", 1);
  20107. }
  20108. Jim_AppendString(interp, scriptObjPtr, line, -1);
  20109. Jim_Free(line);
  20110. if (Jim_ScriptIsComplete(interp, scriptObjPtr, &state))
  20111. break;
  20112. snprintf(prompt, sizeof(prompt), "%c> ", state);
  20113. }
  20114. #ifdef USE_LINENOISE
  20115. if (strcmp(Jim_String(scriptObjPtr), "h") == 0) {
  20116. Jim_HistoryShow();
  20117. Jim_DecrRefCount(interp, scriptObjPtr);
  20118. continue;
  20119. }
  20120. Jim_HistoryAdd(Jim_String(scriptObjPtr));
  20121. if (history_file) {
  20122. Jim_HistorySave(history_file);
  20123. }
  20124. #endif
  20125. retcode = Jim_EvalObj(interp, scriptObjPtr);
  20126. Jim_DecrRefCount(interp, scriptObjPtr);
  20127. if (retcode == JIM_EXIT) {
  20128. break;
  20129. }
  20130. if (retcode == JIM_ERR) {
  20131. Jim_MakeErrorMessage(interp);
  20132. }
  20133. result = Jim_GetString(Jim_GetResult(interp), &reslen);
  20134. if (reslen) {
  20135. if (fwrite(result, reslen, 1, stdout) == 0) {
  20136. }
  20137. putchar('\n');
  20138. }
  20139. }
  20140. out:
  20141. Jim_Free(history_file);
  20142. return retcode;
  20143. }
  20144. #include <stdio.h>
  20145. #include <stdlib.h>
  20146. #include <string.h>
  20147. extern int Jim_initjimshInit(Jim_Interp *interp);
  20148. static void JimSetArgv(Jim_Interp *interp, int argc, char *const argv[])
  20149. {
  20150. int n;
  20151. Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
  20152. for (n = 0; n < argc; n++) {
  20153. Jim_Obj *obj = Jim_NewStringObj(interp, argv[n], -1);
  20154. Jim_ListAppendElement(interp, listObj, obj);
  20155. }
  20156. Jim_SetVariableStr(interp, "argv", listObj);
  20157. Jim_SetVariableStr(interp, "argc", Jim_NewIntObj(interp, argc));
  20158. }
  20159. static void JimPrintErrorMessage(Jim_Interp *interp)
  20160. {
  20161. Jim_MakeErrorMessage(interp);
  20162. fprintf(stderr, "%s\n", Jim_String(Jim_GetResult(interp)));
  20163. }
  20164. void usage(const char* executable_name)
  20165. {
  20166. printf("jimsh version %d.%d\n", JIM_VERSION / 100, JIM_VERSION % 100);
  20167. printf("Usage: %s\n", executable_name);
  20168. printf("or : %s [options] [filename]\n", executable_name);
  20169. printf("\n");
  20170. printf("Without options: Interactive mode\n");
  20171. printf("\n");
  20172. printf("Options:\n");
  20173. printf(" --version : prints the version string\n");
  20174. printf(" --help : prints this text\n");
  20175. printf(" -e CMD : executes command CMD\n");
  20176. printf(" NOTE: all subsequent options will be passed as arguments to the command\n");
  20177. printf(" [filename|-] : executes the script contained in the named file, or from stdin if \"-\"\n");
  20178. printf(" NOTE: all subsequent options will be passed to the script\n\n");
  20179. }
  20180. int main(int argc, char *const argv[])
  20181. {
  20182. int retcode;
  20183. Jim_Interp *interp;
  20184. char *const orig_argv0 = argv[0];
  20185. if (argc > 1 && strcmp(argv[1], "--version") == 0) {
  20186. printf("%d.%d\n", JIM_VERSION / 100, JIM_VERSION % 100);
  20187. return 0;
  20188. }
  20189. else if (argc > 1 && strcmp(argv[1], "--help") == 0) {
  20190. usage(argv[0]);
  20191. return 0;
  20192. }
  20193. interp = Jim_CreateInterp();
  20194. Jim_RegisterCoreCommands(interp);
  20195. if (Jim_InitStaticExtensions(interp) != JIM_OK) {
  20196. JimPrintErrorMessage(interp);
  20197. }
  20198. Jim_SetVariableStrWithStr(interp, "jim::argv0", orig_argv0);
  20199. Jim_SetVariableStrWithStr(interp, JIM_INTERACTIVE, argc == 1 ? "1" : "0");
  20200. #ifdef USE_LINENOISE
  20201. Jim_SetVariableStrWithStr(interp, "jim::lineedit", "1");
  20202. #else
  20203. Jim_SetVariableStrWithStr(interp, "jim::lineedit", "0");
  20204. #endif
  20205. retcode = Jim_initjimshInit(interp);
  20206. if (argc == 1) {
  20207. if (retcode == JIM_ERR) {
  20208. JimPrintErrorMessage(interp);
  20209. }
  20210. if (retcode != JIM_EXIT) {
  20211. JimSetArgv(interp, 0, NULL);
  20212. retcode = Jim_InteractivePrompt(interp);
  20213. }
  20214. }
  20215. else {
  20216. if (argc > 2 && strcmp(argv[1], "-e") == 0) {
  20217. JimSetArgv(interp, argc - 3, argv + 3);
  20218. retcode = Jim_Eval(interp, argv[2]);
  20219. if (retcode != JIM_ERR) {
  20220. int len;
  20221. const char *msg = Jim_GetString(Jim_GetResult(interp), &len);
  20222. if (fwrite(msg, len, 1, stdout) == 0) {
  20223. }
  20224. putchar('\n');
  20225. }
  20226. }
  20227. else {
  20228. Jim_SetVariableStr(interp, "argv0", Jim_NewStringObj(interp, argv[1], -1));
  20229. JimSetArgv(interp, argc - 2, argv + 2);
  20230. if (strcmp(argv[1], "-") == 0) {
  20231. retcode = Jim_Eval(interp, "eval [info source [stdin read] stdin 1]");
  20232. } else {
  20233. retcode = Jim_EvalFile(interp, argv[1]);
  20234. }
  20235. }
  20236. if (retcode == JIM_ERR) {
  20237. JimPrintErrorMessage(interp);
  20238. }
  20239. }
  20240. if (retcode == JIM_EXIT) {
  20241. retcode = Jim_GetExitCode(interp);
  20242. }
  20243. else if (retcode == JIM_ERR) {
  20244. retcode = 1;
  20245. }
  20246. else {
  20247. retcode = 0;
  20248. }
  20249. Jim_FreeInterp(interp);
  20250. return retcode;
  20251. }
  20252. #endif