12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472 |
- /* This is single source file, bootstrap version of Jim Tcl. See http://jim.tcl.tk/ */
- #define JIM_COMPAT
- #define JIM_ANSIC
- #define JIM_REGEXP
- #define HAVE_NO_AUTOCONF
- #define JIM_TINY
- #define _JIMAUTOCONF_H
- #define TCL_LIBRARY "."
- #define jim_ext_bootstrap
- #define jim_ext_aio
- #define jim_ext_readdir
- #define jim_ext_regexp
- #define jim_ext_file
- #define jim_ext_glob
- #define jim_ext_exec
- #define jim_ext_clock
- #define jim_ext_array
- #define jim_ext_stdlib
- #define jim_ext_tclcompat
- #if defined(_MSC_VER)
- #define TCL_PLATFORM_OS "windows"
- #define TCL_PLATFORM_PLATFORM "windows"
- #define TCL_PLATFORM_PATH_SEPARATOR ";"
- #define HAVE_MKDIR_ONE_ARG
- #define HAVE_SYSTEM
- #elif defined(__MINGW32__)
- #define TCL_PLATFORM_OS "mingw"
- #define TCL_PLATFORM_PLATFORM "windows"
- #define TCL_PLATFORM_PATH_SEPARATOR ";"
- #define HAVE_MKDIR_ONE_ARG
- #define HAVE_SYSTEM
- #define HAVE_SYS_TIME_H
- #define HAVE_DIRENT_H
- #define HAVE_UNISTD_H
- #define HAVE_UMASK
- #include <sys/stat.h>
- #ifndef S_IRWXG
- #define S_IRWXG 0
- #endif
- #ifndef S_IRWXO
- #define S_IRWXO 0
- #endif
- #else
- #define TCL_PLATFORM_OS "unknown"
- #define TCL_PLATFORM_PLATFORM "unix"
- #define TCL_PLATFORM_PATH_SEPARATOR ":"
- #ifdef _MINIX
- #define vfork fork
- #define _POSIX_SOURCE
- #else
- #define _GNU_SOURCE
- #endif
- #define HAVE_FORK
- #define HAVE_WAITPID
- #define HAVE_ISATTY
- #define HAVE_MKSTEMP
- #define HAVE_LINK
- #define HAVE_SYS_TIME_H
- #define HAVE_DIRENT_H
- #define HAVE_UNISTD_H
- #define HAVE_UMASK
- #define HAVE_PIPE
- #define _FILE_OFFSET_BITS 64
- #endif
- #define JIM_VERSION 84
- #ifndef JIM_WIN32COMPAT_H
- #define JIM_WIN32COMPAT_H
- #ifdef __cplusplus
- extern "C" {
- #endif
- #if defined(_WIN32) || defined(WIN32)
- #define HAVE_DLOPEN
- void *dlopen(const char *path, int mode);
- int dlclose(void *handle);
- void *dlsym(void *handle, const char *symbol);
- char *dlerror(void);
- #if defined(__MINGW32__)
- #define JIM_SPRINTF_DOUBLE_NEEDS_FIX
- #endif
- #ifdef _MSC_VER
- #if _MSC_VER >= 1000
- #pragma warning(disable:4146)
- #endif
- #include <limits.h>
- #define jim_wide _int64
- #ifndef HAVE_LONG_LONG
- #define HAVE_LONG_LONG
- #endif
- #ifndef LLONG_MAX
- #define LLONG_MAX 9223372036854775807I64
- #endif
- #ifndef LLONG_MIN
- #define LLONG_MIN (-LLONG_MAX - 1I64)
- #endif
- #define JIM_WIDE_MIN LLONG_MIN
- #define JIM_WIDE_MAX LLONG_MAX
- #define JIM_WIDE_MODIFIER "I64d"
- #define strcasecmp _stricmp
- #define strtoull _strtoui64
- #include <io.h>
- #include <winsock.h>
- int gettimeofday(struct timeval *tv, void *unused);
- #define HAVE_OPENDIR
- struct dirent {
- char *d_name;
- };
- typedef struct DIR {
- long handle;
- struct _finddata_t info;
- struct dirent result;
- char *name;
- } DIR;
- DIR *opendir(const char *name);
- int closedir(DIR *dir);
- struct dirent *readdir(DIR *dir);
- #endif
- #endif
- #ifdef __cplusplus
- }
- #endif
- #endif
- #ifndef UTF8_UTIL_H
- #define UTF8_UTIL_H
- #ifdef __cplusplus
- extern "C" {
- #endif
- #define MAX_UTF8_LEN 4
- int utf8_fromunicode(char *p, unsigned uc);
- #ifndef JIM_UTF8
- #include <ctype.h>
- #define utf8_strlen(S, B) ((B) < 0 ? (int)strlen(S) : (B))
- #define utf8_strwidth(S, B) utf8_strlen((S), (B))
- #define utf8_tounicode(S, CP) (*(CP) = (unsigned char)*(S), 1)
- #define utf8_getchars(CP, C) (*(CP) = (C), 1)
- #define utf8_upper(C) toupper(C)
- #define utf8_title(C) toupper(C)
- #define utf8_lower(C) tolower(C)
- #define utf8_index(C, I) (I)
- #define utf8_charlen(C) 1
- #define utf8_prev_len(S, L) 1
- #define utf8_width(C) 1
- #else
- #endif
- #ifdef __cplusplus
- }
- #endif
- #endif
- #ifndef __JIM__H
- #define __JIM__H
- #ifdef __cplusplus
- extern "C" {
- #endif
- #include <time.h>
- #include <limits.h>
- #include <stdlib.h>
- #include <stdarg.h>
- #ifndef HAVE_NO_AUTOCONF
- #endif
- #ifndef jim_wide
- # ifdef HAVE_LONG_LONG
- # define jim_wide long long
- # ifndef LLONG_MAX
- # define LLONG_MAX 9223372036854775807LL
- # endif
- # ifndef LLONG_MIN
- # define LLONG_MIN (-LLONG_MAX - 1LL)
- # endif
- # define JIM_WIDE_MIN LLONG_MIN
- # define JIM_WIDE_MAX LLONG_MAX
- # else
- # define jim_wide long
- # define JIM_WIDE_MIN LONG_MIN
- # define JIM_WIDE_MAX LONG_MAX
- # endif
- # ifdef HAVE_LONG_LONG
- # define JIM_WIDE_MODIFIER "lld"
- # else
- # define JIM_WIDE_MODIFIER "ld"
- # define strtoull strtoul
- # endif
- #endif
- #define UCHAR(c) ((unsigned char)(c))
- #define JIM_ABI_VERSION 101
- #define JIM_OK 0
- #define JIM_ERR 1
- #define JIM_RETURN 2
- #define JIM_BREAK 3
- #define JIM_CONTINUE 4
- #define JIM_SIGNAL 5
- #define JIM_EXIT 6
- #define JIM_EVAL 7
- #define JIM_MAX_CALLFRAME_DEPTH 1000
- #define JIM_MAX_EVAL_DEPTH 2000
- #define JIM_PRIV_FLAG_SHIFT 20
- #define JIM_NONE 0
- #define JIM_ERRMSG 1
- #define JIM_ENUM_ABBREV 2
- #define JIM_UNSHARED 4
- #define JIM_MUSTEXIST 8
- #define JIM_NORESULT 16
- #define JIM_SUBST_NOVAR 1
- #define JIM_SUBST_NOCMD 2
- #define JIM_SUBST_NOESC 4
- #define JIM_SUBST_FLAG 128
- #define JIM_CASESENS 0
- #define JIM_NOCASE 1
- #define JIM_OPT_END 2
- #define JIM_PATH_LEN 1024
- #define JIM_NOTUSED(V) ((void) V)
- #define JIM_LIBPATH "auto_path"
- #define JIM_INTERACTIVE "tcl_interactive"
- typedef struct Jim_Stack {
- int len;
- int maxlen;
- void **vector;
- } Jim_Stack;
- typedef struct Jim_HashEntry {
- void *key;
- union {
- void *val;
- int intval;
- } u;
- struct Jim_HashEntry *next;
- } Jim_HashEntry;
- typedef struct Jim_HashTableType {
- unsigned int (*hashFunction)(const void *key);
- void *(*keyDup)(void *privdata, const void *key);
- void *(*valDup)(void *privdata, const void *obj);
- int (*keyCompare)(void *privdata, const void *key1, const void *key2);
- void (*keyDestructor)(void *privdata, void *key);
- void (*valDestructor)(void *privdata, void *obj);
- } Jim_HashTableType;
- typedef struct Jim_HashTable {
- Jim_HashEntry **table;
- const Jim_HashTableType *type;
- void *privdata;
- unsigned int size;
- unsigned int sizemask;
- unsigned int used;
- unsigned int collisions;
- unsigned int uniq;
- } Jim_HashTable;
- typedef struct Jim_HashTableIterator {
- Jim_HashTable *ht;
- Jim_HashEntry *entry, *nextEntry;
- int index;
- } Jim_HashTableIterator;
- #define JIM_HT_INITIAL_SIZE 16
- #define Jim_FreeEntryVal(ht, entry) \
- if ((ht)->type->valDestructor) \
- (ht)->type->valDestructor((ht)->privdata, (entry)->u.val)
- #define Jim_SetHashVal(ht, entry, _val_) do { \
- if ((ht)->type->valDup) \
- (entry)->u.val = (ht)->type->valDup((ht)->privdata, (_val_)); \
- else \
- (entry)->u.val = (_val_); \
- } while(0)
- #define Jim_SetHashIntVal(ht, entry, _val_) (entry)->u.intval = (_val_)
- #define Jim_FreeEntryKey(ht, entry) \
- if ((ht)->type->keyDestructor) \
- (ht)->type->keyDestructor((ht)->privdata, (entry)->key)
- #define Jim_SetHashKey(ht, entry, _key_) do { \
- if ((ht)->type->keyDup) \
- (entry)->key = (ht)->type->keyDup((ht)->privdata, (_key_)); \
- else \
- (entry)->key = (void *)(_key_); \
- } while(0)
- #define Jim_CompareHashKeys(ht, key1, key2) \
- (((ht)->type->keyCompare) ? \
- (ht)->type->keyCompare((ht)->privdata, (key1), (key2)) : \
- (key1) == (key2))
- #define Jim_HashKey(ht, key) ((ht)->type->hashFunction(key) + (ht)->uniq)
- #define Jim_GetHashEntryKey(he) ((he)->key)
- #define Jim_GetHashEntryVal(he) ((he)->u.val)
- #define Jim_GetHashEntryIntVal(he) ((he)->u.intval)
- #define Jim_GetHashTableCollisions(ht) ((ht)->collisions)
- #define Jim_GetHashTableSize(ht) ((ht)->size)
- #define Jim_GetHashTableUsed(ht) ((ht)->used)
- typedef struct Jim_Obj {
- char *bytes;
- const struct Jim_ObjType *typePtr;
- int refCount;
- int length;
- union {
- jim_wide wideValue;
- int intValue;
- double doubleValue;
- void *ptr;
- struct {
- void *ptr1;
- void *ptr2;
- } twoPtrValue;
- struct {
- void *ptr;
- int int1;
- int int2;
- } ptrIntValue;
- struct {
- struct Jim_VarVal *vv;
- unsigned long callFrameId;
- int global;
- } varValue;
- struct {
- struct Jim_Obj *nsObj;
- struct Jim_Cmd *cmdPtr;
- unsigned long procEpoch;
- } cmdValue;
- struct {
- struct Jim_Obj **ele;
- int len;
- int maxLen;
- } listValue;
- struct Jim_Dict *dictValue;
- struct {
- int maxLength;
- int charLength;
- } strValue;
- struct {
- unsigned long id;
- struct Jim_Reference *refPtr;
- } refValue;
- struct {
- struct Jim_Obj *fileNameObj;
- int lineNumber;
- } sourceValue;
- struct {
- struct Jim_Obj *varNameObjPtr;
- struct Jim_Obj *indexObjPtr;
- } dictSubstValue;
- struct {
- int line;
- int argc;
- } scriptLineValue;
- } internalRep;
- struct Jim_Obj *prevObjPtr;
- struct Jim_Obj *nextObjPtr;
- } Jim_Obj;
- #define Jim_IncrRefCount(objPtr) \
- ++(objPtr)->refCount
- #define Jim_DecrRefCount(interp, objPtr) \
- if (--(objPtr)->refCount <= 0) Jim_FreeObj(interp, objPtr)
- #define Jim_IsShared(objPtr) \
- ((objPtr)->refCount > 1)
- #define Jim_FreeNewObj Jim_FreeObj
- #define Jim_FreeIntRep(i,o) \
- if ((o)->typePtr && (o)->typePtr->freeIntRepProc) \
- (o)->typePtr->freeIntRepProc(i, o)
- #define Jim_GetIntRepPtr(o) (o)->internalRep.ptr
- #define Jim_SetIntRepPtr(o, p) \
- (o)->internalRep.ptr = (p)
- struct Jim_Interp;
- typedef void (Jim_FreeInternalRepProc)(struct Jim_Interp *interp,
- struct Jim_Obj *objPtr);
- typedef void (Jim_DupInternalRepProc)(struct Jim_Interp *interp,
- struct Jim_Obj *srcPtr, Jim_Obj *dupPtr);
- typedef void (Jim_UpdateStringProc)(struct Jim_Obj *objPtr);
- typedef struct Jim_ObjType {
- const char *name;
- Jim_FreeInternalRepProc *freeIntRepProc;
- Jim_DupInternalRepProc *dupIntRepProc;
- Jim_UpdateStringProc *updateStringProc;
- int flags;
- } Jim_ObjType;
- #define JIM_TYPE_NONE 0
- #define JIM_TYPE_REFERENCES 1
- typedef struct Jim_CallFrame {
- unsigned long id;
- int level;
- struct Jim_HashTable vars;
- struct Jim_HashTable *staticVars;
- struct Jim_CallFrame *parent;
- Jim_Obj *const *argv;
- int argc;
- Jim_Obj *procArgsObjPtr;
- Jim_Obj *procBodyObjPtr;
- struct Jim_CallFrame *next;
- Jim_Obj *nsObj;
- Jim_Obj *unused_fileNameObj;
- int unused_line;
- Jim_Stack *localCommands;
- struct Jim_Obj *tailcallObj;
- struct Jim_Cmd *tailcallCmd;
- } Jim_CallFrame;
- typedef struct Jim_EvalFrame {
- Jim_CallFrame *framePtr;
- int level;
- int procLevel;
- struct Jim_Cmd *cmd;
- struct Jim_EvalFrame *parent;
- Jim_Obj *const *argv;
- int argc;
- Jim_Obj *scriptObj;
- } Jim_EvalFrame;
- typedef struct Jim_VarVal {
- Jim_Obj *objPtr;
- struct Jim_CallFrame *linkFramePtr;
- int refCount;
- } Jim_VarVal;
- typedef int Jim_CmdProc(struct Jim_Interp *interp, int argc,
- Jim_Obj *const *argv);
- typedef void Jim_DelCmdProc(struct Jim_Interp *interp, void *privData);
- typedef struct Jim_Dict {
- struct JimDictHashEntry {
- int offset;
- unsigned hash;
- } *ht;
- unsigned int size;
- unsigned int sizemask;
- unsigned int uniq;
- Jim_Obj **table;
- int len;
- int maxLen;
- unsigned int dummy;
- } Jim_Dict;
- typedef struct Jim_Cmd {
- int inUse;
- int isproc;
- struct Jim_Cmd *prevCmd;
- Jim_Obj *cmdNameObj;
- union {
- struct {
- Jim_CmdProc *cmdProc;
- Jim_DelCmdProc *delProc;
- void *privData;
- } native;
- struct {
- Jim_Obj *argListObjPtr;
- Jim_Obj *bodyObjPtr;
- Jim_HashTable *staticVars;
- int argListLen;
- int reqArity;
- int optArity;
- int argsPos;
- int upcall;
- struct Jim_ProcArg {
- Jim_Obj *nameObjPtr;
- Jim_Obj *defaultObjPtr;
- } *arglist;
- Jim_Obj *nsObj;
- } proc;
- } u;
- } Jim_Cmd;
- typedef struct Jim_PrngState {
- unsigned char sbox[256];
- unsigned int i, j;
- } Jim_PrngState;
- typedef struct Jim_Interp {
- Jim_Obj *result;
- int unused_errorLine;
- Jim_Obj *currentFilenameObj;
- int break_level;
- int maxCallFrameDepth;
- int maxEvalDepth;
- int evalDepth;
- int returnCode;
- int returnLevel;
- int exitCode;
- long id;
- int signal_level;
- jim_wide sigmask;
- int (*signal_set_result)(struct Jim_Interp *interp, jim_wide sigmask);
- Jim_CallFrame *framePtr;
- Jim_CallFrame *topFramePtr;
- struct Jim_HashTable commands;
- unsigned long procEpoch; /* Incremented every time the result
- of procedures names lookup caching
- may no longer be valid. */
- unsigned long callFrameEpoch; /* Incremented every time a new
- callframe is created. This id is used for the
- 'ID' field contained in the Jim_CallFrame
- structure. */
- int local;
- int quitting;
- int safeexpr;
- Jim_Obj *liveList;
- Jim_Obj *freeList;
- Jim_Obj *unused_currentScriptObj;
- Jim_EvalFrame topEvalFrame;
- Jim_EvalFrame *evalFrame;
- int procLevel;
- Jim_Obj * const *unused_argv;
- Jim_Obj *nullScriptObj;
- Jim_Obj *emptyObj;
- Jim_Obj *trueObj;
- Jim_Obj *falseObj;
- unsigned long referenceNextId;
- struct Jim_HashTable references;
- unsigned long lastCollectId; /* reference max Id of the last GC
- execution. It's set to ~0 while the collection
- is running as sentinel to avoid to recursive
- calls via the [collect] command inside
- finalizers. */
- jim_wide lastCollectTime;
- Jim_Obj *stackTrace;
- Jim_Obj *errorProc;
- Jim_Obj *unknown;
- Jim_Obj *defer;
- Jim_Obj *traceCmdObj;
- int unknown_called;
- int errorFlag;
- void *cmdPrivData; /* Used to pass the private data pointer to
- a command. It is set to what the user specified
- via Jim_CreateCommand(). */
- Jim_Cmd *oldCmdCache;
- int oldCmdCacheSize;
- struct Jim_CallFrame *freeFramesList;
- struct Jim_HashTable assocData;
- Jim_PrngState *prngState;
- struct Jim_HashTable packages;
- Jim_Stack *loadHandles;
- } Jim_Interp;
- #define Jim_SetResultString(i,s,l) Jim_SetResult(i, Jim_NewStringObj(i,s,l))
- #define Jim_SetResultInt(i,intval) Jim_SetResult(i, Jim_NewIntObj(i,intval))
- #define Jim_SetResultBool(i,b) Jim_SetResultInt(i, b)
- #define Jim_SetEmptyResult(i) Jim_SetResult(i, (i)->emptyObj)
- #define Jim_GetResult(i) ((i)->result)
- #define Jim_CmdPrivData(i) ((i)->cmdPrivData)
- #define Jim_SetResult(i,o) do { \
- Jim_Obj *_resultObjPtr_ = (o); \
- Jim_IncrRefCount(_resultObjPtr_); \
- Jim_DecrRefCount(i,(i)->result); \
- (i)->result = _resultObjPtr_; \
- } while(0)
- #define Jim_GetId(i) (++(i)->id)
- #define JIM_REFERENCE_TAGLEN 7 /* The tag is fixed-length, because the reference
- string representation must be fixed length. */
- typedef struct Jim_Reference {
- Jim_Obj *objPtr;
- Jim_Obj *finalizerCmdNamePtr;
- char tag[JIM_REFERENCE_TAGLEN+1];
- } Jim_Reference;
- #define Jim_NewEmptyStringObj(i) Jim_NewStringObj(i, "", 0)
- #define Jim_FreeHashTableIterator(iter) Jim_Free(iter)
- #define JIM_EXPORT extern
- JIM_EXPORT void *(*Jim_Allocator)(void *ptr, size_t size);
- #define Jim_Free(P) Jim_Allocator((P), 0)
- #define Jim_Realloc(P, S) Jim_Allocator((P), (S))
- #define Jim_Alloc(S) Jim_Allocator(NULL, (S))
- JIM_EXPORT char * Jim_StrDup (const char *s);
- JIM_EXPORT char *Jim_StrDupLen(const char *s, int l);
- JIM_EXPORT char **Jim_GetEnviron(void);
- JIM_EXPORT void Jim_SetEnviron(char **env);
- JIM_EXPORT int Jim_MakeTempFile(Jim_Interp *interp, const char *filename_template, int unlink_file);
- #ifndef CLOCK_REALTIME
- # define CLOCK_REALTIME 0
- #endif
- #ifndef CLOCK_MONOTONIC
- # define CLOCK_MONOTONIC 1
- #endif
- #ifndef CLOCK_MONOTONIC_RAW
- # define CLOCK_MONOTONIC_RAW CLOCK_MONOTONIC
- #endif
- JIM_EXPORT jim_wide Jim_GetTimeUsec(unsigned type);
- JIM_EXPORT int Jim_Eval(Jim_Interp *interp, const char *script);
- JIM_EXPORT int Jim_EvalSource(Jim_Interp *interp, const char *filename, int lineno, const char *script);
- #define Jim_Eval_Named(I, S, F, L) Jim_EvalSource((I), (F), (L), (S))
- JIM_EXPORT int Jim_EvalGlobal(Jim_Interp *interp, const char *script);
- JIM_EXPORT int Jim_EvalFile(Jim_Interp *interp, const char *filename);
- JIM_EXPORT int Jim_EvalFileGlobal(Jim_Interp *interp, const char *filename);
- JIM_EXPORT int Jim_EvalObj (Jim_Interp *interp, Jim_Obj *scriptObjPtr);
- JIM_EXPORT int Jim_EvalObjVector (Jim_Interp *interp, int objc,
- Jim_Obj *const *objv);
- JIM_EXPORT int Jim_EvalObjList(Jim_Interp *interp, Jim_Obj *listObj);
- JIM_EXPORT int Jim_EvalObjPrefix(Jim_Interp *interp, Jim_Obj *prefix,
- int objc, Jim_Obj *const *objv);
- #define Jim_EvalPrefix(i, p, oc, ov) Jim_EvalObjPrefix((i), Jim_NewStringObj((i), (p), -1), (oc), (ov))
- JIM_EXPORT int Jim_EvalNamespace(Jim_Interp *interp, Jim_Obj *scriptObj, Jim_Obj *nsObj);
- JIM_EXPORT int Jim_SubstObj (Jim_Interp *interp, Jim_Obj *substObjPtr,
- Jim_Obj **resObjPtrPtr, int flags);
- JIM_EXPORT Jim_Obj *Jim_GetSourceInfo(Jim_Interp *interp, Jim_Obj *objPtr,
- int *lineptr);
- JIM_EXPORT void Jim_SetSourceInfo(Jim_Interp *interp, Jim_Obj *objPtr,
- Jim_Obj *fileNameObj, int lineNumber);
- JIM_EXPORT void Jim_InitStack(Jim_Stack *stack);
- JIM_EXPORT void Jim_FreeStack(Jim_Stack *stack);
- JIM_EXPORT int Jim_StackLen(Jim_Stack *stack);
- JIM_EXPORT void Jim_StackPush(Jim_Stack *stack, void *element);
- JIM_EXPORT void * Jim_StackPop(Jim_Stack *stack);
- JIM_EXPORT void * Jim_StackPeek(Jim_Stack *stack);
- JIM_EXPORT void Jim_FreeStackElements(Jim_Stack *stack, void (*freeFunc)(void *ptr));
- JIM_EXPORT int Jim_InitHashTable (Jim_HashTable *ht,
- const Jim_HashTableType *type, void *privdata);
- JIM_EXPORT void Jim_ExpandHashTable (Jim_HashTable *ht,
- unsigned int size);
- JIM_EXPORT int Jim_AddHashEntry (Jim_HashTable *ht, const void *key,
- void *val);
- JIM_EXPORT int Jim_ReplaceHashEntry (Jim_HashTable *ht,
- const void *key, void *val);
- JIM_EXPORT int Jim_DeleteHashEntry (Jim_HashTable *ht,
- const void *key);
- JIM_EXPORT int Jim_FreeHashTable (Jim_HashTable *ht);
- JIM_EXPORT Jim_HashEntry * Jim_FindHashEntry (Jim_HashTable *ht,
- const void *key);
- JIM_EXPORT Jim_HashTableIterator *Jim_GetHashTableIterator
- (Jim_HashTable *ht);
- JIM_EXPORT Jim_HashEntry * Jim_NextHashEntry
- (Jim_HashTableIterator *iter);
- JIM_EXPORT Jim_Obj * Jim_NewObj (Jim_Interp *interp);
- JIM_EXPORT void Jim_FreeObj (Jim_Interp *interp, Jim_Obj *objPtr);
- JIM_EXPORT void Jim_InvalidateStringRep (Jim_Obj *objPtr);
- JIM_EXPORT Jim_Obj * Jim_DuplicateObj (Jim_Interp *interp,
- Jim_Obj *objPtr);
- JIM_EXPORT const char * Jim_GetString(Jim_Obj *objPtr,
- int *lenPtr);
- JIM_EXPORT const char *Jim_String(Jim_Obj *objPtr);
- JIM_EXPORT int Jim_Length(Jim_Obj *objPtr);
- JIM_EXPORT Jim_Obj * Jim_NewStringObj (Jim_Interp *interp,
- const char *s, int len);
- JIM_EXPORT Jim_Obj *Jim_NewStringObjUtf8(Jim_Interp *interp,
- const char *s, int charlen);
- JIM_EXPORT Jim_Obj * Jim_NewStringObjNoAlloc (Jim_Interp *interp,
- char *s, int len);
- JIM_EXPORT void Jim_AppendString (Jim_Interp *interp, Jim_Obj *objPtr,
- const char *str, int len);
- JIM_EXPORT void Jim_AppendObj (Jim_Interp *interp, Jim_Obj *objPtr,
- Jim_Obj *appendObjPtr);
- JIM_EXPORT void Jim_AppendStrings (Jim_Interp *interp,
- Jim_Obj *objPtr, ...);
- JIM_EXPORT int Jim_StringEqObj(Jim_Obj *aObjPtr, Jim_Obj *bObjPtr);
- JIM_EXPORT int Jim_StringMatchObj (Jim_Interp *interp, Jim_Obj *patternObjPtr,
- Jim_Obj *objPtr, int nocase);
- JIM_EXPORT Jim_Obj * Jim_StringRangeObj (Jim_Interp *interp,
- Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr,
- Jim_Obj *lastObjPtr);
- JIM_EXPORT Jim_Obj * Jim_FormatString (Jim_Interp *interp,
- Jim_Obj *fmtObjPtr, int objc, Jim_Obj *const *objv);
- JIM_EXPORT Jim_Obj * Jim_ScanString (Jim_Interp *interp, Jim_Obj *strObjPtr,
- Jim_Obj *fmtObjPtr, int flags);
- JIM_EXPORT int Jim_CompareStringImmediate (Jim_Interp *interp,
- Jim_Obj *objPtr, const char *str);
- JIM_EXPORT int Jim_StringCompareObj(Jim_Interp *interp, Jim_Obj *firstObjPtr,
- Jim_Obj *secondObjPtr, int nocase);
- JIM_EXPORT int Jim_Utf8Length(Jim_Interp *interp, Jim_Obj *objPtr);
- JIM_EXPORT Jim_Obj * Jim_NewReference (Jim_Interp *interp,
- Jim_Obj *objPtr, Jim_Obj *tagPtr, Jim_Obj *cmdNamePtr);
- JIM_EXPORT Jim_Reference * Jim_GetReference (Jim_Interp *interp,
- Jim_Obj *objPtr);
- JIM_EXPORT int Jim_SetFinalizer (Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *cmdNamePtr);
- JIM_EXPORT int Jim_GetFinalizer (Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj **cmdNamePtrPtr);
- JIM_EXPORT Jim_Interp * Jim_CreateInterp (void);
- JIM_EXPORT void Jim_FreeInterp (Jim_Interp *i);
- JIM_EXPORT int Jim_GetExitCode (Jim_Interp *interp);
- JIM_EXPORT const char *Jim_ReturnCode(int code);
- JIM_EXPORT void Jim_SetResultFormatted(Jim_Interp *interp, const char *format, ...);
- JIM_EXPORT void Jim_RegisterCoreCommands (Jim_Interp *interp);
- JIM_EXPORT int Jim_CreateCommand (Jim_Interp *interp,
- const char *cmdName, Jim_CmdProc *cmdProc, void *privData,
- Jim_DelCmdProc *delProc);
- JIM_EXPORT int Jim_DeleteCommand (Jim_Interp *interp,
- Jim_Obj *cmdNameObj);
- JIM_EXPORT int Jim_RenameCommand (Jim_Interp *interp,
- Jim_Obj *oldNameObj, Jim_Obj *newNameObj);
- JIM_EXPORT Jim_Cmd * Jim_GetCommand (Jim_Interp *interp,
- Jim_Obj *objPtr, int flags);
- JIM_EXPORT int Jim_SetVariable (Jim_Interp *interp,
- Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr);
- JIM_EXPORT int Jim_SetVariableStr (Jim_Interp *interp,
- const char *name, Jim_Obj *objPtr);
- JIM_EXPORT int Jim_SetGlobalVariableStr (Jim_Interp *interp,
- const char *name, Jim_Obj *objPtr);
- JIM_EXPORT int Jim_SetVariableStrWithStr (Jim_Interp *interp,
- const char *name, const char *val);
- JIM_EXPORT int Jim_SetVariableLink (Jim_Interp *interp,
- Jim_Obj *nameObjPtr, Jim_Obj *targetNameObjPtr,
- Jim_CallFrame *targetCallFrame);
- JIM_EXPORT Jim_Obj * Jim_MakeGlobalNamespaceName(Jim_Interp *interp,
- Jim_Obj *nameObjPtr);
- JIM_EXPORT Jim_Obj * Jim_GetVariable (Jim_Interp *interp,
- Jim_Obj *nameObjPtr, int flags);
- JIM_EXPORT Jim_Obj * Jim_GetGlobalVariable (Jim_Interp *interp,
- Jim_Obj *nameObjPtr, int flags);
- JIM_EXPORT Jim_Obj * Jim_GetVariableStr (Jim_Interp *interp,
- const char *name, int flags);
- JIM_EXPORT Jim_Obj * Jim_GetGlobalVariableStr (Jim_Interp *interp,
- const char *name, int flags);
- JIM_EXPORT int Jim_UnsetVariable (Jim_Interp *interp,
- Jim_Obj *nameObjPtr, int flags);
- JIM_EXPORT Jim_CallFrame *Jim_GetCallFrameByLevel(Jim_Interp *interp,
- Jim_Obj *levelObjPtr);
- JIM_EXPORT int Jim_Collect (Jim_Interp *interp);
- JIM_EXPORT void Jim_CollectIfNeeded (Jim_Interp *interp);
- JIM_EXPORT int Jim_GetIndex (Jim_Interp *interp, Jim_Obj *objPtr,
- int *indexPtr);
- JIM_EXPORT Jim_Obj * Jim_NewListObj (Jim_Interp *interp,
- Jim_Obj *const *elements, int len);
- JIM_EXPORT void Jim_ListInsertElements (Jim_Interp *interp,
- Jim_Obj *listPtr, int listindex, int objc, Jim_Obj *const *objVec);
- JIM_EXPORT void Jim_ListAppendElement (Jim_Interp *interp,
- Jim_Obj *listPtr, Jim_Obj *objPtr);
- JIM_EXPORT void Jim_ListAppendList (Jim_Interp *interp,
- Jim_Obj *listPtr, Jim_Obj *appendListPtr);
- JIM_EXPORT int Jim_ListLength (Jim_Interp *interp, Jim_Obj *objPtr);
- JIM_EXPORT int Jim_ListIndex (Jim_Interp *interp, Jim_Obj *listPrt,
- int listindex, Jim_Obj **objPtrPtr, int seterr);
- JIM_EXPORT Jim_Obj *Jim_ListGetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx);
- JIM_EXPORT int Jim_SetListIndex (Jim_Interp *interp,
- Jim_Obj *varNamePtr, Jim_Obj *const *indexv, int indexc,
- Jim_Obj *newObjPtr);
- JIM_EXPORT Jim_Obj * Jim_ConcatObj (Jim_Interp *interp, int objc,
- Jim_Obj *const *objv);
- JIM_EXPORT Jim_Obj *Jim_ListJoin(Jim_Interp *interp,
- Jim_Obj *listObjPtr, const char *joinStr, int joinStrLen);
- JIM_EXPORT Jim_Obj * Jim_NewDictObj (Jim_Interp *interp,
- Jim_Obj *const *elements, int len);
- JIM_EXPORT int Jim_DictKey (Jim_Interp *interp, Jim_Obj *dictPtr,
- Jim_Obj *keyPtr, Jim_Obj **objPtrPtr, int flags);
- JIM_EXPORT int Jim_DictKeysVector (Jim_Interp *interp,
- Jim_Obj *dictPtr, Jim_Obj *const *keyv, int keyc,
- Jim_Obj **objPtrPtr, int flags);
- JIM_EXPORT int Jim_SetDictKeysVector (Jim_Interp *interp,
- Jim_Obj *varNamePtr, Jim_Obj *const *keyv, int keyc,
- Jim_Obj *newObjPtr, int flags);
- JIM_EXPORT Jim_Obj **Jim_DictPairs(Jim_Interp *interp,
- Jim_Obj *dictPtr, int *len);
- JIM_EXPORT int Jim_DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
- Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr);
- #define JIM_DICTMATCH_KEYS 0x0001
- #define JIM_DICTMATCH_VALUES 0x002
- JIM_EXPORT int Jim_DictMatchTypes(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *patternObj, int match_type, int return_types);
- JIM_EXPORT int Jim_DictSize(Jim_Interp *interp, Jim_Obj *objPtr);
- JIM_EXPORT int Jim_DictInfo(Jim_Interp *interp, Jim_Obj *objPtr);
- JIM_EXPORT Jim_Obj *Jim_DictMerge(Jim_Interp *interp, int objc, Jim_Obj *const *objv);
- JIM_EXPORT int Jim_GetReturnCode (Jim_Interp *interp, Jim_Obj *objPtr,
- int *intPtr);
- JIM_EXPORT int Jim_EvalExpression (Jim_Interp *interp,
- Jim_Obj *exprObjPtr);
- JIM_EXPORT int Jim_GetBoolFromExpr (Jim_Interp *interp,
- Jim_Obj *exprObjPtr, int *boolPtr);
- JIM_EXPORT int Jim_GetBoolean(Jim_Interp *interp, Jim_Obj *objPtr,
- int *booleanPtr);
- JIM_EXPORT int Jim_GetWide (Jim_Interp *interp, Jim_Obj *objPtr,
- jim_wide *widePtr);
- JIM_EXPORT int Jim_GetWideExpr(Jim_Interp *interp, Jim_Obj *objPtr,
- jim_wide *widePtr);
- JIM_EXPORT int Jim_GetLong (Jim_Interp *interp, Jim_Obj *objPtr,
- long *longPtr);
- #define Jim_NewWideObj Jim_NewIntObj
- JIM_EXPORT Jim_Obj * Jim_NewIntObj (Jim_Interp *interp,
- jim_wide wideValue);
- JIM_EXPORT int Jim_GetDouble(Jim_Interp *interp, Jim_Obj *objPtr,
- double *doublePtr);
- JIM_EXPORT void Jim_SetDouble(Jim_Interp *interp, Jim_Obj *objPtr,
- double doubleValue);
- JIM_EXPORT Jim_Obj * Jim_NewDoubleObj(Jim_Interp *interp, double doubleValue);
- JIM_EXPORT void Jim_WrongNumArgs (Jim_Interp *interp, int argc,
- Jim_Obj *const *argv, const char *msg);
- JIM_EXPORT int Jim_GetEnum (Jim_Interp *interp, Jim_Obj *objPtr,
- const char * const *tablePtr, int *indexPtr, const char *name, int flags);
- JIM_EXPORT int Jim_CheckShowCommands(Jim_Interp *interp, Jim_Obj *objPtr,
- const char *const *tablePtr);
- JIM_EXPORT int Jim_ScriptIsComplete(Jim_Interp *interp,
- Jim_Obj *scriptObj, char *stateCharPtr);
- JIM_EXPORT int Jim_FindByName(const char *name, const char * const array[], size_t len);
- typedef void (Jim_InterpDeleteProc)(Jim_Interp *interp, void *data);
- JIM_EXPORT void * Jim_GetAssocData(Jim_Interp *interp, const char *key);
- JIM_EXPORT int Jim_SetAssocData(Jim_Interp *interp, const char *key,
- Jim_InterpDeleteProc *delProc, void *data);
- JIM_EXPORT int Jim_DeleteAssocData(Jim_Interp *interp, const char *key);
- JIM_EXPORT int Jim_CheckAbiVersion(Jim_Interp *interp, int abi_version);
- JIM_EXPORT int Jim_PackageProvide (Jim_Interp *interp,
- const char *name, const char *ver, int flags);
- JIM_EXPORT int Jim_PackageRequire (Jim_Interp *interp,
- const char *name, int flags);
- #define Jim_PackageProvideCheck(INTERP, NAME) \
- if (Jim_CheckAbiVersion(INTERP, JIM_ABI_VERSION) == JIM_ERR || Jim_PackageProvide(INTERP, NAME, "1.0", JIM_ERRMSG)) \
- return JIM_ERR
- JIM_EXPORT void Jim_MakeErrorMessage (Jim_Interp *interp);
- JIM_EXPORT int Jim_InteractivePrompt (Jim_Interp *interp);
- JIM_EXPORT void Jim_HistoryLoad(const char *filename);
- JIM_EXPORT void Jim_HistorySave(const char *filename);
- JIM_EXPORT char *Jim_HistoryGetline(Jim_Interp *interp, const char *prompt);
- JIM_EXPORT void Jim_HistorySetCompletion(Jim_Interp *interp, Jim_Obj *completionCommandObj);
- JIM_EXPORT void Jim_HistorySetHints(Jim_Interp *interp, Jim_Obj *hintsCommandObj);
- JIM_EXPORT void Jim_HistoryAdd(const char *line);
- JIM_EXPORT void Jim_HistoryShow(void);
- JIM_EXPORT void Jim_HistorySetMaxLen(int length);
- JIM_EXPORT int Jim_HistoryGetMaxLen(void);
- JIM_EXPORT int Jim_InitStaticExtensions(Jim_Interp *interp);
- JIM_EXPORT int Jim_StringToWide(const char *str, jim_wide *widePtr, int base);
- JIM_EXPORT int Jim_IsBigEndian(void);
- #define Jim_CheckSignal(i) ((i)->signal_level && (i)->sigmask)
- JIM_EXPORT void Jim_SignalSetIgnored(jim_wide mask);
- JIM_EXPORT int Jim_LoadLibrary(Jim_Interp *interp, const char *pathName);
- JIM_EXPORT void Jim_FreeLoadHandles(Jim_Interp *interp);
- JIM_EXPORT int Jim_AioFilehandle(Jim_Interp *interp, Jim_Obj *command);
- JIM_EXPORT int Jim_IsDict(Jim_Obj *objPtr);
- JIM_EXPORT int Jim_IsList(Jim_Obj *objPtr);
- #ifdef __cplusplus
- }
- #endif
- #endif
- #ifndef JIM_SUBCMD_H
- #define JIM_SUBCMD_H
- #ifdef __cplusplus
- extern "C" {
- #endif
- #define JIM_MODFLAG_HIDDEN 0x0001
- #define JIM_MODFLAG_FULLARGV 0x0002
- typedef int jim_subcmd_function(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
- typedef struct {
- const char *cmd;
- const char *args;
- jim_subcmd_function *function;
- short minargs;
- short maxargs;
- unsigned short flags;
- } jim_subcmd_type;
- #define JIM_DEF_SUBCMD(name, args, minargs, maxargs) { name, args, NULL, minargs, maxargs }
- #define JIM_DEF_SUBCMD_HIDDEN(name, args, minargs, maxargs) { name, args, NULL, minargs, maxargs, JIM_MODFLAG_HIDDEN }
- const jim_subcmd_type *
- Jim_ParseSubCmd(Jim_Interp *interp, const jim_subcmd_type *command_table, int argc, Jim_Obj *const *argv);
- int Jim_SubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
- int Jim_CallSubCmd(Jim_Interp *interp, const jim_subcmd_type *ct, int argc, Jim_Obj *const *argv);
- void Jim_SubCmdArgError(Jim_Interp *interp, const jim_subcmd_type *ct, Jim_Obj *subcmd);
- #ifdef __cplusplus
- }
- #endif
- #endif
- #ifndef JIMREGEXP_H
- #define JIMREGEXP_H
- #ifdef __cplusplus
- extern "C" {
- #endif
- #include <stdlib.h>
- typedef struct {
- int rm_so;
- int rm_eo;
- } regmatch_t;
- typedef struct regexp {
- int re_nsub;
- int cflags;
- int err;
- int regstart;
- int reganch;
- int regmust;
- int regmlen;
- int *program;
- const char *regparse;
- int p;
- int proglen;
- int eflags;
- const char *start;
- const char *reginput;
- const char *regbol;
- regmatch_t *pmatch;
- int nmatch;
- } regexp;
- typedef regexp regex_t;
- #define REG_EXTENDED 0
- #define REG_NEWLINE 1
- #define REG_ICASE 2
- #define REG_NOTBOL 16
- enum {
- REG_NOERROR,
- REG_NOMATCH,
- REG_BADPAT,
- REG_ERR_NULL_ARGUMENT,
- REG_ERR_UNKNOWN,
- REG_ERR_TOO_BIG,
- REG_ERR_NOMEM,
- REG_ERR_TOO_MANY_PAREN,
- REG_ERR_UNMATCHED_PAREN,
- REG_ERR_UNMATCHED_BRACES,
- REG_ERR_BAD_COUNT,
- REG_ERR_JUNK_ON_END,
- REG_ERR_OPERAND_COULD_BE_EMPTY,
- REG_ERR_NESTED_COUNT,
- REG_ERR_INTERNAL,
- REG_ERR_COUNT_FOLLOWS_NOTHING,
- REG_ERR_INVALID_ESCAPE,
- REG_ERR_CORRUPTED,
- REG_ERR_NULL_CHAR,
- REG_ERR_UNMATCHED_BRACKET,
- REG_ERR_NUM
- };
- int jim_regcomp(regex_t *preg, const char *regex, int cflags);
- int jim_regexec(regex_t *preg, const char *string, size_t nmatch, regmatch_t pmatch[], int eflags);
- size_t jim_regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size);
- void jim_regfree(regex_t *preg);
- #ifdef __cplusplus
- }
- #endif
- #endif
- #ifndef JIM_SIGNAL_H
- #define JIM_SIGNAL_H
- #ifdef __cplusplus
- extern "C" {
- #endif
- const char *Jim_SignalId(int sig);
- #ifdef __cplusplus
- }
- #endif
- #endif
- #ifndef JIMIOCOMPAT_H
- #define JIMIOCOMPAT_H
- #include <stdio.h>
- #include <errno.h>
- #include <sys/stat.h>
- void Jim_SetResultErrno(Jim_Interp *interp, const char *msg);
- int Jim_OpenForWrite(const char *filename, int append);
- int Jim_OpenForRead(const char *filename);
- #if defined(__MINGW32__) || defined(_WIN32)
- #ifndef STRICT
- #define STRICT
- #endif
- #define WIN32_LEAN_AND_MEAN
- #include <windows.h>
- #include <fcntl.h>
- #include <io.h>
- #include <process.h>
- typedef HANDLE phandle_t;
- #define JIM_BAD_PHANDLE INVALID_HANDLE_VALUE
- #define WIFEXITED(STATUS) (((STATUS) & 0xff00) == 0)
- #define WEXITSTATUS(STATUS) ((STATUS) & 0x00ff)
- #define WIFSIGNALED(STATUS) (((STATUS) & 0xff00) != 0)
- #define WTERMSIG(STATUS) (((STATUS) >> 8) & 0xff)
- #define WNOHANG 1
- int Jim_Errno(void);
- long waitpid(phandle_t phandle, int *status, int nohang);
- phandle_t JimWaitPid(long processid, int *status, int nohang);
- long JimProcessPid(phandle_t phandle);
- #define HAVE_PIPE
- #define pipe(P) _pipe((P), 0, O_NOINHERIT)
- typedef struct __stat64 jim_stat_t;
- #define Jim_Stat _stat64
- #define Jim_FileStat _fstat64
- #define Jim_Lseek _lseeki64
- #define O_TEXT _O_TEXT
- #else
- #if defined(HAVE_STAT64)
- typedef struct stat64 jim_stat_t;
- #define Jim_Stat stat64
- #if defined(HAVE_FSTAT64)
- #define Jim_FileStat fstat64
- #endif
- #if defined(HAVE_LSTAT64)
- #define Jim_LinkStat lstat64
- #endif
- #else
- typedef struct stat jim_stat_t;
- #define Jim_Stat stat
- #if defined(HAVE_FSTAT)
- #define Jim_FileStat fstat
- #endif
- #if defined(HAVE_LSTAT)
- #define Jim_LinkStat lstat
- #endif
- #endif
- #if defined(HAVE_LSEEK64)
- #define Jim_Lseek lseek64
- #else
- #define Jim_Lseek lseek
- #endif
- #if defined(HAVE_UNISTD_H)
- #include <unistd.h>
- #include <fcntl.h>
- #include <sys/wait.h>
- typedef int phandle_t;
- #define Jim_Errno() errno
- #define JIM_BAD_PHANDLE -1
- #define JimProcessPid(PIDTYPE) (PIDTYPE)
- #define JimWaitPid waitpid
- #ifndef HAVE_EXECVPE
- #define execvpe(ARG0, ARGV, ENV) execvp(ARG0, ARGV)
- #endif
- #endif
- #ifndef O_TEXT
- #define O_TEXT 0
- #endif
- #endif
- int Jim_FileStoreStatData(Jim_Interp *interp, Jim_Obj *varName, const jim_stat_t *sb);
- #endif
- int Jim_bootstrapInit(Jim_Interp *interp)
- {
- if (Jim_PackageProvide(interp, "bootstrap", "1.0", JIM_ERRMSG))
- return JIM_ERR;
- return Jim_EvalSource(interp, "bootstrap.tcl", 1,
- "\n"
- "proc package {cmd args} {\n"
- " if {$cmd eq \"require\"} {\n"
- " foreach path $::auto_path {\n"
- " lassign $args pkg\n"
- " set pkgpath $path/$pkg.tcl\n"
- " if {$path eq \".\"} {\n"
- " set pkgpath $pkg.tcl\n"
- " }\n"
- " if {[file exists $pkgpath]} {\n"
- " tailcall uplevel #0 [list source $pkgpath]\n"
- " }\n"
- " }\n"
- " }\n"
- "}\n"
- "set tcl_platform(bootstrap) 1\n"
- );
- }
- int Jim_initjimshInit(Jim_Interp *interp)
- {
- if (Jim_PackageProvide(interp, "initjimsh", "1.0", JIM_ERRMSG))
- return JIM_ERR;
- return Jim_EvalSource(interp, "initjimsh.tcl", 1,
- "\n"
- "\n"
- "\n"
- "proc _jimsh_init {} {\n"
- " rename _jimsh_init {}\n"
- " global jim::exe jim::argv0 tcl_interactive auto_path tcl_platform\n"
- "\n"
- "\n"
- " if {[exists jim::argv0]} {\n"
- " if {[string match \"*/*\" $jim::argv0]} {\n"
- " set jim::exe [file join [pwd] $jim::argv0]\n"
- " } else {\n"
- " set jim::argv0 [file tail $jim::argv0]\n"
- " set path [split [env PATH \"\"] $tcl_platform(pathSeparator)]\n"
- " if {$tcl_platform(platform) eq \"windows\"} {\n"
- "\n"
- " set path [lmap p [list \"\" {*}$path] { string map {\\\\ /} $p }]\n"
- " }\n"
- " foreach p $path {\n"
- " set exec [file join [pwd] $p $jim::argv0]\n"
- " if {[file executable $exec]} {\n"
- " set jim::exe $exec\n"
- " break\n"
- " }\n"
- " }\n"
- " }\n"
- " }\n"
- "\n"
- "\n"
- " lappend p {*}[split [env JIMLIB {}] $tcl_platform(pathSeparator)]\n"
- " if {[exists jim::exe]} {\n"
- " lappend p [file dirname $jim::exe]\n"
- " }\n"
- " lappend p {*}$auto_path\n"
- " set auto_path $p\n"
- "\n"
- " if {$tcl_interactive && [env HOME {}] ne \"\"} {\n"
- " foreach src {.jimrc jimrc.tcl} {\n"
- " if {[file exists [env HOME]/$src]} {\n"
- " uplevel #0 source [env HOME]/$src\n"
- " break\n"
- " }\n"
- " }\n"
- " }\n"
- " return \"\"\n"
- "}\n"
- "\n"
- "if {$tcl_platform(platform) eq \"windows\"} {\n"
- " set jim::argv0 [string map {\\\\ /} $jim::argv0]\n"
- "}\n"
- "\n"
- "\n"
- "set tcl::autocomplete_commands {array clock debug dict file history info namespace package signal socket string tcl::prefix zlib}\n"
- "\n"
- "\n"
- "\n"
- "proc tcl::autocomplete {prefix} {\n"
- " if {[set space [string first \" \" $prefix]] != -1} {\n"
- " set cmd [string range $prefix 0 $space-1]\n"
- " if {$cmd in $::tcl::autocomplete_commands || [info channel $cmd] ne \"\"} {\n"
- " set arg [string range $prefix $space+1 end]\n"
- "\n"
- " return [lmap p [$cmd -commands] {\n"
- " if {![string match \"${arg}*\" $p]} continue\n"
- " function \"$cmd $p\"\n"
- " }]\n"
- " }\n"
- " }\n"
- "\n"
- " if {[string match \"source *\" $prefix]} {\n"
- " set path [string range $prefix 7 end]\n"
- " return [lmap p [glob -nocomplain \"${path}*\"] {\n"
- " function \"source $p\"\n"
- " }]\n"
- " }\n"
- "\n"
- " return [lmap p [lsort [info commands $prefix*]] {\n"
- " if {[string match \"* *\" $p]} {\n"
- " continue\n"
- " }\n"
- " function $p\n"
- " }]\n"
- "}\n"
- "\n"
- "\n"
- "set tcl::stdhint_commands {array clock debug dict file history info namespace package signal string zlib}\n"
- "\n"
- "set tcl::stdhint_cols {\n"
- " none {0}\n"
- " black {30}\n"
- " red {31}\n"
- " green {32}\n"
- " yellow {33}\n"
- " blue {34}\n"
- " purple {35}\n"
- " cyan {36}\n"
- " normal {37}\n"
- " grey {30 1}\n"
- " gray {30 1}\n"
- " lred {31 1}\n"
- " lgreen {32 1}\n"
- " lyellow {33 1}\n"
- " lblue {34 1}\n"
- " lpurple {35 1}\n"
- " lcyan {36 1}\n"
- " white {37 1}\n"
- "}\n"
- "\n"
- "\n"
- "set tcl::stdhint_col $tcl::stdhint_cols(lcyan)\n"
- "\n"
- "\n"
- "proc tcl::stdhint {string} {\n"
- " set result \"\"\n"
- " if {[llength $string] >= 2} {\n"
- " lassign $string cmd arg\n"
- " if {$cmd in $::tcl::stdhint_commands || [info channel $cmd] ne \"\"} {\n"
- " catch {\n"
- " set help [$cmd -help $arg]\n"
- " if {[string match \"Usage: $cmd *\" $help]} {\n"
- " set n [llength $string]\n"
- " set subcmd [lindex $help $n]\n"
- " incr n\n"
- " set hint [join [lrange $help $n end]]\n"
- " set prefix \"\"\n"
- " if {![string match \"* \" $string]} {\n"
- " if {$n == 3 && $subcmd ne $arg} {\n"
- "\n"
- " set prefix \"[string range $subcmd [string length $arg] end] \"\n"
- " } else {\n"
- " set prefix \" \"\n"
- " }\n"
- " }\n"
- " set result [list $prefix$hint {*}$::tcl::stdhint_col]\n"
- " }\n"
- " }\n"
- " }\n"
- " }\n"
- " return $result\n"
- "}\n"
- "\n"
- "_jimsh_init\n"
- );
- }
- int Jim_globInit(Jim_Interp *interp)
- {
- if (Jim_PackageProvide(interp, "glob", "1.0", JIM_ERRMSG))
- return JIM_ERR;
- return Jim_EvalSource(interp, "glob.tcl", 1,
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "package require readdir\n"
- "\n"
- "\n"
- "proc glob.globdir {dir pattern} {\n"
- " if {[file exists $dir/$pattern]} {\n"
- "\n"
- " return [list $pattern]\n"
- " }\n"
- "\n"
- " set result {}\n"
- " set files [readdir $dir]\n"
- " lappend files . ..\n"
- "\n"
- " foreach name $files {\n"
- " if {[string match $pattern $name]} {\n"
- "\n"
- " if {[string index $name 0] eq \".\" && [string index $pattern 0] ne \".\"} {\n"
- " continue\n"
- " }\n"
- " lappend result $name\n"
- " }\n"
- " }\n"
- "\n"
- " return $result\n"
- "}\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "proc glob.explode {pattern} {\n"
- " set oldexp {}\n"
- " set newexp {\"\"}\n"
- "\n"
- " while 1 {\n"
- " set oldexp $newexp\n"
- " set newexp {}\n"
- " set ob [string first \\{ $pattern]\n"
- " set cb [string first \\} $pattern]\n"
- "\n"
- " if {$ob < $cb && $ob != -1} {\n"
- " set mid [string range $pattern 0 $ob-1]\n"
- " set subexp [lassign [glob.explode [string range $pattern $ob+1 end]] pattern]\n"
- " if {$pattern eq \"\"} {\n"
- " error \"unmatched open brace in glob pattern\"\n"
- " }\n"
- " set pattern [string range $pattern 1 end]\n"
- "\n"
- " foreach subs $subexp {\n"
- " foreach sub [split $subs ,] {\n"
- " foreach old $oldexp {\n"
- " lappend newexp $old$mid$sub\n"
- " }\n"
- " }\n"
- " }\n"
- " } elseif {$cb != -1} {\n"
- " set suf [string range $pattern 0 $cb-1]\n"
- " set rest [string range $pattern $cb end]\n"
- " break\n"
- " } else {\n"
- " set suf $pattern\n"
- " set rest \"\"\n"
- " break\n"
- " }\n"
- " }\n"
- "\n"
- " foreach old $oldexp {\n"
- " lappend newexp $old$suf\n"
- " }\n"
- " list $rest {*}$newexp\n"
- "}\n"
- "\n"
- "\n"
- "\n"
- "proc glob.glob {base pattern} {\n"
- " set dir [file dirname $pattern]\n"
- " if {$pattern eq $dir || $pattern eq \"\"} {\n"
- " return [list [file join $base $dir] $pattern]\n"
- " } elseif {$pattern eq [file tail $pattern]} {\n"
- " set dir \"\"\n"
- " }\n"
- "\n"
- "\n"
- " set dirlist [glob.glob $base $dir]\n"
- " set pattern [file tail $pattern]\n"
- "\n"
- "\n"
- " set result {}\n"
- " foreach {realdir dir} $dirlist {\n"
- " if {![file isdir $realdir]} {\n"
- " continue\n"
- " }\n"
- " if {[string index $dir end] ne \"/\" && $dir ne \"\"} {\n"
- " append dir /\n"
- " }\n"
- " foreach name [glob.globdir $realdir $pattern] {\n"
- " lappend result [file join $realdir $name] $dir$name\n"
- " }\n"
- " }\n"
- " return $result\n"
- "}\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "proc glob {args} {\n"
- " set nocomplain 0\n"
- " set base \"\"\n"
- " set tails 0\n"
- "\n"
- " set n 0\n"
- " foreach arg $args {\n"
- " if {[info exists param]} {\n"
- " set $param $arg\n"
- " unset param\n"
- " incr n\n"
- " continue\n"
- " }\n"
- " switch -glob -- $arg {\n"
- " -d* {\n"
- " set switch $arg\n"
- " set param base\n"
- " }\n"
- " -n* {\n"
- " set nocomplain 1\n"
- " }\n"
- " -ta* {\n"
- " set tails 1\n"
- " }\n"
- " -- {\n"
- " incr n\n"
- " break\n"
- " }\n"
- " -* {\n"
- " return -code error \"bad option \\\"$arg\\\": must be -directory, -nocomplain, -tails, or --\"\n"
- " }\n"
- " * {\n"
- " break\n"
- " }\n"
- " }\n"
- " incr n\n"
- " }\n"
- " if {[info exists param]} {\n"
- " return -code error \"missing argument to \\\"$switch\\\"\"\n"
- " }\n"
- " if {[llength $args] <= $n} {\n"
- " return -code error \"wrong # args: should be \\\"glob ?options? pattern ?pattern ...?\\\"\"\n"
- " }\n"
- "\n"
- " set args [lrange $args $n end]\n"
- "\n"
- " set result {}\n"
- " foreach pattern $args {\n"
- " set escpattern [string map {\n"
- " \\\\\\\\ \\x01 \\\\\\{ \\x02 \\\\\\} \\x03 \\\\, \\x04\n"
- " } $pattern]\n"
- " set patexps [lassign [glob.explode $escpattern] rest]\n"
- " if {$rest ne \"\"} {\n"
- " return -code error \"unmatched close brace in glob pattern\"\n"
- " }\n"
- " foreach patexp $patexps {\n"
- " set patexp [string map {\n"
- " \\x01 \\\\\\\\ \\x02 \\{ \\x03 \\} \\x04 ,\n"
- " } $patexp]\n"
- " foreach {realname name} [glob.glob $base $patexp] {\n"
- " incr n\n"
- " if {$tails} {\n"
- " lappend result $name\n"
- " } else {\n"
- " lappend result [file join $base $name]\n"
- " }\n"
- " }\n"
- " }\n"
- " }\n"
- "\n"
- " if {!$nocomplain && [llength $result] == 0} {\n"
- " set s $(([llength $args] > 1) ? \"s\" : \"\")\n"
- " return -code error \"no files matched glob pattern$s \\\"[join $args]\\\"\"\n"
- " }\n"
- "\n"
- " return $result\n"
- "}\n"
- );
- }
- int Jim_stdlibInit(Jim_Interp *interp)
- {
- if (Jim_PackageProvide(interp, "stdlib", "1.0", JIM_ERRMSG))
- return JIM_ERR;
- return Jim_EvalSource(interp, "stdlib.tcl", 1,
- "\n"
- "\n"
- "if {![exists -command ref]} {\n"
- "\n"
- " proc ref {args} {{count 0}} {\n"
- " format %08x [incr count]\n"
- " }\n"
- "}\n"
- "\n"
- "\n"
- "proc lambda {arglist args} {\n"
- " tailcall proc [ref {} function lambda.finalizer] $arglist {*}$args\n"
- "}\n"
- "\n"
- "proc lambda.finalizer {name val} {\n"
- " rename $name {}\n"
- "}\n"
- "\n"
- "\n"
- "proc curry {args} {\n"
- " alias [ref {} function lambda.finalizer] {*}$args\n"
- "}\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "proc function {value} {\n"
- " return $value\n"
- "}\n"
- "\n"
- "\n"
- "proc stackdump {stacktrace} {\n"
- " set lines {}\n"
- " lappend lines \"Traceback (most recent call last):\"\n"
- " foreach {cmd l f p} [lreverse $stacktrace] {\n"
- " set line {}\n"
- " if {$f ne \"\"} {\n"
- " append line \" File \\\"$f\\\", line $l\"\n"
- " }\n"
- " if {$p ne \"\"} {\n"
- " append line \", in $p\"\n"
- " }\n"
- " if {$line ne \"\"} {\n"
- " lappend lines $line\n"
- " if {$cmd ne \"\"} {\n"
- " set nl [string first \\n $cmd 1]\n"
- " if {$nl >= 0} {\n"
- " set cmd [string range $cmd 0 $nl-1]...\n"
- " }\n"
- " lappend lines \" $cmd\"\n"
- " }\n"
- " }\n"
- " }\n"
- " if {[llength $lines] > 1} {\n"
- " return [join $lines \\n]\n"
- " }\n"
- "}\n"
- "\n"
- "\n"
- "\n"
- "proc defer {script} {\n"
- " upvar jim::defer v\n"
- " lappend v $script\n"
- "}\n"
- "\n"
- "\n"
- "\n"
- "proc errorInfo {msg {stacktrace \"\"}} {\n"
- " if {$stacktrace eq \"\"} {\n"
- "\n"
- " set stacktrace [info stacktrace]\n"
- " }\n"
- " lassign $stacktrace p f l cmd\n"
- " if {$f ne \"\"} {\n"
- " set result \"$f:$l: Error: \"\n"
- " }\n"
- " append result \"$msg\\n\"\n"
- " append result [stackdump $stacktrace]\n"
- "\n"
- "\n"
- " string trim $result\n"
- "}\n"
- "\n"
- "\n"
- "\n"
- "proc {info nameofexecutable} {} {\n"
- " if {[exists ::jim::exe]} {\n"
- " return $::jim::exe\n"
- " }\n"
- "}\n"
- "\n"
- "\n"
- "proc {dict update} {&varName args script} {\n"
- " set keys {}\n"
- " foreach {n v} $args {\n"
- " upvar $v var_$v\n"
- " if {[dict exists $varName $n]} {\n"
- " set var_$v [dict get $varName $n]\n"
- " }\n"
- " }\n"
- " catch {uplevel 1 $script} msg opts\n"
- " if {[info exists varName]} {\n"
- " foreach {n v} $args {\n"
- " if {[info exists var_$v]} {\n"
- " dict set varName $n [set var_$v]\n"
- " } else {\n"
- " dict unset varName $n\n"
- " }\n"
- " }\n"
- " }\n"
- " return {*}$opts $msg\n"
- "}\n"
- "\n"
- "proc {dict replace} {dictionary {args {key value}}} {\n"
- " if {[llength ${key value}] % 2} {\n"
- " tailcall {dict replace}\n"
- " }\n"
- " tailcall dict merge $dictionary ${key value}\n"
- "}\n"
- "\n"
- "\n"
- "proc {dict lappend} {varName key {args value}} {\n"
- " upvar $varName dict\n"
- " if {[exists dict] && [dict exists $dict $key]} {\n"
- " set list [dict get $dict $key]\n"
- " }\n"
- " lappend list {*}$value\n"
- " dict set dict $key $list\n"
- "}\n"
- "\n"
- "\n"
- "proc {dict append} {varName key {args value}} {\n"
- " upvar $varName dict\n"
- " if {[exists dict] && [dict exists $dict $key]} {\n"
- " set str [dict get $dict $key]\n"
- " }\n"
- " append str {*}$value\n"
- " dict set dict $key $str\n"
- "}\n"
- "\n"
- "\n"
- "proc {dict incr} {varName key {increment 1}} {\n"
- " upvar $varName dict\n"
- " if {[exists dict] && [dict exists $dict $key]} {\n"
- " set value [dict get $dict $key]\n"
- " }\n"
- " incr value $increment\n"
- " dict set dict $key $value\n"
- "}\n"
- "\n"
- "\n"
- "proc {dict remove} {dictionary {args key}} {\n"
- " foreach k $key {\n"
- " dict unset dictionary $k\n"
- " }\n"
- " return $dictionary\n"
- "}\n"
- "\n"
- "\n"
- "proc {dict for} {vars dictionary script} {\n"
- " if {[llength $vars] != 2} {\n"
- " return -code error \"must have exactly two variable names\"\n"
- " }\n"
- " dict size $dictionary\n"
- " tailcall foreach $vars $dictionary $script\n"
- "}\n"
- );
- }
- int Jim_tclcompatInit(Jim_Interp *interp)
- {
- if (Jim_PackageProvide(interp, "tclcompat", "1.0", JIM_ERRMSG))
- return JIM_ERR;
- return Jim_EvalSource(interp, "tclcompat.tcl", 1,
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "set env [env]\n"
- "\n"
- "\n"
- "if {[exists -command stdout]} {\n"
- "\n"
- " foreach p {gets flush close eof seek tell} {\n"
- " proc $p {chan args} {p} {\n"
- " tailcall $chan $p {*}$args\n"
- " }\n"
- " }\n"
- " unset p\n"
- "\n"
- "\n"
- "\n"
- " proc puts {{-nonewline {}} {chan stdout} msg} {\n"
- " if {${-nonewline} ni {-nonewline {}}} {\n"
- " tailcall ${-nonewline} puts $msg\n"
- " }\n"
- " tailcall $chan puts {*}${-nonewline} $msg\n"
- " }\n"
- "\n"
- "\n"
- "\n"
- "\n"
- "\n"
- " proc read {{-nonewline {}} chan} {\n"
- " if {${-nonewline} ni {-nonewline {}}} {\n"
- " tailcall ${-nonewline} read {*}${chan}\n"
- " }\n"
- " tailcall $chan read {*}${-nonewline}\n"
- " }\n"
- "\n"
- " proc fconfigure {f args} {\n"
- " foreach {n v} $args {\n"
- " switch -glob -- $n {\n"
- " -bl* {\n"
- " $f ndelay $(!$v)\n"
- " }\n"
- " -bu* {\n"
- " $f buffering $v\n"
- " }\n"
- " -tr* {\n"
- "\n"
- " }\n"
- " default {\n"
- " return -code error \"fconfigure: unknown option $n\"\n"
- " }\n"
- " }\n"
- " }\n"
- " }\n"
- "}\n"
- "\n"
- "\n"
- "proc fileevent {args} {\n"
- " tailcall {*}$args\n"
- "}\n"
- "\n"
- "\n"
- "\n"
- "proc parray {arrayname {pattern *} {puts puts}} {\n"
- " upvar $arrayname a\n"
- "\n"
- " set max 0\n"
- " foreach name [array names a $pattern]] {\n"
- " if {[string length $name] > $max} {\n"
- " set max [string length $name]\n"
- " }\n"
- " }\n"
- " incr max [string length $arrayname]\n"
- " incr max 2\n"
- " foreach name [lsort [array names a $pattern]] {\n"
- " $puts [format \"%-${max}s = %s\" $arrayname\\($name\\) $a($name)]\n"
- " }\n"
- "}\n"
- "\n"
- "\n"
- "proc {file copy} {{force {}} source target} {\n"
- " try {\n"
- " if {$force ni {{} -force}} {\n"
- " error \"bad option \\\"$force\\\": should be -force\"\n"
- " }\n"
- "\n"
- " set in [open $source rb]\n"
- "\n"
- " if {[file exists $target]} {\n"
- " if {$force eq \"\"} {\n"
- " error \"error copying \\\"$source\\\" to \\\"$target\\\": file already exists\"\n"
- " }\n"
- "\n"
- " if {$source eq $target} {\n"
- " return\n"
- " }\n"
- "\n"
- "\n"
- " file stat $source ss\n"
- " file stat $target ts\n"
- " if {$ss(dev) == $ts(dev) && $ss(ino) == $ts(ino) && $ss(ino)} {\n"
- " return\n"
- " }\n"
- " }\n"
- " set out [open $target wb]\n"
- " $in copyto $out\n"
- " $out close\n"
- " } on error {msg opts} {\n"
- " incr opts(-level)\n"
- " return {*}$opts $msg\n"
- " } finally {\n"
- " catch {$in close}\n"
- " }\n"
- "}\n"
- "\n"
- "\n"
- "\n"
- "proc popen {cmd {mode r}} {\n"
- " lassign [pipe] r w\n"
- " try {\n"
- " if {[string match \"w*\" $mode]} {\n"
- " lappend cmd <@$r &\n"
- " set pids [exec {*}$cmd]\n"
- " $r close\n"
- " set f $w\n"
- " } else {\n"
- " lappend cmd >@$w &\n"
- " set pids [exec {*}$cmd]\n"
- " $w close\n"
- " set f $r\n"
- " }\n"
- " lambda {cmd args} {f pids} {\n"
- " if {$cmd eq \"pid\"} {\n"
- " return $pids\n"
- " }\n"
- " if {$cmd eq \"close\"} {\n"
- " $f close\n"
- "\n"
- " set retopts {}\n"
- " foreach p $pids {\n"
- " lassign [wait $p] status - rc\n"
- " if {$status eq \"CHILDSTATUS\"} {\n"
- " if {$rc == 0} {\n"
- " continue\n"
- " }\n"
- " set msg \"child process exited abnormally\"\n"
- " } else {\n"
- " set msg \"child killed: received signal\"\n"
- " }\n"
- " set retopts [list -code error -errorcode [list $status $p $rc] $msg]\n"
- " }\n"
- " return {*}$retopts\n"
- " }\n"
- " tailcall $f $cmd {*}$args\n"
- " }\n"
- " } on error {error opts} {\n"
- " $r close\n"
- " $w close\n"
- " error $error\n"
- " }\n"
- "}\n"
- "\n"
- "\n"
- "local proc pid {{channelId {}}} {\n"
- " if {$channelId eq \"\"} {\n"
- " tailcall upcall pid\n"
- " }\n"
- " if {[catch {$channelId tell}]} {\n"
- " return -code error \"can not find channel named \\\"$channelId\\\"\"\n"
- " }\n"
- " if {[catch {$channelId pid} pids]} {\n"
- " return \"\"\n"
- " }\n"
- " return $pids\n"
- "}\n"
- "\n"
- "\n"
- "\n"
- "proc throw {code {msg \"\"}} {\n"
- " return -code $code $msg\n"
- "}\n"
- "\n"
- "\n"
- "proc {file delete force} {path} {\n"
- " foreach e [readdir $path] {\n"
- " file delete -force $path/$e\n"
- " }\n"
- " file delete $path\n"
- "}\n"
- );
- }
- #include <stdio.h>
- #include <string.h>
- #include <errno.h>
- #include <fcntl.h>
- #include <assert.h>
- #ifdef HAVE_UNISTD_H
- #include <unistd.h>
- #include <sys/stat.h>
- #endif
- #ifdef HAVE_UTIL_H
- #include <util.h>
- #endif
- #ifdef HAVE_PTY_H
- #include <pty.h>
- #endif
- #if defined(HAVE_SYS_SOCKET_H) && defined(HAVE_SELECT) && defined(HAVE_NETINET_IN_H) && defined(HAVE_NETDB_H) && defined(HAVE_ARPA_INET_H)
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <netinet/tcp.h>
- #include <arpa/inet.h>
- #include <netdb.h>
- #ifdef HAVE_SYS_UN_H
- #include <sys/un.h>
- #endif
- #define HAVE_SOCKETS
- #elif defined (__MINGW32__)
- #endif
- #if defined(JIM_SSL)
- #include <openssl/ssl.h>
- #include <openssl/err.h>
- #endif
- #ifdef HAVE_TERMIOS_H
- #endif
- #define AIO_CMD_LEN 32
- #define AIO_DEFAULT_RBUF_LEN 256
- #define AIO_DEFAULT_WBUF_LIMIT (64 * 1024)
- #define AIO_KEEPOPEN 1
- #define AIO_NODELETE 2
- #define AIO_EOF 4
- #define AIO_WBUF_NONE 8
- #define AIO_NONBLOCK 16
- #define AIO_ONEREAD 32
- enum wbuftype {
- WBUF_OPT_NONE,
- WBUF_OPT_LINE,
- WBUF_OPT_FULL,
- };
- #if defined(JIM_IPV6)
- #define IPV6 1
- #else
- #define IPV6 0
- #ifndef PF_INET6
- #define PF_INET6 0
- #endif
- #endif
- #if defined(HAVE_SYS_UN_H) && defined(PF_UNIX)
- #define UNIX_SOCKETS 1
- #else
- #define UNIX_SOCKETS 0
- #endif
- #ifndef MAXPATHLEN
- #define MAXPATHLEN JIM_PATH_LEN
- #endif
- static int JimReadableTimeout(int fd, long ms)
- {
- #ifdef HAVE_SELECT
- int retval;
- struct timeval tv;
- fd_set rfds;
- FD_ZERO(&rfds);
- FD_SET(fd, &rfds);
- tv.tv_sec = ms / 1000;
- tv.tv_usec = (ms % 1000) * 1000;
- retval = select(fd + 1, &rfds, NULL, NULL, ms == 0 ? NULL : &tv);
- if (retval > 0) {
- return JIM_OK;
- }
- return JIM_ERR;
- #else
- return JIM_OK;
- #endif
- }
- struct AioFile;
- typedef struct {
- int (*writer)(struct AioFile *af, const char *buf, int len);
- int (*reader)(struct AioFile *af, char *buf, int len, int pending);
- int (*error)(const struct AioFile *af);
- const char *(*strerror)(struct AioFile *af);
- int (*verify)(struct AioFile *af);
- } JimAioFopsType;
- typedef struct AioFile
- {
- Jim_Obj *filename;
- int wbuft;
- int flags;
- long timeout;
- int fd;
- int addr_family;
- void *ssl;
- const JimAioFopsType *fops;
- Jim_Obj *readbuf;
- Jim_Obj *writebuf;
- char *rbuf;
- size_t rbuf_len;
- size_t wbuf_limit;
- } AioFile;
- static void aio_consume(Jim_Obj *objPtr, int n);
- static int stdio_writer(struct AioFile *af, const char *buf, int len)
- {
- int ret = write(af->fd, buf, len);
- if (ret < 0 && errno == EPIPE) {
- aio_consume(af->writebuf, Jim_Length(af->writebuf));
- }
- return ret;
- }
- static int stdio_reader(struct AioFile *af, char *buf, int len, int nb)
- {
- if (nb || af->timeout == 0 || JimReadableTimeout(af->fd, af->timeout) == JIM_OK) {
- int ret;
- errno = 0;
- ret = read(af->fd, buf, len);
- if (ret <= 0 && errno != EAGAIN && errno != EINTR) {
- af->flags |= AIO_EOF;
- }
- return ret;
- }
- errno = ETIMEDOUT;
- return -1;
- }
- static int stdio_error(const AioFile *af)
- {
- if (af->flags & AIO_EOF) {
- return JIM_OK;
- }
- switch (errno) {
- case EAGAIN:
- case EINTR:
- case ETIMEDOUT:
- #ifdef ECONNRESET
- case ECONNRESET:
- #endif
- #ifdef ECONNABORTED
- case ECONNABORTED:
- #endif
- return JIM_OK;
- default:
- return JIM_ERR;
- }
- }
- static const char *stdio_strerror(struct AioFile *af)
- {
- return strerror(errno);
- }
- static const JimAioFopsType stdio_fops = {
- stdio_writer,
- stdio_reader,
- stdio_error,
- stdio_strerror,
- NULL,
- };
- static void aio_set_nonblocking(AioFile *af, int nb)
- {
- #ifdef O_NDELAY
- int old = !!(af->flags & AIO_NONBLOCK);
- if (old != nb) {
- int fmode = fcntl(af->fd, F_GETFL);
- if (nb) {
- fmode |= O_NDELAY;
- af->flags |= AIO_NONBLOCK;
- }
- else {
- fmode &= ~O_NDELAY;
- af->flags &= ~AIO_NONBLOCK;
- }
- (void)fcntl(af->fd, F_SETFL, fmode);
- }
- #endif
- }
- static int aio_start_nonblocking(AioFile *af)
- {
- int old = !!(af->flags & AIO_NONBLOCK);
- if (af->timeout) {
- aio_set_nonblocking(af, 1);
- }
- return old;
- }
- static int JimAioSubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
- static AioFile *JimMakeChannel(Jim_Interp *interp, int fd, Jim_Obj *filename,
- const char *hdlfmt, int family, int flags);
- static const char *JimAioErrorString(AioFile *af)
- {
- if (af && af->fops)
- return af->fops->strerror(af);
- return strerror(errno);
- }
- static void JimAioSetError(Jim_Interp *interp, Jim_Obj *name)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- if (name) {
- Jim_SetResultFormatted(interp, "%#s: %s", name, JimAioErrorString(af));
- }
- else {
- Jim_SetResultString(interp, JimAioErrorString(af), -1);
- }
- }
- static int aio_eof(AioFile *af)
- {
- return af->flags & AIO_EOF;
- }
- static int JimCheckStreamError(Jim_Interp *interp, AioFile *af)
- {
- int ret = 0;
- if (!aio_eof(af)) {
- ret = af->fops->error(af);
- if (ret) {
- JimAioSetError(interp, af->filename);
- }
- }
- return ret;
- }
- static void aio_consume(Jim_Obj *objPtr, int n)
- {
- assert(objPtr->bytes);
- assert(n <= objPtr->length);
- memmove(objPtr->bytes, objPtr->bytes + n, objPtr->length - n + 1);
- objPtr->length -= n;
- }
- static int aio_flush(Jim_Interp *interp, AioFile *af);
- #ifdef jim_ext_eventloop
- static int aio_autoflush(Jim_Interp *interp, void *clientData, int mask)
- {
- AioFile *af = clientData;
- aio_flush(interp, af);
- if (Jim_Length(af->writebuf) == 0) {
- return -1;
- }
- return 0;
- }
- #endif
- static int aio_flush(Jim_Interp *interp, AioFile *af)
- {
- int len;
- const char *pt = Jim_GetString(af->writebuf, &len);
- if (len) {
- int ret = af->fops->writer(af, pt, len);
- if (ret > 0) {
- aio_consume(af->writebuf, ret);
- }
- if (ret < 0) {
- return JimCheckStreamError(interp, af);
- }
- if (Jim_Length(af->writebuf)) {
- #ifdef jim_ext_eventloop
- void *handler = Jim_FindFileHandler(interp, af->fd, JIM_EVENT_WRITABLE);
- if (handler == NULL) {
- Jim_CreateFileHandler(interp, af->fd, JIM_EVENT_WRITABLE, aio_autoflush, af, NULL);
- return JIM_OK;
- }
- else if (handler == af) {
- return JIM_OK;
- }
- #endif
- Jim_SetResultString(interp, "send buffer is full", -1);
- return JIM_ERR;
- }
- }
- return JIM_OK;
- }
- static int aio_read_len(Jim_Interp *interp, AioFile *af, unsigned flags, int neededLen)
- {
- if (!af->readbuf) {
- af->readbuf = Jim_NewStringObj(interp, NULL, 0);
- }
- if (neededLen >= 0) {
- neededLen -= Jim_Length(af->readbuf);
- if (neededLen <= 0) {
- return JIM_OK;
- }
- }
- while (neededLen && !aio_eof(af)) {
- int retval;
- int readlen;
- if (neededLen == -1) {
- readlen = af->rbuf_len;
- }
- else {
- readlen = (neededLen > af->rbuf_len ? af->rbuf_len : neededLen);
- }
- if (!af->rbuf) {
- af->rbuf = Jim_Alloc(af->rbuf_len);
- }
- retval = af->fops->reader(af, af->rbuf, readlen, flags & AIO_NONBLOCK);
- if (retval > 0) {
- if (retval) {
- Jim_AppendString(interp, af->readbuf, af->rbuf, retval);
- }
- if (neededLen != -1) {
- neededLen -= retval;
- }
- if (flags & AIO_ONEREAD) {
- return JIM_OK;
- }
- continue;
- }
- if ((flags & AIO_ONEREAD) || JimCheckStreamError(interp, af)) {
- return JIM_ERR;
- }
- break;
- }
- return JIM_OK;
- }
- static Jim_Obj *aio_read_consume(Jim_Interp *interp, AioFile *af, int neededLen)
- {
- Jim_Obj *objPtr = NULL;
- if (neededLen < 0 || af->readbuf == NULL || Jim_Length(af->readbuf) <= neededLen) {
- objPtr = af->readbuf;
- af->readbuf = NULL;
- }
- else if (af->readbuf) {
- int len;
- const char *pt = Jim_GetString(af->readbuf, &len);
- objPtr = Jim_NewStringObj(interp, pt, neededLen);
- aio_consume(af->readbuf, neededLen);
- }
- return objPtr;
- }
- static void JimAioDelProc(Jim_Interp *interp, void *privData)
- {
- AioFile *af = privData;
- JIM_NOTUSED(interp);
- aio_flush(interp, af);
- Jim_DecrRefCount(interp, af->writebuf);
- #if UNIX_SOCKETS
- if (af->addr_family == PF_UNIX && (af->flags & AIO_NODELETE) == 0) {
- Jim_Obj *filenameObj = aio_sockname(interp, af->fd);
- if (filenameObj) {
- if (Jim_Length(filenameObj)) {
- remove(Jim_String(filenameObj));
- }
- Jim_FreeNewObj(interp, filenameObj);
- }
- }
- #endif
- Jim_DecrRefCount(interp, af->filename);
- #ifdef jim_ext_eventloop
- Jim_DeleteFileHandler(interp, af->fd, JIM_EVENT_READABLE | JIM_EVENT_WRITABLE | JIM_EVENT_EXCEPTION);
- #endif
- #if defined(JIM_SSL)
- if (af->ssl != NULL) {
- SSL_free(af->ssl);
- }
- #endif
- if (!(af->flags & AIO_KEEPOPEN)) {
- close(af->fd);
- }
- if (af->readbuf) {
- Jim_FreeNewObj(interp, af->readbuf);
- }
- Jim_Free(af->rbuf);
- Jim_Free(af);
- }
- static int aio_cmd_read(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- int nonewline = 0;
- jim_wide neededLen = -1;
- static const char * const options[] = { "-pending", "-nonewline", NULL };
- enum { OPT_PENDING, OPT_NONEWLINE };
- int option;
- int nb;
- Jim_Obj *objPtr;
- if (argc) {
- if (*Jim_String(argv[0]) == '-') {
- if (Jim_GetEnum(interp, argv[0], options, &option, NULL, JIM_ERRMSG) != JIM_OK) {
- return JIM_ERR;
- }
- switch (option) {
- case OPT_PENDING:
- break;
- case OPT_NONEWLINE:
- nonewline++;
- break;
- }
- }
- else {
- if (Jim_GetWide(interp, argv[0], &neededLen) != JIM_OK)
- return JIM_ERR;
- if (neededLen < 0) {
- Jim_SetResultString(interp, "invalid parameter: negative len", -1);
- return JIM_ERR;
- }
- }
- argc--;
- argv++;
- }
- if (argc) {
- return -1;
- }
- nb = aio_start_nonblocking(af);
- if (aio_read_len(interp, af, nb ? AIO_NONBLOCK : 0, neededLen) != JIM_OK) {
- aio_set_nonblocking(af, nb);
- return JIM_ERR;
- }
- objPtr = aio_read_consume(interp, af, neededLen);
- aio_set_nonblocking(af, nb);
- if (objPtr) {
- if (nonewline) {
- int len;
- const char *s = Jim_GetString(objPtr, &len);
- if (len > 0 && s[len - 1] == '\n') {
- objPtr->length--;
- objPtr->bytes[objPtr->length] = '\0';
- }
- }
- Jim_SetResult(interp, objPtr);
- }
- else {
- Jim_SetEmptyResult(interp);
- }
- return JIM_OK;
- }
- int Jim_AioFilehandle(Jim_Interp *interp, Jim_Obj *command)
- {
- Jim_Cmd *cmdPtr = Jim_GetCommand(interp, command, JIM_ERRMSG);
- if (cmdPtr && !cmdPtr->isproc && cmdPtr->u.native.cmdProc == JimAioSubCmdProc) {
- return ((AioFile *) cmdPtr->u.native.privData)->fd;
- }
- Jim_SetResultFormatted(interp, "Not a filehandle: \"%#s\"", command);
- return -1;
- }
- static int aio_cmd_getfd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- aio_flush(interp, af);
- Jim_SetResultInt(interp, af->fd);
- return JIM_OK;
- }
- static int aio_cmd_copy(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- jim_wide count = 0;
- jim_wide maxlen = JIM_WIDE_MAX;
- int ok = 1;
- Jim_Obj *objv[4];
- if (argc == 2) {
- if (Jim_GetWide(interp, argv[1], &maxlen) != JIM_OK) {
- return JIM_ERR;
- }
- }
- objv[0] = argv[0];
- objv[1] = Jim_NewStringObj(interp, "flush", -1);
- if (Jim_EvalObjVector(interp, 2, objv) != JIM_OK) {
- Jim_SetResultFormatted(interp, "Not a filehandle: \"%#s\"", argv[0]);
- return JIM_ERR;
- }
- objv[0] = argv[0];
- objv[1] = Jim_NewStringObj(interp, "puts", -1);
- objv[2] = Jim_NewStringObj(interp, "-nonewline", -1);
- Jim_IncrRefCount(objv[1]);
- Jim_IncrRefCount(objv[2]);
- while (count < maxlen) {
- jim_wide len = maxlen - count;
- if (len > af->rbuf_len) {
- len = af->rbuf_len;
- }
- if (aio_read_len(interp, af, 0, len) != JIM_OK) {
- ok = 0;
- break;
- }
- objv[3] = aio_read_consume(interp, af, len);
- count += Jim_Length(objv[3]);
- if (Jim_EvalObjVector(interp, 4, objv) != JIM_OK) {
- ok = 0;
- break;
- }
- if (aio_eof(af)) {
- break;
- }
- if (count >= 16384 && af->rbuf_len < 65536) {
- af->rbuf_len = 65536;
- af->rbuf = Jim_Realloc(af->rbuf, af->rbuf_len);
- }
- }
- Jim_DecrRefCount(interp, objv[1]);
- Jim_DecrRefCount(interp, objv[2]);
- if (!ok) {
- return JIM_ERR;
- }
- Jim_SetResultInt(interp, count);
- return JIM_OK;
- }
- static int aio_cmd_gets(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- Jim_Obj *objPtr = NULL;
- int len;
- int nb;
- unsigned flags = AIO_ONEREAD;
- char *nl = NULL;
- int offset = 0;
- errno = 0;
- nb = aio_start_nonblocking(af);
- if (nb) {
- flags |= AIO_NONBLOCK;
- }
- while (!aio_eof(af)) {
- if (af->readbuf) {
- const char *pt = Jim_GetString(af->readbuf, &len);
- nl = memchr(pt + offset, '\n', len - offset);
- if (nl) {
- objPtr = Jim_NewStringObj(interp, pt, nl - pt);
- aio_consume(af->readbuf, nl - pt + 1);
- break;
- }
- offset = len;
- }
- if (aio_read_len(interp, af, flags, -1) != JIM_OK) {
- break;
- }
- }
- aio_set_nonblocking(af, nb);
- if (!nl && aio_eof(af) && af->readbuf) {
- objPtr = af->readbuf;
- af->readbuf = NULL;
- }
- else if (!objPtr) {
- objPtr = Jim_NewStringObj(interp, NULL, 0);
- }
- if (argc) {
- if (Jim_SetVariable(interp, argv[0], objPtr) != JIM_OK) {
- Jim_FreeNewObj(interp, objPtr);
- return JIM_ERR;
- }
- len = Jim_Length(objPtr);
- if (!nl && len == 0) {
- len = -1;
- }
- Jim_SetResultInt(interp, len);
- }
- else {
- Jim_SetResult(interp, objPtr);
- }
- return JIM_OK;
- }
- static int aio_cmd_puts(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- int wlen;
- const char *wdata;
- Jim_Obj *strObj;
- int wnow = 0;
- int nl = 1;
- if (argc == 2) {
- if (!Jim_CompareStringImmediate(interp, argv[0], "-nonewline")) {
- return -1;
- }
- strObj = argv[1];
- nl = 0;
- }
- else {
- strObj = argv[0];
- }
- #ifdef JIM_MAINTAINER
- if (Jim_IsShared(af->writebuf)) {
- Jim_DecrRefCount(interp, af->writebuf);
- af->writebuf = Jim_DuplicateObj(interp, af->writebuf);
- Jim_IncrRefCount(af->writebuf);
- }
- #endif
- Jim_AppendObj(interp, af->writebuf, strObj);
- if (nl) {
- Jim_AppendString(interp, af->writebuf, "\n", 1);
- }
- wdata = Jim_GetString(af->writebuf, &wlen);
- switch (af->wbuft) {
- case WBUF_OPT_NONE:
- wnow = 1;
- break;
- case WBUF_OPT_LINE:
- if (nl || memchr(wdata, '\n', wlen) != NULL) {
- wnow = 1;
- }
- break;
- case WBUF_OPT_FULL:
- if (wlen >= af->wbuf_limit) {
- wnow = 1;
- }
- break;
- }
- if (wnow) {
- return aio_flush(interp, af);
- }
- return JIM_OK;
- }
- static int aio_cmd_isatty(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- #ifdef HAVE_ISATTY
- AioFile *af = Jim_CmdPrivData(interp);
- Jim_SetResultInt(interp, isatty(af->fd));
- #else
- Jim_SetResultInt(interp, 0);
- #endif
- return JIM_OK;
- }
- static int aio_cmd_flush(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- return aio_flush(interp, af);
- }
- static int aio_cmd_eof(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- Jim_SetResultInt(interp, !!aio_eof(af));
- return JIM_OK;
- }
- static int aio_cmd_close(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- if (argc == 3) {
- int option = -1;
- #if defined(HAVE_SOCKETS)
- static const char * const options[] = { "r", "w", "-nodelete", NULL };
- enum { OPT_R, OPT_W, OPT_NODELETE };
- if (Jim_GetEnum(interp, argv[2], options, &option, NULL, JIM_ERRMSG) != JIM_OK) {
- return JIM_ERR;
- }
- #endif
- switch (option) {
- #if defined(HAVE_SHUTDOWN)
- case OPT_R:
- case OPT_W:
- if (shutdown(af->fd, option == OPT_R ? SHUT_RD : SHUT_WR) == 0) {
- return JIM_OK;
- }
- JimAioSetError(interp, NULL);
- return JIM_ERR;
- #endif
- #if UNIX_SOCKETS
- case OPT_NODELETE:
- if (af->addr_family == PF_UNIX) {
- af->flags |= AIO_NODELETE;
- break;
- }
- #endif
- default:
- Jim_SetResultString(interp, "not supported", -1);
- return JIM_ERR;
- }
- }
- af->flags &= ~AIO_KEEPOPEN;
- return Jim_DeleteCommand(interp, argv[0]);
- }
- static int aio_cmd_seek(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- int orig = SEEK_SET;
- jim_wide offset;
- if (argc == 2) {
- if (Jim_CompareStringImmediate(interp, argv[1], "start"))
- orig = SEEK_SET;
- else if (Jim_CompareStringImmediate(interp, argv[1], "current"))
- orig = SEEK_CUR;
- else if (Jim_CompareStringImmediate(interp, argv[1], "end"))
- orig = SEEK_END;
- else {
- return -1;
- }
- }
- if (Jim_GetWide(interp, argv[0], &offset) != JIM_OK) {
- return JIM_ERR;
- }
- if (orig != SEEK_CUR || offset != 0) {
- aio_flush(interp, af);
- }
- if (Jim_Lseek(af->fd, offset, orig) == -1) {
- JimAioSetError(interp, af->filename);
- return JIM_ERR;
- }
- if (af->readbuf) {
- Jim_FreeNewObj(interp, af->readbuf);
- af->readbuf = NULL;
- }
- af->flags &= ~AIO_EOF;
- return JIM_OK;
- }
- static int aio_cmd_tell(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- Jim_SetResultInt(interp, Jim_Lseek(af->fd, 0, SEEK_CUR));
- return JIM_OK;
- }
- static int aio_cmd_filename(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- Jim_SetResult(interp, af->filename);
- return JIM_OK;
- }
- #ifdef O_NDELAY
- static int aio_cmd_ndelay(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- if (argc) {
- long nb;
- if (Jim_GetLong(interp, argv[0], &nb) != JIM_OK) {
- return JIM_ERR;
- }
- aio_set_nonblocking(af, nb);
- }
- Jim_SetResultInt(interp, (af->flags & AIO_NONBLOCK) ? 1 : 0);
- return JIM_OK;
- }
- #endif
- #ifdef HAVE_FSYNC
- static int aio_cmd_sync(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- if (aio_flush(interp, af) != JIM_OK) {
- return JIM_ERR;
- }
- fsync(af->fd);
- return JIM_OK;
- }
- #endif
- static int aio_cmd_buffering(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- Jim_Obj *resultObj;
- static const char * const options[] = {
- "none",
- "line",
- "full",
- NULL
- };
- if (argc) {
- if (Jim_GetEnum(interp, argv[0], options, &af->wbuft, NULL, JIM_ERRMSG) != JIM_OK) {
- return JIM_ERR;
- }
- if (af->wbuft == WBUF_OPT_FULL && argc == 2) {
- long l;
- if (Jim_GetLong(interp, argv[1], &l) != JIM_OK || l <= 0) {
- return JIM_ERR;
- }
- af->wbuf_limit = l;
- }
- if (af->wbuft == WBUF_OPT_NONE) {
- if (aio_flush(interp, af) != JIM_OK) {
- return JIM_ERR;
- }
- }
- }
- resultObj = Jim_NewListObj(interp, NULL, 0);
- Jim_ListAppendElement(interp, resultObj, Jim_NewStringObj(interp, options[af->wbuft], -1));
- if (af->wbuft == WBUF_OPT_FULL) {
- Jim_ListAppendElement(interp, resultObj, Jim_NewIntObj(interp, af->wbuf_limit));
- }
- Jim_SetResult(interp, resultObj);
- return JIM_OK;
- }
- static int aio_cmd_readsize(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- if (argc) {
- long l;
- if (Jim_GetLong(interp, argv[0], &l) != JIM_OK || l <= 0) {
- return JIM_ERR;
- }
- af->rbuf_len = l;
- if (af->rbuf) {
- af->rbuf = Jim_Realloc(af->rbuf, af->rbuf_len);
- }
- }
- Jim_SetResultInt(interp, af->rbuf_len);
- return JIM_OK;
- }
- #ifdef jim_ext_eventloop
- static int aio_cmd_timeout(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- #ifdef HAVE_SELECT
- AioFile *af = Jim_CmdPrivData(interp);
- if (argc == 1) {
- if (Jim_GetLong(interp, argv[0], &af->timeout) != JIM_OK) {
- return JIM_ERR;
- }
- }
- Jim_SetResultInt(interp, af->timeout);
- return JIM_OK;
- #else
- Jim_SetResultString(interp, "timeout not supported", -1);
- return JIM_ERR;
- #endif
- }
- static int aio_eventinfo(Jim_Interp *interp, AioFile * af, unsigned mask,
- int argc, Jim_Obj * const *argv)
- {
- if (argc == 0) {
- Jim_Obj *objPtr = Jim_FindFileHandler(interp, af->fd, mask);
- if (objPtr) {
- Jim_SetResult(interp, objPtr);
- }
- return JIM_OK;
- }
- Jim_DeleteFileHandler(interp, af->fd, mask);
- if (Jim_Length(argv[0])) {
- Jim_CreateScriptFileHandler(interp, af->fd, mask, argv[0]);
- }
- return JIM_OK;
- }
- static int aio_cmd_readable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- return aio_eventinfo(interp, af, JIM_EVENT_READABLE, argc, argv);
- }
- static int aio_cmd_writable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- return aio_eventinfo(interp, af, JIM_EVENT_WRITABLE, argc, argv);
- }
- static int aio_cmd_onexception(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- AioFile *af = Jim_CmdPrivData(interp);
- return aio_eventinfo(interp, af, JIM_EVENT_EXCEPTION, argc, argv);
- }
- #endif
- #if defined(jim_ext_file) && defined(Jim_FileStat)
- static int aio_cmd_stat(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- jim_stat_t sb;
- AioFile *af = Jim_CmdPrivData(interp);
- if (Jim_FileStat(af->fd, &sb) == -1) {
- JimAioSetError(interp, NULL);
- return JIM_ERR;
- }
- return Jim_FileStoreStatData(interp, argc == 0 ? NULL : argv[0], &sb);
- }
- #endif
- static const jim_subcmd_type aio_command_table[] = {
- { "read",
- "?-nonewline|len?",
- aio_cmd_read,
- 0,
- 2,
- },
- { "copyto",
- "handle ?size?",
- aio_cmd_copy,
- 1,
- 2,
- },
- { "getfd",
- NULL,
- aio_cmd_getfd,
- 0,
- 0,
- },
- { "gets",
- "?var?",
- aio_cmd_gets,
- 0,
- 1,
- },
- { "puts",
- "?-nonewline? str",
- aio_cmd_puts,
- 1,
- 2,
- },
- { "isatty",
- NULL,
- aio_cmd_isatty,
- 0,
- 0,
- },
- { "flush",
- NULL,
- aio_cmd_flush,
- 0,
- 0,
- },
- { "eof",
- NULL,
- aio_cmd_eof,
- 0,
- 0,
- },
- { "close",
- "?r(ead)|w(rite)?",
- aio_cmd_close,
- 0,
- 1,
- JIM_MODFLAG_FULLARGV,
- },
- { "seek",
- "offset ?start|current|end",
- aio_cmd_seek,
- 1,
- 2,
- },
- { "tell",
- NULL,
- aio_cmd_tell,
- 0,
- 0,
- },
- { "filename",
- NULL,
- aio_cmd_filename,
- 0,
- 0,
- },
- #ifdef O_NDELAY
- { "ndelay",
- "?0|1?",
- aio_cmd_ndelay,
- 0,
- 1,
- },
- #endif
- #ifdef HAVE_FSYNC
- { "sync",
- NULL,
- aio_cmd_sync,
- 0,
- 0,
- },
- #endif
- { "buffering",
- "?none|line|full? ?size?",
- aio_cmd_buffering,
- 0,
- 2,
- },
- { "readsize",
- "?size?",
- aio_cmd_readsize,
- 0,
- 1,
- },
- #if defined(jim_ext_file) && defined(Jim_FileStat)
- { "stat",
- "?var?",
- aio_cmd_stat,
- 0,
- 1,
- },
- #endif
- #ifdef jim_ext_eventloop
- { "readable",
- "?readable-script?",
- aio_cmd_readable,
- 0,
- 1,
- },
- { "writable",
- "?writable-script?",
- aio_cmd_writable,
- 0,
- 1,
- },
- { "onexception",
- "?exception-script?",
- aio_cmd_onexception,
- 0,
- 1,
- },
- { "timeout",
- "?ms?",
- aio_cmd_timeout,
- 0,
- 1,
- },
- #endif
- { NULL }
- };
- static int JimAioSubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- return Jim_CallSubCmd(interp, Jim_ParseSubCmd(interp, aio_command_table, argc, argv), argc, argv);
- }
- static int parse_posix_open_mode(Jim_Interp *interp, Jim_Obj *modeObj)
- {
- int i;
- int flags = 0;
- #ifndef O_NOCTTY
- #define O_NOCTTY 0
- #endif
- static const char * const modetypes[] = {
- "RDONLY", "WRONLY", "RDWR", "APPEND", "BINARY", "CREAT", "EXCL", "NOCTTY", "TRUNC", NULL
- };
- static const int modeflags[] = {
- O_RDONLY, O_WRONLY, O_RDWR, O_APPEND, 0, O_CREAT, O_EXCL, O_NOCTTY, O_TRUNC,
- };
- for (i = 0; i < Jim_ListLength(interp, modeObj); i++) {
- int opt;
- Jim_Obj *objPtr = Jim_ListGetIndex(interp, modeObj, i);
- if (Jim_GetEnum(interp, objPtr, modetypes, &opt, "access mode", JIM_ERRMSG) != JIM_OK) {
- return -1;
- }
- flags |= modeflags[opt];
- }
- return flags;
- }
- static int parse_open_mode(Jim_Interp *interp, Jim_Obj *filenameObj, Jim_Obj *modeObj)
- {
- int flags;
- const char *mode = Jim_String(modeObj);
- if (*mode == 'R' || *mode == 'W') {
- return parse_posix_open_mode(interp, modeObj);
- }
- if (*mode == 'r') {
- flags = O_RDONLY;
- }
- else if (*mode == 'w') {
- flags = O_WRONLY | O_CREAT | O_TRUNC;
- }
- else if (*mode == 'a') {
- flags = O_WRONLY | O_CREAT | O_APPEND;
- }
- else {
- Jim_SetResultFormatted(interp, "%s: invalid open mode '%s'", Jim_String(filenameObj), mode);
- return -1;
- }
- mode++;
- if (*mode == 'b') {
- #ifdef O_BINARY
- flags |= O_BINARY;
- #endif
- mode++;
- }
- if (*mode == 't') {
- #ifdef O_TEXT
- flags |= O_TEXT;
- #endif
- mode++;
- }
- if (*mode == '+') {
- mode++;
- flags &= ~(O_RDONLY | O_WRONLY);
- flags |= O_RDWR;
- }
- if (*mode == 'x') {
- mode++;
- #ifdef O_EXCL
- flags |= O_EXCL;
- #endif
- }
- if (*mode == 'F') {
- mode++;
- #ifdef O_LARGEFILE
- flags |= O_LARGEFILE;
- #endif
- }
- if (*mode == 'e') {
- mode++;
- }
- return flags;
- }
- static int JimAioOpenCommand(Jim_Interp *interp, int argc,
- Jim_Obj *const *argv)
- {
- int openflags;
- const char *filename;
- int fd = -1;
- int n = 0;
- int flags = 0;
- if (argc > 2 && Jim_CompareStringImmediate(interp, argv[2], "-noclose")) {
- flags = AIO_KEEPOPEN;
- n++;
- }
- if (argc < 2 || argc > 3 + n) {
- Jim_WrongNumArgs(interp, 1, argv, "filename ?-noclose? ?mode?");
- return JIM_ERR;
- }
- filename = Jim_String(argv[1]);
- #ifdef jim_ext_tclcompat
- {
- if (*filename == '|') {
- Jim_Obj *evalObj[3];
- int i = 0;
- evalObj[i++] = Jim_NewStringObj(interp, "::popen", -1);
- evalObj[i++] = Jim_NewStringObj(interp, filename + 1, -1);
- if (argc == 3 + n) {
- evalObj[i++] = argv[2 + n];
- }
- return Jim_EvalObjVector(interp, i, evalObj);
- }
- }
- #endif
- if (argc == 3 + n) {
- openflags = parse_open_mode(interp, argv[1], argv[2 + n]);
- if (openflags == -1) {
- return JIM_ERR;
- }
- }
- else {
- openflags = O_RDONLY;
- }
- fd = open(filename, openflags, 0666);
- if (fd < 0) {
- JimAioSetError(interp, argv[1]);
- return JIM_ERR;
- }
- return JimMakeChannel(interp, fd, argv[1], "aio.handle%ld", 0, flags) ? JIM_OK : JIM_ERR;
- }
- static AioFile *JimMakeChannel(Jim_Interp *interp, int fd, Jim_Obj *filename,
- const char *hdlfmt, int family, int flags)
- {
- AioFile *af;
- char buf[AIO_CMD_LEN];
- Jim_Obj *cmdname;
- snprintf(buf, sizeof(buf), hdlfmt, Jim_GetId(interp));
- cmdname = Jim_NewStringObj(interp, buf, -1);
- if (!filename) {
- filename = cmdname;
- }
- Jim_IncrRefCount(filename);
- af = Jim_Alloc(sizeof(*af));
- memset(af, 0, sizeof(*af));
- af->filename = filename;
- af->fd = fd;
- af->addr_family = family;
- af->fops = &stdio_fops;
- af->ssl = NULL;
- if (flags & AIO_WBUF_NONE) {
- af->wbuft = WBUF_OPT_NONE;
- }
- else {
- #ifdef HAVE_ISATTY
- af->wbuft = isatty(af->fd) ? WBUF_OPT_LINE : WBUF_OPT_FULL;
- #else
- af->wbuft = WBUF_OPT_FULL;
- #endif
- }
- #ifdef FD_CLOEXEC
- if ((flags & AIO_KEEPOPEN) == 0) {
- (void)fcntl(af->fd, F_SETFD, FD_CLOEXEC);
- }
- #endif
- aio_set_nonblocking(af, !!(flags & AIO_NONBLOCK));
- af->flags |= flags;
- af->writebuf = Jim_NewStringObj(interp, NULL, 0);
- Jim_IncrRefCount(af->writebuf);
- af->wbuf_limit = AIO_DEFAULT_WBUF_LIMIT;
- af->rbuf_len = AIO_DEFAULT_RBUF_LEN;
- Jim_CreateCommand(interp, buf, JimAioSubCmdProc, af, JimAioDelProc);
- Jim_SetResult(interp, Jim_MakeGlobalNamespaceName(interp, cmdname));
- return af;
- }
- #if defined(HAVE_PIPE) || (defined(HAVE_SOCKETPAIR) && UNIX_SOCKETS) || defined(HAVE_OPENPTY)
- static int JimMakeChannelPair(Jim_Interp *interp, int p[2], Jim_Obj *filename,
- const char *hdlfmt, int family, int flags)
- {
- if (JimMakeChannel(interp, p[0], filename, hdlfmt, family, flags)) {
- Jim_Obj *objPtr = Jim_NewListObj(interp, NULL, 0);
- Jim_ListAppendElement(interp, objPtr, Jim_GetResult(interp));
- if (JimMakeChannel(interp, p[1], filename, hdlfmt, family, flags)) {
- Jim_ListAppendElement(interp, objPtr, Jim_GetResult(interp));
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- }
- close(p[0]);
- close(p[1]);
- JimAioSetError(interp, NULL);
- return JIM_ERR;
- }
- #endif
- #ifdef HAVE_PIPE
- static int JimCreatePipe(Jim_Interp *interp, Jim_Obj *filenameObj, int flags)
- {
- int p[2];
- if (pipe(p) != 0) {
- JimAioSetError(interp, NULL);
- return JIM_ERR;
- }
- return JimMakeChannelPair(interp, p, filenameObj, "aio.pipe%ld", 0, flags);
- }
- static int JimAioPipeCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- if (argc != 1) {
- Jim_WrongNumArgs(interp, 1, argv, "");
- return JIM_ERR;
- }
- return JimCreatePipe(interp, argv[0], 0);
- }
- #endif
- #ifdef HAVE_OPENPTY
- static int JimAioOpenPtyCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int p[2];
- char path[MAXPATHLEN];
- if (argc != 1) {
- Jim_WrongNumArgs(interp, 1, argv, "");
- return JIM_ERR;
- }
- if (openpty(&p[0], &p[1], path, NULL, NULL) != 0) {
- JimAioSetError(interp, NULL);
- return JIM_ERR;
- }
- return JimMakeChannelPair(interp, p, Jim_NewStringObj(interp, path, -1), "aio.pty%ld", 0, 0);
- return JimMakeChannelPair(interp, p, Jim_NewStringObj(interp, path, -1), "aio.pty%ld", 0, 0);
- }
- #endif
- int Jim_aioInit(Jim_Interp *interp)
- {
- if (Jim_PackageProvide(interp, "aio", "1.0", JIM_ERRMSG))
- return JIM_ERR;
- #if defined(JIM_SSL)
- Jim_CreateCommand(interp, "load_ssl_certs", JimAioLoadSSLCertsCommand, NULL, NULL);
- #endif
- Jim_CreateCommand(interp, "open", JimAioOpenCommand, NULL, NULL);
- #ifdef HAVE_SOCKETS
- Jim_CreateCommand(interp, "socket", JimAioSockCommand, NULL, NULL);
- #endif
- #ifdef HAVE_PIPE
- Jim_CreateCommand(interp, "pipe", JimAioPipeCommand, NULL, NULL);
- #endif
- JimMakeChannel(interp, fileno(stdin), NULL, "stdin", 0, AIO_KEEPOPEN);
- JimMakeChannel(interp, fileno(stdout), NULL, "stdout", 0, AIO_KEEPOPEN);
- JimMakeChannel(interp, fileno(stderr), NULL, "stderr", 0, AIO_KEEPOPEN | AIO_WBUF_NONE);
- return JIM_OK;
- }
- #include <errno.h>
- #include <stdio.h>
- #include <string.h>
- #ifdef HAVE_DIRENT_H
- #include <dirent.h>
- #endif
- int Jim_ReaddirCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- const char *dirPath;
- DIR *dirPtr;
- struct dirent *entryPtr;
- int nocomplain = 0;
- if (argc == 3 && Jim_CompareStringImmediate(interp, argv[1], "-nocomplain")) {
- nocomplain = 1;
- }
- if (argc != 2 && !nocomplain) {
- Jim_WrongNumArgs(interp, 1, argv, "?-nocomplain? dirPath");
- return JIM_ERR;
- }
- dirPath = Jim_String(argv[1 + nocomplain]);
- dirPtr = opendir(dirPath);
- if (dirPtr == NULL) {
- if (nocomplain) {
- return JIM_OK;
- }
- Jim_SetResultString(interp, strerror(errno), -1);
- return JIM_ERR;
- }
- else {
- Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
- while ((entryPtr = readdir(dirPtr)) != NULL) {
- if (entryPtr->d_name[0] == '.') {
- if (entryPtr->d_name[1] == '\0') {
- continue;
- }
- if ((entryPtr->d_name[1] == '.') && (entryPtr->d_name[2] == '\0'))
- continue;
- }
- Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, entryPtr->d_name, -1));
- }
- closedir(dirPtr);
- Jim_SetResult(interp, listObj);
- return JIM_OK;
- }
- }
- int Jim_readdirInit(Jim_Interp *interp)
- {
- Jim_PackageProvideCheck(interp, "readdir");
- Jim_CreateCommand(interp, "readdir", Jim_ReaddirCmd, NULL, NULL);
- return JIM_OK;
- }
- #include <stdlib.h>
- #include <string.h>
- #if defined(JIM_REGEXP)
- #else
- #include <regex.h>
- #define jim_regcomp regcomp
- #define jim_regexec regexec
- #define jim_regerror regerror
- #define jim_regfree regfree
- #endif
- static void FreeRegexpInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- jim_regfree(objPtr->internalRep.ptrIntValue.ptr);
- Jim_Free(objPtr->internalRep.ptrIntValue.ptr);
- }
- static const Jim_ObjType regexpObjType = {
- "regexp",
- FreeRegexpInternalRep,
- NULL,
- NULL,
- JIM_TYPE_NONE
- };
- static regex_t *SetRegexpFromAny(Jim_Interp *interp, Jim_Obj *objPtr, unsigned flags)
- {
- regex_t *compre;
- const char *pattern;
- int ret;
- if (objPtr->typePtr == ®expObjType &&
- objPtr->internalRep.ptrIntValue.ptr && objPtr->internalRep.ptrIntValue.int1 == flags) {
- return objPtr->internalRep.ptrIntValue.ptr;
- }
- pattern = Jim_String(objPtr);
- compre = Jim_Alloc(sizeof(regex_t));
- if ((ret = jim_regcomp(compre, pattern, REG_EXTENDED | flags)) != 0) {
- char buf[100];
- jim_regerror(ret, compre, buf, sizeof(buf));
- Jim_SetResultFormatted(interp, "couldn't compile regular expression pattern: %s", buf);
- jim_regfree(compre);
- Jim_Free(compre);
- return NULL;
- }
- Jim_FreeIntRep(interp, objPtr);
- objPtr->typePtr = ®expObjType;
- objPtr->internalRep.ptrIntValue.int1 = flags;
- objPtr->internalRep.ptrIntValue.ptr = compre;
- return compre;
- }
- int Jim_RegexpCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int opt_indices = 0;
- int opt_all = 0;
- int opt_inline = 0;
- regex_t *regex;
- int match, i, j;
- int offset = 0;
- regmatch_t *pmatch = NULL;
- int source_len;
- int result = JIM_OK;
- const char *pattern;
- const char *source_str;
- int num_matches = 0;
- int num_vars;
- Jim_Obj *resultListObj = NULL;
- int regcomp_flags = 0;
- int eflags = 0;
- int option;
- enum {
- OPT_INDICES, OPT_NOCASE, OPT_LINE, OPT_ALL, OPT_INLINE, OPT_START, OPT_END
- };
- static const char * const options[] = {
- "-indices", "-nocase", "-line", "-all", "-inline", "-start", "--", NULL
- };
- if (argc < 3) {
- wrongNumArgs:
- Jim_WrongNumArgs(interp, 1, argv,
- "?-switch ...? exp string ?matchVar? ?subMatchVar ...?");
- return JIM_ERR;
- }
- for (i = 1; i < argc; i++) {
- const char *opt = Jim_String(argv[i]);
- if (*opt != '-') {
- break;
- }
- if (Jim_GetEnum(interp, argv[i], options, &option, "switch", JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
- return JIM_ERR;
- }
- if (option == OPT_END) {
- i++;
- break;
- }
- switch (option) {
- case OPT_INDICES:
- opt_indices = 1;
- break;
- case OPT_NOCASE:
- regcomp_flags |= REG_ICASE;
- break;
- case OPT_LINE:
- regcomp_flags |= REG_NEWLINE;
- break;
- case OPT_ALL:
- opt_all = 1;
- break;
- case OPT_INLINE:
- opt_inline = 1;
- break;
- case OPT_START:
- if (++i == argc) {
- goto wrongNumArgs;
- }
- if (Jim_GetIndex(interp, argv[i], &offset) != JIM_OK) {
- return JIM_ERR;
- }
- break;
- }
- }
- if (argc - i < 2) {
- goto wrongNumArgs;
- }
- regex = SetRegexpFromAny(interp, argv[i], regcomp_flags);
- if (!regex) {
- return JIM_ERR;
- }
- pattern = Jim_String(argv[i]);
- source_str = Jim_GetString(argv[i + 1], &source_len);
- num_vars = argc - i - 2;
- if (opt_inline) {
- if (num_vars) {
- Jim_SetResultString(interp, "regexp match variables not allowed when using -inline",
- -1);
- result = JIM_ERR;
- goto done;
- }
- num_vars = regex->re_nsub + 1;
- }
- pmatch = Jim_Alloc((num_vars + 1) * sizeof(*pmatch));
- if (offset) {
- if (offset < 0) {
- offset += source_len + 1;
- }
- if (offset > source_len) {
- source_str += source_len;
- }
- else if (offset > 0) {
- source_str += utf8_index(source_str, offset);
- }
- eflags |= REG_NOTBOL;
- }
- if (opt_inline) {
- resultListObj = Jim_NewListObj(interp, NULL, 0);
- }
- next_match:
- match = jim_regexec(regex, source_str, num_vars + 1, pmatch, eflags);
- if (match >= REG_BADPAT) {
- char buf[100];
- jim_regerror(match, regex, buf, sizeof(buf));
- Jim_SetResultFormatted(interp, "error while matching pattern: %s", buf);
- result = JIM_ERR;
- goto done;
- }
- if (match == REG_NOMATCH) {
- goto done;
- }
- num_matches++;
- if (opt_all && !opt_inline) {
- goto try_next_match;
- }
- j = 0;
- for (i += 2; opt_inline ? j < num_vars : i < argc; i++, j++) {
- Jim_Obj *resultObj;
- if (opt_indices) {
- resultObj = Jim_NewListObj(interp, NULL, 0);
- }
- else {
- resultObj = Jim_NewStringObj(interp, "", 0);
- }
- if (pmatch[j].rm_so == -1) {
- if (opt_indices) {
- Jim_ListAppendElement(interp, resultObj, Jim_NewIntObj(interp, -1));
- Jim_ListAppendElement(interp, resultObj, Jim_NewIntObj(interp, -1));
- }
- }
- else {
- if (opt_indices) {
- int so = utf8_strlen(source_str, pmatch[j].rm_so);
- int eo = utf8_strlen(source_str, pmatch[j].rm_eo);
- Jim_ListAppendElement(interp, resultObj, Jim_NewIntObj(interp, offset + so));
- Jim_ListAppendElement(interp, resultObj, Jim_NewIntObj(interp, offset + eo - 1));
- }
- else {
- Jim_AppendString(interp, resultObj, source_str + pmatch[j].rm_so, pmatch[j].rm_eo - pmatch[j].rm_so);
- }
- }
- if (opt_inline) {
- Jim_ListAppendElement(interp, resultListObj, resultObj);
- }
- else {
- result = Jim_SetVariable(interp, argv[i], resultObj);
- if (result != JIM_OK) {
- Jim_FreeObj(interp, resultObj);
- break;
- }
- }
- }
- try_next_match:
- if (opt_all && (pattern[0] != '^' || (regcomp_flags & REG_NEWLINE)) && *source_str) {
- if (pmatch[0].rm_eo) {
- offset += utf8_strlen(source_str, pmatch[0].rm_eo);
- source_str += pmatch[0].rm_eo;
- }
- else {
- source_str++;
- offset++;
- }
- if (*source_str) {
- eflags = REG_NOTBOL;
- goto next_match;
- }
- }
- done:
- if (result == JIM_OK) {
- if (opt_inline) {
- Jim_SetResult(interp, resultListObj);
- }
- else {
- Jim_SetResultInt(interp, num_matches);
- }
- }
- Jim_Free(pmatch);
- return result;
- }
- #define MAX_SUB_MATCHES 50
- int Jim_RegsubCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int regcomp_flags = 0;
- int regexec_flags = 0;
- int opt_all = 0;
- int opt_command = 0;
- int offset = 0;
- regex_t *regex;
- const char *p;
- int result = JIM_OK;
- regmatch_t pmatch[MAX_SUB_MATCHES + 1];
- int num_matches = 0;
- int i, j, n;
- Jim_Obj *varname;
- Jim_Obj *resultObj;
- Jim_Obj *cmd_prefix = NULL;
- Jim_Obj *regcomp_obj = NULL;
- const char *source_str;
- int source_len;
- const char *replace_str = NULL;
- int replace_len;
- const char *pattern;
- int option;
- enum {
- OPT_NOCASE, OPT_LINE, OPT_ALL, OPT_START, OPT_COMMAND, OPT_END
- };
- static const char * const options[] = {
- "-nocase", "-line", "-all", "-start", "-command", "--", NULL
- };
- if (argc < 4) {
- wrongNumArgs:
- Jim_WrongNumArgs(interp, 1, argv,
- "?-switch ...? exp string subSpec ?varName?");
- return JIM_ERR;
- }
- for (i = 1; i < argc; i++) {
- const char *opt = Jim_String(argv[i]);
- if (*opt != '-') {
- break;
- }
- if (Jim_GetEnum(interp, argv[i], options, &option, "switch", JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
- return JIM_ERR;
- }
- if (option == OPT_END) {
- i++;
- break;
- }
- switch (option) {
- case OPT_NOCASE:
- regcomp_flags |= REG_ICASE;
- break;
- case OPT_LINE:
- regcomp_flags |= REG_NEWLINE;
- break;
- case OPT_ALL:
- opt_all = 1;
- break;
- case OPT_START:
- if (++i == argc) {
- goto wrongNumArgs;
- }
- if (Jim_GetIndex(interp, argv[i], &offset) != JIM_OK) {
- return JIM_ERR;
- }
- break;
- case OPT_COMMAND:
- opt_command = 1;
- break;
- }
- }
- if (argc - i != 3 && argc - i != 4) {
- goto wrongNumArgs;
- }
- regcomp_obj = Jim_DuplicateObj(interp, argv[i]);
- Jim_IncrRefCount(regcomp_obj);
- regex = SetRegexpFromAny(interp, regcomp_obj, regcomp_flags);
- if (!regex) {
- Jim_DecrRefCount(interp, regcomp_obj);
- return JIM_ERR;
- }
- pattern = Jim_String(argv[i]);
- source_str = Jim_GetString(argv[i + 1], &source_len);
- if (opt_command) {
- cmd_prefix = argv[i + 2];
- if (Jim_ListLength(interp, cmd_prefix) == 0) {
- Jim_SetResultString(interp, "command prefix must be a list of at least one element", -1);
- Jim_DecrRefCount(interp, regcomp_obj);
- return JIM_ERR;
- }
- Jim_IncrRefCount(cmd_prefix);
- }
- else {
- replace_str = Jim_GetString(argv[i + 2], &replace_len);
- }
- varname = argv[i + 3];
- resultObj = Jim_NewStringObj(interp, "", 0);
- if (offset) {
- if (offset < 0) {
- offset += source_len + 1;
- }
- if (offset > source_len) {
- offset = source_len;
- }
- else if (offset < 0) {
- offset = 0;
- }
- }
- offset = utf8_index(source_str, offset);
- Jim_AppendString(interp, resultObj, source_str, offset);
- n = source_len - offset;
- p = source_str + offset;
- do {
- int match = jim_regexec(regex, p, MAX_SUB_MATCHES, pmatch, regexec_flags);
- if (match >= REG_BADPAT) {
- char buf[100];
- jim_regerror(match, regex, buf, sizeof(buf));
- Jim_SetResultFormatted(interp, "error while matching pattern: %s", buf);
- return JIM_ERR;
- }
- if (match == REG_NOMATCH) {
- break;
- }
- num_matches++;
- Jim_AppendString(interp, resultObj, p, pmatch[0].rm_so);
- if (opt_command) {
- Jim_Obj *cmdListObj = Jim_DuplicateObj(interp, cmd_prefix);
- for (j = 0; j < MAX_SUB_MATCHES; j++) {
- if (pmatch[j].rm_so == -1) {
- break;
- }
- else {
- Jim_Obj *srcObj = Jim_NewStringObj(interp, p + pmatch[j].rm_so, pmatch[j].rm_eo - pmatch[j].rm_so);
- Jim_ListAppendElement(interp, cmdListObj, srcObj);
- }
- }
- Jim_IncrRefCount(cmdListObj);
- result = Jim_EvalObj(interp, cmdListObj);
- Jim_DecrRefCount(interp, cmdListObj);
- if (result != JIM_OK) {
- goto cmd_error;
- }
- Jim_AppendString(interp, resultObj, Jim_String(Jim_GetResult(interp)), -1);
- }
- else {
- for (j = 0; j < replace_len; j++) {
- int idx;
- int c = replace_str[j];
- if (c == '&') {
- idx = 0;
- }
- else if (c == '\\' && j < replace_len) {
- c = replace_str[++j];
- if ((c >= '0') && (c <= '9')) {
- idx = c - '0';
- }
- else if ((c == '\\') || (c == '&')) {
- Jim_AppendString(interp, resultObj, replace_str + j, 1);
- continue;
- }
- else {
- Jim_AppendString(interp, resultObj, replace_str + j - 1, (j == replace_len) ? 1 : 2);
- continue;
- }
- }
- else {
- Jim_AppendString(interp, resultObj, replace_str + j, 1);
- continue;
- }
- if ((idx < MAX_SUB_MATCHES) && pmatch[idx].rm_so != -1 && pmatch[idx].rm_eo != -1) {
- Jim_AppendString(interp, resultObj, p + pmatch[idx].rm_so,
- pmatch[idx].rm_eo - pmatch[idx].rm_so);
- }
- }
- }
- p += pmatch[0].rm_eo;
- n -= pmatch[0].rm_eo;
- if (!opt_all || n == 0) {
- break;
- }
- if ((regcomp_flags & REG_NEWLINE) == 0 && pattern[0] == '^') {
- break;
- }
- if (pattern[0] == '\0' && n) {
- Jim_AppendString(interp, resultObj, p, 1);
- p++;
- n--;
- }
- if (pmatch[0].rm_eo == pmatch[0].rm_so) {
- regexec_flags = REG_NOTBOL;
- }
- else {
- regexec_flags = 0;
- }
- } while (n);
- Jim_AppendString(interp, resultObj, p, -1);
- cmd_error:
- if (result == JIM_OK) {
- if (argc - i == 4) {
- result = Jim_SetVariable(interp, varname, resultObj);
- if (result == JIM_OK) {
- Jim_SetResultInt(interp, num_matches);
- }
- else {
- Jim_FreeObj(interp, resultObj);
- }
- }
- else {
- Jim_SetResult(interp, resultObj);
- result = JIM_OK;
- }
- }
- else {
- Jim_FreeObj(interp, resultObj);
- }
- if (opt_command) {
- Jim_DecrRefCount(interp, cmd_prefix);
- }
- Jim_DecrRefCount(interp, regcomp_obj);
- return result;
- }
- int Jim_regexpInit(Jim_Interp *interp)
- {
- Jim_PackageProvideCheck(interp, "regexp");
- Jim_CreateCommand(interp, "regexp", Jim_RegexpCmd, NULL, NULL);
- Jim_CreateCommand(interp, "regsub", Jim_RegsubCmd, NULL, NULL);
- return JIM_OK;
- }
- #include <limits.h>
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- #include <errno.h>
- #ifdef HAVE_UTIMES
- #include <sys/time.h>
- #endif
- #ifdef HAVE_UNISTD_H
- #include <unistd.h>
- #elif defined(_MSC_VER)
- #include <direct.h>
- #define F_OK 0
- #define W_OK 2
- #define R_OK 4
- #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
- #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
- #endif
- # ifndef MAXPATHLEN
- # ifdef PATH_MAX
- # define MAXPATHLEN PATH_MAX
- # else
- # define MAXPATHLEN JIM_PATH_LEN
- # endif
- # endif
- #if defined(__MINGW32__) || defined(__MSYS__) || defined(_MSC_VER)
- #define ISWINDOWS 1
- #undef HAVE_SYMLINK
- #else
- #define ISWINDOWS 0
- #endif
- #if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
- #define STAT_MTIME_US(STAT) ((STAT).st_mtimespec.tv_sec * 1000000ll + (STAT).st_mtimespec.tv_nsec / 1000)
- #elif defined(HAVE_STRUCT_STAT_ST_MTIM)
- #define STAT_MTIME_US(STAT) ((STAT).st_mtim.tv_sec * 1000000ll + (STAT).st_mtim.tv_nsec / 1000)
- #endif
- static void JimFixPath(char *path)
- {
- if (ISWINDOWS) {
- char *p = path;
- while ((p = strchr(p, '\\')) != NULL) {
- *p++ = '/';
- }
- }
- }
- static const char *JimGetFileType(int mode)
- {
- if (S_ISREG(mode)) {
- return "file";
- }
- else if (S_ISDIR(mode)) {
- return "directory";
- }
- #ifdef S_ISCHR
- else if (S_ISCHR(mode)) {
- return "characterSpecial";
- }
- #endif
- #ifdef S_ISBLK
- else if (S_ISBLK(mode)) {
- return "blockSpecial";
- }
- #endif
- #ifdef S_ISFIFO
- else if (S_ISFIFO(mode)) {
- return "fifo";
- }
- #endif
- #ifdef S_ISLNK
- else if (S_ISLNK(mode)) {
- return "link";
- }
- #endif
- #ifdef S_ISSOCK
- else if (S_ISSOCK(mode)) {
- return "socket";
- }
- #endif
- return "unknown";
- }
- static void AppendStatElement(Jim_Interp *interp, Jim_Obj *listObj, const char *key, jim_wide value)
- {
- Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, key, -1));
- Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, value));
- }
- int Jim_FileStoreStatData(Jim_Interp *interp, Jim_Obj *varName, const jim_stat_t *sb)
- {
- Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
- AppendStatElement(interp, listObj, "dev", sb->st_dev);
- AppendStatElement(interp, listObj, "ino", sb->st_ino);
- AppendStatElement(interp, listObj, "mode", sb->st_mode);
- AppendStatElement(interp, listObj, "nlink", sb->st_nlink);
- AppendStatElement(interp, listObj, "uid", sb->st_uid);
- AppendStatElement(interp, listObj, "gid", sb->st_gid);
- AppendStatElement(interp, listObj, "size", sb->st_size);
- AppendStatElement(interp, listObj, "atime", sb->st_atime);
- AppendStatElement(interp, listObj, "mtime", sb->st_mtime);
- AppendStatElement(interp, listObj, "ctime", sb->st_ctime);
- #ifdef STAT_MTIME_US
- AppendStatElement(interp, listObj, "mtimeus", STAT_MTIME_US(*sb));
- #endif
- Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "type", -1));
- Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, JimGetFileType((int)sb->st_mode), -1));
- if (varName) {
- Jim_Obj *objPtr;
- objPtr = Jim_GetVariable(interp, varName, JIM_NONE);
- if (objPtr) {
- Jim_Obj *objv[2];
- objv[0] = objPtr;
- objv[1] = listObj;
- objPtr = Jim_DictMerge(interp, 2, objv);
- if (objPtr == NULL) {
- Jim_SetResultFormatted(interp, "can't set \"%#s(dev)\": variable isn't array", varName);
- Jim_FreeNewObj(interp, listObj);
- return JIM_ERR;
- }
- Jim_InvalidateStringRep(objPtr);
- Jim_FreeNewObj(interp, listObj);
- listObj = objPtr;
- }
- Jim_SetVariable(interp, varName, listObj);
- }
- Jim_SetResult(interp, listObj);
- return JIM_OK;
- }
- static int JimPathLenNoTrailingSlashes(const char *path, int len)
- {
- int i;
- for (i = len; i > 1 && path[i - 1] == '/'; i--) {
- if (ISWINDOWS && path[i - 2] == ':') {
- break;
- }
- }
- return i;
- }
- static Jim_Obj *JimStripTrailingSlashes(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- int len = Jim_Length(objPtr);
- const char *path = Jim_String(objPtr);
- int i = JimPathLenNoTrailingSlashes(path, len);
- if (i != len) {
- objPtr = Jim_NewStringObj(interp, path, i);
- }
- Jim_IncrRefCount(objPtr);
- return objPtr;
- }
- static int file_cmd_dirname(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *objPtr = JimStripTrailingSlashes(interp, argv[0]);
- const char *path = Jim_String(objPtr);
- const char *p = strrchr(path, '/');
- if (!p) {
- Jim_SetResultString(interp, ".", -1);
- }
- else if (p[1] == 0) {
- Jim_SetResult(interp, objPtr);
- }
- else if (p == path) {
- Jim_SetResultString(interp, "/", -1);
- }
- else if (ISWINDOWS && p[-1] == ':') {
- Jim_SetResultString(interp, path, p - path + 1);
- }
- else {
- int len = JimPathLenNoTrailingSlashes(path, p - path);
- Jim_SetResultString(interp, path, len);
- }
- Jim_DecrRefCount(interp, objPtr);
- return JIM_OK;
- }
- static int file_cmd_split(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
- const char *path = Jim_String(argv[0]);
- if (*path == '/') {
- Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "/", 1));
- }
- while (1) {
- while (*path == '/') {
- path++;
- }
- if (*path) {
- const char *pt = strchr(path, '/');
- if (pt) {
- Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, path, pt - path));
- path = pt;
- continue;
- }
- Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, path, -1));
- }
- break;
- }
- Jim_SetResult(interp, listObj);
- return JIM_OK;
- }
- static int file_cmd_rootname(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- const char *path = Jim_String(argv[0]);
- const char *lastSlash = strrchr(path, '/');
- const char *p = strrchr(path, '.');
- if (p == NULL || (lastSlash != NULL && lastSlash > p)) {
- Jim_SetResult(interp, argv[0]);
- }
- else {
- Jim_SetResultString(interp, path, p - path);
- }
- return JIM_OK;
- }
- static int file_cmd_extension(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *objPtr = JimStripTrailingSlashes(interp, argv[0]);
- const char *path = Jim_String(objPtr);
- const char *lastSlash = strrchr(path, '/');
- const char *p = strrchr(path, '.');
- if (p == NULL || (lastSlash != NULL && lastSlash >= p)) {
- p = "";
- }
- Jim_SetResultString(interp, p, -1);
- Jim_DecrRefCount(interp, objPtr);
- return JIM_OK;
- }
- static int file_cmd_tail(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *objPtr = JimStripTrailingSlashes(interp, argv[0]);
- const char *path = Jim_String(objPtr);
- const char *lastSlash = strrchr(path, '/');
- if (lastSlash) {
- Jim_SetResultString(interp, lastSlash + 1, -1);
- }
- else {
- Jim_SetResult(interp, objPtr);
- }
- Jim_DecrRefCount(interp, objPtr);
- return JIM_OK;
- }
- #ifndef HAVE_RESTRICT
- #define restrict
- #endif
- static char *JimRealPath(const char *restrict path, char *restrict resolved_path, size_t len)
- {
- #if defined(HAVE__FULLPATH)
- return _fullpath(resolved_path, path, len);
- #elif defined(HAVE_REALPATH)
- return realpath(path, resolved_path);
- #else
- return NULL;
- #endif
- }
- static int file_cmd_normalize(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- const char *path = Jim_String(argv[0]);
- char *newname = Jim_Alloc(MAXPATHLEN);
- if (JimRealPath(path, newname, MAXPATHLEN)) {
- JimFixPath(newname);
- Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, newname, -1));
- return JIM_OK;
- }
- Jim_Free(newname);
- Jim_SetResultFormatted(interp, "can't normalize \"%#s\": %s", argv[0], strerror(errno));
- return JIM_ERR;
- }
- static int file_cmd_join(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int i;
- char *newname = Jim_Alloc(MAXPATHLEN + 1);
- char *last = newname;
- *newname = 0;
- for (i = 0; i < argc; i++) {
- int len;
- const char *part = Jim_GetString(argv[i], &len);
- if (*part == '/') {
- last = newname;
- }
- else if (ISWINDOWS && strchr(part, ':')) {
- last = newname;
- }
- else if (part[0] == '.') {
- if (part[1] == '/') {
- part += 2;
- len -= 2;
- }
- else if (part[1] == 0 && last != newname) {
- continue;
- }
- }
- if (last != newname && last[-1] != '/') {
- *last++ = '/';
- }
- if (len) {
- if (last + len - newname >= MAXPATHLEN) {
- Jim_Free(newname);
- Jim_SetResultString(interp, "Path too long", -1);
- return JIM_ERR;
- }
- memcpy(last, part, len);
- last += len;
- }
- if (last > newname + 1 && last[-1] == '/') {
- if (!ISWINDOWS || !(last > newname + 2 && last[-2] == ':')) {
- *--last = 0;
- }
- }
- }
- *last = 0;
- Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, newname, last - newname));
- return JIM_OK;
- }
- static int file_access(Jim_Interp *interp, Jim_Obj *filename, int mode)
- {
- Jim_SetResultBool(interp, access(Jim_String(filename), mode) != -1);
- return JIM_OK;
- }
- static int file_cmd_readable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- return file_access(interp, argv[0], R_OK);
- }
- static int file_cmd_writable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- return file_access(interp, argv[0], W_OK);
- }
- static int file_cmd_executable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- #ifdef X_OK
- return file_access(interp, argv[0], X_OK);
- #else
- Jim_SetResultBool(interp, 1);
- return JIM_OK;
- #endif
- }
- static int file_cmd_exists(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- return file_access(interp, argv[0], F_OK);
- }
- static int file_cmd_delete(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int force = Jim_CompareStringImmediate(interp, argv[0], "-force");
- if (force || Jim_CompareStringImmediate(interp, argv[0], "--")) {
- argc--;
- argv++;
- }
- while (argc--) {
- const char *path = Jim_String(argv[0]);
- if (unlink(path) == -1 && errno != ENOENT) {
- if (rmdir(path) == -1) {
- if (!force || Jim_EvalPrefix(interp, "file delete force", 1, argv) != JIM_OK) {
- Jim_SetResultFormatted(interp, "couldn't delete file \"%s\": %s", path,
- strerror(errno));
- return JIM_ERR;
- }
- }
- }
- argv++;
- }
- return JIM_OK;
- }
- #ifdef HAVE_MKDIR_ONE_ARG
- #define MKDIR_DEFAULT(PATHNAME) mkdir(PATHNAME)
- #else
- #define MKDIR_DEFAULT(PATHNAME) mkdir(PATHNAME, 0755)
- #endif
- static int mkdir_all(char *path)
- {
- int ok = 1;
- goto first;
- while (ok--) {
- {
- char *slash = strrchr(path, '/');
- if (slash && slash != path) {
- *slash = 0;
- if (mkdir_all(path) != 0) {
- return -1;
- }
- *slash = '/';
- }
- }
- first:
- if (MKDIR_DEFAULT(path) == 0) {
- return 0;
- }
- if (errno == ENOENT) {
- continue;
- }
- if (errno == EEXIST) {
- jim_stat_t sb;
- if (Jim_Stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
- return 0;
- }
- errno = EEXIST;
- }
- break;
- }
- return -1;
- }
- static int file_cmd_mkdir(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- while (argc--) {
- char *path = Jim_StrDup(Jim_String(argv[0]));
- int rc = mkdir_all(path);
- Jim_Free(path);
- if (rc != 0) {
- Jim_SetResultFormatted(interp, "can't create directory \"%#s\": %s", argv[0],
- strerror(errno));
- return JIM_ERR;
- }
- argv++;
- }
- return JIM_OK;
- }
- static int file_cmd_tempfile(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int fd = Jim_MakeTempFile(interp, (argc >= 1) ? Jim_String(argv[0]) : NULL, 0);
- if (fd < 0) {
- return JIM_ERR;
- }
- close(fd);
- return JIM_OK;
- }
- static int file_cmd_rename(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- const char *source;
- const char *dest;
- int force = 0;
- if (argc == 3) {
- if (!Jim_CompareStringImmediate(interp, argv[0], "-force")) {
- return -1;
- }
- force++;
- argv++;
- argc--;
- }
- source = Jim_String(argv[0]);
- dest = Jim_String(argv[1]);
- if (!force && access(dest, F_OK) == 0) {
- Jim_SetResultFormatted(interp, "error renaming \"%#s\" to \"%#s\": target exists", argv[0],
- argv[1]);
- return JIM_ERR;
- }
- #if ISWINDOWS
- if (access(dest, F_OK) == 0) {
- remove(dest);
- }
- #endif
- if (rename(source, dest) != 0) {
- Jim_SetResultFormatted(interp, "error renaming \"%#s\" to \"%#s\": %s", argv[0], argv[1],
- strerror(errno));
- return JIM_ERR;
- }
- return JIM_OK;
- }
- #if defined(HAVE_LINK) && defined(HAVE_SYMLINK)
- static int file_cmd_link(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int ret;
- const char *source;
- const char *dest;
- static const char * const options[] = { "-hard", "-symbolic", NULL };
- enum { OPT_HARD, OPT_SYMBOLIC, };
- int option = OPT_HARD;
- if (argc == 3) {
- if (Jim_GetEnum(interp, argv[0], options, &option, NULL, JIM_ENUM_ABBREV | JIM_ERRMSG) != JIM_OK) {
- return JIM_ERR;
- }
- argv++;
- argc--;
- }
- dest = Jim_String(argv[0]);
- source = Jim_String(argv[1]);
- if (option == OPT_HARD) {
- ret = link(source, dest);
- }
- else {
- ret = symlink(source, dest);
- }
- if (ret != 0) {
- Jim_SetResultFormatted(interp, "error linking \"%#s\" to \"%#s\": %s", argv[0], argv[1],
- strerror(errno));
- return JIM_ERR;
- }
- return JIM_OK;
- }
- #endif
- static int file_stat(Jim_Interp *interp, Jim_Obj *filename, jim_stat_t *sb)
- {
- const char *path = Jim_String(filename);
- if (Jim_Stat(path, sb) == -1) {
- Jim_SetResultFormatted(interp, "could not read \"%#s\": %s", filename, strerror(errno));
- return JIM_ERR;
- }
- return JIM_OK;
- }
- #ifdef Jim_LinkStat
- static int file_lstat(Jim_Interp *interp, Jim_Obj *filename, jim_stat_t *sb)
- {
- const char *path = Jim_String(filename);
- if (Jim_LinkStat(path, sb) == -1) {
- Jim_SetResultFormatted(interp, "could not read \"%#s\": %s", filename, strerror(errno));
- return JIM_ERR;
- }
- return JIM_OK;
- }
- #else
- #define file_lstat file_stat
- #endif
- static int file_cmd_atime(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- jim_stat_t sb;
- if (file_stat(interp, argv[0], &sb) != JIM_OK) {
- return JIM_ERR;
- }
- Jim_SetResultInt(interp, sb.st_atime);
- return JIM_OK;
- }
- static int JimSetFileTimes(Jim_Interp *interp, const char *filename, jim_wide us)
- {
- #ifdef HAVE_UTIMES
- struct timeval times[2];
- times[1].tv_sec = times[0].tv_sec = us / 1000000;
- times[1].tv_usec = times[0].tv_usec = us % 1000000;
- if (utimes(filename, times) != 0) {
- Jim_SetResultFormatted(interp, "can't set time on \"%s\": %s", filename, strerror(errno));
- return JIM_ERR;
- }
- return JIM_OK;
- #else
- Jim_SetResultString(interp, "Not implemented", -1);
- return JIM_ERR;
- #endif
- }
- static int file_cmd_mtime(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- jim_stat_t sb;
- if (argc == 2) {
- jim_wide secs;
- if (Jim_GetWide(interp, argv[1], &secs) != JIM_OK) {
- return JIM_ERR;
- }
- return JimSetFileTimes(interp, Jim_String(argv[0]), secs * 1000000);
- }
- if (file_stat(interp, argv[0], &sb) != JIM_OK) {
- return JIM_ERR;
- }
- Jim_SetResultInt(interp, sb.st_mtime);
- return JIM_OK;
- }
- #ifdef STAT_MTIME_US
- static int file_cmd_mtimeus(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- jim_stat_t sb;
- if (argc == 2) {
- jim_wide us;
- if (Jim_GetWide(interp, argv[1], &us) != JIM_OK) {
- return JIM_ERR;
- }
- return JimSetFileTimes(interp, Jim_String(argv[0]), us);
- }
- if (file_stat(interp, argv[0], &sb) != JIM_OK) {
- return JIM_ERR;
- }
- Jim_SetResultInt(interp, STAT_MTIME_US(sb));
- return JIM_OK;
- }
- #endif
- static int file_cmd_copy(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- return Jim_EvalPrefix(interp, "file copy", argc, argv);
- }
- static int file_cmd_size(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- jim_stat_t sb;
- if (file_stat(interp, argv[0], &sb) != JIM_OK) {
- return JIM_ERR;
- }
- Jim_SetResultInt(interp, sb.st_size);
- return JIM_OK;
- }
- static int file_cmd_isdirectory(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- jim_stat_t sb;
- int ret = 0;
- if (file_stat(interp, argv[0], &sb) == JIM_OK) {
- ret = S_ISDIR(sb.st_mode);
- }
- Jim_SetResultInt(interp, ret);
- return JIM_OK;
- }
- static int file_cmd_isfile(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- jim_stat_t sb;
- int ret = 0;
- if (file_stat(interp, argv[0], &sb) == JIM_OK) {
- ret = S_ISREG(sb.st_mode);
- }
- Jim_SetResultInt(interp, ret);
- return JIM_OK;
- }
- #ifdef HAVE_GETEUID
- static int file_cmd_owned(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- jim_stat_t sb;
- int ret = 0;
- if (file_stat(interp, argv[0], &sb) == JIM_OK) {
- ret = (geteuid() == sb.st_uid);
- }
- Jim_SetResultInt(interp, ret);
- return JIM_OK;
- }
- #endif
- #if defined(HAVE_READLINK)
- static int file_cmd_readlink(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- const char *path = Jim_String(argv[0]);
- char *linkValue = Jim_Alloc(MAXPATHLEN + 1);
- int linkLength = readlink(path, linkValue, MAXPATHLEN);
- if (linkLength == -1) {
- Jim_Free(linkValue);
- Jim_SetResultFormatted(interp, "could not read link \"%#s\": %s", argv[0], strerror(errno));
- return JIM_ERR;
- }
- linkValue[linkLength] = 0;
- Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, linkValue, linkLength));
- return JIM_OK;
- }
- #endif
- static int file_cmd_type(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- jim_stat_t sb;
- if (file_lstat(interp, argv[0], &sb) != JIM_OK) {
- return JIM_ERR;
- }
- Jim_SetResultString(interp, JimGetFileType((int)sb.st_mode), -1);
- return JIM_OK;
- }
- #ifdef Jim_LinkStat
- static int file_cmd_lstat(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- jim_stat_t sb;
- if (file_lstat(interp, argv[0], &sb) != JIM_OK) {
- return JIM_ERR;
- }
- return Jim_FileStoreStatData(interp, argc == 2 ? argv[1] : NULL, &sb);
- }
- #else
- #define file_cmd_lstat file_cmd_stat
- #endif
- static int file_cmd_stat(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- jim_stat_t sb;
- if (file_stat(interp, argv[0], &sb) != JIM_OK) {
- return JIM_ERR;
- }
- return Jim_FileStoreStatData(interp, argc == 2 ? argv[1] : NULL, &sb);
- }
- static const jim_subcmd_type file_command_table[] = {
- { "atime",
- "name",
- file_cmd_atime,
- 1,
- 1,
- },
- { "mtime",
- "name ?time?",
- file_cmd_mtime,
- 1,
- 2,
- },
- #ifdef STAT_MTIME_US
- { "mtimeus",
- "name ?time?",
- file_cmd_mtimeus,
- 1,
- 2,
- },
- #endif
- { "copy",
- "?-force? source dest",
- file_cmd_copy,
- 2,
- 3,
- },
- { "dirname",
- "name",
- file_cmd_dirname,
- 1,
- 1,
- },
- { "rootname",
- "name",
- file_cmd_rootname,
- 1,
- 1,
- },
- { "extension",
- "name",
- file_cmd_extension,
- 1,
- 1,
- },
- { "tail",
- "name",
- file_cmd_tail,
- 1,
- 1,
- },
- { "split",
- "name",
- file_cmd_split,
- 1,
- 1,
- },
- { "normalize",
- "name",
- file_cmd_normalize,
- 1,
- 1,
- },
- { "join",
- "name ?name ...?",
- file_cmd_join,
- 1,
- -1,
- },
- { "readable",
- "name",
- file_cmd_readable,
- 1,
- 1,
- },
- { "writable",
- "name",
- file_cmd_writable,
- 1,
- 1,
- },
- { "executable",
- "name",
- file_cmd_executable,
- 1,
- 1,
- },
- { "exists",
- "name",
- file_cmd_exists,
- 1,
- 1,
- },
- { "delete",
- "?-force|--? name ...",
- file_cmd_delete,
- 1,
- -1,
- },
- { "mkdir",
- "dir ...",
- file_cmd_mkdir,
- 1,
- -1,
- },
- { "tempfile",
- "?template?",
- file_cmd_tempfile,
- 0,
- 1,
- },
- { "rename",
- "?-force? source dest",
- file_cmd_rename,
- 2,
- 3,
- },
- #if defined(HAVE_LINK) && defined(HAVE_SYMLINK)
- { "link",
- "?-symbolic|-hard? newname target",
- file_cmd_link,
- 2,
- 3,
- },
- #endif
- #if defined(HAVE_READLINK)
- { "readlink",
- "name",
- file_cmd_readlink,
- 1,
- 1,
- },
- #endif
- { "size",
- "name",
- file_cmd_size,
- 1,
- 1,
- },
- { "stat",
- "name ?var?",
- file_cmd_stat,
- 1,
- 2,
- },
- { "lstat",
- "name ?var?",
- file_cmd_lstat,
- 1,
- 2,
- },
- { "type",
- "name",
- file_cmd_type,
- 1,
- 1,
- },
- #ifdef HAVE_GETEUID
- { "owned",
- "name",
- file_cmd_owned,
- 1,
- 1,
- },
- #endif
- { "isdirectory",
- "name",
- file_cmd_isdirectory,
- 1,
- 1,
- },
- { "isfile",
- "name",
- file_cmd_isfile,
- 1,
- 1,
- },
- {
- NULL
- }
- };
- static int Jim_CdCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- const char *path;
- if (argc != 2) {
- Jim_WrongNumArgs(interp, 1, argv, "dirname");
- return JIM_ERR;
- }
- path = Jim_String(argv[1]);
- if (chdir(path) != 0) {
- Jim_SetResultFormatted(interp, "couldn't change working directory to \"%s\": %s", path,
- strerror(errno));
- return JIM_ERR;
- }
- return JIM_OK;
- }
- static int Jim_PwdCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- char *cwd = Jim_Alloc(MAXPATHLEN);
- if (getcwd(cwd, MAXPATHLEN) == NULL) {
- Jim_SetResultString(interp, "Failed to get pwd", -1);
- Jim_Free(cwd);
- return JIM_ERR;
- }
- JimFixPath(cwd);
- Jim_SetResultString(interp, cwd, -1);
- Jim_Free(cwd);
- return JIM_OK;
- }
- int Jim_fileInit(Jim_Interp *interp)
- {
- Jim_PackageProvideCheck(interp, "file");
- Jim_CreateCommand(interp, "file", Jim_SubCmdProc, (void *)file_command_table, NULL);
- Jim_CreateCommand(interp, "pwd", Jim_PwdCmd, NULL, NULL);
- Jim_CreateCommand(interp, "cd", Jim_CdCmd, NULL, NULL);
- return JIM_OK;
- }
- #include <string.h>
- #include <ctype.h>
- #if (!(defined(HAVE_VFORK) || defined(HAVE_FORK)) || !defined(HAVE_WAITPID)) && !defined(__MINGW32__)
- static int Jim_ExecCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *cmdlineObj = Jim_NewEmptyStringObj(interp);
- int i, j;
- int rc;
- for (i = 1; i < argc; i++) {
- int len;
- const char *arg = Jim_GetString(argv[i], &len);
- if (i > 1) {
- Jim_AppendString(interp, cmdlineObj, " ", 1);
- }
- if (strpbrk(arg, "\\\" ") == NULL) {
- Jim_AppendString(interp, cmdlineObj, arg, len);
- continue;
- }
- Jim_AppendString(interp, cmdlineObj, "\"", 1);
- for (j = 0; j < len; j++) {
- if (arg[j] == '\\' || arg[j] == '"') {
- Jim_AppendString(interp, cmdlineObj, "\\", 1);
- }
- Jim_AppendString(interp, cmdlineObj, &arg[j], 1);
- }
- Jim_AppendString(interp, cmdlineObj, "\"", 1);
- }
- rc = system(Jim_String(cmdlineObj));
- Jim_FreeNewObj(interp, cmdlineObj);
- if (rc) {
- Jim_Obj *errorCode = Jim_NewListObj(interp, NULL, 0);
- Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "CHILDSTATUS", -1));
- Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, 0));
- Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, rc));
- Jim_SetGlobalVariableStr(interp, "errorCode", errorCode);
- return JIM_ERR;
- }
- return JIM_OK;
- }
- int Jim_execInit(Jim_Interp *interp)
- {
- Jim_PackageProvideCheck(interp, "exec");
- Jim_CreateCommand(interp, "exec", Jim_ExecCmd, NULL, NULL);
- return JIM_OK;
- }
- #else
- #include <errno.h>
- #include <signal.h>
- #include <sys/stat.h>
- struct WaitInfoTable;
- static char **JimOriginalEnviron(void);
- static char **JimSaveEnv(char **env);
- static void JimRestoreEnv(char **env);
- static int JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv,
- phandle_t **pidArrayPtr, int *inPipePtr, int *outPipePtr, int *errFilePtr);
- static void JimDetachPids(struct WaitInfoTable *table, int numPids, const phandle_t *pidPtr);
- static int JimCleanupChildren(Jim_Interp *interp, int numPids, phandle_t *pidPtr, Jim_Obj *errStrObj);
- static int Jim_WaitCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
- #if defined(__MINGW32__)
- static phandle_t JimStartWinProcess(Jim_Interp *interp, char **argv, char **env, int inputId, int outputId, int errorId);
- #endif
- static void Jim_RemoveTrailingNewline(Jim_Obj *objPtr)
- {
- int len;
- const char *s = Jim_GetString(objPtr, &len);
- if (len > 0 && s[len - 1] == '\n') {
- objPtr->length--;
- objPtr->bytes[objPtr->length] = '\0';
- }
- }
- static int JimAppendStreamToString(Jim_Interp *interp, int fd, Jim_Obj *strObj)
- {
- char buf[256];
- int ret = 0;
- while (1) {
- int retval = read(fd, buf, sizeof(buf));
- if (retval > 0) {
- ret = 1;
- Jim_AppendString(interp, strObj, buf, retval);
- }
- if (retval <= 0) {
- break;
- }
- }
- close(fd);
- return ret;
- }
- static char **JimBuildEnv(Jim_Interp *interp)
- {
- int i;
- int size;
- int num;
- int n;
- char **envptr;
- char *envdata;
- Jim_Obj *objPtr = Jim_GetGlobalVariableStr(interp, "env", JIM_NONE);
- if (!objPtr) {
- return JimOriginalEnviron();
- }
- num = Jim_ListLength(interp, objPtr);
- if (num % 2) {
- num--;
- }
- size = Jim_Length(objPtr) + 2;
- envptr = Jim_Alloc(sizeof(*envptr) * (num / 2 + 1) + size);
- envdata = (char *)&envptr[num / 2 + 1];
- n = 0;
- for (i = 0; i < num; i += 2) {
- const char *s1, *s2;
- Jim_Obj *elemObj;
- Jim_ListIndex(interp, objPtr, i, &elemObj, JIM_NONE);
- s1 = Jim_String(elemObj);
- Jim_ListIndex(interp, objPtr, i + 1, &elemObj, JIM_NONE);
- s2 = Jim_String(elemObj);
- envptr[n] = envdata;
- envdata += sprintf(envdata, "%s=%s", s1, s2);
- envdata++;
- n++;
- }
- envptr[n] = NULL;
- *envdata = 0;
- return envptr;
- }
- static void JimFreeEnv(char **env, char **original_environ)
- {
- if (env != original_environ) {
- Jim_Free(env);
- }
- }
- static Jim_Obj *JimMakeErrorCode(Jim_Interp *interp, long pid, int waitStatus, Jim_Obj *errStrObj)
- {
- Jim_Obj *errorCode = Jim_NewListObj(interp, NULL, 0);
- if (pid <= 0) {
- Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "NONE", -1));
- Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, pid));
- Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, -1));
- }
- else if (WIFEXITED(waitStatus)) {
- Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "CHILDSTATUS", -1));
- Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, pid));
- Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, WEXITSTATUS(waitStatus)));
- }
- else {
- const char *type;
- const char *action;
- const char *signame;
- if (WIFSIGNALED(waitStatus)) {
- type = "CHILDKILLED";
- action = "killed";
- signame = Jim_SignalId(WTERMSIG(waitStatus));
- }
- else {
- type = "CHILDSUSP";
- action = "suspended";
- signame = "none";
- }
- Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, type, -1));
- if (errStrObj) {
- Jim_AppendStrings(interp, errStrObj, "child ", action, " by signal ", Jim_SignalId(WTERMSIG(waitStatus)), "\n", NULL);
- }
- Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, pid));
- Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, signame, -1));
- }
- return errorCode;
- }
- static int JimCheckWaitStatus(Jim_Interp *interp, long pid, int waitStatus, Jim_Obj *errStrObj)
- {
- if (WIFEXITED(waitStatus) && WEXITSTATUS(waitStatus) == 0) {
- return JIM_OK;
- }
- Jim_SetGlobalVariableStr(interp, "errorCode", JimMakeErrorCode(interp, pid, waitStatus, errStrObj));
- return JIM_ERR;
- }
- struct WaitInfo
- {
- phandle_t phandle;
- int status;
- int flags;
- };
- struct WaitInfoTable {
- struct WaitInfo *info;
- int size;
- int used;
- int refcount;
- };
- #define WI_DETACHED 2
- #define WAIT_TABLE_GROW_BY 4
- static void JimFreeWaitInfoTable(struct Jim_Interp *interp, void *privData)
- {
- struct WaitInfoTable *table = privData;
- if (--table->refcount == 0) {
- Jim_Free(table->info);
- Jim_Free(table);
- }
- }
- static struct WaitInfoTable *JimAllocWaitInfoTable(void)
- {
- struct WaitInfoTable *table = Jim_Alloc(sizeof(*table));
- table->info = NULL;
- table->size = table->used = 0;
- table->refcount = 1;
- return table;
- }
- static int JimWaitRemove(struct WaitInfoTable *table, phandle_t phandle)
- {
- int i;
- for (i = 0; i < table->used; i++) {
- if (phandle == table->info[i].phandle) {
- if (i != table->used - 1) {
- table->info[i] = table->info[table->used - 1];
- }
- table->used--;
- return 0;
- }
- }
- return -1;
- }
- static int Jim_ExecCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int outputId;
- int errorId;
- phandle_t *pidPtr;
- int numPids, result;
- int child_siginfo = 1;
- Jim_Obj *childErrObj;
- Jim_Obj *errStrObj;
- struct WaitInfoTable *table = Jim_CmdPrivData(interp);
- if (argc > 1 && Jim_CompareStringImmediate(interp, argv[argc - 1], "&")) {
- Jim_Obj *listObj;
- int i;
- argc--;
- numPids = JimCreatePipeline(interp, argc - 1, argv + 1, &pidPtr, NULL, NULL, NULL);
- if (numPids < 0) {
- return JIM_ERR;
- }
- listObj = Jim_NewListObj(interp, NULL, 0);
- for (i = 0; i < numPids; i++) {
- Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, JimProcessPid(pidPtr[i])));
- }
- Jim_SetResult(interp, listObj);
- JimDetachPids(table, numPids, pidPtr);
- Jim_Free(pidPtr);
- return JIM_OK;
- }
- numPids =
- JimCreatePipeline(interp, argc - 1, argv + 1, &pidPtr, NULL, &outputId, &errorId);
- if (numPids < 0) {
- return JIM_ERR;
- }
- result = JIM_OK;
- errStrObj = Jim_NewStringObj(interp, "", 0);
- if (outputId != -1) {
- if (JimAppendStreamToString(interp, outputId, errStrObj) < 0) {
- result = JIM_ERR;
- Jim_SetResultErrno(interp, "error reading from output pipe");
- }
- }
- childErrObj = Jim_NewStringObj(interp, "", 0);
- Jim_IncrRefCount(childErrObj);
- if (JimCleanupChildren(interp, numPids, pidPtr, childErrObj) != JIM_OK) {
- result = JIM_ERR;
- }
- if (errorId != -1) {
- int ret;
- Jim_Lseek(errorId, 0, SEEK_SET);
- ret = JimAppendStreamToString(interp, errorId, errStrObj);
- if (ret < 0) {
- Jim_SetResultErrno(interp, "error reading from error pipe");
- result = JIM_ERR;
- }
- else if (ret > 0) {
- child_siginfo = 0;
- }
- }
- if (child_siginfo) {
- Jim_AppendObj(interp, errStrObj, childErrObj);
- }
- Jim_DecrRefCount(interp, childErrObj);
- Jim_RemoveTrailingNewline(errStrObj);
- Jim_SetResult(interp, errStrObj);
- return result;
- }
- static long JimWaitForProcess(struct WaitInfoTable *table, phandle_t phandle, int *statusPtr)
- {
- if (JimWaitRemove(table, phandle) == 0) {
- return waitpid(phandle, statusPtr, 0);
- }
- return -1;
- }
- static void JimDetachPids(struct WaitInfoTable *table, int numPids, const phandle_t *pidPtr)
- {
- int j;
- for (j = 0; j < numPids; j++) {
- int i;
- for (i = 0; i < table->used; i++) {
- if (pidPtr[j] == table->info[i].phandle) {
- table->info[i].flags |= WI_DETACHED;
- break;
- }
- }
- }
- }
- static int JimGetChannelFd(Jim_Interp *interp, const char *name)
- {
- Jim_Obj *objv[2];
- objv[0] = Jim_NewStringObj(interp, name, -1);
- objv[1] = Jim_NewStringObj(interp, "getfd", -1);
- if (Jim_EvalObjVector(interp, 2, objv) == JIM_OK) {
- jim_wide fd;
- if (Jim_GetWide(interp, Jim_GetResult(interp), &fd) == JIM_OK) {
- return fd;
- }
- }
- return -1;
- }
- static void JimReapDetachedPids(struct WaitInfoTable *table)
- {
- struct WaitInfo *waitPtr;
- int count;
- int dest;
- if (!table) {
- return;
- }
- waitPtr = table->info;
- dest = 0;
- for (count = table->used; count > 0; waitPtr++, count--) {
- if (waitPtr->flags & WI_DETACHED) {
- int status;
- long pid = waitpid(waitPtr->phandle, &status, WNOHANG);
- if (pid > 0) {
- table->used--;
- continue;
- }
- }
- if (waitPtr != &table->info[dest]) {
- table->info[dest] = *waitPtr;
- }
- dest++;
- }
- }
- static int Jim_WaitCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- struct WaitInfoTable *table = Jim_CmdPrivData(interp);
- int nohang = 0;
- long pid;
- phandle_t phandle;
- int status;
- Jim_Obj *errCodeObj;
- if (argc == 1) {
- JimReapDetachedPids(table);
- return JIM_OK;
- }
- if (argc > 1 && Jim_CompareStringImmediate(interp, argv[1], "-nohang")) {
- nohang = 1;
- }
- if (argc != nohang + 2) {
- Jim_WrongNumArgs(interp, 1, argv, "?-nohang? ?pid?");
- return JIM_ERR;
- }
- if (Jim_GetLong(interp, argv[nohang + 1], &pid) != JIM_OK) {
- return JIM_ERR;
- }
- phandle = JimWaitPid(pid, &status, nohang ? WNOHANG : 0);
- if (phandle == JIM_BAD_PHANDLE) {
- pid = -1;
- }
- #ifndef __MINGW32__
- else if (pid < 0) {
- pid = phandle;
- }
- #endif
- errCodeObj = JimMakeErrorCode(interp, pid, status, NULL);
- if (phandle != JIM_BAD_PHANDLE && (WIFEXITED(status) || WIFSIGNALED(status))) {
- JimWaitRemove(table, phandle);
- }
- Jim_SetResult(interp, errCodeObj);
- return JIM_OK;
- }
- static int Jim_PidCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- if (argc != 1) {
- Jim_WrongNumArgs(interp, 1, argv, "");
- return JIM_ERR;
- }
- Jim_SetResultInt(interp, (jim_wide)getpid());
- return JIM_OK;
- }
- static int
- JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv, phandle_t **pidArrayPtr,
- int *inPipePtr, int *outPipePtr, int *errFilePtr)
- {
- phandle_t *pidPtr = NULL; /* Points to alloc-ed array holding all
- * the pids of child processes. */
- int numPids = 0; /* Actual number of processes that exist
- * at *pidPtr right now. */
- int cmdCount; /* Count of number of distinct commands
- * found in argc/argv. */
- const char *input = NULL; /* Describes input for pipeline, depending
- * on "inputFile". NULL means take input
- * from stdin/pipe. */
- int input_len = 0;
- #define FILE_NAME 0
- #define FILE_APPEND 1
- #define FILE_HANDLE 2
- #define FILE_TEXT 3
- int inputFile = FILE_NAME; /* 1 means input is name of input file.
- * 2 means input is filehandle name.
- * 0 means input holds actual
- * text to be input to command. */
- int outputFile = FILE_NAME; /* 0 means output is the name of output file.
- * 1 means output is the name of output file, and append.
- * 2 means output is filehandle name.
- * All this is ignored if output is NULL
- */
- int errorFile = FILE_NAME; /* 0 means error is the name of error file.
- * 1 means error is the name of error file, and append.
- * 2 means error is filehandle name.
- * All this is ignored if error is NULL
- */
- const char *output = NULL; /* Holds name of output file to pipe to,
- * or NULL if output goes to stdout/pipe. */
- const char *error = NULL; /* Holds name of stderr file to pipe to,
- * or NULL if stderr goes to stderr/pipe. */
- int inputId = -1;
- int outputId = -1;
- int errorId = -1;
- int lastOutputId = -1;
- int pipeIds[2];
- int firstArg, lastArg; /* Indexes of first and last arguments in
- * current command. */
- int lastBar;
- int i;
- phandle_t phandle;
- char **save_environ;
- #if defined(HAVE_EXECVPE) && !defined(__MINGW32__)
- char **child_environ;
- #endif
- struct WaitInfoTable *table = Jim_CmdPrivData(interp);
- char **arg_array = Jim_Alloc(sizeof(*arg_array) * (argc + 1));
- int arg_count = 0;
- if (inPipePtr != NULL) {
- *inPipePtr = -1;
- }
- if (outPipePtr != NULL) {
- *outPipePtr = -1;
- }
- if (errFilePtr != NULL) {
- *errFilePtr = -1;
- }
- pipeIds[0] = pipeIds[1] = -1;
- cmdCount = 1;
- lastBar = -1;
- for (i = 0; i < argc; i++) {
- const char *arg = Jim_String(argv[i]);
- if (arg[0] == '<') {
- inputFile = FILE_NAME;
- input = arg + 1;
- if (*input == '<') {
- inputFile = FILE_TEXT;
- input_len = Jim_Length(argv[i]) - 2;
- input++;
- }
- else if (*input == '@') {
- inputFile = FILE_HANDLE;
- input++;
- }
- if (!*input && ++i < argc) {
- input = Jim_GetString(argv[i], &input_len);
- }
- }
- else if (arg[0] == '>') {
- int dup_error = 0;
- outputFile = FILE_NAME;
- output = arg + 1;
- if (*output == '>') {
- outputFile = FILE_APPEND;
- output++;
- }
- if (*output == '&') {
- output++;
- dup_error = 1;
- }
- if (*output == '@') {
- outputFile = FILE_HANDLE;
- output++;
- }
- if (!*output && ++i < argc) {
- output = Jim_String(argv[i]);
- }
- if (dup_error) {
- errorFile = outputFile;
- error = output;
- }
- }
- else if (arg[0] == '2' && arg[1] == '>') {
- error = arg + 2;
- errorFile = FILE_NAME;
- if (*error == '@') {
- errorFile = FILE_HANDLE;
- error++;
- }
- else if (*error == '>') {
- errorFile = FILE_APPEND;
- error++;
- }
- if (!*error && ++i < argc) {
- error = Jim_String(argv[i]);
- }
- }
- else {
- if (strcmp(arg, "|") == 0 || strcmp(arg, "|&") == 0) {
- if (i == lastBar + 1 || i == argc - 1) {
- Jim_SetResultString(interp, "illegal use of | or |& in command", -1);
- goto badargs;
- }
- lastBar = i;
- cmdCount++;
- }
- arg_array[arg_count++] = (char *)arg;
- continue;
- }
- if (i >= argc) {
- Jim_SetResultFormatted(interp, "can't specify \"%s\" as last word in command", arg);
- goto badargs;
- }
- }
- if (arg_count == 0) {
- Jim_SetResultString(interp, "didn't specify command to execute", -1);
- badargs:
- Jim_Free(arg_array);
- return -1;
- }
- save_environ = JimSaveEnv(JimBuildEnv(interp));
- if (input != NULL) {
- if (inputFile == FILE_TEXT) {
- inputId = Jim_MakeTempFile(interp, NULL, 1);
- if (inputId == -1) {
- goto error;
- }
- if (write(inputId, input, input_len) != input_len) {
- Jim_SetResultErrno(interp, "couldn't write temp file");
- close(inputId);
- goto error;
- }
- Jim_Lseek(inputId, 0L, SEEK_SET);
- }
- else if (inputFile == FILE_HANDLE) {
- int fd = JimGetChannelFd(interp, input);
- if (fd < 0) {
- goto error;
- }
- inputId = dup(fd);
- }
- else {
- inputId = Jim_OpenForRead(input);
- if (inputId == -1) {
- Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", input, strerror(Jim_Errno()));
- goto error;
- }
- }
- }
- else if (inPipePtr != NULL) {
- if (pipe(pipeIds) != 0) {
- Jim_SetResultErrno(interp, "couldn't create input pipe for command");
- goto error;
- }
- inputId = pipeIds[0];
- *inPipePtr = pipeIds[1];
- pipeIds[0] = pipeIds[1] = -1;
- }
- if (output != NULL) {
- if (outputFile == FILE_HANDLE) {
- int fd = JimGetChannelFd(interp, output);
- if (fd < 0) {
- goto error;
- }
- lastOutputId = dup(fd);
- }
- else {
- lastOutputId = Jim_OpenForWrite(output, outputFile == FILE_APPEND);
- if (lastOutputId == -1) {
- Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", output, strerror(Jim_Errno()));
- goto error;
- }
- }
- }
- else if (outPipePtr != NULL) {
- if (pipe(pipeIds) != 0) {
- Jim_SetResultErrno(interp, "couldn't create output pipe");
- goto error;
- }
- lastOutputId = pipeIds[1];
- *outPipePtr = pipeIds[0];
- pipeIds[0] = pipeIds[1] = -1;
- }
- if (error != NULL) {
- if (errorFile == FILE_HANDLE) {
- if (strcmp(error, "1") == 0) {
- if (lastOutputId != -1) {
- errorId = dup(lastOutputId);
- }
- else {
- error = "stdout";
- }
- }
- if (errorId == -1) {
- int fd = JimGetChannelFd(interp, error);
- if (fd < 0) {
- goto error;
- }
- errorId = dup(fd);
- }
- }
- else {
- errorId = Jim_OpenForWrite(error, errorFile == FILE_APPEND);
- if (errorId == -1) {
- Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", error, strerror(Jim_Errno()));
- goto error;
- }
- }
- }
- else if (errFilePtr != NULL) {
- errorId = Jim_MakeTempFile(interp, NULL, 1);
- if (errorId == -1) {
- goto error;
- }
- *errFilePtr = dup(errorId);
- }
- pidPtr = Jim_Alloc(cmdCount * sizeof(*pidPtr));
- for (firstArg = 0; firstArg < arg_count; numPids++, firstArg = lastArg + 1) {
- int pipe_dup_err = 0;
- int origErrorId = errorId;
- for (lastArg = firstArg; lastArg < arg_count; lastArg++) {
- if (strcmp(arg_array[lastArg], "|") == 0) {
- break;
- }
- if (strcmp(arg_array[lastArg], "|&") == 0) {
- pipe_dup_err = 1;
- break;
- }
- }
- if (lastArg == firstArg) {
- Jim_SetResultString(interp, "missing command to exec", -1);
- goto error;
- }
- arg_array[lastArg] = NULL;
- if (lastArg == arg_count) {
- outputId = lastOutputId;
- lastOutputId = -1;
- }
- else {
- if (pipe(pipeIds) != 0) {
- Jim_SetResultErrno(interp, "couldn't create pipe");
- goto error;
- }
- outputId = pipeIds[1];
- }
- if (pipe_dup_err) {
- errorId = outputId;
- }
- #ifdef __MINGW32__
- phandle = JimStartWinProcess(interp, &arg_array[firstArg], save_environ, inputId, outputId, errorId);
- if (phandle == JIM_BAD_PHANDLE) {
- Jim_SetResultFormatted(interp, "couldn't exec \"%s\"", arg_array[firstArg]);
- goto error;
- }
- #else
- i = strlen(arg_array[firstArg]);
- #ifdef HAVE_EXECVPE
- child_environ = Jim_GetEnviron();
- #endif
- #ifdef HAVE_VFORK
- phandle = vfork();
- #else
- phandle = fork();
- #endif
- if (phandle < 0) {
- Jim_SetResultErrno(interp, "couldn't fork child process");
- goto error;
- }
- if (phandle == 0) {
- if (inputId != -1 && inputId != fileno(stdin)) {
- dup2(inputId, fileno(stdin));
- close(inputId);
- }
- if (outputId != -1 && outputId != fileno(stdout)) {
- dup2(outputId, fileno(stdout));
- if (outputId != errorId) {
- close(outputId);
- }
- }
- if (errorId != -1 && errorId != fileno(stderr)) {
- dup2(errorId, fileno(stderr));
- close(errorId);
- }
- if (outPipePtr && *outPipePtr != -1) {
- close(*outPipePtr);
- }
- if (errFilePtr && *errFilePtr != -1) {
- close(*errFilePtr);
- }
- if (pipeIds[0] != -1) {
- close(pipeIds[0]);
- }
- if (lastOutputId != -1) {
- close(lastOutputId);
- }
- execvpe(arg_array[firstArg], &arg_array[firstArg], child_environ);
- if (write(fileno(stderr), "couldn't exec \"", 15) &&
- write(fileno(stderr), arg_array[firstArg], i) &&
- write(fileno(stderr), "\"\n", 2)) {
- }
- #ifdef JIM_MAINTAINER
- {
- static char *const false_argv[2] = {"false", NULL};
- execvp(false_argv[0],false_argv);
- }
- #endif
- _exit(127);
- }
- #endif
- if (table->used == table->size) {
- table->size += WAIT_TABLE_GROW_BY;
- table->info = Jim_Realloc(table->info, table->size * sizeof(*table->info));
- }
- table->info[table->used].phandle = phandle;
- table->info[table->used].flags = 0;
- table->used++;
- pidPtr[numPids] = phandle;
- errorId = origErrorId;
- if (inputId != -1) {
- close(inputId);
- }
- if (outputId != -1) {
- close(outputId);
- }
- inputId = pipeIds[0];
- pipeIds[0] = pipeIds[1] = -1;
- }
- *pidArrayPtr = pidPtr;
- cleanup:
- if (inputId != -1) {
- close(inputId);
- }
- if (lastOutputId != -1) {
- close(lastOutputId);
- }
- if (errorId != -1) {
- close(errorId);
- }
- Jim_Free(arg_array);
- JimRestoreEnv(save_environ);
- return numPids;
- error:
- if ((inPipePtr != NULL) && (*inPipePtr != -1)) {
- close(*inPipePtr);
- *inPipePtr = -1;
- }
- if ((outPipePtr != NULL) && (*outPipePtr != -1)) {
- close(*outPipePtr);
- *outPipePtr = -1;
- }
- if ((errFilePtr != NULL) && (*errFilePtr != -1)) {
- close(*errFilePtr);
- *errFilePtr = -1;
- }
- if (pipeIds[0] != -1) {
- close(pipeIds[0]);
- }
- if (pipeIds[1] != -1) {
- close(pipeIds[1]);
- }
- if (pidPtr != NULL) {
- for (i = 0; i < numPids; i++) {
- if (pidPtr[i] != JIM_BAD_PHANDLE) {
- JimDetachPids(table, 1, &pidPtr[i]);
- }
- }
- Jim_Free(pidPtr);
- }
- numPids = -1;
- goto cleanup;
- }
- static int JimCleanupChildren(Jim_Interp *interp, int numPids, phandle_t *pidPtr, Jim_Obj *errStrObj)
- {
- struct WaitInfoTable *table = Jim_CmdPrivData(interp);
- int result = JIM_OK;
- int i;
- for (i = 0; i < numPids; i++) {
- int waitStatus = 0;
- long pid = JimWaitForProcess(table, pidPtr[i], &waitStatus);
- if (pid > 0) {
- if (JimCheckWaitStatus(interp, pid, waitStatus, errStrObj) != JIM_OK) {
- result = JIM_ERR;
- }
- }
- }
- Jim_Free(pidPtr);
- return result;
- }
- int Jim_execInit(Jim_Interp *interp)
- {
- struct WaitInfoTable *waitinfo;
- Jim_PackageProvideCheck(interp, "exec");
- waitinfo = JimAllocWaitInfoTable();
- Jim_CreateCommand(interp, "exec", Jim_ExecCmd, waitinfo, JimFreeWaitInfoTable);
- waitinfo->refcount++;
- Jim_CreateCommand(interp, "wait", Jim_WaitCommand, waitinfo, JimFreeWaitInfoTable);
- Jim_CreateCommand(interp, "pid", Jim_PidCommand, 0, 0);
- return JIM_OK;
- }
- #if defined(__MINGW32__)
- static int
- JimWinFindExecutable(const char *originalName, char fullPath[MAX_PATH])
- {
- int i;
- static char extensions[][5] = {".exe", "", ".bat"};
- for (i = 0; i < (int) (sizeof(extensions) / sizeof(extensions[0])); i++) {
- snprintf(fullPath, MAX_PATH, "%s%s", originalName, extensions[i]);
- if (SearchPath(NULL, fullPath, NULL, MAX_PATH, fullPath, NULL) == 0) {
- continue;
- }
- if (GetFileAttributes(fullPath) & FILE_ATTRIBUTE_DIRECTORY) {
- continue;
- }
- return 0;
- }
- return -1;
- }
- static char **JimSaveEnv(char **env)
- {
- return env;
- }
- static void JimRestoreEnv(char **env)
- {
- JimFreeEnv(env, Jim_GetEnviron());
- }
- static char **JimOriginalEnviron(void)
- {
- return NULL;
- }
- static Jim_Obj *
- JimWinBuildCommandLine(Jim_Interp *interp, char **argv)
- {
- char *start, *special;
- int quote, i;
- Jim_Obj *strObj = Jim_NewStringObj(interp, "", 0);
- for (i = 0; argv[i]; i++) {
- if (i > 0) {
- Jim_AppendString(interp, strObj, " ", 1);
- }
- if (argv[i][0] == '\0') {
- quote = 1;
- }
- else {
- quote = 0;
- for (start = argv[i]; *start != '\0'; start++) {
- if (isspace(UCHAR(*start))) {
- quote = 1;
- break;
- }
- }
- }
- if (quote) {
- Jim_AppendString(interp, strObj, "\"" , 1);
- }
- start = argv[i];
- for (special = argv[i]; ; ) {
- if ((*special == '\\') && (special[1] == '\\' ||
- special[1] == '"' || (quote && special[1] == '\0'))) {
- Jim_AppendString(interp, strObj, start, special - start);
- start = special;
- while (1) {
- special++;
- if (*special == '"' || (quote && *special == '\0')) {
- Jim_AppendString(interp, strObj, start, special - start);
- break;
- }
- if (*special != '\\') {
- break;
- }
- }
- Jim_AppendString(interp, strObj, start, special - start);
- start = special;
- }
- if (*special == '"') {
- if (special == start) {
- Jim_AppendString(interp, strObj, "\"", 1);
- }
- else {
- Jim_AppendString(interp, strObj, start, special - start);
- }
- Jim_AppendString(interp, strObj, "\\\"", 2);
- start = special + 1;
- }
- if (*special == '\0') {
- break;
- }
- special++;
- }
- Jim_AppendString(interp, strObj, start, special - start);
- if (quote) {
- Jim_AppendString(interp, strObj, "\"", 1);
- }
- }
- return strObj;
- }
- static phandle_t
- JimStartWinProcess(Jim_Interp *interp, char **argv, char **env, int inputId, int outputId, int errorId)
- {
- STARTUPINFO startInfo;
- PROCESS_INFORMATION procInfo;
- HANDLE hProcess;
- char execPath[MAX_PATH];
- phandle_t phandle = INVALID_HANDLE_VALUE;
- Jim_Obj *cmdLineObj;
- char *winenv;
- if (JimWinFindExecutable(argv[0], execPath) < 0) {
- return phandle;
- }
- argv[0] = execPath;
- hProcess = GetCurrentProcess();
- cmdLineObj = JimWinBuildCommandLine(interp, argv);
- ZeroMemory(&startInfo, sizeof(startInfo));
- startInfo.cb = sizeof(startInfo);
- startInfo.dwFlags = STARTF_USESTDHANDLES;
- startInfo.hStdInput = INVALID_HANDLE_VALUE;
- startInfo.hStdOutput= INVALID_HANDLE_VALUE;
- startInfo.hStdError = INVALID_HANDLE_VALUE;
- if (inputId == -1) {
- inputId = _fileno(stdin);
- }
- DuplicateHandle(hProcess, (HANDLE)_get_osfhandle(inputId), hProcess, &startInfo.hStdInput,
- 0, TRUE, DUPLICATE_SAME_ACCESS);
- if (startInfo.hStdInput == INVALID_HANDLE_VALUE) {
- goto end;
- }
- if (outputId == -1) {
- outputId = _fileno(stdout);
- }
- DuplicateHandle(hProcess, (HANDLE)_get_osfhandle(outputId), hProcess, &startInfo.hStdOutput,
- 0, TRUE, DUPLICATE_SAME_ACCESS);
- if (startInfo.hStdOutput == INVALID_HANDLE_VALUE) {
- goto end;
- }
- if (errorId == -1) {
- errorId = _fileno(stderr);
- }
- DuplicateHandle(hProcess, (HANDLE)_get_osfhandle(errorId), hProcess, &startInfo.hStdError,
- 0, TRUE, DUPLICATE_SAME_ACCESS);
- if (startInfo.hStdError == INVALID_HANDLE_VALUE) {
- goto end;
- }
- if (env == NULL) {
- winenv = NULL;
- }
- else if (env[0] == NULL) {
- winenv = (char *)"\0";
- }
- else {
- winenv = env[0];
- }
- if (!CreateProcess(NULL, (char *)Jim_String(cmdLineObj), NULL, NULL, TRUE,
- 0, winenv, NULL, &startInfo, &procInfo)) {
- goto end;
- }
- WaitForInputIdle(procInfo.hProcess, 5000);
- CloseHandle(procInfo.hThread);
- phandle = procInfo.hProcess;
- end:
- Jim_FreeNewObj(interp, cmdLineObj);
- if (startInfo.hStdInput != INVALID_HANDLE_VALUE) {
- CloseHandle(startInfo.hStdInput);
- }
- if (startInfo.hStdOutput != INVALID_HANDLE_VALUE) {
- CloseHandle(startInfo.hStdOutput);
- }
- if (startInfo.hStdError != INVALID_HANDLE_VALUE) {
- CloseHandle(startInfo.hStdError);
- }
- return phandle;
- }
- #else
- static char **JimOriginalEnviron(void)
- {
- return Jim_GetEnviron();
- }
- static char **JimSaveEnv(char **env)
- {
- char **saveenv = Jim_GetEnviron();
- Jim_SetEnviron(env);
- return saveenv;
- }
- static void JimRestoreEnv(char **env)
- {
- JimFreeEnv(Jim_GetEnviron(), env);
- Jim_SetEnviron(env);
- }
- #endif
- #endif
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- #include <time.h>
- #ifdef HAVE_SYS_TIME_H
- #include <sys/time.h>
- #endif
- struct clock_options {
- int gmt;
- const char *format;
- };
- static int parse_clock_options(Jim_Interp *interp, int argc, Jim_Obj *const *argv, struct clock_options *opts)
- {
- static const char * const options[] = { "-gmt", "-format", NULL };
- enum { OPT_GMT, OPT_FORMAT, };
- int i;
- for (i = 0; i < argc; i += 2) {
- int option;
- if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
- return JIM_ERR;
- }
- switch (option) {
- case OPT_GMT:
- if (Jim_GetBoolean(interp, argv[i + 1], &opts->gmt) != JIM_OK) {
- return JIM_ERR;
- }
- break;
- case OPT_FORMAT:
- opts->format = Jim_String(argv[i + 1]);
- break;
- }
- }
- return JIM_OK;
- }
- static int clock_cmd_format(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- char buf[100];
- time_t t;
- jim_wide seconds;
- struct clock_options options = { 0, "%a %b %d %H:%M:%S %Z %Y" };
- struct tm *tm;
- if (Jim_GetWide(interp, argv[0], &seconds) != JIM_OK) {
- return JIM_ERR;
- }
- if (argc % 2 == 0) {
- return -1;
- }
- if (parse_clock_options(interp, argc - 1, argv + 1, &options) == JIM_ERR) {
- return JIM_ERR;
- }
- t = seconds;
- tm = options.gmt ? gmtime(&t) : localtime(&t);
- if (tm == NULL || strftime(buf, sizeof(buf), options.format, tm) == 0) {
- Jim_SetResultString(interp, "format string too long or invalid time", -1);
- return JIM_ERR;
- }
- Jim_SetResultString(interp, buf, -1);
- return JIM_OK;
- }
- #ifdef HAVE_STRPTIME
- static time_t jim_timegm(const struct tm *tm)
- {
- int m = tm->tm_mon + 1;
- int y = 1900 + tm->tm_year - (m <= 2);
- int era = (y >= 0 ? y : y - 399) / 400;
- unsigned yoe = (unsigned)(y - era * 400);
- unsigned doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + tm->tm_mday - 1;
- unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
- long days = (era * 146097 + (int)doe - 719468);
- int secs = tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
- return days * 24 * 60 * 60 + secs;
- }
- static int clock_cmd_scan(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- char *pt;
- struct tm tm;
- time_t now = time(NULL);
- struct clock_options options = { 0, NULL };
- if (argc % 2 == 0) {
- return -1;
- }
- if (parse_clock_options(interp, argc - 1, argv + 1, &options) == JIM_ERR) {
- return JIM_ERR;
- }
- if (options.format == NULL) {
- return -1;
- }
- localtime_r(&now, &tm);
- pt = strptime(Jim_String(argv[0]), options.format, &tm);
- if (pt == 0 || *pt != 0) {
- Jim_SetResultString(interp, "Failed to parse time according to format", -1);
- return JIM_ERR;
- }
- tm.tm_isdst = options.gmt ? 0 : -1;
- Jim_SetResultInt(interp, options.gmt ? jim_timegm(&tm) : mktime(&tm));
- return JIM_OK;
- }
- #endif
- static int clock_cmd_seconds(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_SetResultInt(interp, Jim_GetTimeUsec(CLOCK_REALTIME) / 1000000);
- return JIM_OK;
- }
- static int clock_cmd_clicks(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_SetResultInt(interp, Jim_GetTimeUsec(CLOCK_MONOTONIC_RAW));
- return JIM_OK;
- }
- static int clock_cmd_micros(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_SetResultInt(interp, Jim_GetTimeUsec(CLOCK_REALTIME));
- return JIM_OK;
- }
- static int clock_cmd_millis(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_SetResultInt(interp, Jim_GetTimeUsec(CLOCK_REALTIME) / 1000);
- return JIM_OK;
- }
- static const jim_subcmd_type clock_command_table[] = {
- { "clicks",
- NULL,
- clock_cmd_clicks,
- 0,
- 0,
- },
- { "format",
- "seconds ?-format string? ?-gmt boolean?",
- clock_cmd_format,
- 1,
- 5,
- },
- { "microseconds",
- NULL,
- clock_cmd_micros,
- 0,
- 0,
- },
- { "milliseconds",
- NULL,
- clock_cmd_millis,
- 0,
- 0,
- },
- #ifdef HAVE_STRPTIME
- { "scan",
- "str -format format ?-gmt boolean?",
- clock_cmd_scan,
- 3,
- 5,
- },
- #endif
- { "seconds",
- NULL,
- clock_cmd_seconds,
- 0,
- 0,
- },
- { NULL }
- };
- int Jim_clockInit(Jim_Interp *interp)
- {
- Jim_PackageProvideCheck(interp, "clock");
- Jim_CreateCommand(interp, "clock", Jim_SubCmdProc, (void *)clock_command_table, NULL);
- return JIM_OK;
- }
- #include <limits.h>
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- #include <errno.h>
- static int array_cmd_exists(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *dictObj = Jim_GetVariable(interp, argv[0], JIM_UNSHARED);
- Jim_SetResultInt(interp, dictObj && Jim_DictSize(interp, dictObj) != -1);
- return JIM_OK;
- }
- static int array_cmd_get(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
- Jim_Obj *patternObj;
- if (!objPtr) {
- return JIM_OK;
- }
- patternObj = (argc == 1) ? NULL : argv[1];
- if (patternObj == NULL || Jim_CompareStringImmediate(interp, patternObj, "*")) {
- if (Jim_IsList(objPtr) && Jim_ListLength(interp, objPtr) % 2 == 0) {
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- }
- return Jim_DictMatchTypes(interp, objPtr, patternObj, JIM_DICTMATCH_KEYS, JIM_DICTMATCH_KEYS | JIM_DICTMATCH_VALUES);
- }
- static int array_cmd_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
- if (!objPtr) {
- return JIM_OK;
- }
- return Jim_DictMatchTypes(interp, objPtr, argc == 1 ? NULL : argv[1], JIM_DICTMATCH_KEYS, JIM_DICTMATCH_KEYS);
- }
- static int array_cmd_unset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int i;
- int len;
- Jim_Obj *resultObj;
- Jim_Obj *objPtr;
- Jim_Obj **dictValuesObj;
- if (argc == 1 || Jim_CompareStringImmediate(interp, argv[1], "*")) {
- Jim_UnsetVariable(interp, argv[0], JIM_NONE);
- return JIM_OK;
- }
- objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
- if (objPtr == NULL) {
- return JIM_OK;
- }
- dictValuesObj = Jim_DictPairs(interp, objPtr, &len);
- if (dictValuesObj == NULL) {
- Jim_SetResultString(interp, "", -1);
- return JIM_OK;
- }
- resultObj = Jim_NewDictObj(interp, NULL, 0);
- for (i = 0; i < len; i += 2) {
- if (!Jim_StringMatchObj(interp, argv[1], dictValuesObj[i], 0)) {
- Jim_DictAddElement(interp, resultObj, dictValuesObj[i], dictValuesObj[i + 1]);
- }
- }
- Jim_SetVariable(interp, argv[0], resultObj);
- return JIM_OK;
- }
- static int array_cmd_size(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *objPtr;
- int len = 0;
- objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
- if (objPtr) {
- len = Jim_DictSize(interp, objPtr);
- if (len < 0) {
- Jim_SetResultInt(interp, 0);
- return JIM_OK;
- }
- }
- Jim_SetResultInt(interp, len);
- return JIM_OK;
- }
- static int array_cmd_stat(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
- if (objPtr) {
- return Jim_DictInfo(interp, objPtr);
- }
- Jim_SetResultFormatted(interp, "\"%#s\" isn't an array", argv[0], NULL);
- return JIM_ERR;
- }
- static int array_cmd_set(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int i;
- int len;
- Jim_Obj *listObj = argv[1];
- Jim_Obj *dictObj;
- len = Jim_ListLength(interp, listObj);
- if (len % 2) {
- Jim_SetResultString(interp, "list must have an even number of elements", -1);
- return JIM_ERR;
- }
- dictObj = Jim_GetVariable(interp, argv[0], JIM_UNSHARED);
- if (!dictObj) {
- return Jim_SetVariable(interp, argv[0], listObj);
- }
- else if (Jim_DictSize(interp, dictObj) < 0) {
- return JIM_ERR;
- }
- if (Jim_IsShared(dictObj)) {
- dictObj = Jim_DuplicateObj(interp, dictObj);
- }
- for (i = 0; i < len; i += 2) {
- Jim_Obj *nameObj;
- Jim_Obj *valueObj;
- Jim_ListIndex(interp, listObj, i, &nameObj, JIM_NONE);
- Jim_ListIndex(interp, listObj, i + 1, &valueObj, JIM_NONE);
- Jim_DictAddElement(interp, dictObj, nameObj, valueObj);
- }
- return Jim_SetVariable(interp, argv[0], dictObj);
- }
- static const jim_subcmd_type array_command_table[] = {
- { "exists",
- "arrayName",
- array_cmd_exists,
- 1,
- 1,
- },
- { "get",
- "arrayName ?pattern?",
- array_cmd_get,
- 1,
- 2,
- },
- { "names",
- "arrayName ?pattern?",
- array_cmd_names,
- 1,
- 2,
- },
- { "set",
- "arrayName list",
- array_cmd_set,
- 2,
- 2,
- },
- { "size",
- "arrayName",
- array_cmd_size,
- 1,
- 1,
- },
- { "stat",
- "arrayName",
- array_cmd_stat,
- 1,
- 1,
- },
- { "unset",
- "arrayName ?pattern?",
- array_cmd_unset,
- 1,
- 2,
- },
- { NULL
- }
- };
- int Jim_arrayInit(Jim_Interp *interp)
- {
- Jim_PackageProvideCheck(interp, "array");
- Jim_CreateCommand(interp, "array", Jim_SubCmdProc, (void *)array_command_table, NULL);
- return JIM_OK;
- }
- int Jim_InitStaticExtensions(Jim_Interp *interp)
- {
- extern int Jim_bootstrapInit(Jim_Interp *);
- extern int Jim_aioInit(Jim_Interp *);
- extern int Jim_readdirInit(Jim_Interp *);
- extern int Jim_regexpInit(Jim_Interp *);
- extern int Jim_fileInit(Jim_Interp *);
- extern int Jim_globInit(Jim_Interp *);
- extern int Jim_execInit(Jim_Interp *);
- extern int Jim_clockInit(Jim_Interp *);
- extern int Jim_arrayInit(Jim_Interp *);
- extern int Jim_stdlibInit(Jim_Interp *);
- extern int Jim_tclcompatInit(Jim_Interp *);
- Jim_bootstrapInit(interp);
- Jim_aioInit(interp);
- Jim_readdirInit(interp);
- Jim_regexpInit(interp);
- Jim_fileInit(interp);
- Jim_globInit(interp);
- Jim_execInit(interp);
- Jim_clockInit(interp);
- Jim_arrayInit(interp);
- Jim_stdlibInit(interp);
- Jim_tclcompatInit(interp);
- return JIM_OK;
- }
- #ifndef JIM_TINY
- #define JIM_OPTIMIZATION
- #endif
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <stdarg.h>
- #include <ctype.h>
- #include <limits.h>
- #include <assert.h>
- #include <errno.h>
- #include <time.h>
- #include <setjmp.h>
- #ifdef HAVE_SYS_TIME_H
- #include <sys/time.h>
- #endif
- #ifdef HAVE_EXECINFO_H
- #include <execinfo.h>
- #endif
- #ifdef HAVE_CRT_EXTERNS_H
- #include <crt_externs.h>
- #endif
- #include <math.h>
- #ifndef TCL_LIBRARY
- #define TCL_LIBRARY "."
- #endif
- #ifndef TCL_PLATFORM_OS
- #define TCL_PLATFORM_OS "unknown"
- #endif
- #ifndef TCL_PLATFORM_PLATFORM
- #define TCL_PLATFORM_PLATFORM "unknown"
- #endif
- #ifndef TCL_PLATFORM_PATH_SEPARATOR
- #define TCL_PLATFORM_PATH_SEPARATOR ":"
- #endif
- #ifdef JIM_MAINTAINER
- #define JIM_DEBUG_COMMAND
- #define JIM_DEBUG_PANIC
- #endif
- #define JIM_INTEGER_SPACE 24
- #if defined(DEBUG_SHOW_SCRIPT) || defined(DEBUG_SHOW_SCRIPT_TOKENS) || defined(JIM_DEBUG_COMMAND) || defined(DEBUG_SHOW_SUBST)
- static const char *jim_tt_name(int type);
- #endif
- #ifdef JIM_DEBUG_PANIC
- static void JimPanicDump(int fail_condition, const char *fmt, ...);
- #define JimPanic(X) JimPanicDump X
- #else
- #define JimPanic(X)
- #endif
- #ifdef JIM_OPTIMIZATION
- static int JimIsWide(Jim_Obj *objPtr);
- #define JIM_IF_OPTIM(X) X
- #else
- #define JIM_IF_OPTIM(X)
- #endif
- static char JimEmptyStringRep[] = "";
- static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf, int action);
- static int ListSetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int listindex, Jim_Obj *newObjPtr,
- int flags);
- static int Jim_ListIndices(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *const *indexv, int indexc,
- Jim_Obj **resultObj, int flags);
- static int JimDeleteLocalProcs(Jim_Interp *interp, Jim_Stack *localCommands);
- static Jim_Obj *JimExpandDictSugar(Jim_Interp *interp, Jim_Obj *objPtr);
- static void SetDictSubstFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
- static void JimSetFailedEnumResult(Jim_Interp *interp, const char *arg, const char *badtype,
- const char *prefix, const char *const *tablePtr, const char *name);
- static int JimCallProcedure(Jim_Interp *interp, Jim_Cmd *cmd, int argc, Jim_Obj *const *argv);
- static int JimGetWideNoErr(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr);
- static int JimSign(jim_wide w);
- static void JimPrngSeed(Jim_Interp *interp, unsigned char *seed, int seedLen);
- static void JimRandomBytes(Jim_Interp *interp, void *dest, unsigned int len);
- static int JimSetNewVariable(Jim_HashTable *ht, Jim_Obj *nameObjPtr, Jim_VarVal *vv);
- static Jim_VarVal *JimFindVariable(Jim_HashTable *ht, Jim_Obj *nameObjPtr);
- static int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
- #define JIM_DICT_SUGAR 100
- #define JimWideValue(objPtr) (objPtr)->internalRep.wideValue
- #define JimObjTypeName(O) ((O)->typePtr ? (O)->typePtr->name : "none")
- static int utf8_tounicode_case(const char *s, int *uc, int upper)
- {
- int l = utf8_tounicode(s, uc);
- if (upper) {
- *uc = utf8_upper(*uc);
- }
- return l;
- }
- static Jim_Obj *JimPushInterpObjImpl(Jim_Obj **iop, Jim_Obj *no)
- {
- Jim_Obj *io = *iop;
- Jim_IncrRefCount(no);
- *iop = no;
- return io;
- }
- #define JimPushInterpObj(IO, NO) JimPushInterpObjImpl(&(IO), NO)
- #define JimPopInterpObj(I, IO, SO) do { Jim_DecrRefCount(I, IO); IO = SO; } while (0)
- #define JIM_CHARSET_SCAN 2
- #define JIM_CHARSET_GLOB 0
- static const char *JimCharsetMatch(const char *pattern, int plen, int c, int flags)
- {
- int not = 0;
- int pchar;
- int match = 0;
- int nocase = 0;
- int n;
- if (flags & JIM_NOCASE) {
- nocase++;
- c = utf8_upper(c);
- }
- if (flags & JIM_CHARSET_SCAN) {
- if (*pattern == '^') {
- not++;
- pattern++;
- plen--;
- }
- if (*pattern == ']') {
- goto first;
- }
- }
- while (plen && *pattern != ']') {
- if (pattern[0] == '\\') {
- first:
- n = utf8_tounicode_case(pattern, &pchar, nocase);
- pattern += n;
- plen -= n;
- }
- else {
- int start;
- int end;
- n = utf8_tounicode_case(pattern, &start, nocase);
- pattern += n;
- plen -= n;
- if (pattern[0] == '-' && plen > 1) {
- n = 1 + utf8_tounicode_case(pattern + 1, &end, nocase);
- pattern += n;
- plen -= n;
- if ((c >= start && c <= end) || (c >= end && c <= start)) {
- match = 1;
- }
- continue;
- }
- pchar = start;
- }
- if (pchar == c) {
- match = 1;
- }
- }
- if (not) {
- match = !match;
- }
- return match ? pattern : NULL;
- }
- static int JimGlobMatch(const char *pattern, int plen, const char *string, int slen, int nocase)
- {
- int c;
- int pchar;
- int n;
- const char *p;
- while (plen) {
- switch (pattern[0]) {
- case '*':
- while (pattern[1] == '*' && plen) {
- pattern++;
- plen--;
- }
- pattern++;
- plen--;
- if (!plen) {
- return 1;
- }
- while (slen) {
- if (JimGlobMatch(pattern, plen, string, slen, nocase))
- return 1;
- n = utf8_tounicode(string, &c);
- string += n;
- slen -= n;
- }
- return 0;
- case '?':
- n = utf8_tounicode(string, &c);
- string += n;
- slen -= n;
- break;
- case '[': {
- n = utf8_tounicode(string, &c);
- string += n;
- slen -= n;
- p = JimCharsetMatch(pattern + 1, plen - 1, c, nocase ? JIM_NOCASE : 0);
- if (!p) {
- return 0;
- }
- plen -= p - pattern;
- pattern = p;
- if (!plen) {
- continue;
- }
- break;
- }
- case '\\':
- if (pattern[1]) {
- pattern++;
- plen--;
- }
- default:
- n = utf8_tounicode_case(string, &c, nocase);
- string += n;
- slen -= n;
- utf8_tounicode_case(pattern, &pchar, nocase);
- if (pchar != c) {
- return 0;
- }
- break;
- }
- n = utf8_tounicode_case(pattern, &pchar, nocase);
- pattern += n;
- plen -= n;
- if (!slen) {
- while (*pattern == '*' && plen) {
- pattern++;
- plen--;
- }
- break;
- }
- }
- if (!plen && !slen) {
- return 1;
- }
- return 0;
- }
- static int JimStringCompareUtf8(const char *s1, int l1, const char *s2, int l2, int nocase)
- {
- int minlen = l1;
- if (l2 < l1) {
- minlen = l2;
- }
- while (minlen) {
- int c1, c2;
- s1 += utf8_tounicode_case(s1, &c1, nocase);
- s2 += utf8_tounicode_case(s2, &c2, nocase);
- if (c1 != c2) {
- return JimSign(c1 - c2);
- }
- minlen--;
- }
- if (l1 < l2) {
- return -1;
- }
- if (l1 > l2) {
- return 1;
- }
- return 0;
- }
- static int JimStringFirst(const char *s1, int l1, const char *s2, int l2, int idx)
- {
- int i;
- int l1bytelen;
- if (!l1 || !l2 || l1 > l2) {
- return -1;
- }
- if (idx < 0)
- idx = 0;
- s2 += utf8_index(s2, idx);
- l1bytelen = utf8_index(s1, l1);
- for (i = idx; i <= l2 - l1; i++) {
- int c;
- if (memcmp(s2, s1, l1bytelen) == 0) {
- return i;
- }
- s2 += utf8_tounicode(s2, &c);
- }
- return -1;
- }
- static int JimStringLast(const char *s1, int l1, const char *s2, int l2)
- {
- const char *p;
- if (!l1 || !l2 || l1 > l2)
- return -1;
- for (p = s2 + l2 - 1; p != s2 - 1; p--) {
- if (*p == *s1 && memcmp(s1, p, l1) == 0) {
- return p - s2;
- }
- }
- return -1;
- }
- #ifdef JIM_UTF8
- static int JimStringLastUtf8(const char *s1, int l1, const char *s2, int l2)
- {
- int n = JimStringLast(s1, utf8_index(s1, l1), s2, utf8_index(s2, l2));
- if (n > 0) {
- n = utf8_strlen(s2, n);
- }
- return n;
- }
- #endif
- static int JimCheckConversion(const char *str, const char *endptr)
- {
- if (str[0] == '\0' || str == endptr) {
- return JIM_ERR;
- }
- if (endptr[0] != '\0') {
- while (*endptr) {
- if (!isspace(UCHAR(*endptr))) {
- return JIM_ERR;
- }
- endptr++;
- }
- }
- return JIM_OK;
- }
- static int JimNumberBase(const char *str, int *base, int *sign)
- {
- int i = 0;
- *base = 0;
- while (isspace(UCHAR(str[i]))) {
- i++;
- }
- if (str[i] == '-') {
- *sign = -1;
- i++;
- }
- else {
- if (str[i] == '+') {
- i++;
- }
- *sign = 1;
- }
- if (str[i] != '0') {
- return 0;
- }
- switch (str[i + 1]) {
- case 'x': case 'X': *base = 16; break;
- case 'o': case 'O': *base = 8; break;
- case 'b': case 'B': *base = 2; break;
- case 'd': case 'D': *base = 10; break;
- default: return 0;
- }
- i += 2;
- if (str[i] != '-' && str[i] != '+' && !isspace(UCHAR(str[i]))) {
- return i;
- }
- *base = 0;
- return 0;
- }
- static long jim_strtol(const char *str, char **endptr)
- {
- int sign;
- int base;
- int i = JimNumberBase(str, &base, &sign);
- if (base != 0) {
- long value = strtol(str + i, endptr, base);
- if (endptr == NULL || *endptr != str + i) {
- return value * sign;
- }
- }
- return strtol(str, endptr, 10);
- }
- static jim_wide jim_strtoull(const char *str, char **endptr)
- {
- #ifdef HAVE_LONG_LONG
- int sign;
- int base;
- int i = JimNumberBase(str, &base, &sign);
- if (base != 0) {
- jim_wide value = strtoull(str + i, endptr, base);
- if (endptr == NULL || *endptr != str + i) {
- return value * sign;
- }
- }
- return strtoull(str, endptr, 10);
- #else
- return (unsigned long)jim_strtol(str, endptr);
- #endif
- }
- int Jim_StringToWide(const char *str, jim_wide * widePtr, int base)
- {
- char *endptr;
- if (base) {
- *widePtr = strtoull(str, &endptr, base);
- }
- else {
- *widePtr = jim_strtoull(str, &endptr);
- }
- return JimCheckConversion(str, endptr);
- }
- int Jim_StringToDouble(const char *str, double *doublePtr)
- {
- char *endptr;
- errno = 0;
- *doublePtr = strtod(str, &endptr);
- return JimCheckConversion(str, endptr);
- }
- static jim_wide JimPowWide(jim_wide b, jim_wide e)
- {
- jim_wide res = 1;
- if (b == 1) {
- return 1;
- }
- if (e < 0) {
- if (b != -1) {
- return 0;
- }
- e = -e;
- }
- while (e)
- {
- if (e & 1) {
- res *= b;
- }
- e >>= 1;
- b *= b;
- }
- return res;
- }
- #ifdef JIM_DEBUG_PANIC
- static void JimPanicDump(int condition, const char *fmt, ...)
- {
- va_list ap;
- if (!condition) {
- return;
- }
- va_start(ap, fmt);
- fprintf(stderr, "\nJIM INTERPRETER PANIC: ");
- vfprintf(stderr, fmt, ap);
- fprintf(stderr, "\n\n");
- va_end(ap);
- #if defined(HAVE_BACKTRACE)
- {
- void *array[40];
- int size, i;
- char **strings;
- size = backtrace(array, 40);
- strings = backtrace_symbols(array, size);
- for (i = 0; i < size; i++)
- fprintf(stderr, "[backtrace] %s\n", strings[i]);
- fprintf(stderr, "[backtrace] Include the above lines and the output\n");
- fprintf(stderr, "[backtrace] of 'nm <executable>' in the bug report.\n");
- }
- #endif
- exit(1);
- }
- #endif
- void *JimDefaultAllocator(void *ptr, size_t size)
- {
- if (size == 0) {
- free(ptr);
- return NULL;
- }
- else if (ptr) {
- return realloc(ptr, size);
- }
- else {
- return malloc(size);
- }
- }
- void *(*Jim_Allocator)(void *ptr, size_t size) = JimDefaultAllocator;
- char *Jim_StrDup(const char *s)
- {
- return Jim_StrDupLen(s, strlen(s));
- }
- char *Jim_StrDupLen(const char *s, int l)
- {
- char *copy = Jim_Alloc(l + 1);
- memcpy(copy, s, l);
- copy[l] = 0;
- return copy;
- }
- jim_wide Jim_GetTimeUsec(unsigned type)
- {
- long long now;
- struct timeval tv;
- #if defined(HAVE_CLOCK_GETTIME)
- struct timespec ts;
- if (clock_gettime(type, &ts) == 0) {
- now = ts.tv_sec * 1000000LL + ts.tv_nsec / 1000;
- }
- else
- #endif
- {
- gettimeofday(&tv, NULL);
- now = tv.tv_sec * 1000000LL + tv.tv_usec;
- }
- return now;
- }
- static void JimExpandHashTableIfNeeded(Jim_HashTable *ht);
- static unsigned int JimHashTableNextPower(unsigned int size);
- static Jim_HashEntry *JimInsertHashEntry(Jim_HashTable *ht, const void *key, int replace);
- unsigned int Jim_IntHashFunction(unsigned int key)
- {
- key += ~(key << 15);
- key ^= (key >> 10);
- key += (key << 3);
- key ^= (key >> 6);
- key += ~(key << 11);
- key ^= (key >> 16);
- return key;
- }
- unsigned int Jim_GenHashFunction(const unsigned char *string, int length)
- {
- unsigned result = 0;
- string += length;
- while (length--) {
- result += (result << 3) + (unsigned char)(*--string);
- }
- return result;
- }
- static void JimResetHashTable(Jim_HashTable *ht)
- {
- ht->table = NULL;
- ht->size = 0;
- ht->sizemask = 0;
- ht->used = 0;
- ht->collisions = 0;
- #ifdef JIM_RANDOMISE_HASH
- ht->uniq = (rand() ^ time(NULL) ^ clock());
- #else
- ht->uniq = 0;
- #endif
- }
- static void JimInitHashTableIterator(Jim_HashTable *ht, Jim_HashTableIterator *iter)
- {
- iter->ht = ht;
- iter->index = -1;
- iter->entry = NULL;
- iter->nextEntry = NULL;
- }
- int Jim_InitHashTable(Jim_HashTable *ht, const Jim_HashTableType *type, void *privDataPtr)
- {
- JimResetHashTable(ht);
- ht->type = type;
- ht->privdata = privDataPtr;
- return JIM_OK;
- }
- void Jim_ExpandHashTable(Jim_HashTable *ht, unsigned int size)
- {
- Jim_HashTable n;
- unsigned int realsize = JimHashTableNextPower(size), i;
- if (size <= ht->used)
- return;
- Jim_InitHashTable(&n, ht->type, ht->privdata);
- n.size = realsize;
- n.sizemask = realsize - 1;
- n.table = Jim_Alloc(realsize * sizeof(Jim_HashEntry *));
- n.uniq = ht->uniq;
- memset(n.table, 0, realsize * sizeof(Jim_HashEntry *));
- n.used = ht->used;
- for (i = 0; ht->used > 0; i++) {
- Jim_HashEntry *he, *nextHe;
- if (ht->table[i] == NULL)
- continue;
- he = ht->table[i];
- while (he) {
- unsigned int h;
- nextHe = he->next;
- h = Jim_HashKey(ht, he->key) & n.sizemask;
- he->next = n.table[h];
- n.table[h] = he;
- ht->used--;
- he = nextHe;
- }
- }
- assert(ht->used == 0);
- Jim_Free(ht->table);
- *ht = n;
- }
- int Jim_AddHashEntry(Jim_HashTable *ht, const void *key, void *val)
- {
- Jim_HashEntry *entry = JimInsertHashEntry(ht, key, 0);;
- if (entry == NULL)
- return JIM_ERR;
- Jim_SetHashKey(ht, entry, key);
- Jim_SetHashVal(ht, entry, val);
- return JIM_OK;
- }
- int Jim_ReplaceHashEntry(Jim_HashTable *ht, const void *key, void *val)
- {
- int existed;
- Jim_HashEntry *entry;
- entry = JimInsertHashEntry(ht, key, 1);
- if (entry->key) {
- if (ht->type->valDestructor && ht->type->valDup) {
- void *newval = ht->type->valDup(ht->privdata, val);
- ht->type->valDestructor(ht->privdata, entry->u.val);
- entry->u.val = newval;
- }
- else {
- Jim_FreeEntryVal(ht, entry);
- Jim_SetHashVal(ht, entry, val);
- }
- existed = 1;
- }
- else {
- Jim_SetHashKey(ht, entry, key);
- Jim_SetHashVal(ht, entry, val);
- existed = 0;
- }
- return existed;
- }
- int Jim_DeleteHashEntry(Jim_HashTable *ht, const void *key)
- {
- if (ht->used) {
- unsigned int h = Jim_HashKey(ht, key) & ht->sizemask;
- Jim_HashEntry *prevHe = NULL;
- Jim_HashEntry *he = ht->table[h];
- while (he) {
- if (Jim_CompareHashKeys(ht, key, he->key)) {
- if (prevHe)
- prevHe->next = he->next;
- else
- ht->table[h] = he->next;
- ht->used--;
- Jim_FreeEntryKey(ht, he);
- Jim_FreeEntryVal(ht, he);
- Jim_Free(he);
- return JIM_OK;
- }
- prevHe = he;
- he = he->next;
- }
- }
- return JIM_ERR;
- }
- void Jim_ClearHashTable(Jim_HashTable *ht)
- {
- unsigned int i;
- for (i = 0; ht->used > 0; i++) {
- Jim_HashEntry *he, *nextHe;
- he = ht->table[i];
- while (he) {
- nextHe = he->next;
- Jim_FreeEntryKey(ht, he);
- Jim_FreeEntryVal(ht, he);
- Jim_Free(he);
- ht->used--;
- he = nextHe;
- }
- ht->table[i] = NULL;
- }
- }
- int Jim_FreeHashTable(Jim_HashTable *ht)
- {
- Jim_ClearHashTable(ht);
- Jim_Free(ht->table);
- JimResetHashTable(ht);
- return JIM_OK;
- }
- Jim_HashEntry *Jim_FindHashEntry(Jim_HashTable *ht, const void *key)
- {
- Jim_HashEntry *he;
- unsigned int h;
- if (ht->used == 0)
- return NULL;
- h = Jim_HashKey(ht, key) & ht->sizemask;
- he = ht->table[h];
- while (he) {
- if (Jim_CompareHashKeys(ht, key, he->key))
- return he;
- he = he->next;
- }
- return NULL;
- }
- Jim_HashTableIterator *Jim_GetHashTableIterator(Jim_HashTable *ht)
- {
- Jim_HashTableIterator *iter = Jim_Alloc(sizeof(*iter));
- JimInitHashTableIterator(ht, iter);
- return iter;
- }
- Jim_HashEntry *Jim_NextHashEntry(Jim_HashTableIterator *iter)
- {
- while (1) {
- if (iter->entry == NULL) {
- iter->index++;
- if (iter->index >= (signed)iter->ht->size)
- break;
- iter->entry = iter->ht->table[iter->index];
- }
- else {
- iter->entry = iter->nextEntry;
- }
- if (iter->entry) {
- iter->nextEntry = iter->entry->next;
- return iter->entry;
- }
- }
- return NULL;
- }
- static void JimExpandHashTableIfNeeded(Jim_HashTable *ht)
- {
- if (ht->size == 0)
- Jim_ExpandHashTable(ht, JIM_HT_INITIAL_SIZE);
- if (ht->size == ht->used)
- Jim_ExpandHashTable(ht, ht->size * 2);
- }
- static unsigned int JimHashTableNextPower(unsigned int size)
- {
- unsigned int i = JIM_HT_INITIAL_SIZE;
- if (size >= 2147483648U)
- return 2147483648U;
- while (1) {
- if (i >= size)
- return i;
- i *= 2;
- }
- }
- static Jim_HashEntry *JimInsertHashEntry(Jim_HashTable *ht, const void *key, int replace)
- {
- unsigned int h;
- Jim_HashEntry *he;
- JimExpandHashTableIfNeeded(ht);
- h = Jim_HashKey(ht, key) & ht->sizemask;
- he = ht->table[h];
- while (he) {
- if (Jim_CompareHashKeys(ht, key, he->key))
- return replace ? he : NULL;
- he = he->next;
- }
- he = Jim_Alloc(sizeof(*he));
- he->next = ht->table[h];
- ht->table[h] = he;
- ht->used++;
- he->key = NULL;
- return he;
- }
- static unsigned int JimStringCopyHTHashFunction(const void *key)
- {
- return Jim_GenHashFunction(key, strlen(key));
- }
- static void *JimStringCopyHTDup(void *privdata, const void *key)
- {
- return Jim_StrDup(key);
- }
- static int JimStringCopyHTKeyCompare(void *privdata, const void *key1, const void *key2)
- {
- return strcmp(key1, key2) == 0;
- }
- static void JimStringCopyHTKeyDestructor(void *privdata, void *key)
- {
- Jim_Free(key);
- }
- static const Jim_HashTableType JimPackageHashTableType = {
- JimStringCopyHTHashFunction,
- JimStringCopyHTDup,
- NULL,
- JimStringCopyHTKeyCompare,
- JimStringCopyHTKeyDestructor,
- NULL
- };
- typedef struct AssocDataValue
- {
- Jim_InterpDeleteProc *delProc;
- void *data;
- } AssocDataValue;
- static void JimAssocDataHashTableValueDestructor(void *privdata, void *data)
- {
- AssocDataValue *assocPtr = (AssocDataValue *) data;
- if (assocPtr->delProc != NULL)
- assocPtr->delProc((Jim_Interp *)privdata, assocPtr->data);
- Jim_Free(data);
- }
- static const Jim_HashTableType JimAssocDataHashTableType = {
- JimStringCopyHTHashFunction,
- JimStringCopyHTDup,
- NULL,
- JimStringCopyHTKeyCompare,
- JimStringCopyHTKeyDestructor,
- JimAssocDataHashTableValueDestructor
- };
- void Jim_InitStack(Jim_Stack *stack)
- {
- stack->len = 0;
- stack->maxlen = 0;
- stack->vector = NULL;
- }
- void Jim_FreeStack(Jim_Stack *stack)
- {
- Jim_Free(stack->vector);
- }
- int Jim_StackLen(Jim_Stack *stack)
- {
- return stack->len;
- }
- void Jim_StackPush(Jim_Stack *stack, void *element)
- {
- int neededLen = stack->len + 1;
- if (neededLen > stack->maxlen) {
- stack->maxlen = neededLen < 20 ? 20 : neededLen * 2;
- stack->vector = Jim_Realloc(stack->vector, sizeof(void *) * stack->maxlen);
- }
- stack->vector[stack->len] = element;
- stack->len++;
- }
- void *Jim_StackPop(Jim_Stack *stack)
- {
- if (stack->len == 0)
- return NULL;
- stack->len--;
- return stack->vector[stack->len];
- }
- void *Jim_StackPeek(Jim_Stack *stack)
- {
- if (stack->len == 0)
- return NULL;
- return stack->vector[stack->len - 1];
- }
- void Jim_FreeStackElements(Jim_Stack *stack, void (*freeFunc) (void *ptr))
- {
- int i;
- for (i = 0; i < stack->len; i++)
- freeFunc(stack->vector[i]);
- }
- #define JIM_TT_NONE 0
- #define JIM_TT_STR 1
- #define JIM_TT_ESC 2
- #define JIM_TT_VAR 3
- #define JIM_TT_DICTSUGAR 4
- #define JIM_TT_CMD 5
- #define JIM_TT_SEP 6
- #define JIM_TT_EOL 7
- #define JIM_TT_EOF 8
- #define JIM_TT_LINE 9
- #define JIM_TT_WORD 10
- #define JIM_TT_SUBEXPR_START 11
- #define JIM_TT_SUBEXPR_END 12
- #define JIM_TT_SUBEXPR_COMMA 13
- #define JIM_TT_EXPR_INT 14
- #define JIM_TT_EXPR_DOUBLE 15
- #define JIM_TT_EXPR_BOOLEAN 16
- #define JIM_TT_EXPRSUGAR 17
- #define JIM_TT_EXPR_OP 20
- #define TOKEN_IS_SEP(type) (type >= JIM_TT_SEP && type <= JIM_TT_EOF)
- #define TOKEN_IS_EXPR_START(type) (type == JIM_TT_NONE || type == JIM_TT_SUBEXPR_START || type == JIM_TT_SUBEXPR_COMMA)
- #define TOKEN_IS_EXPR_OP(type) (type >= JIM_TT_EXPR_OP)
- struct JimParseMissing {
- int ch;
- int line;
- };
- struct JimParserCtx
- {
- const char *p;
- int len;
- int linenr;
- const char *tstart;
- const char *tend;
- int tline;
- int tt;
- int eof;
- int inquote;
- int comment;
- struct JimParseMissing missing;
- const char *errmsg;
- };
- static int JimParseScript(struct JimParserCtx *pc);
- static int JimParseSep(struct JimParserCtx *pc);
- static int JimParseEol(struct JimParserCtx *pc);
- static int JimParseCmd(struct JimParserCtx *pc);
- static int JimParseQuote(struct JimParserCtx *pc);
- static int JimParseVar(struct JimParserCtx *pc);
- static int JimParseBrace(struct JimParserCtx *pc);
- static int JimParseStr(struct JimParserCtx *pc);
- static int JimParseComment(struct JimParserCtx *pc);
- static void JimParseSubCmd(struct JimParserCtx *pc);
- static int JimParseSubQuote(struct JimParserCtx *pc);
- static Jim_Obj *JimParserGetTokenObj(Jim_Interp *interp, struct JimParserCtx *pc);
- static void JimParserInit(struct JimParserCtx *pc, const char *prg, int len, int linenr)
- {
- pc->p = prg;
- pc->len = len;
- pc->tstart = NULL;
- pc->tend = NULL;
- pc->tline = 0;
- pc->tt = JIM_TT_NONE;
- pc->eof = 0;
- pc->inquote = 0;
- pc->linenr = linenr;
- pc->comment = 1;
- pc->missing.ch = ' ';
- pc->missing.line = linenr;
- }
- static int JimParseScript(struct JimParserCtx *pc)
- {
- while (1) {
- if (!pc->len) {
- pc->tstart = pc->p;
- pc->tend = pc->p - 1;
- pc->tline = pc->linenr;
- pc->tt = JIM_TT_EOL;
- if (pc->inquote) {
- pc->missing.ch = '"';
- }
- pc->eof = 1;
- return JIM_OK;
- }
- switch (*(pc->p)) {
- case '\\':
- if (*(pc->p + 1) == '\n' && !pc->inquote) {
- return JimParseSep(pc);
- }
- pc->comment = 0;
- return JimParseStr(pc);
- case ' ':
- case '\t':
- case '\r':
- case '\f':
- if (!pc->inquote)
- return JimParseSep(pc);
- pc->comment = 0;
- return JimParseStr(pc);
- case '\n':
- case ';':
- pc->comment = 1;
- if (!pc->inquote)
- return JimParseEol(pc);
- return JimParseStr(pc);
- case '[':
- pc->comment = 0;
- return JimParseCmd(pc);
- case '$':
- pc->comment = 0;
- if (JimParseVar(pc) == JIM_ERR) {
- pc->tstart = pc->tend = pc->p++;
- pc->len--;
- pc->tt = JIM_TT_ESC;
- }
- return JIM_OK;
- case '#':
- if (pc->comment) {
- JimParseComment(pc);
- continue;
- }
- return JimParseStr(pc);
- default:
- pc->comment = 0;
- return JimParseStr(pc);
- }
- return JIM_OK;
- }
- }
- static int JimParseSep(struct JimParserCtx *pc)
- {
- pc->tstart = pc->p;
- pc->tline = pc->linenr;
- while (isspace(UCHAR(*pc->p)) || (*pc->p == '\\' && *(pc->p + 1) == '\n')) {
- if (*pc->p == '\n') {
- break;
- }
- if (*pc->p == '\\') {
- pc->p++;
- pc->len--;
- pc->linenr++;
- }
- pc->p++;
- pc->len--;
- }
- pc->tend = pc->p - 1;
- pc->tt = JIM_TT_SEP;
- return JIM_OK;
- }
- static int JimParseEol(struct JimParserCtx *pc)
- {
- pc->tstart = pc->p;
- pc->tline = pc->linenr;
- while (isspace(UCHAR(*pc->p)) || *pc->p == ';') {
- if (*pc->p == '\n')
- pc->linenr++;
- pc->p++;
- pc->len--;
- }
- pc->tend = pc->p - 1;
- pc->tt = JIM_TT_EOL;
- return JIM_OK;
- }
- static void JimParseSubBrace(struct JimParserCtx *pc)
- {
- int level = 1;
- pc->p++;
- pc->len--;
- while (pc->len) {
- switch (*pc->p) {
- case '\\':
- if (pc->len > 1) {
- if (*++pc->p == '\n') {
- pc->linenr++;
- }
- pc->len--;
- }
- break;
- case '{':
- level++;
- break;
- case '}':
- if (--level == 0) {
- pc->tend = pc->p - 1;
- pc->p++;
- pc->len--;
- return;
- }
- break;
- case '\n':
- pc->linenr++;
- break;
- }
- pc->p++;
- pc->len--;
- }
- pc->missing.ch = '{';
- pc->missing.line = pc->tline;
- pc->tend = pc->p - 1;
- }
- static int JimParseSubQuote(struct JimParserCtx *pc)
- {
- int tt = JIM_TT_STR;
- int line = pc->tline;
- pc->p++;
- pc->len--;
- while (pc->len) {
- switch (*pc->p) {
- case '\\':
- if (pc->len > 1) {
- if (*++pc->p == '\n') {
- pc->linenr++;
- }
- pc->len--;
- tt = JIM_TT_ESC;
- }
- break;
- case '"':
- pc->tend = pc->p - 1;
- pc->p++;
- pc->len--;
- return tt;
- case '[':
- JimParseSubCmd(pc);
- tt = JIM_TT_ESC;
- continue;
- case '\n':
- pc->linenr++;
- break;
- case '$':
- tt = JIM_TT_ESC;
- break;
- }
- pc->p++;
- pc->len--;
- }
- pc->missing.ch = '"';
- pc->missing.line = line;
- pc->tend = pc->p - 1;
- return tt;
- }
- static void JimParseSubCmd(struct JimParserCtx *pc)
- {
- int level = 1;
- int startofword = 1;
- int line = pc->tline;
- pc->p++;
- pc->len--;
- while (pc->len) {
- switch (*pc->p) {
- case '\\':
- if (pc->len > 1) {
- if (*++pc->p == '\n') {
- pc->linenr++;
- }
- pc->len--;
- }
- break;
- case '[':
- level++;
- break;
- case ']':
- if (--level == 0) {
- pc->tend = pc->p - 1;
- pc->p++;
- pc->len--;
- return;
- }
- break;
- case '"':
- if (startofword) {
- JimParseSubQuote(pc);
- if (pc->missing.ch == '"') {
- return;
- }
- continue;
- }
- break;
- case '{':
- JimParseSubBrace(pc);
- startofword = 0;
- continue;
- case '\n':
- pc->linenr++;
- break;
- }
- startofword = isspace(UCHAR(*pc->p));
- pc->p++;
- pc->len--;
- }
- pc->missing.ch = '[';
- pc->missing.line = line;
- pc->tend = pc->p - 1;
- }
- static int JimParseBrace(struct JimParserCtx *pc)
- {
- pc->tstart = pc->p + 1;
- pc->tline = pc->linenr;
- pc->tt = JIM_TT_STR;
- JimParseSubBrace(pc);
- return JIM_OK;
- }
- static int JimParseCmd(struct JimParserCtx *pc)
- {
- pc->tstart = pc->p + 1;
- pc->tline = pc->linenr;
- pc->tt = JIM_TT_CMD;
- JimParseSubCmd(pc);
- return JIM_OK;
- }
- static int JimParseQuote(struct JimParserCtx *pc)
- {
- pc->tstart = pc->p + 1;
- pc->tline = pc->linenr;
- pc->tt = JimParseSubQuote(pc);
- return JIM_OK;
- }
- static int JimParseVar(struct JimParserCtx *pc)
- {
- pc->p++;
- pc->len--;
- #ifdef EXPRSUGAR_BRACKET
- if (*pc->p == '[') {
- JimParseCmd(pc);
- pc->tt = JIM_TT_EXPRSUGAR;
- return JIM_OK;
- }
- #endif
- pc->tstart = pc->p;
- pc->tt = JIM_TT_VAR;
- pc->tline = pc->linenr;
- if (*pc->p == '{') {
- pc->tstart = ++pc->p;
- pc->len--;
- while (pc->len && *pc->p != '}') {
- if (*pc->p == '\n') {
- pc->linenr++;
- }
- pc->p++;
- pc->len--;
- }
- pc->tend = pc->p - 1;
- if (pc->len) {
- pc->p++;
- pc->len--;
- }
- }
- else {
- while (1) {
- if (pc->p[0] == ':' && pc->p[1] == ':') {
- while (*pc->p == ':') {
- pc->p++;
- pc->len--;
- }
- continue;
- }
- if (isalnum(UCHAR(*pc->p)) || *pc->p == '_' || UCHAR(*pc->p) >= 0x80) {
- pc->p++;
- pc->len--;
- continue;
- }
- break;
- }
- if (*pc->p == '(') {
- int count = 1;
- const char *paren = NULL;
- pc->tt = JIM_TT_DICTSUGAR;
- while (count && pc->len) {
- pc->p++;
- pc->len--;
- if (*pc->p == '\\' && pc->len >= 1) {
- pc->p++;
- pc->len--;
- }
- else if (*pc->p == '(') {
- count++;
- }
- else if (*pc->p == ')') {
- paren = pc->p;
- count--;
- }
- }
- if (count == 0) {
- pc->p++;
- pc->len--;
- }
- else if (paren) {
- paren++;
- pc->len += (pc->p - paren);
- pc->p = paren;
- }
- #ifndef EXPRSUGAR_BRACKET
- if (*pc->tstart == '(') {
- pc->tt = JIM_TT_EXPRSUGAR;
- }
- #endif
- }
- pc->tend = pc->p - 1;
- }
- if (pc->tstart == pc->p) {
- pc->p--;
- pc->len++;
- return JIM_ERR;
- }
- return JIM_OK;
- }
- static int JimParseStr(struct JimParserCtx *pc)
- {
- if (pc->tt == JIM_TT_SEP || pc->tt == JIM_TT_EOL ||
- pc->tt == JIM_TT_NONE || pc->tt == JIM_TT_STR) {
- if (*pc->p == '{') {
- return JimParseBrace(pc);
- }
- if (*pc->p == '"') {
- pc->inquote = 1;
- pc->p++;
- pc->len--;
- pc->missing.line = pc->tline;
- }
- }
- pc->tstart = pc->p;
- pc->tline = pc->linenr;
- while (1) {
- if (pc->len == 0) {
- if (pc->inquote) {
- pc->missing.ch = '"';
- }
- pc->tend = pc->p - 1;
- pc->tt = JIM_TT_ESC;
- return JIM_OK;
- }
- switch (*pc->p) {
- case '\\':
- if (!pc->inquote && *(pc->p + 1) == '\n') {
- pc->tend = pc->p - 1;
- pc->tt = JIM_TT_ESC;
- return JIM_OK;
- }
- if (pc->len >= 2) {
- if (*(pc->p + 1) == '\n') {
- pc->linenr++;
- }
- pc->p++;
- pc->len--;
- }
- else if (pc->len == 1) {
- pc->missing.ch = '\\';
- }
- break;
- case '(':
- if (pc->len > 1 && pc->p[1] != '$') {
- break;
- }
- case ')':
- if (*pc->p == '(' || pc->tt == JIM_TT_VAR) {
- if (pc->p == pc->tstart) {
- pc->p++;
- pc->len--;
- }
- pc->tend = pc->p - 1;
- pc->tt = JIM_TT_ESC;
- return JIM_OK;
- }
- break;
- case '$':
- case '[':
- pc->tend = pc->p - 1;
- pc->tt = JIM_TT_ESC;
- return JIM_OK;
- case ' ':
- case '\t':
- case '\n':
- case '\r':
- case '\f':
- case ';':
- if (!pc->inquote) {
- pc->tend = pc->p - 1;
- pc->tt = JIM_TT_ESC;
- return JIM_OK;
- }
- else if (*pc->p == '\n') {
- pc->linenr++;
- }
- break;
- case '"':
- if (pc->inquote) {
- pc->tend = pc->p - 1;
- pc->tt = JIM_TT_ESC;
- pc->p++;
- pc->len--;
- pc->inquote = 0;
- return JIM_OK;
- }
- break;
- }
- pc->p++;
- pc->len--;
- }
- return JIM_OK;
- }
- static int JimParseComment(struct JimParserCtx *pc)
- {
- while (*pc->p) {
- if (*pc->p == '\\') {
- pc->p++;
- pc->len--;
- if (pc->len == 0) {
- pc->missing.ch = '\\';
- return JIM_OK;
- }
- if (*pc->p == '\n') {
- pc->linenr++;
- }
- }
- else if (*pc->p == '\n') {
- pc->p++;
- pc->len--;
- pc->linenr++;
- break;
- }
- pc->p++;
- pc->len--;
- }
- return JIM_OK;
- }
- static int xdigitval(int c)
- {
- if (c >= '0' && c <= '9')
- return c - '0';
- if (c >= 'a' && c <= 'f')
- return c - 'a' + 10;
- if (c >= 'A' && c <= 'F')
- return c - 'A' + 10;
- return -1;
- }
- static int odigitval(int c)
- {
- if (c >= '0' && c <= '7')
- return c - '0';
- return -1;
- }
- static int JimEscape(char *dest, const char *s, int slen)
- {
- char *p = dest;
- int i, len;
- for (i = 0; i < slen; i++) {
- switch (s[i]) {
- case '\\':
- switch (s[i + 1]) {
- case 'a':
- *p++ = 0x7;
- i++;
- break;
- case 'b':
- *p++ = 0x8;
- i++;
- break;
- case 'f':
- *p++ = 0xc;
- i++;
- break;
- case 'n':
- *p++ = 0xa;
- i++;
- break;
- case 'r':
- *p++ = 0xd;
- i++;
- break;
- case 't':
- *p++ = 0x9;
- i++;
- break;
- case 'u':
- case 'U':
- case 'x':
- {
- unsigned val = 0;
- int k;
- int maxchars = 2;
- i++;
- if (s[i] == 'U') {
- maxchars = 8;
- }
- else if (s[i] == 'u') {
- if (s[i + 1] == '{') {
- maxchars = 6;
- i++;
- }
- else {
- maxchars = 4;
- }
- }
- for (k = 0; k < maxchars; k++) {
- int c = xdigitval(s[i + k + 1]);
- if (c == -1) {
- break;
- }
- val = (val << 4) | c;
- }
- if (s[i] == '{') {
- if (k == 0 || val > 0x1fffff || s[i + k + 1] != '}') {
- i--;
- k = 0;
- }
- else {
- k++;
- }
- }
- if (k) {
- if (s[i] == 'x') {
- *p++ = val;
- }
- else {
- p += utf8_fromunicode(p, val);
- }
- i += k;
- break;
- }
- *p++ = s[i];
- }
- break;
- case 'v':
- *p++ = 0xb;
- i++;
- break;
- case '\0':
- *p++ = '\\';
- i++;
- break;
- case '\n':
- *p++ = ' ';
- do {
- i++;
- } while (s[i + 1] == ' ' || s[i + 1] == '\t');
- break;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- {
- int val = 0;
- int c = odigitval(s[i + 1]);
- val = c;
- c = odigitval(s[i + 2]);
- if (c == -1) {
- *p++ = val;
- i++;
- break;
- }
- val = (val * 8) + c;
- c = odigitval(s[i + 3]);
- if (c == -1) {
- *p++ = val;
- i += 2;
- break;
- }
- val = (val * 8) + c;
- *p++ = val;
- i += 3;
- }
- break;
- default:
- *p++ = s[i + 1];
- i++;
- break;
- }
- break;
- default:
- *p++ = s[i];
- break;
- }
- }
- len = p - dest;
- *p = '\0';
- return len;
- }
- static Jim_Obj *JimParserGetTokenObj(Jim_Interp *interp, struct JimParserCtx *pc)
- {
- const char *start, *end;
- char *token;
- int len;
- start = pc->tstart;
- end = pc->tend;
- len = (end - start) + 1;
- if (len < 0) {
- len = 0;
- }
- token = Jim_Alloc(len + 1);
- if (pc->tt != JIM_TT_ESC) {
- memcpy(token, start, len);
- token[len] = '\0';
- }
- else {
- len = JimEscape(token, start, len);
- }
- return Jim_NewStringObjNoAlloc(interp, token, len);
- }
- static int JimParseListSep(struct JimParserCtx *pc);
- static int JimParseListStr(struct JimParserCtx *pc);
- static int JimParseListQuote(struct JimParserCtx *pc);
- static int JimParseList(struct JimParserCtx *pc)
- {
- if (isspace(UCHAR(*pc->p))) {
- return JimParseListSep(pc);
- }
- switch (*pc->p) {
- case '"':
- return JimParseListQuote(pc);
- case '{':
- return JimParseBrace(pc);
- default:
- if (pc->len) {
- return JimParseListStr(pc);
- }
- break;
- }
- pc->tstart = pc->tend = pc->p;
- pc->tline = pc->linenr;
- pc->tt = JIM_TT_EOL;
- pc->eof = 1;
- return JIM_OK;
- }
- static int JimParseListSep(struct JimParserCtx *pc)
- {
- pc->tstart = pc->p;
- pc->tline = pc->linenr;
- while (isspace(UCHAR(*pc->p))) {
- if (*pc->p == '\n') {
- pc->linenr++;
- }
- pc->p++;
- pc->len--;
- }
- pc->tend = pc->p - 1;
- pc->tt = JIM_TT_SEP;
- return JIM_OK;
- }
- static int JimParseListQuote(struct JimParserCtx *pc)
- {
- pc->p++;
- pc->len--;
- pc->tstart = pc->p;
- pc->tline = pc->linenr;
- pc->tt = JIM_TT_STR;
- while (pc->len) {
- switch (*pc->p) {
- case '\\':
- pc->tt = JIM_TT_ESC;
- if (--pc->len == 0) {
- pc->tend = pc->p;
- return JIM_OK;
- }
- pc->p++;
- break;
- case '\n':
- pc->linenr++;
- break;
- case '"':
- pc->tend = pc->p - 1;
- pc->p++;
- pc->len--;
- return JIM_OK;
- }
- pc->p++;
- pc->len--;
- }
- pc->tend = pc->p - 1;
- return JIM_OK;
- }
- static int JimParseListStr(struct JimParserCtx *pc)
- {
- pc->tstart = pc->p;
- pc->tline = pc->linenr;
- pc->tt = JIM_TT_STR;
- while (pc->len) {
- if (isspace(UCHAR(*pc->p))) {
- pc->tend = pc->p - 1;
- return JIM_OK;
- }
- if (*pc->p == '\\') {
- if (--pc->len == 0) {
- pc->tend = pc->p;
- return JIM_OK;
- }
- pc->tt = JIM_TT_ESC;
- pc->p++;
- }
- pc->p++;
- pc->len--;
- }
- pc->tend = pc->p - 1;
- return JIM_OK;
- }
- Jim_Obj *Jim_NewObj(Jim_Interp *interp)
- {
- Jim_Obj *objPtr;
- if (interp->freeList != NULL) {
- objPtr = interp->freeList;
- interp->freeList = objPtr->nextObjPtr;
- }
- else {
- objPtr = Jim_Alloc(sizeof(*objPtr));
- }
- objPtr->refCount = 0;
- objPtr->prevObjPtr = NULL;
- objPtr->nextObjPtr = interp->liveList;
- if (interp->liveList)
- interp->liveList->prevObjPtr = objPtr;
- interp->liveList = objPtr;
- return objPtr;
- }
- void Jim_FreeObj(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- JimPanic((objPtr->refCount != 0, "!!!Object %p freed with bad refcount %d, type=%s", objPtr,
- objPtr->refCount, objPtr->typePtr ? objPtr->typePtr->name : "<none>"));
- Jim_FreeIntRep(interp, objPtr);
- if (objPtr->bytes != NULL) {
- if (objPtr->bytes != JimEmptyStringRep)
- Jim_Free(objPtr->bytes);
- }
- if (objPtr->prevObjPtr)
- objPtr->prevObjPtr->nextObjPtr = objPtr->nextObjPtr;
- if (objPtr->nextObjPtr)
- objPtr->nextObjPtr->prevObjPtr = objPtr->prevObjPtr;
- if (interp->liveList == objPtr)
- interp->liveList = objPtr->nextObjPtr;
- #ifdef JIM_DISABLE_OBJECT_POOL
- Jim_Free(objPtr);
- #else
- objPtr->prevObjPtr = NULL;
- objPtr->nextObjPtr = interp->freeList;
- if (interp->freeList)
- interp->freeList->prevObjPtr = objPtr;
- interp->freeList = objPtr;
- objPtr->refCount = -1;
- #endif
- }
- void Jim_InvalidateStringRep(Jim_Obj *objPtr)
- {
- if (objPtr->bytes != NULL) {
- if (objPtr->bytes != JimEmptyStringRep)
- Jim_Free(objPtr->bytes);
- }
- objPtr->bytes = NULL;
- }
- Jim_Obj *Jim_DuplicateObj(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- Jim_Obj *dupPtr;
- dupPtr = Jim_NewObj(interp);
- if (objPtr->bytes == NULL) {
- dupPtr->bytes = NULL;
- }
- else if (objPtr->length == 0) {
- dupPtr->bytes = JimEmptyStringRep;
- dupPtr->length = 0;
- dupPtr->typePtr = NULL;
- return dupPtr;
- }
- else {
- dupPtr->bytes = Jim_Alloc(objPtr->length + 1);
- dupPtr->length = objPtr->length;
- memcpy(dupPtr->bytes, objPtr->bytes, objPtr->length + 1);
- }
- dupPtr->typePtr = objPtr->typePtr;
- if (objPtr->typePtr != NULL) {
- if (objPtr->typePtr->dupIntRepProc == NULL) {
- dupPtr->internalRep = objPtr->internalRep;
- }
- else {
- objPtr->typePtr->dupIntRepProc(interp, objPtr, dupPtr);
- }
- }
- return dupPtr;
- }
- const char *Jim_GetString(Jim_Obj *objPtr, int *lenPtr)
- {
- if (objPtr->bytes == NULL) {
- JimPanic((objPtr->typePtr->updateStringProc == NULL, "UpdateStringProc called against '%s' type.", objPtr->typePtr->name));
- objPtr->typePtr->updateStringProc(objPtr);
- }
- if (lenPtr)
- *lenPtr = objPtr->length;
- return objPtr->bytes;
- }
- int Jim_Length(Jim_Obj *objPtr)
- {
- if (objPtr->bytes == NULL) {
- Jim_GetString(objPtr, NULL);
- }
- return objPtr->length;
- }
- const char *Jim_String(Jim_Obj *objPtr)
- {
- if (objPtr->bytes == NULL) {
- Jim_GetString(objPtr, NULL);
- }
- return objPtr->bytes;
- }
- static void JimSetStringBytes(Jim_Obj *objPtr, const char *str)
- {
- objPtr->bytes = Jim_StrDup(str);
- objPtr->length = strlen(str);
- }
- static void FreeDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
- static void DupDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
- static const Jim_ObjType dictSubstObjType = {
- "dict-substitution",
- FreeDictSubstInternalRep,
- DupDictSubstInternalRep,
- NULL,
- JIM_TYPE_NONE,
- };
- static void FreeInterpolatedInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
- static void DupInterpolatedInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
- static const Jim_ObjType interpolatedObjType = {
- "interpolated",
- FreeInterpolatedInternalRep,
- DupInterpolatedInternalRep,
- NULL,
- JIM_TYPE_NONE,
- };
- static void FreeInterpolatedInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.indexObjPtr);
- }
- static void DupInterpolatedInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
- {
- dupPtr->internalRep = srcPtr->internalRep;
- Jim_IncrRefCount(dupPtr->internalRep.dictSubstValue.indexObjPtr);
- }
- static void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
- static int SetStringFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
- static const Jim_ObjType stringObjType = {
- "string",
- NULL,
- DupStringInternalRep,
- NULL,
- JIM_TYPE_REFERENCES,
- };
- static void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
- {
- JIM_NOTUSED(interp);
- dupPtr->internalRep.strValue.maxLength = srcPtr->length;
- dupPtr->internalRep.strValue.charLength = srcPtr->internalRep.strValue.charLength;
- }
- static int SetStringFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- if (objPtr->typePtr != &stringObjType) {
- if (objPtr->bytes == NULL) {
- JimPanic((objPtr->typePtr->updateStringProc == NULL, "UpdateStringProc called against '%s' type.", objPtr->typePtr->name));
- objPtr->typePtr->updateStringProc(objPtr);
- }
- Jim_FreeIntRep(interp, objPtr);
- objPtr->typePtr = &stringObjType;
- objPtr->internalRep.strValue.maxLength = objPtr->length;
- objPtr->internalRep.strValue.charLength = -1;
- }
- return JIM_OK;
- }
- int Jim_Utf8Length(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- #ifdef JIM_UTF8
- SetStringFromAny(interp, objPtr);
- if (objPtr->internalRep.strValue.charLength < 0) {
- objPtr->internalRep.strValue.charLength = utf8_strlen(objPtr->bytes, objPtr->length);
- }
- return objPtr->internalRep.strValue.charLength;
- #else
- return Jim_Length(objPtr);
- #endif
- }
- Jim_Obj *Jim_NewStringObj(Jim_Interp *interp, const char *s, int len)
- {
- Jim_Obj *objPtr = Jim_NewObj(interp);
- if (len == -1)
- len = strlen(s);
- if (len == 0) {
- objPtr->bytes = JimEmptyStringRep;
- }
- else {
- objPtr->bytes = Jim_StrDupLen(s, len);
- }
- objPtr->length = len;
- objPtr->typePtr = NULL;
- return objPtr;
- }
- Jim_Obj *Jim_NewStringObjUtf8(Jim_Interp *interp, const char *s, int charlen)
- {
- #ifdef JIM_UTF8
- int bytelen = utf8_index(s, charlen);
- Jim_Obj *objPtr = Jim_NewStringObj(interp, s, bytelen);
- objPtr->typePtr = &stringObjType;
- objPtr->internalRep.strValue.maxLength = bytelen;
- objPtr->internalRep.strValue.charLength = charlen;
- return objPtr;
- #else
- return Jim_NewStringObj(interp, s, charlen);
- #endif
- }
- Jim_Obj *Jim_NewStringObjNoAlloc(Jim_Interp *interp, char *s, int len)
- {
- Jim_Obj *objPtr = Jim_NewObj(interp);
- objPtr->bytes = s;
- objPtr->length = (len == -1) ? strlen(s) : len;
- objPtr->typePtr = NULL;
- return objPtr;
- }
- static void StringAppendString(Jim_Obj *objPtr, const char *str, int len)
- {
- int needlen;
- if (len == -1)
- len = strlen(str);
- needlen = objPtr->length + len;
- if (objPtr->internalRep.strValue.maxLength < needlen ||
- objPtr->internalRep.strValue.maxLength == 0) {
- needlen *= 2;
- if (needlen < 7) {
- needlen = 7;
- }
- if (objPtr->bytes == JimEmptyStringRep) {
- objPtr->bytes = Jim_Alloc(needlen + 1);
- }
- else {
- objPtr->bytes = Jim_Realloc(objPtr->bytes, needlen + 1);
- }
- objPtr->internalRep.strValue.maxLength = needlen;
- }
- memcpy(objPtr->bytes + objPtr->length, str, len);
- objPtr->bytes[objPtr->length + len] = '\0';
- if (objPtr->internalRep.strValue.charLength >= 0) {
- objPtr->internalRep.strValue.charLength += utf8_strlen(objPtr->bytes + objPtr->length, len);
- }
- objPtr->length += len;
- }
- void Jim_AppendString(Jim_Interp *interp, Jim_Obj *objPtr, const char *str, int len)
- {
- JimPanic((Jim_IsShared(objPtr), "Jim_AppendString called with shared object"));
- SetStringFromAny(interp, objPtr);
- StringAppendString(objPtr, str, len);
- }
- void Jim_AppendObj(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *appendObjPtr)
- {
- int len;
- const char *str = Jim_GetString(appendObjPtr, &len);
- Jim_AppendString(interp, objPtr, str, len);
- }
- void Jim_AppendStrings(Jim_Interp *interp, Jim_Obj *objPtr, ...)
- {
- va_list ap;
- SetStringFromAny(interp, objPtr);
- va_start(ap, objPtr);
- while (1) {
- const char *s = va_arg(ap, const char *);
- if (s == NULL)
- break;
- Jim_AppendString(interp, objPtr, s, -1);
- }
- va_end(ap);
- }
- int Jim_StringEqObj(Jim_Obj *aObjPtr, Jim_Obj *bObjPtr)
- {
- if (aObjPtr == bObjPtr) {
- return 1;
- }
- else {
- int Alen, Blen;
- const char *sA = Jim_GetString(aObjPtr, &Alen);
- const char *sB = Jim_GetString(bObjPtr, &Blen);
- return Alen == Blen && memcmp(sA, sB, Alen) == 0;
- }
- }
- int Jim_StringMatchObj(Jim_Interp *interp, Jim_Obj *patternObjPtr, Jim_Obj *objPtr, int nocase)
- {
- int plen, slen;
- const char *pattern = Jim_GetString(patternObjPtr, &plen);
- const char *string = Jim_GetString(objPtr, &slen);
- return JimGlobMatch(pattern, plen, string, slen, nocase);
- }
- int Jim_StringCompareObj(Jim_Interp *interp, Jim_Obj *firstObjPtr, Jim_Obj *secondObjPtr, int nocase)
- {
- const char *s1 = Jim_String(firstObjPtr);
- int l1 = Jim_Utf8Length(interp, firstObjPtr);
- const char *s2 = Jim_String(secondObjPtr);
- int l2 = Jim_Utf8Length(interp, secondObjPtr);
- return JimStringCompareUtf8(s1, l1, s2, l2, nocase);
- }
- static int JimRelToAbsIndex(int len, int idx)
- {
- if (idx < 0 && idx > -INT_MAX)
- return len + idx;
- return idx;
- }
- static void JimRelToAbsRange(int len, int *firstPtr, int *lastPtr, int *rangeLenPtr)
- {
- int rangeLen;
- if (*firstPtr > *lastPtr) {
- rangeLen = 0;
- }
- else {
- rangeLen = *lastPtr - *firstPtr + 1;
- if (rangeLen) {
- if (*firstPtr < 0) {
- rangeLen += *firstPtr;
- *firstPtr = 0;
- }
- if (*lastPtr >= len) {
- rangeLen -= (*lastPtr - (len - 1));
- *lastPtr = len - 1;
- }
- }
- }
- if (rangeLen < 0)
- rangeLen = 0;
- *rangeLenPtr = rangeLen;
- }
- static int JimStringGetRange(Jim_Interp *interp, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr,
- int len, int *first, int *last, int *range)
- {
- if (Jim_GetIndex(interp, firstObjPtr, first) != JIM_OK) {
- return JIM_ERR;
- }
- if (Jim_GetIndex(interp, lastObjPtr, last) != JIM_OK) {
- return JIM_ERR;
- }
- *first = JimRelToAbsIndex(len, *first);
- *last = JimRelToAbsIndex(len, *last);
- JimRelToAbsRange(len, first, last, range);
- return JIM_OK;
- }
- Jim_Obj *Jim_StringByteRangeObj(Jim_Interp *interp,
- Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)
- {
- int first, last;
- const char *str;
- int rangeLen;
- int bytelen;
- str = Jim_GetString(strObjPtr, &bytelen);
- if (JimStringGetRange(interp, firstObjPtr, lastObjPtr, bytelen, &first, &last, &rangeLen) != JIM_OK) {
- return NULL;
- }
- if (first == 0 && rangeLen == bytelen) {
- return strObjPtr;
- }
- return Jim_NewStringObj(interp, str + first, rangeLen);
- }
- Jim_Obj *Jim_StringRangeObj(Jim_Interp *interp,
- Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)
- {
- #ifdef JIM_UTF8
- int first, last;
- const char *str;
- int len, rangeLen;
- int bytelen;
- str = Jim_GetString(strObjPtr, &bytelen);
- len = Jim_Utf8Length(interp, strObjPtr);
- if (JimStringGetRange(interp, firstObjPtr, lastObjPtr, len, &first, &last, &rangeLen) != JIM_OK) {
- return NULL;
- }
- if (first == 0 && rangeLen == len) {
- return strObjPtr;
- }
- if (len == bytelen) {
- return Jim_NewStringObj(interp, str + first, rangeLen);
- }
- return Jim_NewStringObjUtf8(interp, str + utf8_index(str, first), rangeLen);
- #else
- return Jim_StringByteRangeObj(interp, strObjPtr, firstObjPtr, lastObjPtr);
- #endif
- }
- Jim_Obj *JimStringReplaceObj(Jim_Interp *interp,
- Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr, Jim_Obj *newStrObj)
- {
- int first, last;
- const char *str;
- int len, rangeLen;
- Jim_Obj *objPtr;
- len = Jim_Utf8Length(interp, strObjPtr);
- if (JimStringGetRange(interp, firstObjPtr, lastObjPtr, len, &first, &last, &rangeLen) != JIM_OK) {
- return NULL;
- }
- if (last < first) {
- return strObjPtr;
- }
- str = Jim_String(strObjPtr);
- objPtr = Jim_NewStringObjUtf8(interp, str, first);
- if (newStrObj) {
- Jim_AppendObj(interp, objPtr, newStrObj);
- }
- Jim_AppendString(interp, objPtr, str + utf8_index(str, last + 1), len - last - 1);
- return objPtr;
- }
- static void JimStrCopyUpperLower(char *dest, const char *str, int uc)
- {
- while (*str) {
- int c;
- str += utf8_tounicode(str, &c);
- dest += utf8_getchars(dest, uc ? utf8_upper(c) : utf8_lower(c));
- }
- *dest = 0;
- }
- static Jim_Obj *JimStringToLower(Jim_Interp *interp, Jim_Obj *strObjPtr)
- {
- char *buf;
- int len;
- const char *str;
- str = Jim_GetString(strObjPtr, &len);
- #ifdef JIM_UTF8
- len *= 2;
- #endif
- buf = Jim_Alloc(len + 1);
- JimStrCopyUpperLower(buf, str, 0);
- return Jim_NewStringObjNoAlloc(interp, buf, -1);
- }
- static Jim_Obj *JimStringToUpper(Jim_Interp *interp, Jim_Obj *strObjPtr)
- {
- char *buf;
- const char *str;
- int len;
- str = Jim_GetString(strObjPtr, &len);
- #ifdef JIM_UTF8
- len *= 2;
- #endif
- buf = Jim_Alloc(len + 1);
- JimStrCopyUpperLower(buf, str, 1);
- return Jim_NewStringObjNoAlloc(interp, buf, -1);
- }
- static Jim_Obj *JimStringToTitle(Jim_Interp *interp, Jim_Obj *strObjPtr)
- {
- char *buf, *p;
- int len;
- int c;
- const char *str;
- str = Jim_GetString(strObjPtr, &len);
- #ifdef JIM_UTF8
- len *= 2;
- #endif
- buf = p = Jim_Alloc(len + 1);
- str += utf8_tounicode(str, &c);
- p += utf8_getchars(p, utf8_title(c));
- JimStrCopyUpperLower(p, str, 0);
- return Jim_NewStringObjNoAlloc(interp, buf, -1);
- }
- static const char *utf8_memchr(const char *str, int len, int c)
- {
- #ifdef JIM_UTF8
- while (len) {
- int sc;
- int n = utf8_tounicode(str, &sc);
- if (sc == c) {
- return str;
- }
- str += n;
- len -= n;
- }
- return NULL;
- #else
- return memchr(str, c, len);
- #endif
- }
- static const char *JimFindTrimLeft(const char *str, int len, const char *trimchars, int trimlen)
- {
- while (len) {
- int c;
- int n = utf8_tounicode(str, &c);
- if (utf8_memchr(trimchars, trimlen, c) == NULL) {
- break;
- }
- str += n;
- len -= n;
- }
- return str;
- }
- static const char *JimFindTrimRight(const char *str, int len, const char *trimchars, int trimlen)
- {
- str += len;
- while (len) {
- int c;
- int n = utf8_prev_len(str, len);
- len -= n;
- str -= n;
- n = utf8_tounicode(str, &c);
- if (utf8_memchr(trimchars, trimlen, c) == NULL) {
- return str + n;
- }
- }
- return NULL;
- }
- static const char default_trim_chars[] = " \t\n\r";
- static int default_trim_chars_len = sizeof(default_trim_chars);
- static Jim_Obj *JimStringTrimLeft(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
- {
- int len;
- const char *str = Jim_GetString(strObjPtr, &len);
- const char *trimchars = default_trim_chars;
- int trimcharslen = default_trim_chars_len;
- const char *newstr;
- if (trimcharsObjPtr) {
- trimchars = Jim_GetString(trimcharsObjPtr, &trimcharslen);
- }
- newstr = JimFindTrimLeft(str, len, trimchars, trimcharslen);
- if (newstr == str) {
- return strObjPtr;
- }
- return Jim_NewStringObj(interp, newstr, len - (newstr - str));
- }
- static Jim_Obj *JimStringTrimRight(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
- {
- int len;
- const char *trimchars = default_trim_chars;
- int trimcharslen = default_trim_chars_len;
- const char *nontrim;
- if (trimcharsObjPtr) {
- trimchars = Jim_GetString(trimcharsObjPtr, &trimcharslen);
- }
- SetStringFromAny(interp, strObjPtr);
- len = Jim_Length(strObjPtr);
- nontrim = JimFindTrimRight(strObjPtr->bytes, len, trimchars, trimcharslen);
- if (nontrim == NULL) {
- return Jim_NewEmptyStringObj(interp);
- }
- if (nontrim == strObjPtr->bytes + len) {
- return strObjPtr;
- }
- if (Jim_IsShared(strObjPtr)) {
- strObjPtr = Jim_NewStringObj(interp, strObjPtr->bytes, (nontrim - strObjPtr->bytes));
- }
- else {
- strObjPtr->bytes[nontrim - strObjPtr->bytes] = 0;
- strObjPtr->length = (nontrim - strObjPtr->bytes);
- }
- return strObjPtr;
- }
- static Jim_Obj *JimStringTrim(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
- {
- Jim_Obj *objPtr = JimStringTrimLeft(interp, strObjPtr, trimcharsObjPtr);
- strObjPtr = JimStringTrimRight(interp, objPtr, trimcharsObjPtr);
- if (objPtr != strObjPtr && objPtr->refCount == 0) {
- Jim_FreeNewObj(interp, objPtr);
- }
- return strObjPtr;
- }
- #ifdef HAVE_ISASCII
- #define jim_isascii isascii
- #else
- static int jim_isascii(int c)
- {
- return !(c & ~0x7f);
- }
- #endif
- static int JimStringIs(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *strClass, int strict)
- {
- static const char * const strclassnames[] = {
- "integer", "alpha", "alnum", "ascii", "digit",
- "double", "lower", "upper", "space", "xdigit",
- "control", "print", "graph", "punct", "boolean",
- NULL
- };
- enum {
- STR_IS_INTEGER, STR_IS_ALPHA, STR_IS_ALNUM, STR_IS_ASCII, STR_IS_DIGIT,
- STR_IS_DOUBLE, STR_IS_LOWER, STR_IS_UPPER, STR_IS_SPACE, STR_IS_XDIGIT,
- STR_IS_CONTROL, STR_IS_PRINT, STR_IS_GRAPH, STR_IS_PUNCT, STR_IS_BOOLEAN,
- };
- int strclass;
- int len;
- int i;
- const char *str;
- int (*isclassfunc)(int c) = NULL;
- if (Jim_GetEnum(interp, strClass, strclassnames, &strclass, "class", JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
- return JIM_ERR;
- }
- str = Jim_GetString(strObjPtr, &len);
- if (len == 0) {
- Jim_SetResultBool(interp, !strict);
- return JIM_OK;
- }
- switch (strclass) {
- case STR_IS_INTEGER:
- {
- jim_wide w;
- Jim_SetResultBool(interp, JimGetWideNoErr(interp, strObjPtr, &w) == JIM_OK);
- return JIM_OK;
- }
- case STR_IS_DOUBLE:
- {
- double d;
- Jim_SetResultBool(interp, Jim_GetDouble(interp, strObjPtr, &d) == JIM_OK && errno != ERANGE);
- return JIM_OK;
- }
- case STR_IS_BOOLEAN:
- {
- int b;
- Jim_SetResultBool(interp, Jim_GetBoolean(interp, strObjPtr, &b) == JIM_OK);
- return JIM_OK;
- }
- case STR_IS_ALPHA: isclassfunc = isalpha; break;
- case STR_IS_ALNUM: isclassfunc = isalnum; break;
- case STR_IS_ASCII: isclassfunc = jim_isascii; break;
- case STR_IS_DIGIT: isclassfunc = isdigit; break;
- case STR_IS_LOWER: isclassfunc = islower; break;
- case STR_IS_UPPER: isclassfunc = isupper; break;
- case STR_IS_SPACE: isclassfunc = isspace; break;
- case STR_IS_XDIGIT: isclassfunc = isxdigit; break;
- case STR_IS_CONTROL: isclassfunc = iscntrl; break;
- case STR_IS_PRINT: isclassfunc = isprint; break;
- case STR_IS_GRAPH: isclassfunc = isgraph; break;
- case STR_IS_PUNCT: isclassfunc = ispunct; break;
- default:
- return JIM_ERR;
- }
- for (i = 0; i < len; i++) {
- if (!isclassfunc(UCHAR(str[i]))) {
- Jim_SetResultBool(interp, 0);
- return JIM_OK;
- }
- }
- Jim_SetResultBool(interp, 1);
- return JIM_OK;
- }
- static const Jim_ObjType comparedStringObjType = {
- "compared-string",
- NULL,
- NULL,
- NULL,
- JIM_TYPE_REFERENCES,
- };
- int Jim_CompareStringImmediate(Jim_Interp *interp, Jim_Obj *objPtr, const char *str)
- {
- if (objPtr->typePtr == &comparedStringObjType && objPtr->internalRep.ptr == str) {
- return 1;
- }
- else {
- if (strcmp(str, Jim_String(objPtr)) != 0)
- return 0;
- if (objPtr->typePtr != &comparedStringObjType) {
- Jim_FreeIntRep(interp, objPtr);
- objPtr->typePtr = &comparedStringObjType;
- }
- objPtr->internalRep.ptr = (char *)str;
- return 1;
- }
- }
- static int qsortCompareStringPointers(const void *a, const void *b)
- {
- char *const *sa = (char *const *)a;
- char *const *sb = (char *const *)b;
- return strcmp(*sa, *sb);
- }
- static void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
- static void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
- static const Jim_ObjType sourceObjType = {
- "source",
- FreeSourceInternalRep,
- DupSourceInternalRep,
- NULL,
- JIM_TYPE_REFERENCES,
- };
- void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- Jim_DecrRefCount(interp, objPtr->internalRep.sourceValue.fileNameObj);
- }
- void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
- {
- dupPtr->internalRep.sourceValue = srcPtr->internalRep.sourceValue;
- Jim_IncrRefCount(dupPtr->internalRep.sourceValue.fileNameObj);
- }
- static const Jim_ObjType scriptLineObjType = {
- "scriptline",
- NULL,
- NULL,
- NULL,
- JIM_NONE,
- };
- static Jim_Obj *JimNewScriptLineObj(Jim_Interp *interp, int argc, int line)
- {
- Jim_Obj *objPtr;
- #ifdef DEBUG_SHOW_SCRIPT
- char buf[100];
- snprintf(buf, sizeof(buf), "line=%d, argc=%d", line, argc);
- objPtr = Jim_NewStringObj(interp, buf, -1);
- #else
- objPtr = Jim_NewEmptyStringObj(interp);
- #endif
- objPtr->typePtr = &scriptLineObjType;
- objPtr->internalRep.scriptLineValue.argc = argc;
- objPtr->internalRep.scriptLineValue.line = line;
- return objPtr;
- }
- static void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
- static void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
- static const Jim_ObjType scriptObjType = {
- "script",
- FreeScriptInternalRep,
- DupScriptInternalRep,
- NULL,
- JIM_TYPE_NONE,
- };
- typedef struct ScriptToken
- {
- Jim_Obj *objPtr;
- int type;
- } ScriptToken;
- typedef struct ScriptObj
- {
- ScriptToken *token;
- Jim_Obj *fileNameObj;
- int len;
- int substFlags;
- int inUse; /* Used to share a ScriptObj. Currently
- only used by Jim_EvalObj() as protection against
- shimmering of the currently evaluated object. */
- int firstline;
- int linenr;
- int missing;
- } ScriptObj;
- static void JimSetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
- static int JimParseCheckMissing(Jim_Interp *interp, int ch);
- static ScriptObj *JimGetScript(Jim_Interp *interp, Jim_Obj *objPtr);
- static void JimSetErrorStack(Jim_Interp *interp, ScriptObj *script);
- void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- int i;
- struct ScriptObj *script = (void *)objPtr->internalRep.ptr;
- if (--script->inUse != 0)
- return;
- for (i = 0; i < script->len; i++) {
- Jim_DecrRefCount(interp, script->token[i].objPtr);
- }
- Jim_Free(script->token);
- Jim_DecrRefCount(interp, script->fileNameObj);
- Jim_Free(script);
- }
- void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
- {
- JIM_NOTUSED(interp);
- JIM_NOTUSED(srcPtr);
- dupPtr->typePtr = NULL;
- }
- typedef struct
- {
- const char *token;
- int len;
- int type;
- int line;
- } ParseToken;
- typedef struct
- {
- ParseToken *list;
- int size;
- int count;
- ParseToken static_list[20];
- } ParseTokenList;
- static void ScriptTokenListInit(ParseTokenList *tokenlist)
- {
- tokenlist->list = tokenlist->static_list;
- tokenlist->size = sizeof(tokenlist->static_list) / sizeof(ParseToken);
- tokenlist->count = 0;
- }
- static void ScriptTokenListFree(ParseTokenList *tokenlist)
- {
- if (tokenlist->list != tokenlist->static_list) {
- Jim_Free(tokenlist->list);
- }
- }
- static void ScriptAddToken(ParseTokenList *tokenlist, const char *token, int len, int type,
- int line)
- {
- ParseToken *t;
- if (tokenlist->count == tokenlist->size) {
- tokenlist->size *= 2;
- if (tokenlist->list != tokenlist->static_list) {
- tokenlist->list =
- Jim_Realloc(tokenlist->list, tokenlist->size * sizeof(*tokenlist->list));
- }
- else {
- tokenlist->list = Jim_Alloc(tokenlist->size * sizeof(*tokenlist->list));
- memcpy(tokenlist->list, tokenlist->static_list,
- tokenlist->count * sizeof(*tokenlist->list));
- }
- }
- t = &tokenlist->list[tokenlist->count++];
- t->token = token;
- t->len = len;
- t->type = type;
- t->line = line;
- }
- static int JimCountWordTokens(struct ScriptObj *script, ParseToken *t)
- {
- int expand = 1;
- int count = 0;
- if (t->type == JIM_TT_STR && !TOKEN_IS_SEP(t[1].type)) {
- if ((t->len == 1 && *t->token == '*') || (t->len == 6 && strncmp(t->token, "expand", 6) == 0)) {
- expand = -1;
- t++;
- }
- else {
- if (script->missing == ' ') {
- script->missing = '}';
- script->linenr = t[1].line;
- }
- }
- }
- while (!TOKEN_IS_SEP(t->type)) {
- t++;
- count++;
- }
- return count * expand;
- }
- static Jim_Obj *JimMakeScriptObj(Jim_Interp *interp, const ParseToken *t)
- {
- Jim_Obj *objPtr;
- if (t->type == JIM_TT_ESC && memchr(t->token, '\\', t->len) != NULL) {
- int len = t->len;
- char *str = Jim_Alloc(len + 1);
- len = JimEscape(str, t->token, len);
- objPtr = Jim_NewStringObjNoAlloc(interp, str, len);
- }
- else {
- objPtr = Jim_NewStringObj(interp, t->token, t->len);
- }
- return objPtr;
- }
- static void ScriptObjAddTokens(Jim_Interp *interp, struct ScriptObj *script,
- ParseTokenList *tokenlist)
- {
- int i;
- struct ScriptToken *token;
- int lineargs = 0;
- ScriptToken *linefirst;
- int count;
- int linenr;
- #ifdef DEBUG_SHOW_SCRIPT_TOKENS
- printf("==== Tokens ====\n");
- for (i = 0; i < tokenlist->count; i++) {
- printf("[%2d]@%d %s '%.*s'\n", i, tokenlist->list[i].line, jim_tt_name(tokenlist->list[i].type),
- tokenlist->list[i].len, tokenlist->list[i].token);
- }
- #endif
- count = tokenlist->count;
- for (i = 0; i < tokenlist->count; i++) {
- if (tokenlist->list[i].type == JIM_TT_EOL) {
- count++;
- }
- }
- linenr = script->firstline = tokenlist->list[0].line;
- token = script->token = Jim_Alloc(sizeof(ScriptToken) * count);
- linefirst = token++;
- for (i = 0; i < tokenlist->count; ) {
- int wordtokens;
- while (tokenlist->list[i].type == JIM_TT_SEP) {
- i++;
- }
- wordtokens = JimCountWordTokens(script, tokenlist->list + i);
- if (wordtokens == 0) {
- if (lineargs) {
- linefirst->type = JIM_TT_LINE;
- linefirst->objPtr = JimNewScriptLineObj(interp, lineargs, linenr);
- Jim_IncrRefCount(linefirst->objPtr);
- lineargs = 0;
- linefirst = token++;
- }
- i++;
- continue;
- }
- else if (wordtokens != 1) {
- token->type = JIM_TT_WORD;
- token->objPtr = Jim_NewIntObj(interp, wordtokens);
- Jim_IncrRefCount(token->objPtr);
- token++;
- if (wordtokens < 0) {
- i++;
- wordtokens = -wordtokens - 1;
- lineargs--;
- }
- }
- if (lineargs == 0) {
- linenr = tokenlist->list[i].line;
- }
- lineargs++;
- while (wordtokens--) {
- const ParseToken *t = &tokenlist->list[i++];
- token->type = t->type;
- token->objPtr = JimMakeScriptObj(interp, t);
- Jim_IncrRefCount(token->objPtr);
- Jim_SetSourceInfo(interp, token->objPtr, script->fileNameObj, t->line);
- token++;
- }
- }
- if (lineargs == 0) {
- token--;
- }
- script->len = token - script->token;
- JimPanic((script->len >= count, "allocated script array is too short"));
- #ifdef DEBUG_SHOW_SCRIPT
- printf("==== Script (%s) ====\n", Jim_String(script->fileNameObj));
- for (i = 0; i < script->len; i++) {
- const ScriptToken *t = &script->token[i];
- printf("[%2d] %s %s\n", i, jim_tt_name(t->type), Jim_String(t->objPtr));
- }
- #endif
- }
- int Jim_ScriptIsComplete(Jim_Interp *interp, Jim_Obj *scriptObj, char *stateCharPtr)
- {
- ScriptObj *script = JimGetScript(interp, scriptObj);
- if (stateCharPtr) {
- *stateCharPtr = script->missing;
- }
- return script->missing == ' ' || script->missing == '}';
- }
- static int JimParseCheckMissing(Jim_Interp *interp, int ch)
- {
- const char *msg;
- switch (ch) {
- case '\\':
- case ' ':
- return JIM_OK;
- case '[':
- msg = "unmatched \"[\"";
- break;
- case '{':
- msg = "missing close-brace";
- break;
- case '}':
- msg = "extra characters after close-brace";
- break;
- case '"':
- default:
- msg = "missing quote";
- break;
- }
- Jim_SetResultString(interp, msg, -1);
- return JIM_ERR;
- }
- Jim_Obj *Jim_GetSourceInfo(Jim_Interp *interp, Jim_Obj *objPtr, int *lineptr)
- {
- int line;
- Jim_Obj *fileNameObj;
- if (objPtr->typePtr == &sourceObjType) {
- fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
- line = objPtr->internalRep.sourceValue.lineNumber;
- }
- else if (objPtr->typePtr == &scriptObjType) {
- ScriptObj *script = JimGetScript(interp, objPtr);
- fileNameObj = script->fileNameObj;
- line = script->firstline;
- }
- else {
- fileNameObj = interp->emptyObj;
- line = 1;
- }
- *lineptr = line;
- return fileNameObj;
- }
- void Jim_SetSourceInfo(Jim_Interp *interp, Jim_Obj *objPtr,
- Jim_Obj *fileNameObj, int lineNumber)
- {
- JimPanic((Jim_IsShared(objPtr), "Jim_SetSourceInfo called with shared object"));
- Jim_FreeIntRep(interp, objPtr);
- Jim_IncrRefCount(fileNameObj);
- objPtr->internalRep.sourceValue.fileNameObj = fileNameObj;
- objPtr->internalRep.sourceValue.lineNumber = lineNumber;
- objPtr->typePtr = &sourceObjType;
- }
- static void SubstObjAddTokens(Jim_Interp *interp, struct ScriptObj *script,
- ParseTokenList *tokenlist)
- {
- int i;
- struct ScriptToken *token;
- token = script->token = Jim_Alloc(sizeof(ScriptToken) * tokenlist->count);
- for (i = 0; i < tokenlist->count; i++) {
- const ParseToken *t = &tokenlist->list[i];
- token->type = t->type;
- token->objPtr = JimMakeScriptObj(interp, t);
- Jim_IncrRefCount(token->objPtr);
- token++;
- }
- script->len = i;
- }
- static void JimSetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
- {
- int scriptTextLen;
- const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);
- struct JimParserCtx parser;
- struct ScriptObj *script;
- ParseTokenList tokenlist;
- Jim_Obj *fileNameObj;
- int line;
- fileNameObj = Jim_GetSourceInfo(interp, objPtr, &line);
- ScriptTokenListInit(&tokenlist);
- JimParserInit(&parser, scriptText, scriptTextLen, line);
- while (!parser.eof) {
- JimParseScript(&parser);
- ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
- parser.tline);
- }
- ScriptAddToken(&tokenlist, scriptText + scriptTextLen, 0, JIM_TT_EOF, 0);
- script = Jim_Alloc(sizeof(*script));
- memset(script, 0, sizeof(*script));
- script->inUse = 1;
- script->fileNameObj = fileNameObj;
- Jim_IncrRefCount(script->fileNameObj);
- script->missing = parser.missing.ch;
- script->linenr = parser.missing.line;
- ScriptObjAddTokens(interp, script, &tokenlist);
- ScriptTokenListFree(&tokenlist);
- Jim_FreeIntRep(interp, objPtr);
- Jim_SetIntRepPtr(objPtr, script);
- objPtr->typePtr = &scriptObjType;
- }
- static ScriptObj *JimGetScript(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- if (objPtr == interp->emptyObj) {
- objPtr = interp->nullScriptObj;
- }
- if (objPtr->typePtr != &scriptObjType || ((struct ScriptObj *)Jim_GetIntRepPtr(objPtr))->substFlags) {
- JimSetScriptFromAny(interp, objPtr);
- }
- return (ScriptObj *)Jim_GetIntRepPtr(objPtr);
- }
- void Jim_InterpIncrProcEpoch(Jim_Interp *interp)
- {
- interp->procEpoch++;
- while (interp->oldCmdCache) {
- Jim_Cmd *next = interp->oldCmdCache->prevCmd;
- Jim_Free(interp->oldCmdCache);
- interp->oldCmdCache = next;
- }
- interp->oldCmdCacheSize = 0;
- }
- static void JimIncrCmdRefCount(Jim_Cmd *cmdPtr)
- {
- cmdPtr->inUse++;
- }
- static void JimDecrCmdRefCount(Jim_Interp *interp, Jim_Cmd *cmdPtr)
- {
- if (--cmdPtr->inUse == 0) {
- if (cmdPtr->isproc) {
- Jim_DecrRefCount(interp, cmdPtr->u.proc.argListObjPtr);
- Jim_DecrRefCount(interp, cmdPtr->u.proc.bodyObjPtr);
- Jim_DecrRefCount(interp, cmdPtr->u.proc.nsObj);
- if (cmdPtr->u.proc.staticVars) {
- Jim_FreeHashTable(cmdPtr->u.proc.staticVars);
- Jim_Free(cmdPtr->u.proc.staticVars);
- }
- }
- else {
- if (cmdPtr->u.native.delProc) {
- cmdPtr->u.native.delProc(interp, cmdPtr->u.native.privData);
- }
- }
- if (cmdPtr->prevCmd) {
- JimDecrCmdRefCount(interp, cmdPtr->prevCmd);
- }
- cmdPtr->prevCmd = interp->oldCmdCache;
- interp->oldCmdCache = cmdPtr;
- if (!interp->quitting && ++interp->oldCmdCacheSize >= 1000) {
- Jim_InterpIncrProcEpoch(interp);
- }
- }
- }
- static void JimIncrVarRef(Jim_VarVal *vv)
- {
- vv->refCount++;
- }
- static void JimDecrVarRef(Jim_Interp *interp, Jim_VarVal *vv)
- {
- assert(vv->refCount > 0);
- if (--vv->refCount == 0) {
- if (vv->objPtr) {
- Jim_DecrRefCount(interp, vv->objPtr);
- }
- Jim_Free(vv);
- }
- }
- static void JimVariablesHTValDestructor(void *interp, void *val)
- {
- JimDecrVarRef(interp, val);
- }
- static unsigned int JimObjectHTHashFunction(const void *key)
- {
- Jim_Obj *keyObj = (Jim_Obj *)key;
- int length;
- const char *string;
- #ifdef JIM_OPTIMIZATION
- if (JimIsWide(keyObj) && keyObj->bytes == NULL) {
- jim_wide objValue = JimWideValue(keyObj);
- if (objValue > INT_MIN && objValue < INT_MAX) {
- unsigned result = 0;
- unsigned value = (unsigned)objValue;
- if (objValue < 0) {
- value = (unsigned)-objValue;
- }
- do {
- result += (result << 3) + (value % 10 + '0');
- value /= 10;
- } while (value);
- if (objValue < 0) {
- result += (result << 3) + '-';
- }
- return result;
- }
- }
- #endif
- string = Jim_GetString(keyObj, &length);
- return Jim_GenHashFunction((const unsigned char *)string, length);
- }
- static int JimObjectHTKeyCompare(void *privdata, const void *key1, const void *key2)
- {
- return Jim_StringEqObj((Jim_Obj *)key1, (Jim_Obj *)key2);
- }
- static void *JimObjectHTKeyValDup(void *privdata, const void *val)
- {
- Jim_IncrRefCount((Jim_Obj *)val);
- return (void *)val;
- }
- static void JimObjectHTKeyValDestructor(void *interp, void *val)
- {
- Jim_DecrRefCount(interp, (Jim_Obj *)val);
- }
- static void *JimVariablesHTValDup(void *privdata, const void *val)
- {
- JimIncrVarRef((Jim_VarVal *)val);
- return (void *)val;
- }
- static const Jim_HashTableType JimVariablesHashTableType = {
- JimObjectHTHashFunction,
- JimObjectHTKeyValDup,
- JimVariablesHTValDup,
- JimObjectHTKeyCompare,
- JimObjectHTKeyValDestructor,
- JimVariablesHTValDestructor
- };
- static const char *Jim_GetStringNoQualifier(Jim_Obj *objPtr, int *length)
- {
- int len;
- const char *str = Jim_GetString(objPtr, &len);
- if (len >= 2 && str[0] == ':' && str[1] == ':') {
- while (len && *str == ':') {
- len--;
- str++;
- }
- }
- *length = len;
- return str;
- }
- static unsigned int JimCommandsHT_HashFunction(const void *key)
- {
- int len;
- const char *str = Jim_GetStringNoQualifier((Jim_Obj *)key, &len);
- return Jim_GenHashFunction((const unsigned char *)str, len);
- }
- static int JimCommandsHT_KeyCompare(void *privdata, const void *key1, const void *key2)
- {
- int len1, len2;
- const char *str1 = Jim_GetStringNoQualifier((Jim_Obj *)key1, &len1);
- const char *str2 = Jim_GetStringNoQualifier((Jim_Obj *)key2, &len2);
- return len1 == len2 && memcmp(str1, str2, len1) == 0;
- }
- static void JimCommandsHT_ValDestructor(void *interp, void *val)
- {
- JimDecrCmdRefCount(interp, val);
- }
- static const Jim_HashTableType JimCommandsHashTableType = {
- JimCommandsHT_HashFunction,
- JimObjectHTKeyValDup,
- NULL,
- JimCommandsHT_KeyCompare,
- JimObjectHTKeyValDestructor,
- JimCommandsHT_ValDestructor
- };
- Jim_Obj *Jim_MakeGlobalNamespaceName(Jim_Interp *interp, Jim_Obj *nameObjPtr)
- {
- #ifdef jim_ext_namespace
- Jim_Obj *resultObj;
- const char *name = Jim_String(nameObjPtr);
- if (name[0] == ':' && name[1] == ':') {
- return nameObjPtr;
- }
- Jim_IncrRefCount(nameObjPtr);
- resultObj = Jim_NewStringObj(interp, "::", -1);
- Jim_AppendObj(interp, resultObj, nameObjPtr);
- Jim_DecrRefCount(interp, nameObjPtr);
- return resultObj;
- #else
- return nameObjPtr;
- #endif
- }
- static Jim_Obj *JimQualifyName(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- #ifdef jim_ext_namespace
- if (Jim_Length(interp->framePtr->nsObj)) {
- int len;
- const char *name = Jim_GetString(objPtr, &len);
- if (len < 2 || name[0] != ':' || name[1] != ':') {
- objPtr = Jim_DuplicateObj(interp, interp->framePtr->nsObj);
- Jim_AppendStrings(interp, objPtr, "::", name, NULL);
- }
- }
- #endif
- Jim_IncrRefCount(objPtr);
- return objPtr;
- }
- static void JimCreateCommand(Jim_Interp *interp, Jim_Obj *nameObjPtr, Jim_Cmd *cmd)
- {
- JimPanic((nameObjPtr->refCount == 0, "JimCreateCommand called with zero ref count name"));
- if (interp->local) {
- Jim_HashEntry *he = Jim_FindHashEntry(&interp->commands, nameObjPtr);
- if (he) {
- cmd->prevCmd = Jim_GetHashEntryVal(he);
- Jim_SetHashVal(&interp->commands, he, cmd);
- Jim_InterpIncrProcEpoch(interp);
- return;
- }
- }
- Jim_ReplaceHashEntry(&interp->commands, nameObjPtr, cmd);
- }
- int Jim_CreateCommandObj(Jim_Interp *interp, Jim_Obj *cmdNameObj,
- Jim_CmdProc *cmdProc, void *privData, Jim_DelCmdProc *delProc)
- {
- Jim_Cmd *cmdPtr = Jim_Alloc(sizeof(*cmdPtr));
- memset(cmdPtr, 0, sizeof(*cmdPtr));
- cmdPtr->inUse = 1;
- cmdPtr->u.native.delProc = delProc;
- cmdPtr->u.native.cmdProc = cmdProc;
- cmdPtr->u.native.privData = privData;
- Jim_IncrRefCount(cmdNameObj);
- JimCreateCommand(interp, cmdNameObj, cmdPtr);
- Jim_DecrRefCount(interp, cmdNameObj);
- return JIM_OK;
- }
- int Jim_CreateCommand(Jim_Interp *interp, const char *cmdNameStr,
- Jim_CmdProc *cmdProc, void *privData, Jim_DelCmdProc *delProc)
- {
- return Jim_CreateCommandObj(interp, Jim_NewStringObj(interp, cmdNameStr, -1), cmdProc, privData, delProc);
- }
- static int JimCreateProcedureStatics(Jim_Interp *interp, Jim_Cmd *cmdPtr, Jim_Obj *staticsListObjPtr)
- {
- int len, i;
- len = Jim_ListLength(interp, staticsListObjPtr);
- if (len == 0) {
- return JIM_OK;
- }
- cmdPtr->u.proc.staticVars = Jim_Alloc(sizeof(Jim_HashTable));
- Jim_InitHashTable(cmdPtr->u.proc.staticVars, &JimVariablesHashTableType, interp);
- for (i = 0; i < len; i++) {
- Jim_Obj *initObjPtr = NULL;
- Jim_Obj *nameObjPtr;
- Jim_VarVal *vv = NULL;
- Jim_Obj *objPtr = Jim_ListGetIndex(interp, staticsListObjPtr, i);
- int subLen = Jim_ListLength(interp, objPtr);
- int byref = 0;
- if (subLen != 1 && subLen != 2) {
- Jim_SetResultFormatted(interp, "too many fields in static specifier \"%#s\"",
- objPtr);
- return JIM_ERR;
- }
- nameObjPtr = Jim_ListGetIndex(interp, objPtr, 0);
- if (subLen == 1) {
- int len;
- const char *pt = Jim_GetString(nameObjPtr, &len);
- if (*pt == '&') {
- nameObjPtr = Jim_NewStringObj(interp, pt + 1, len - 1);
- byref = 1;
- }
- }
- Jim_IncrRefCount(nameObjPtr);
- if (subLen == 1) {
- switch (SetVariableFromAny(interp, nameObjPtr)) {
- case JIM_DICT_SUGAR:
- if (byref) {
- Jim_SetResultFormatted(interp, "Can't link to array element \"%#s\"", nameObjPtr);
- }
- else {
- Jim_SetResultFormatted(interp, "Can't initialise array element \"%#s\"", nameObjPtr);
- }
- Jim_DecrRefCount(interp, nameObjPtr);
- return JIM_ERR;
- case JIM_OK:
- if (byref) {
- vv = nameObjPtr->internalRep.varValue.vv;
- }
- else {
- initObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_NONE);
- }
- break;
- case JIM_ERR:
- Jim_SetResultFormatted(interp,
- "variable for initialization of static \"%#s\" not found in the local context",
- nameObjPtr);
- Jim_DecrRefCount(interp, nameObjPtr);
- return JIM_ERR;
- }
- }
- else {
- initObjPtr = Jim_ListGetIndex(interp, objPtr, 1);
- }
- if (vv == NULL) {
- vv = Jim_Alloc(sizeof(*vv));
- vv->objPtr = initObjPtr;
- Jim_IncrRefCount(vv->objPtr);
- vv->linkFramePtr = NULL;
- vv->refCount = 0;
- }
- if (JimSetNewVariable(cmdPtr->u.proc.staticVars, nameObjPtr, vv) != JIM_OK) {
- Jim_SetResultFormatted(interp,
- "static variable name \"%#s\" duplicated in statics list", nameObjPtr);
- JimIncrVarRef(vv);
- JimDecrVarRef(interp, vv);
- Jim_DecrRefCount(interp, nameObjPtr);
- return JIM_ERR;
- }
- Jim_DecrRefCount(interp, nameObjPtr);
- }
- return JIM_OK;
- }
- #ifdef jim_ext_namespace
- static const char *Jim_memrchr(const char *p, int c, int len)
- {
- int i;
- for (i = len; i > 0; i--) {
- if (p[i] == c) {
- return p + i;
- }
- }
- return NULL;
- }
- #endif
- static void JimUpdateProcNamespace(Jim_Interp *interp, Jim_Cmd *cmdPtr, Jim_Obj *nameObjPtr)
- {
- #ifdef jim_ext_namespace
- if (cmdPtr->isproc) {
- int len;
- const char *cmdname = Jim_GetStringNoQualifier(nameObjPtr, &len);
- const char *pt = Jim_memrchr(cmdname, ':', len);
- if (pt && pt != cmdname && pt[-1] == ':') {
- pt++;
- Jim_DecrRefCount(interp, cmdPtr->u.proc.nsObj);
- cmdPtr->u.proc.nsObj = Jim_NewStringObj(interp, cmdname, pt - cmdname - 2);
- Jim_IncrRefCount(cmdPtr->u.proc.nsObj);
- Jim_Obj *tempObj = Jim_NewStringObj(interp, pt, len - (pt - cmdname));
- if (Jim_FindHashEntry(&interp->commands, tempObj)) {
- Jim_InterpIncrProcEpoch(interp);
- }
- Jim_FreeNewObj(interp, tempObj);
- }
- }
- #endif
- }
- static Jim_Cmd *JimCreateProcedureCmd(Jim_Interp *interp, Jim_Obj *argListObjPtr,
- Jim_Obj *staticsListObjPtr, Jim_Obj *bodyObjPtr, Jim_Obj *nsObj)
- {
- Jim_Cmd *cmdPtr;
- int argListLen;
- int i;
- argListLen = Jim_ListLength(interp, argListObjPtr);
- cmdPtr = Jim_Alloc(sizeof(*cmdPtr) + sizeof(struct Jim_ProcArg) * argListLen);
- assert(cmdPtr);
- memset(cmdPtr, 0, sizeof(*cmdPtr));
- cmdPtr->inUse = 1;
- cmdPtr->isproc = 1;
- cmdPtr->u.proc.argListObjPtr = argListObjPtr;
- cmdPtr->u.proc.argListLen = argListLen;
- cmdPtr->u.proc.bodyObjPtr = bodyObjPtr;
- cmdPtr->u.proc.argsPos = -1;
- cmdPtr->u.proc.arglist = (struct Jim_ProcArg *)(cmdPtr + 1);
- cmdPtr->u.proc.nsObj = nsObj ? nsObj : interp->emptyObj;
- Jim_IncrRefCount(argListObjPtr);
- Jim_IncrRefCount(bodyObjPtr);
- Jim_IncrRefCount(cmdPtr->u.proc.nsObj);
- if (staticsListObjPtr && JimCreateProcedureStatics(interp, cmdPtr, staticsListObjPtr) != JIM_OK) {
- goto err;
- }
- for (i = 0; i < argListLen; i++) {
- Jim_Obj *argPtr;
- Jim_Obj *nameObjPtr;
- Jim_Obj *defaultObjPtr;
- int len;
- argPtr = Jim_ListGetIndex(interp, argListObjPtr, i);
- len = Jim_ListLength(interp, argPtr);
- if (len == 0) {
- Jim_SetResultString(interp, "argument with no name", -1);
- err:
- JimDecrCmdRefCount(interp, cmdPtr);
- return NULL;
- }
- if (len > 2) {
- Jim_SetResultFormatted(interp, "too many fields in argument specifier \"%#s\"", argPtr);
- goto err;
- }
- if (len == 2) {
- nameObjPtr = Jim_ListGetIndex(interp, argPtr, 0);
- defaultObjPtr = Jim_ListGetIndex(interp, argPtr, 1);
- }
- else {
- nameObjPtr = argPtr;
- defaultObjPtr = NULL;
- }
- if (Jim_CompareStringImmediate(interp, nameObjPtr, "args")) {
- if (cmdPtr->u.proc.argsPos >= 0) {
- Jim_SetResultString(interp, "'args' specified more than once", -1);
- goto err;
- }
- cmdPtr->u.proc.argsPos = i;
- }
- else {
- if (len == 2) {
- cmdPtr->u.proc.optArity++;
- }
- else {
- cmdPtr->u.proc.reqArity++;
- }
- }
- cmdPtr->u.proc.arglist[i].nameObjPtr = nameObjPtr;
- cmdPtr->u.proc.arglist[i].defaultObjPtr = defaultObjPtr;
- }
- return cmdPtr;
- }
- int Jim_DeleteCommand(Jim_Interp *interp, Jim_Obj *nameObj)
- {
- int ret = JIM_OK;
- nameObj = JimQualifyName(interp, nameObj);
- if (Jim_DeleteHashEntry(&interp->commands, nameObj) == JIM_ERR) {
- Jim_SetResultFormatted(interp, "can't delete \"%#s\": command doesn't exist", nameObj);
- ret = JIM_ERR;
- }
- Jim_DecrRefCount(interp, nameObj);
- return ret;
- }
- int Jim_RenameCommand(Jim_Interp *interp, Jim_Obj *oldNameObj, Jim_Obj *newNameObj)
- {
- int ret = JIM_ERR;
- Jim_HashEntry *he;
- Jim_Cmd *cmdPtr;
- if (Jim_Length(newNameObj) == 0) {
- return Jim_DeleteCommand(interp, oldNameObj);
- }
- oldNameObj = JimQualifyName(interp, oldNameObj);
- newNameObj = JimQualifyName(interp, newNameObj);
- he = Jim_FindHashEntry(&interp->commands, oldNameObj);
- if (he == NULL) {
- Jim_SetResultFormatted(interp, "can't rename \"%#s\": command doesn't exist", oldNameObj);
- }
- else if (Jim_FindHashEntry(&interp->commands, newNameObj)) {
- Jim_SetResultFormatted(interp, "can't rename to \"%#s\": command already exists", newNameObj);
- }
- else {
- cmdPtr = Jim_GetHashEntryVal(he);
- if (cmdPtr->prevCmd) {
- Jim_SetResultFormatted(interp, "can't rename local command \"%#s\"", oldNameObj);
- }
- else {
- JimIncrCmdRefCount(cmdPtr);
- JimUpdateProcNamespace(interp, cmdPtr, newNameObj);
- Jim_AddHashEntry(&interp->commands, newNameObj, cmdPtr);
- Jim_DeleteHashEntry(&interp->commands, oldNameObj);
- Jim_InterpIncrProcEpoch(interp);
- ret = JIM_OK;
- }
- }
- Jim_DecrRefCount(interp, oldNameObj);
- Jim_DecrRefCount(interp, newNameObj);
- return ret;
- }
- static void FreeCommandInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- Jim_DecrRefCount(interp, objPtr->internalRep.cmdValue.nsObj);
- }
- static void DupCommandInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
- {
- dupPtr->internalRep.cmdValue = srcPtr->internalRep.cmdValue;
- dupPtr->typePtr = srcPtr->typePtr;
- Jim_IncrRefCount(dupPtr->internalRep.cmdValue.nsObj);
- }
- static const Jim_ObjType commandObjType = {
- "command",
- FreeCommandInternalRep,
- DupCommandInternalRep,
- NULL,
- JIM_TYPE_REFERENCES,
- };
- Jim_Cmd *Jim_GetCommand(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
- {
- Jim_Cmd *cmd;
- if (objPtr->typePtr == &commandObjType
- && objPtr->internalRep.cmdValue.procEpoch == interp->procEpoch
- #ifdef jim_ext_namespace
- && Jim_StringEqObj(objPtr->internalRep.cmdValue.nsObj, interp->framePtr->nsObj)
- #endif
- && objPtr->internalRep.cmdValue.cmdPtr->inUse) {
- cmd = objPtr->internalRep.cmdValue.cmdPtr;
- }
- else {
- Jim_Obj *qualifiedNameObj = JimQualifyName(interp, objPtr);
- Jim_HashEntry *he = Jim_FindHashEntry(&interp->commands, qualifiedNameObj);
- #ifdef jim_ext_namespace
- if (he == NULL && Jim_Length(interp->framePtr->nsObj)) {
- he = Jim_FindHashEntry(&interp->commands, objPtr);
- }
- #endif
- if (he == NULL) {
- if (flags & JIM_ERRMSG) {
- Jim_SetResultFormatted(interp, "invalid command name \"%#s\"", objPtr);
- }
- Jim_DecrRefCount(interp, qualifiedNameObj);
- return NULL;
- }
- cmd = Jim_GetHashEntryVal(he);
- cmd->cmdNameObj = Jim_GetHashEntryKey(he);
- Jim_FreeIntRep(interp, objPtr);
- objPtr->typePtr = &commandObjType;
- objPtr->internalRep.cmdValue.procEpoch = interp->procEpoch;
- objPtr->internalRep.cmdValue.cmdPtr = cmd;
- objPtr->internalRep.cmdValue.nsObj = interp->framePtr->nsObj;
- Jim_IncrRefCount(interp->framePtr->nsObj);
- Jim_DecrRefCount(interp, qualifiedNameObj);
- }
- while (cmd->u.proc.upcall) {
- cmd = cmd->prevCmd;
- }
- return cmd;
- }
- static const Jim_ObjType variableObjType = {
- "variable",
- NULL,
- NULL,
- NULL,
- JIM_TYPE_REFERENCES,
- };
- static int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
- {
- const char *varName;
- Jim_CallFrame *framePtr;
- int global;
- int len;
- Jim_VarVal *vv;
- if (objPtr->typePtr == &variableObjType) {
- framePtr = objPtr->internalRep.varValue.global ? interp->topFramePtr : interp->framePtr;
- if (objPtr->internalRep.varValue.callFrameId == framePtr->id) {
- return JIM_OK;
- }
- }
- else if (objPtr->typePtr == &dictSubstObjType) {
- return JIM_DICT_SUGAR;
- }
- varName = Jim_GetString(objPtr, &len);
- if (len && varName[len - 1] == ')' && strchr(varName, '(') != NULL) {
- return JIM_DICT_SUGAR;
- }
- if (varName[0] == ':' && varName[1] == ':') {
- while (*varName == ':') {
- varName++;
- len--;
- }
- global = 1;
- framePtr = interp->topFramePtr;
- Jim_Obj *tempObj = Jim_NewStringObj(interp, varName, len);
- vv = JimFindVariable(&framePtr->vars, tempObj);
- Jim_FreeNewObj(interp, tempObj);
- }
- else {
- global = 0;
- framePtr = interp->framePtr;
- vv = JimFindVariable(&framePtr->vars, objPtr);
- if (vv == NULL && framePtr->staticVars) {
- vv = JimFindVariable(framePtr->staticVars, objPtr);
- }
- }
- if (vv == NULL) {
- return JIM_ERR;
- }
- Jim_FreeIntRep(interp, objPtr);
- objPtr->typePtr = &variableObjType;
- objPtr->internalRep.varValue.callFrameId = framePtr->id;
- objPtr->internalRep.varValue.vv = vv;
- objPtr->internalRep.varValue.global = global;
- return JIM_OK;
- }
- static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *ObjPtr, Jim_Obj *valObjPtr);
- static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *ObjPtr, int flags);
- static int JimSetNewVariable(Jim_HashTable *ht, Jim_Obj *nameObjPtr, Jim_VarVal *vv)
- {
- return Jim_AddHashEntry(ht, nameObjPtr, vv);
- }
- static Jim_VarVal *JimFindVariable(Jim_HashTable *ht, Jim_Obj *nameObjPtr)
- {
- Jim_HashEntry *he = Jim_FindHashEntry(ht, nameObjPtr);
- if (he) {
- return (Jim_VarVal *)Jim_GetHashEntryVal(he);
- }
- return NULL;
- }
- static int JimUnsetVariable(Jim_HashTable *ht, Jim_Obj *nameObjPtr)
- {
- return Jim_DeleteHashEntry(ht, nameObjPtr);
- }
- static Jim_VarVal *JimCreateVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr)
- {
- const char *name;
- Jim_CallFrame *framePtr;
- int global;
- int len;
- Jim_VarVal *vv = Jim_Alloc(sizeof(*vv));
- vv->objPtr = valObjPtr;
- Jim_IncrRefCount(valObjPtr);
- vv->linkFramePtr = NULL;
- vv->refCount = 0;
- name = Jim_GetString(nameObjPtr, &len);
- if (name[0] == ':' && name[1] == ':') {
- while (*name == ':') {
- name++;
- len--;
- }
- framePtr = interp->topFramePtr;
- global = 1;
- JimSetNewVariable(&framePtr->vars, Jim_NewStringObj(interp, name, len), vv);
- }
- else {
- framePtr = interp->framePtr;
- global = 0;
- JimSetNewVariable(&framePtr->vars, nameObjPtr, vv);
- }
- Jim_FreeIntRep(interp, nameObjPtr);
- nameObjPtr->typePtr = &variableObjType;
- nameObjPtr->internalRep.varValue.callFrameId = framePtr->id;
- nameObjPtr->internalRep.varValue.vv = vv;
- nameObjPtr->internalRep.varValue.global = global;
- return vv;
- }
- int Jim_SetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr)
- {
- int err;
- Jim_VarVal *vv;
- switch (SetVariableFromAny(interp, nameObjPtr)) {
- case JIM_DICT_SUGAR:
- return JimDictSugarSet(interp, nameObjPtr, valObjPtr);
- case JIM_ERR:
- JimCreateVariable(interp, nameObjPtr, valObjPtr);
- break;
- case JIM_OK:
- vv = nameObjPtr->internalRep.varValue.vv;
- if (vv->linkFramePtr == NULL) {
- Jim_IncrRefCount(valObjPtr);
- Jim_DecrRefCount(interp, vv->objPtr);
- vv->objPtr = valObjPtr;
- }
- else {
- Jim_CallFrame *savedCallFrame;
- savedCallFrame = interp->framePtr;
- interp->framePtr = vv->linkFramePtr;
- err = Jim_SetVariable(interp, vv->objPtr, valObjPtr);
- interp->framePtr = savedCallFrame;
- if (err != JIM_OK)
- return err;
- }
- }
- return JIM_OK;
- }
- int Jim_SetVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)
- {
- Jim_Obj *nameObjPtr;
- int result;
- nameObjPtr = Jim_NewStringObj(interp, name, -1);
- Jim_IncrRefCount(nameObjPtr);
- result = Jim_SetVariable(interp, nameObjPtr, objPtr);
- Jim_DecrRefCount(interp, nameObjPtr);
- return result;
- }
- int Jim_SetGlobalVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)
- {
- Jim_CallFrame *savedFramePtr;
- int result;
- savedFramePtr = interp->framePtr;
- interp->framePtr = interp->topFramePtr;
- result = Jim_SetVariableStr(interp, name, objPtr);
- interp->framePtr = savedFramePtr;
- return result;
- }
- int Jim_SetVariableStrWithStr(Jim_Interp *interp, const char *name, const char *val)
- {
- Jim_Obj *valObjPtr;
- int result;
- valObjPtr = Jim_NewStringObj(interp, val, -1);
- Jim_IncrRefCount(valObjPtr);
- result = Jim_SetVariableStr(interp, name, valObjPtr);
- Jim_DecrRefCount(interp, valObjPtr);
- return result;
- }
- int Jim_SetVariableLink(Jim_Interp *interp, Jim_Obj *nameObjPtr,
- Jim_Obj *targetNameObjPtr, Jim_CallFrame *targetCallFrame)
- {
- const char *varName;
- const char *targetName;
- Jim_CallFrame *framePtr;
- Jim_VarVal *vv;
- int len;
- int varnamelen;
- switch (SetVariableFromAny(interp, nameObjPtr)) {
- case JIM_DICT_SUGAR:
- Jim_SetResultFormatted(interp, "bad variable name \"%#s\": upvar won't create a scalar variable that looks like an array element", nameObjPtr);
- return JIM_ERR;
- case JIM_OK:
- vv = nameObjPtr->internalRep.varValue.vv;
- if (vv->linkFramePtr == NULL) {
- Jim_SetResultFormatted(interp, "variable \"%#s\" already exists", nameObjPtr);
- return JIM_ERR;
- }
- vv->linkFramePtr = NULL;
- break;
- }
- varName = Jim_GetString(nameObjPtr, &varnamelen);
- if (varName[0] == ':' && varName[1] == ':') {
- while (*varName == ':') {
- varName++;
- varnamelen--;
- }
- framePtr = interp->topFramePtr;
- }
- else {
- framePtr = interp->framePtr;
- }
- targetName = Jim_GetString(targetNameObjPtr, &len);
- if (targetName[0] == ':' && targetName[1] == ':') {
- while (*targetName == ':') {
- targetName++;
- len--;
- }
- targetNameObjPtr = Jim_NewStringObj(interp, targetName, len);
- targetCallFrame = interp->topFramePtr;
- }
- Jim_IncrRefCount(targetNameObjPtr);
- if (framePtr->level < targetCallFrame->level) {
- Jim_SetResultFormatted(interp,
- "bad variable name \"%#s\": upvar won't create namespace variable that refers to procedure variable",
- nameObjPtr);
- Jim_DecrRefCount(interp, targetNameObjPtr);
- return JIM_ERR;
- }
- if (framePtr == targetCallFrame) {
- Jim_Obj *objPtr = targetNameObjPtr;
- while (1) {
- if (Jim_Length(objPtr) == varnamelen && memcmp(Jim_String(objPtr), varName, varnamelen) == 0) {
- Jim_SetResultString(interp, "can't upvar from variable to itself", -1);
- Jim_DecrRefCount(interp, targetNameObjPtr);
- return JIM_ERR;
- }
- if (SetVariableFromAny(interp, objPtr) != JIM_OK)
- break;
- vv = objPtr->internalRep.varValue.vv;
- if (vv->linkFramePtr != targetCallFrame)
- break;
- objPtr = vv->objPtr;
- }
- }
- Jim_SetVariable(interp, nameObjPtr, targetNameObjPtr);
- nameObjPtr->internalRep.varValue.vv->linkFramePtr = targetCallFrame;
- Jim_DecrRefCount(interp, targetNameObjPtr);
- return JIM_OK;
- }
- Jim_Obj *Jim_GetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
- {
- if (interp->safeexpr) {
- return nameObjPtr;
- }
- switch (SetVariableFromAny(interp, nameObjPtr)) {
- case JIM_OK:{
- Jim_VarVal *vv = nameObjPtr->internalRep.varValue.vv;
- if (vv->linkFramePtr == NULL) {
- return vv->objPtr;
- }
- else {
- Jim_Obj *objPtr;
- Jim_CallFrame *savedCallFrame = interp->framePtr;
- interp->framePtr = vv->linkFramePtr;
- objPtr = Jim_GetVariable(interp, vv->objPtr, flags);
- interp->framePtr = savedCallFrame;
- if (objPtr) {
- return objPtr;
- }
- }
- }
- break;
- case JIM_DICT_SUGAR:
- return JimDictSugarGet(interp, nameObjPtr, flags);
- }
- if (flags & JIM_ERRMSG) {
- Jim_SetResultFormatted(interp, "can't read \"%#s\": no such variable", nameObjPtr);
- }
- return NULL;
- }
- Jim_Obj *Jim_GetGlobalVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
- {
- Jim_CallFrame *savedFramePtr;
- Jim_Obj *objPtr;
- savedFramePtr = interp->framePtr;
- interp->framePtr = interp->topFramePtr;
- objPtr = Jim_GetVariable(interp, nameObjPtr, flags);
- interp->framePtr = savedFramePtr;
- return objPtr;
- }
- Jim_Obj *Jim_GetVariableStr(Jim_Interp *interp, const char *name, int flags)
- {
- Jim_Obj *nameObjPtr, *varObjPtr;
- nameObjPtr = Jim_NewStringObj(interp, name, -1);
- Jim_IncrRefCount(nameObjPtr);
- varObjPtr = Jim_GetVariable(interp, nameObjPtr, flags);
- Jim_DecrRefCount(interp, nameObjPtr);
- return varObjPtr;
- }
- Jim_Obj *Jim_GetGlobalVariableStr(Jim_Interp *interp, const char *name, int flags)
- {
- Jim_CallFrame *savedFramePtr;
- Jim_Obj *objPtr;
- savedFramePtr = interp->framePtr;
- interp->framePtr = interp->topFramePtr;
- objPtr = Jim_GetVariableStr(interp, name, flags);
- interp->framePtr = savedFramePtr;
- return objPtr;
- }
- int Jim_UnsetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
- {
- Jim_VarVal *vv;
- int retval;
- Jim_CallFrame *framePtr;
- retval = SetVariableFromAny(interp, nameObjPtr);
- if (retval == JIM_DICT_SUGAR) {
- return JimDictSugarSet(interp, nameObjPtr, NULL);
- }
- else if (retval == JIM_OK) {
- vv = nameObjPtr->internalRep.varValue.vv;
- if (vv->linkFramePtr) {
- framePtr = interp->framePtr;
- interp->framePtr = vv->linkFramePtr;
- retval = Jim_UnsetVariable(interp, vv->objPtr, JIM_NONE);
- interp->framePtr = framePtr;
- }
- else {
- if (nameObjPtr->internalRep.varValue.global) {
- int len;
- const char *name = Jim_GetString(nameObjPtr, &len);
- while (*name == ':') {
- name++;
- len--;
- }
- framePtr = interp->topFramePtr;
- Jim_Obj *tempObj = Jim_NewStringObj(interp, name, len);
- retval = JimUnsetVariable(&framePtr->vars, tempObj);
- Jim_FreeNewObj(interp, tempObj);
- }
- else {
- framePtr = interp->framePtr;
- retval = JimUnsetVariable(&framePtr->vars, nameObjPtr);
- }
- if (retval == JIM_OK) {
- framePtr->id = interp->callFrameEpoch++;
- }
- }
- }
- if (retval != JIM_OK && (flags & JIM_ERRMSG)) {
- Jim_SetResultFormatted(interp, "can't unset \"%#s\": no such variable", nameObjPtr);
- }
- return retval;
- }
- static void JimDictSugarParseVarKey(Jim_Interp *interp, Jim_Obj *objPtr,
- Jim_Obj **varPtrPtr, Jim_Obj **keyPtrPtr)
- {
- const char *str, *p;
- int len, keyLen;
- Jim_Obj *varObjPtr, *keyObjPtr;
- str = Jim_GetString(objPtr, &len);
- p = strchr(str, '(');
- JimPanic((p == NULL, "JimDictSugarParseVarKey() called for non-dict-sugar (%s)", str));
- varObjPtr = Jim_NewStringObj(interp, str, p - str);
- p++;
- keyLen = (str + len) - p;
- if (str[len - 1] == ')') {
- keyLen--;
- }
- keyObjPtr = Jim_NewStringObj(interp, p, keyLen);
- Jim_IncrRefCount(varObjPtr);
- Jim_IncrRefCount(keyObjPtr);
- *varPtrPtr = varObjPtr;
- *keyPtrPtr = keyObjPtr;
- }
- static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *valObjPtr)
- {
- int err;
- SetDictSubstFromAny(interp, objPtr);
- err = Jim_SetDictKeysVector(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr,
- &objPtr->internalRep.dictSubstValue.indexObjPtr, 1, valObjPtr, JIM_MUSTEXIST);
- if (err == JIM_OK) {
- Jim_SetEmptyResult(interp);
- }
- else {
- if (!valObjPtr) {
- if (Jim_GetVariable(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr, JIM_NONE)) {
- Jim_SetResultFormatted(interp, "can't unset \"%#s\": no such element in array",
- objPtr);
- return err;
- }
- }
- Jim_SetResultFormatted(interp, "can't %s \"%#s\": variable isn't array",
- (valObjPtr ? "set" : "unset"), objPtr);
- }
- return err;
- }
- static Jim_Obj *JimDictExpandArrayVariable(Jim_Interp *interp, Jim_Obj *varObjPtr,
- Jim_Obj *keyObjPtr, int flags)
- {
- Jim_Obj *dictObjPtr;
- Jim_Obj *resObjPtr = NULL;
- int ret;
- dictObjPtr = Jim_GetVariable(interp, varObjPtr, JIM_ERRMSG);
- if (!dictObjPtr) {
- return NULL;
- }
- ret = Jim_DictKey(interp, dictObjPtr, keyObjPtr, &resObjPtr, JIM_NONE);
- if (ret != JIM_OK) {
- Jim_SetResultFormatted(interp,
- "can't read \"%#s(%#s)\": %s array", varObjPtr, keyObjPtr,
- ret < 0 ? "variable isn't" : "no such element in");
- }
- else if ((flags & JIM_UNSHARED) && Jim_IsShared(dictObjPtr)) {
- Jim_SetVariable(interp, varObjPtr, Jim_DuplicateObj(interp, dictObjPtr));
- }
- return resObjPtr;
- }
- static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
- {
- SetDictSubstFromAny(interp, objPtr);
- return JimDictExpandArrayVariable(interp,
- objPtr->internalRep.dictSubstValue.varNameObjPtr,
- objPtr->internalRep.dictSubstValue.indexObjPtr, flags);
- }
- void FreeDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr);
- Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.indexObjPtr);
- }
- static void DupDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
- {
- dupPtr->internalRep = srcPtr->internalRep;
- Jim_IncrRefCount(dupPtr->internalRep.dictSubstValue.varNameObjPtr);
- Jim_IncrRefCount(dupPtr->internalRep.dictSubstValue.indexObjPtr);
- }
- static void SetDictSubstFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- if (objPtr->typePtr != &dictSubstObjType) {
- Jim_Obj *varObjPtr, *keyObjPtr;
- if (objPtr->typePtr == &interpolatedObjType) {
- varObjPtr = objPtr->internalRep.dictSubstValue.varNameObjPtr;
- keyObjPtr = objPtr->internalRep.dictSubstValue.indexObjPtr;
- Jim_IncrRefCount(varObjPtr);
- Jim_IncrRefCount(keyObjPtr);
- }
- else {
- JimDictSugarParseVarKey(interp, objPtr, &varObjPtr, &keyObjPtr);
- }
- Jim_FreeIntRep(interp, objPtr);
- objPtr->typePtr = &dictSubstObjType;
- objPtr->internalRep.dictSubstValue.varNameObjPtr = varObjPtr;
- objPtr->internalRep.dictSubstValue.indexObjPtr = keyObjPtr;
- }
- }
- static Jim_Obj *JimExpandDictSugar(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- Jim_Obj *resObjPtr = NULL;
- Jim_Obj *substKeyObjPtr = NULL;
- if (interp->safeexpr) {
- return objPtr;
- }
- SetDictSubstFromAny(interp, objPtr);
- if (Jim_SubstObj(interp, objPtr->internalRep.dictSubstValue.indexObjPtr,
- &substKeyObjPtr, JIM_NONE)
- != JIM_OK) {
- return NULL;
- }
- Jim_IncrRefCount(substKeyObjPtr);
- resObjPtr =
- JimDictExpandArrayVariable(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr,
- substKeyObjPtr, 0);
- Jim_DecrRefCount(interp, substKeyObjPtr);
- return resObjPtr;
- }
- static Jim_CallFrame *JimCreateCallFrame(Jim_Interp *interp, Jim_CallFrame *parent, Jim_Obj *nsObj)
- {
- Jim_CallFrame *cf;
- if (interp->freeFramesList) {
- cf = interp->freeFramesList;
- interp->freeFramesList = cf->next;
- cf->argv = NULL;
- cf->argc = 0;
- cf->procArgsObjPtr = NULL;
- cf->procBodyObjPtr = NULL;
- cf->next = NULL;
- cf->staticVars = NULL;
- cf->localCommands = NULL;
- cf->tailcallObj = NULL;
- cf->tailcallCmd = NULL;
- }
- else {
- cf = Jim_Alloc(sizeof(*cf));
- memset(cf, 0, sizeof(*cf));
- Jim_InitHashTable(&cf->vars, &JimVariablesHashTableType, interp);
- }
- cf->id = interp->callFrameEpoch++;
- cf->parent = parent;
- cf->level = parent ? parent->level + 1 : 0;
- cf->nsObj = nsObj;
- Jim_IncrRefCount(nsObj);
- return cf;
- }
- static int JimDeleteLocalProcs(Jim_Interp *interp, Jim_Stack *localCommands)
- {
- if (localCommands) {
- Jim_Obj *cmdNameObj;
- while ((cmdNameObj = Jim_StackPop(localCommands)) != NULL) {
- Jim_HashTable *ht = &interp->commands;
- Jim_HashEntry *he = Jim_FindHashEntry(ht, cmdNameObj);
- if (he) {
- Jim_Cmd *cmd = Jim_GetHashEntryVal(he);
- if (cmd->prevCmd) {
- Jim_Cmd *prevCmd = cmd->prevCmd;
- cmd->prevCmd = NULL;
- JimDecrCmdRefCount(interp, cmd);
- Jim_SetHashVal(ht, he, prevCmd);
- }
- else {
- Jim_DeleteHashEntry(ht, cmdNameObj);
- }
- }
- Jim_DecrRefCount(interp, cmdNameObj);
- }
- Jim_FreeStack(localCommands);
- Jim_Free(localCommands);
- }
- return JIM_OK;
- }
- static int JimInvokeDefer(Jim_Interp *interp, int retcode)
- {
- Jim_Obj *objPtr;
- if (JimFindVariable(&interp->framePtr->vars, interp->defer) == NULL) {
- return retcode;
- }
- objPtr = Jim_GetVariable(interp, interp->defer, JIM_NONE);
- if (objPtr) {
- int ret = JIM_OK;
- int i;
- int listLen = Jim_ListLength(interp, objPtr);
- Jim_Obj *resultObjPtr;
- Jim_IncrRefCount(objPtr);
- resultObjPtr = Jim_GetResult(interp);
- Jim_IncrRefCount(resultObjPtr);
- Jim_SetEmptyResult(interp);
- for (i = listLen; i > 0; i--) {
- Jim_Obj *scriptObjPtr = Jim_ListGetIndex(interp, objPtr, i - 1);
- ret = Jim_EvalObj(interp, scriptObjPtr);
- if (ret != JIM_OK) {
- break;
- }
- }
- if (ret == JIM_OK || retcode == JIM_ERR) {
- Jim_SetResult(interp, resultObjPtr);
- }
- else {
- retcode = ret;
- }
- Jim_DecrRefCount(interp, resultObjPtr);
- Jim_DecrRefCount(interp, objPtr);
- }
- return retcode;
- }
- #define JIM_FCF_FULL 0
- #define JIM_FCF_REUSE 1
- static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf, int action)
- {
- JimDeleteLocalProcs(interp, cf->localCommands);
- if (cf->procArgsObjPtr)
- Jim_DecrRefCount(interp, cf->procArgsObjPtr);
- if (cf->procBodyObjPtr)
- Jim_DecrRefCount(interp, cf->procBodyObjPtr);
- Jim_DecrRefCount(interp, cf->nsObj);
- if (action == JIM_FCF_FULL || cf->vars.size != JIM_HT_INITIAL_SIZE)
- Jim_FreeHashTable(&cf->vars);
- else {
- Jim_ClearHashTable(&cf->vars);
- }
- cf->next = interp->freeFramesList;
- interp->freeFramesList = cf;
- }
- int Jim_IsBigEndian(void)
- {
- union {
- unsigned short s;
- unsigned char c[2];
- } uval = {0x0102};
- return uval.c[0] == 1;
- }
- Jim_Interp *Jim_CreateInterp(void)
- {
- Jim_Interp *i = Jim_Alloc(sizeof(*i));
- memset(i, 0, sizeof(*i));
- i->maxCallFrameDepth = JIM_MAX_CALLFRAME_DEPTH;
- i->maxEvalDepth = JIM_MAX_EVAL_DEPTH;
- i->lastCollectTime = Jim_GetTimeUsec(CLOCK_MONOTONIC_RAW);
- Jim_InitHashTable(&i->commands, &JimCommandsHashTableType, i);
- #ifdef JIM_REFERENCES
- Jim_InitHashTable(&i->references, &JimReferencesHashTableType, i);
- #endif
- Jim_InitHashTable(&i->assocData, &JimAssocDataHashTableType, i);
- Jim_InitHashTable(&i->packages, &JimPackageHashTableType, NULL);
- i->emptyObj = Jim_NewEmptyStringObj(i);
- i->trueObj = Jim_NewIntObj(i, 1);
- i->falseObj = Jim_NewIntObj(i, 0);
- i->framePtr = i->topFramePtr = JimCreateCallFrame(i, NULL, i->emptyObj);
- i->result = i->emptyObj;
- i->stackTrace = Jim_NewListObj(i, NULL, 0);
- i->unknown = Jim_NewStringObj(i, "unknown", -1);
- i->defer = Jim_NewStringObj(i, "jim::defer", -1);
- i->errorProc = i->emptyObj;
- i->nullScriptObj = Jim_NewEmptyStringObj(i);
- i->evalFrame = &i->topEvalFrame;
- i->currentFilenameObj = Jim_NewEmptyStringObj(i);
- Jim_IncrRefCount(i->emptyObj);
- Jim_IncrRefCount(i->result);
- Jim_IncrRefCount(i->stackTrace);
- Jim_IncrRefCount(i->unknown);
- Jim_IncrRefCount(i->defer);
- Jim_IncrRefCount(i->nullScriptObj);
- Jim_IncrRefCount(i->errorProc);
- Jim_IncrRefCount(i->trueObj);
- Jim_IncrRefCount(i->falseObj);
- Jim_IncrRefCount(i->currentFilenameObj);
- Jim_SetVariableStrWithStr(i, JIM_LIBPATH, TCL_LIBRARY);
- Jim_SetVariableStrWithStr(i, JIM_INTERACTIVE, "0");
- Jim_SetVariableStrWithStr(i, "tcl_platform(engine)", "Jim");
- Jim_SetVariableStrWithStr(i, "tcl_platform(os)", TCL_PLATFORM_OS);
- Jim_SetVariableStrWithStr(i, "tcl_platform(platform)", TCL_PLATFORM_PLATFORM);
- Jim_SetVariableStrWithStr(i, "tcl_platform(pathSeparator)", TCL_PLATFORM_PATH_SEPARATOR);
- Jim_SetVariableStrWithStr(i, "tcl_platform(byteOrder)", Jim_IsBigEndian() ? "bigEndian" : "littleEndian");
- Jim_SetVariableStrWithStr(i, "tcl_platform(threaded)", "0");
- Jim_SetVariableStrWithStr(i, "tcl_platform(bootstrap)", "0");
- Jim_SetVariableStr(i, "tcl_platform(pointerSize)", Jim_NewIntObj(i, sizeof(void *)));
- Jim_SetVariableStr(i, "tcl_platform(wordSize)", Jim_NewIntObj(i, sizeof(jim_wide)));
- Jim_SetVariableStr(i, "tcl_platform(stackFormat)", Jim_NewIntObj(i, 4));
- return i;
- }
- void Jim_FreeInterp(Jim_Interp *i)
- {
- Jim_CallFrame *cf, *cfx;
- Jim_Obj *objPtr, *nextObjPtr;
- i->quitting = 1;
- for (cf = i->framePtr; cf; cf = cfx) {
- JimInvokeDefer(i, JIM_OK);
- cfx = cf->parent;
- JimFreeCallFrame(i, cf, JIM_FCF_FULL);
- }
- Jim_FreeHashTable(&i->commands);
- Jim_DecrRefCount(i, i->emptyObj);
- Jim_DecrRefCount(i, i->trueObj);
- Jim_DecrRefCount(i, i->falseObj);
- Jim_DecrRefCount(i, i->result);
- Jim_DecrRefCount(i, i->stackTrace);
- Jim_DecrRefCount(i, i->errorProc);
- Jim_DecrRefCount(i, i->unknown);
- Jim_DecrRefCount(i, i->defer);
- Jim_DecrRefCount(i, i->nullScriptObj);
- Jim_DecrRefCount(i, i->currentFilenameObj);
- Jim_InterpIncrProcEpoch(i);
- #ifdef JIM_REFERENCES
- Jim_FreeHashTable(&i->references);
- #endif
- Jim_FreeHashTable(&i->packages);
- Jim_Free(i->prngState);
- Jim_FreeHashTable(&i->assocData);
- if (i->traceCmdObj) {
- Jim_DecrRefCount(i, i->traceCmdObj);
- }
- #ifdef JIM_MAINTAINER
- if (i->liveList != NULL) {
- objPtr = i->liveList;
- printf("\n-------------------------------------\n");
- printf("Objects still in the free list:\n");
- while (objPtr) {
- const char *type = objPtr->typePtr ? objPtr->typePtr->name : "string";
- Jim_String(objPtr);
- if (objPtr->bytes && strlen(objPtr->bytes) > 20) {
- printf("%p (%d) %-10s: '%.20s...'\n",
- (void *)objPtr, objPtr->refCount, type, objPtr->bytes);
- }
- else {
- printf("%p (%d) %-10s: '%s'\n",
- (void *)objPtr, objPtr->refCount, type, objPtr->bytes ? objPtr->bytes : "(null)");
- }
- if (objPtr->typePtr == &sourceObjType) {
- printf("FILE %s LINE %d\n",
- Jim_String(objPtr->internalRep.sourceValue.fileNameObj),
- objPtr->internalRep.sourceValue.lineNumber);
- }
- objPtr = objPtr->nextObjPtr;
- }
- printf("-------------------------------------\n\n");
- JimPanic((1, "Live list non empty freeing the interpreter! Leak?"));
- }
- #endif
- objPtr = i->freeList;
- while (objPtr) {
- nextObjPtr = objPtr->nextObjPtr;
- Jim_Free(objPtr);
- objPtr = nextObjPtr;
- }
- for (cf = i->freeFramesList; cf; cf = cfx) {
- cfx = cf->next;
- if (cf->vars.table)
- Jim_FreeHashTable(&cf->vars);
- Jim_Free(cf);
- }
- Jim_Free(i);
- }
- Jim_CallFrame *Jim_GetCallFrameByLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr)
- {
- long level;
- const char *str;
- Jim_CallFrame *framePtr;
- if (levelObjPtr) {
- str = Jim_String(levelObjPtr);
- if (str[0] == '#') {
- char *endptr;
- level = jim_strtol(str + 1, &endptr);
- if (str[1] == '\0' || endptr[0] != '\0') {
- level = -1;
- }
- }
- else {
- if (Jim_GetLong(interp, levelObjPtr, &level) != JIM_OK || level < 0) {
- level = -1;
- }
- else {
- level = interp->framePtr->level - level;
- }
- }
- }
- else {
- str = "1";
- level = interp->framePtr->level - 1;
- }
- if (level == 0) {
- return interp->topFramePtr;
- }
- if (level > 0) {
- for (framePtr = interp->framePtr; framePtr; framePtr = framePtr->parent) {
- if (framePtr->level == level) {
- return framePtr;
- }
- }
- }
- Jim_SetResultFormatted(interp, "bad level \"%s\"", str);
- return NULL;
- }
- static Jim_CallFrame *JimGetCallFrameByInteger(Jim_Interp *interp, long level)
- {
- Jim_CallFrame *framePtr;
- if (level == 0) {
- return interp->framePtr;
- }
- if (level < 0) {
- level = interp->framePtr->level + level;
- }
- if (level > 0) {
- for (framePtr = interp->framePtr; framePtr; framePtr = framePtr->parent) {
- if (framePtr->level == level) {
- return framePtr;
- }
- }
- }
- return NULL;
- }
- static Jim_EvalFrame *JimGetEvalFrameByProcLevel(Jim_Interp *interp, int proclevel)
- {
- Jim_EvalFrame *evalFrame;
- if (proclevel == 0) {
- return interp->evalFrame;
- }
- if (proclevel < 0) {
- proclevel = interp->procLevel + proclevel;
- }
- if (proclevel >= 0) {
- for (evalFrame = interp->evalFrame; evalFrame; evalFrame = evalFrame->parent) {
- if (evalFrame->procLevel == proclevel) {
- return evalFrame;
- }
- }
- }
- return NULL;
- }
- static Jim_Obj *JimProcForEvalFrame(Jim_Interp *interp, Jim_EvalFrame *frame)
- {
- if (frame == interp->evalFrame || (frame->cmd && frame->cmd->cmdNameObj)) {
- Jim_EvalFrame *e;
- for (e = frame->parent; e; e = e->parent) {
- if (e->cmd && e->cmd->isproc && e->cmd->cmdNameObj) {
- break;
- }
- }
- if (e && e->cmd && e->cmd->cmdNameObj) {
- return e->cmd->cmdNameObj;
- }
- }
- return NULL;
- }
- static void JimAddStackFrame(Jim_Interp *interp, Jim_EvalFrame *frame, Jim_Obj *listObj)
- {
- Jim_Obj *procNameObj = JimProcForEvalFrame(interp, frame);
- Jim_Obj *fileNameObj = interp->emptyObj;
- int linenr = 1;
- if (frame->scriptObj) {
- ScriptObj *script = JimGetScript(interp, frame->scriptObj);
- fileNameObj = script->fileNameObj;
- linenr = script->linenr;
- }
- Jim_ListAppendElement(interp, listObj, procNameObj ? procNameObj : interp->emptyObj);
- Jim_ListAppendElement(interp, listObj, fileNameObj);
- Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, linenr));
- Jim_ListAppendElement(interp, listObj, Jim_NewListObj(interp, frame->argv, frame->argc));
- }
- static void JimSetStackTrace(Jim_Interp *interp, Jim_Obj *stackTraceObj)
- {
- Jim_IncrRefCount(stackTraceObj);
- Jim_DecrRefCount(interp, interp->stackTrace);
- interp->stackTrace = stackTraceObj;
- interp->errorFlag = 1;
- }
- static void JimSetErrorStack(Jim_Interp *interp, ScriptObj *script)
- {
- if (!interp->errorFlag) {
- int i;
- Jim_Obj *stackTrace = Jim_NewListObj(interp, NULL, 0);
- if (interp->procLevel == 0 && script) {
- Jim_ListAppendElement(interp, stackTrace, interp->emptyObj);
- Jim_ListAppendElement(interp, stackTrace, script->fileNameObj);
- Jim_ListAppendElement(interp, stackTrace, Jim_NewIntObj(interp, script->linenr));
- Jim_ListAppendElement(interp, stackTrace, interp->emptyObj);
- }
- else {
- for (i = 0; i <= interp->procLevel; i++) {
- Jim_EvalFrame *frame = JimGetEvalFrameByProcLevel(interp, -i);
- if (frame) {
- JimAddStackFrame(interp, frame, stackTrace);
- }
- }
- }
- JimSetStackTrace(interp, stackTrace);
- }
- }
- int Jim_SetAssocData(Jim_Interp *interp, const char *key, Jim_InterpDeleteProc * delProc,
- void *data)
- {
- AssocDataValue *assocEntryPtr = (AssocDataValue *) Jim_Alloc(sizeof(AssocDataValue));
- assocEntryPtr->delProc = delProc;
- assocEntryPtr->data = data;
- return Jim_AddHashEntry(&interp->assocData, key, assocEntryPtr);
- }
- void *Jim_GetAssocData(Jim_Interp *interp, const char *key)
- {
- Jim_HashEntry *entryPtr = Jim_FindHashEntry(&interp->assocData, key);
- if (entryPtr != NULL) {
- AssocDataValue *assocEntryPtr = Jim_GetHashEntryVal(entryPtr);
- return assocEntryPtr->data;
- }
- return NULL;
- }
- int Jim_DeleteAssocData(Jim_Interp *interp, const char *key)
- {
- return Jim_DeleteHashEntry(&interp->assocData, key);
- }
- int Jim_GetExitCode(Jim_Interp *interp)
- {
- return interp->exitCode;
- }
- static void UpdateStringOfInt(struct Jim_Obj *objPtr);
- static int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags);
- static const Jim_ObjType intObjType = {
- "int",
- NULL,
- NULL,
- UpdateStringOfInt,
- JIM_TYPE_NONE,
- };
- static const Jim_ObjType coercedDoubleObjType = {
- "coerced-double",
- NULL,
- NULL,
- UpdateStringOfInt,
- JIM_TYPE_NONE,
- };
- static void UpdateStringOfInt(struct Jim_Obj *objPtr)
- {
- char buf[JIM_INTEGER_SPACE + 1];
- jim_wide wideValue = JimWideValue(objPtr);
- int pos = 0;
- if (wideValue == 0) {
- buf[pos++] = '0';
- }
- else {
- char tmp[JIM_INTEGER_SPACE];
- int num = 0;
- int i;
- if (wideValue < 0) {
- buf[pos++] = '-';
- i = wideValue % 10;
- tmp[num++] = (i > 0) ? (10 - i) : -i;
- wideValue /= -10;
- }
- while (wideValue) {
- tmp[num++] = wideValue % 10;
- wideValue /= 10;
- }
- for (i = 0; i < num; i++) {
- buf[pos++] = '0' + tmp[num - i - 1];
- }
- }
- buf[pos] = 0;
- JimSetStringBytes(objPtr, buf);
- }
- static int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
- {
- jim_wide wideValue;
- const char *str;
- if (objPtr->typePtr == &coercedDoubleObjType) {
- objPtr->typePtr = &intObjType;
- return JIM_OK;
- }
- str = Jim_String(objPtr);
- if (Jim_StringToWide(str, &wideValue, 0) != JIM_OK) {
- if (flags & JIM_ERRMSG) {
- Jim_SetResultFormatted(interp, "expected integer but got \"%#s\"", objPtr);
- }
- return JIM_ERR;
- }
- if ((wideValue == JIM_WIDE_MIN || wideValue == JIM_WIDE_MAX) && errno == ERANGE) {
- Jim_SetResultString(interp, "Integer value too big to be represented", -1);
- return JIM_ERR;
- }
- Jim_FreeIntRep(interp, objPtr);
- objPtr->typePtr = &intObjType;
- objPtr->internalRep.wideValue = wideValue;
- return JIM_OK;
- }
- #ifdef JIM_OPTIMIZATION
- static int JimIsWide(Jim_Obj *objPtr)
- {
- return objPtr->typePtr == &intObjType;
- }
- #endif
- int Jim_GetWide(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr)
- {
- if (objPtr->typePtr != &intObjType && SetIntFromAny(interp, objPtr, JIM_ERRMSG) == JIM_ERR)
- return JIM_ERR;
- *widePtr = JimWideValue(objPtr);
- return JIM_OK;
- }
- int Jim_GetWideExpr(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr)
- {
- int ret = JIM_OK;
- if (objPtr->typePtr == &sourceObjType || objPtr->typePtr == NULL) {
- SetIntFromAny(interp, objPtr, 0);
- }
- if (objPtr->typePtr == &intObjType) {
- *widePtr = JimWideValue(objPtr);
- }
- else {
- JimPanic((interp->safeexpr, "interp->safeexpr is set"));
- interp->safeexpr++;
- ret = Jim_EvalExpression(interp, objPtr);
- interp->safeexpr--;
- if (ret == JIM_OK) {
- ret = Jim_GetWide(interp, Jim_GetResult(interp), widePtr);
- }
- if (ret != JIM_OK) {
- Jim_SetResultFormatted(interp, "expected integer expression but got \"%#s\"", objPtr);
- }
- }
- return ret;
- }
- static int JimGetWideNoErr(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr)
- {
- if (objPtr->typePtr != &intObjType && SetIntFromAny(interp, objPtr, JIM_NONE) == JIM_ERR)
- return JIM_ERR;
- *widePtr = JimWideValue(objPtr);
- return JIM_OK;
- }
- int Jim_GetLong(Jim_Interp *interp, Jim_Obj *objPtr, long *longPtr)
- {
- jim_wide wideValue;
- int retval;
- retval = Jim_GetWide(interp, objPtr, &wideValue);
- if (retval == JIM_OK) {
- *longPtr = (long)wideValue;
- return JIM_OK;
- }
- return JIM_ERR;
- }
- Jim_Obj *Jim_NewIntObj(Jim_Interp *interp, jim_wide wideValue)
- {
- Jim_Obj *objPtr;
- objPtr = Jim_NewObj(interp);
- objPtr->typePtr = &intObjType;
- objPtr->bytes = NULL;
- objPtr->internalRep.wideValue = wideValue;
- return objPtr;
- }
- #define JIM_DOUBLE_SPACE 30
- static void UpdateStringOfDouble(struct Jim_Obj *objPtr);
- static int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
- static const Jim_ObjType doubleObjType = {
- "double",
- NULL,
- NULL,
- UpdateStringOfDouble,
- JIM_TYPE_NONE,
- };
- #if !HAVE_DECL_ISNAN
- #undef isnan
- #define isnan(X) ((X) != (X))
- #endif
- #if !HAVE_DECL_ISINF
- #undef isinf
- #define isinf(X) (1.0 / (X) == 0.0)
- #endif
- static void UpdateStringOfDouble(struct Jim_Obj *objPtr)
- {
- double value = objPtr->internalRep.doubleValue;
- if (isnan(value)) {
- JimSetStringBytes(objPtr, "NaN");
- return;
- }
- if (isinf(value)) {
- if (value < 0) {
- JimSetStringBytes(objPtr, "-Inf");
- }
- else {
- JimSetStringBytes(objPtr, "Inf");
- }
- return;
- }
- {
- char buf[JIM_DOUBLE_SPACE + 1];
- int i;
- int len = sprintf(buf, "%.12g", value);
- for (i = 0; i < len; i++) {
- if (buf[i] == '.' || buf[i] == 'e') {
- #if defined(JIM_SPRINTF_DOUBLE_NEEDS_FIX)
- char *e = strchr(buf, 'e');
- if (e && (e[1] == '-' || e[1] == '+') && e[2] == '0') {
- e += 2;
- memmove(e, e + 1, len - (e - buf));
- }
- #endif
- break;
- }
- }
- if (buf[i] == '\0') {
- buf[i++] = '.';
- buf[i++] = '0';
- buf[i] = '\0';
- }
- JimSetStringBytes(objPtr, buf);
- }
- }
- static int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- double doubleValue;
- jim_wide wideValue;
- const char *str;
- #ifdef HAVE_LONG_LONG
- #define MIN_INT_IN_DOUBLE -(1LL << 53)
- #define MAX_INT_IN_DOUBLE -(MIN_INT_IN_DOUBLE + 1)
- if (objPtr->typePtr == &intObjType
- && JimWideValue(objPtr) >= MIN_INT_IN_DOUBLE
- && JimWideValue(objPtr) <= MAX_INT_IN_DOUBLE) {
- objPtr->typePtr = &coercedDoubleObjType;
- return JIM_OK;
- }
- #endif
- str = Jim_String(objPtr);
- if (Jim_StringToWide(str, &wideValue, 10) == JIM_OK) {
- Jim_FreeIntRep(interp, objPtr);
- objPtr->typePtr = &coercedDoubleObjType;
- objPtr->internalRep.wideValue = wideValue;
- return JIM_OK;
- }
- else {
- if (Jim_StringToDouble(str, &doubleValue) != JIM_OK) {
- Jim_SetResultFormatted(interp, "expected floating-point number but got \"%#s\"", objPtr);
- return JIM_ERR;
- }
- Jim_FreeIntRep(interp, objPtr);
- }
- objPtr->typePtr = &doubleObjType;
- objPtr->internalRep.doubleValue = doubleValue;
- return JIM_OK;
- }
- int Jim_GetDouble(Jim_Interp *interp, Jim_Obj *objPtr, double *doublePtr)
- {
- if (objPtr->typePtr == &coercedDoubleObjType) {
- *doublePtr = JimWideValue(objPtr);
- return JIM_OK;
- }
- if (objPtr->typePtr != &doubleObjType && SetDoubleFromAny(interp, objPtr) == JIM_ERR)
- return JIM_ERR;
- if (objPtr->typePtr == &coercedDoubleObjType) {
- *doublePtr = JimWideValue(objPtr);
- }
- else {
- *doublePtr = objPtr->internalRep.doubleValue;
- }
- return JIM_OK;
- }
- Jim_Obj *Jim_NewDoubleObj(Jim_Interp *interp, double doubleValue)
- {
- Jim_Obj *objPtr;
- objPtr = Jim_NewObj(interp);
- objPtr->typePtr = &doubleObjType;
- objPtr->bytes = NULL;
- objPtr->internalRep.doubleValue = doubleValue;
- return objPtr;
- }
- static int SetBooleanFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags);
- int Jim_GetBoolean(Jim_Interp *interp, Jim_Obj *objPtr, int * booleanPtr)
- {
- if (objPtr->typePtr != &intObjType && SetBooleanFromAny(interp, objPtr, JIM_ERRMSG) == JIM_ERR)
- return JIM_ERR;
- *booleanPtr = (int) JimWideValue(objPtr);
- return JIM_OK;
- }
- static const char * const jim_true_false_strings[8] = {
- "1", "true", "yes", "on",
- "0", "false", "no", "off"
- };
- static const int jim_true_false_lens[8] = {
- 1, 4, 3, 2,
- 1, 5, 2, 3,
- };
- static int SetBooleanFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
- {
- int index = Jim_FindByName(Jim_String(objPtr), jim_true_false_strings,
- sizeof(jim_true_false_strings) / sizeof(*jim_true_false_strings));
- if (index < 0) {
- if (flags & JIM_ERRMSG) {
- Jim_SetResultFormatted(interp, "expected boolean but got \"%#s\"", objPtr);
- }
- return JIM_ERR;
- }
- Jim_FreeIntRep(interp, objPtr);
- objPtr->typePtr = &intObjType;
- objPtr->internalRep.wideValue = index < 4 ? 1 : 0;
- return JIM_OK;
- }
- static void ListInsertElements(Jim_Obj *listPtr, int idx, int elemc, Jim_Obj *const *elemVec);
- static void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr);
- static void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
- static void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
- static void UpdateStringOfList(struct Jim_Obj *objPtr);
- static int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
- static const Jim_ObjType listObjType = {
- "list",
- FreeListInternalRep,
- DupListInternalRep,
- UpdateStringOfList,
- JIM_TYPE_NONE,
- };
- void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- int i;
- for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
- Jim_DecrRefCount(interp, objPtr->internalRep.listValue.ele[i]);
- }
- Jim_Free(objPtr->internalRep.listValue.ele);
- }
- void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
- {
- int i;
- JIM_NOTUSED(interp);
- dupPtr->internalRep.listValue.len = srcPtr->internalRep.listValue.len;
- dupPtr->internalRep.listValue.maxLen = srcPtr->internalRep.listValue.maxLen;
- dupPtr->internalRep.listValue.ele =
- Jim_Alloc(sizeof(Jim_Obj *) * srcPtr->internalRep.listValue.maxLen);
- memcpy(dupPtr->internalRep.listValue.ele, srcPtr->internalRep.listValue.ele,
- sizeof(Jim_Obj *) * srcPtr->internalRep.listValue.len);
- for (i = 0; i < dupPtr->internalRep.listValue.len; i++) {
- Jim_IncrRefCount(dupPtr->internalRep.listValue.ele[i]);
- }
- dupPtr->typePtr = &listObjType;
- }
- #define JIM_ELESTR_SIMPLE 0
- #define JIM_ELESTR_BRACE 1
- #define JIM_ELESTR_QUOTE 2
- static unsigned char ListElementQuotingType(const char *s, int len)
- {
- int i, level, blevel, trySimple = 1;
- if (len == 0)
- return JIM_ELESTR_BRACE;
- if (s[0] == '"' || s[0] == '{') {
- trySimple = 0;
- goto testbrace;
- }
- for (i = 0; i < len; i++) {
- switch (s[i]) {
- case ' ':
- case '$':
- case '"':
- case '[':
- case ']':
- case ';':
- case '\\':
- case '\r':
- case '\n':
- case '\t':
- case '\f':
- case '\v':
- trySimple = 0;
- case '{':
- case '}':
- goto testbrace;
- }
- }
- return JIM_ELESTR_SIMPLE;
- testbrace:
- if (s[len - 1] == '\\')
- return JIM_ELESTR_QUOTE;
- level = 0;
- blevel = 0;
- for (i = 0; i < len; i++) {
- switch (s[i]) {
- case '{':
- level++;
- break;
- case '}':
- level--;
- if (level < 0)
- return JIM_ELESTR_QUOTE;
- break;
- case '[':
- blevel++;
- break;
- case ']':
- blevel--;
- break;
- case '\\':
- if (s[i + 1] == '\n')
- return JIM_ELESTR_QUOTE;
- else if (s[i + 1] != '\0')
- i++;
- break;
- }
- }
- if (blevel < 0) {
- return JIM_ELESTR_QUOTE;
- }
- if (level == 0) {
- if (!trySimple)
- return JIM_ELESTR_BRACE;
- for (i = 0; i < len; i++) {
- switch (s[i]) {
- case ' ':
- case '$':
- case '"':
- case '[':
- case ']':
- case ';':
- case '\\':
- case '\r':
- case '\n':
- case '\t':
- case '\f':
- case '\v':
- return JIM_ELESTR_BRACE;
- break;
- }
- }
- return JIM_ELESTR_SIMPLE;
- }
- return JIM_ELESTR_QUOTE;
- }
- static int BackslashQuoteString(const char *s, int len, char *q)
- {
- char *p = q;
- while (len--) {
- switch (*s) {
- case ' ':
- case '$':
- case '"':
- case '[':
- case ']':
- case '{':
- case '}':
- case ';':
- case '\\':
- *p++ = '\\';
- *p++ = *s++;
- break;
- case '\n':
- *p++ = '\\';
- *p++ = 'n';
- s++;
- break;
- case '\r':
- *p++ = '\\';
- *p++ = 'r';
- s++;
- break;
- case '\t':
- *p++ = '\\';
- *p++ = 't';
- s++;
- break;
- case '\f':
- *p++ = '\\';
- *p++ = 'f';
- s++;
- break;
- case '\v':
- *p++ = '\\';
- *p++ = 'v';
- s++;
- break;
- default:
- *p++ = *s++;
- break;
- }
- }
- *p = '\0';
- return p - q;
- }
- static void JimMakeListStringRep(Jim_Obj *objPtr, Jim_Obj **objv, int objc)
- {
- #define STATIC_QUOTING_LEN 32
- int i, bufLen, realLength;
- const char *strRep;
- char *p;
- unsigned char *quotingType, staticQuoting[STATIC_QUOTING_LEN];
- if (objc > STATIC_QUOTING_LEN) {
- quotingType = Jim_Alloc(objc);
- }
- else {
- quotingType = staticQuoting;
- }
- bufLen = 0;
- for (i = 0; i < objc; i++) {
- int len;
- strRep = Jim_GetString(objv[i], &len);
- quotingType[i] = ListElementQuotingType(strRep, len);
- switch (quotingType[i]) {
- case JIM_ELESTR_SIMPLE:
- if (i != 0 || strRep[0] != '#') {
- bufLen += len;
- break;
- }
- quotingType[i] = JIM_ELESTR_BRACE;
- case JIM_ELESTR_BRACE:
- bufLen += len + 2;
- break;
- case JIM_ELESTR_QUOTE:
- bufLen += len * 2;
- break;
- }
- bufLen++;
- }
- bufLen++;
- p = objPtr->bytes = Jim_Alloc(bufLen + 1);
- realLength = 0;
- for (i = 0; i < objc; i++) {
- int len, qlen;
- strRep = Jim_GetString(objv[i], &len);
- switch (quotingType[i]) {
- case JIM_ELESTR_SIMPLE:
- memcpy(p, strRep, len);
- p += len;
- realLength += len;
- break;
- case JIM_ELESTR_BRACE:
- *p++ = '{';
- memcpy(p, strRep, len);
- p += len;
- *p++ = '}';
- realLength += len + 2;
- break;
- case JIM_ELESTR_QUOTE:
- if (i == 0 && strRep[0] == '#') {
- *p++ = '\\';
- realLength++;
- }
- qlen = BackslashQuoteString(strRep, len, p);
- p += qlen;
- realLength += qlen;
- break;
- }
- if (i + 1 != objc) {
- *p++ = ' ';
- realLength++;
- }
- }
- *p = '\0';
- objPtr->length = realLength;
- if (quotingType != staticQuoting) {
- Jim_Free(quotingType);
- }
- }
- static void UpdateStringOfList(struct Jim_Obj *objPtr)
- {
- JimMakeListStringRep(objPtr, objPtr->internalRep.listValue.ele, objPtr->internalRep.listValue.len);
- }
- static int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
- {
- struct JimParserCtx parser;
- const char *str;
- int strLen;
- Jim_Obj *fileNameObj;
- int linenr;
- if (objPtr->typePtr == &listObjType) {
- return JIM_OK;
- }
- if (Jim_IsDict(objPtr) && objPtr->bytes == NULL) {
- Jim_Dict *dict = objPtr->internalRep.dictValue;
- objPtr->typePtr = &listObjType;
- objPtr->internalRep.listValue.len = dict->len;
- objPtr->internalRep.listValue.maxLen = dict->maxLen;
- objPtr->internalRep.listValue.ele = dict->table;
- Jim_Free(dict->ht);
- Jim_Free(dict);
- return JIM_OK;
- }
- fileNameObj = Jim_GetSourceInfo(interp, objPtr, &linenr);
- Jim_IncrRefCount(fileNameObj);
- str = Jim_GetString(objPtr, &strLen);
- Jim_FreeIntRep(interp, objPtr);
- objPtr->typePtr = &listObjType;
- objPtr->internalRep.listValue.len = 0;
- objPtr->internalRep.listValue.maxLen = 0;
- objPtr->internalRep.listValue.ele = NULL;
- if (strLen) {
- JimParserInit(&parser, str, strLen, linenr);
- while (!parser.eof) {
- Jim_Obj *elementPtr;
- JimParseList(&parser);
- if (parser.tt != JIM_TT_STR && parser.tt != JIM_TT_ESC)
- continue;
- elementPtr = JimParserGetTokenObj(interp, &parser);
- Jim_SetSourceInfo(interp, elementPtr, fileNameObj, parser.tline);
- ListAppendElement(objPtr, elementPtr);
- }
- }
- Jim_DecrRefCount(interp, fileNameObj);
- return JIM_OK;
- }
- Jim_Obj *Jim_NewListObj(Jim_Interp *interp, Jim_Obj *const *elements, int len)
- {
- Jim_Obj *objPtr;
- objPtr = Jim_NewObj(interp);
- objPtr->typePtr = &listObjType;
- objPtr->bytes = NULL;
- objPtr->internalRep.listValue.ele = NULL;
- objPtr->internalRep.listValue.len = 0;
- objPtr->internalRep.listValue.maxLen = 0;
- if (len) {
- ListInsertElements(objPtr, 0, len, elements);
- }
- return objPtr;
- }
- static void JimListGetElements(Jim_Interp *interp, Jim_Obj *listObj, int *listLen,
- Jim_Obj ***listVec)
- {
- *listLen = Jim_ListLength(interp, listObj);
- *listVec = listObj->internalRep.listValue.ele;
- }
- static int JimSign(jim_wide w)
- {
- if (w == 0) {
- return 0;
- }
- else if (w < 0) {
- return -1;
- }
- return 1;
- }
- struct lsort_info {
- jmp_buf jmpbuf;
- Jim_Obj *command;
- Jim_Interp *interp;
- enum {
- JIM_LSORT_ASCII,
- JIM_LSORT_NOCASE,
- JIM_LSORT_INTEGER,
- JIM_LSORT_REAL,
- JIM_LSORT_COMMAND,
- JIM_LSORT_DICT
- } type;
- int order;
- Jim_Obj **indexv;
- int indexc;
- int unique;
- int (*subfn)(Jim_Obj **, Jim_Obj **);
- };
- static struct lsort_info *sort_info;
- static int ListSortIndexHelper(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
- {
- Jim_Obj *lObj, *rObj;
- if (Jim_ListIndices(sort_info->interp, *lhsObj, sort_info->indexv, sort_info->indexc, &lObj, JIM_ERRMSG) != JIM_OK ||
- Jim_ListIndices(sort_info->interp, *rhsObj, sort_info->indexv, sort_info->indexc, &rObj, JIM_ERRMSG) != JIM_OK) {
- longjmp(sort_info->jmpbuf, JIM_ERR);
- }
- return sort_info->subfn(&lObj, &rObj);
- }
- static int ListSortString(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
- {
- return Jim_StringCompareObj(sort_info->interp, *lhsObj, *rhsObj, 0) * sort_info->order;
- }
- static int ListSortStringNoCase(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
- {
- return Jim_StringCompareObj(sort_info->interp, *lhsObj, *rhsObj, 1) * sort_info->order;
- }
- static int ListSortDict(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
- {
- const char *left = Jim_String(*lhsObj);
- const char *right = Jim_String(*rhsObj);
- while (1) {
- if (isdigit(UCHAR(*left)) && isdigit(UCHAR(*right))) {
- jim_wide lint, rint;
- char *lend, *rend;
- lint = jim_strtoull(left, &lend);
- rint = jim_strtoull(right, &rend);
- if (lint != rint) {
- return JimSign(lint - rint) * sort_info->order;
- }
- if (lend -left != rend - right) {
- return JimSign((lend - left) - (rend - right)) * sort_info->order;
- }
- left = lend;
- right = rend;
- }
- else {
- int cl, cr;
- left += utf8_tounicode_case(left, &cl, 1);
- right += utf8_tounicode_case(right, &cr, 1);
- if (cl != cr) {
- return JimSign(cl - cr) * sort_info->order;
- }
- if (cl == 0) {
- return Jim_StringCompareObj(sort_info->interp, *lhsObj, *rhsObj, 0) * sort_info->order;
- }
- }
- }
- }
- static int ListSortInteger(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
- {
- jim_wide lhs = 0, rhs = 0;
- if (Jim_GetWide(sort_info->interp, *lhsObj, &lhs) != JIM_OK ||
- Jim_GetWide(sort_info->interp, *rhsObj, &rhs) != JIM_OK) {
- longjmp(sort_info->jmpbuf, JIM_ERR);
- }
- return JimSign(lhs - rhs) * sort_info->order;
- }
- static int ListSortReal(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
- {
- double lhs = 0, rhs = 0;
- if (Jim_GetDouble(sort_info->interp, *lhsObj, &lhs) != JIM_OK ||
- Jim_GetDouble(sort_info->interp, *rhsObj, &rhs) != JIM_OK) {
- longjmp(sort_info->jmpbuf, JIM_ERR);
- }
- if (lhs == rhs) {
- return 0;
- }
- if (lhs > rhs) {
- return sort_info->order;
- }
- return -sort_info->order;
- }
- static int ListSortCommand(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
- {
- Jim_Obj *compare_script;
- int rc;
- jim_wide ret = 0;
- compare_script = Jim_DuplicateObj(sort_info->interp, sort_info->command);
- Jim_ListAppendElement(sort_info->interp, compare_script, *lhsObj);
- Jim_ListAppendElement(sort_info->interp, compare_script, *rhsObj);
- rc = Jim_EvalObj(sort_info->interp, compare_script);
- if (rc != JIM_OK || Jim_GetWide(sort_info->interp, Jim_GetResult(sort_info->interp), &ret) != JIM_OK) {
- longjmp(sort_info->jmpbuf, rc);
- }
- return JimSign(ret) * sort_info->order;
- }
- static void ListRemoveDuplicates(Jim_Obj *listObjPtr, int (*comp)(Jim_Obj **lhs, Jim_Obj **rhs))
- {
- int src;
- int dst = 0;
- Jim_Obj **ele = listObjPtr->internalRep.listValue.ele;
- for (src = 1; src < listObjPtr->internalRep.listValue.len; src++) {
- if (comp(&ele[dst], &ele[src]) == 0) {
- Jim_DecrRefCount(sort_info->interp, ele[dst]);
- }
- else {
- dst++;
- }
- ele[dst] = ele[src];
- }
- dst++;
- if (dst < listObjPtr->internalRep.listValue.len) {
- ele[dst] = ele[src];
- }
- listObjPtr->internalRep.listValue.len = dst;
- }
- static int ListSortElements(Jim_Interp *interp, Jim_Obj *listObjPtr, struct lsort_info *info)
- {
- struct lsort_info *prev_info;
- typedef int (qsort_comparator) (const void *, const void *);
- int (*fn) (Jim_Obj **, Jim_Obj **);
- Jim_Obj **vector;
- int len;
- int rc;
- JimPanic((Jim_IsShared(listObjPtr), "ListSortElements called with shared object"));
- SetListFromAny(interp, listObjPtr);
- prev_info = sort_info;
- sort_info = info;
- vector = listObjPtr->internalRep.listValue.ele;
- len = listObjPtr->internalRep.listValue.len;
- switch (info->type) {
- case JIM_LSORT_ASCII:
- fn = ListSortString;
- break;
- case JIM_LSORT_NOCASE:
- fn = ListSortStringNoCase;
- break;
- case JIM_LSORT_INTEGER:
- fn = ListSortInteger;
- break;
- case JIM_LSORT_REAL:
- fn = ListSortReal;
- break;
- case JIM_LSORT_COMMAND:
- fn = ListSortCommand;
- break;
- case JIM_LSORT_DICT:
- fn = ListSortDict;
- break;
- default:
- fn = NULL;
- JimPanic((1, "ListSort called with invalid sort type"));
- return -1;
- }
- if (info->indexc) {
- info->subfn = fn;
- fn = ListSortIndexHelper;
- }
- if ((rc = setjmp(info->jmpbuf)) == 0) {
- qsort(vector, len, sizeof(Jim_Obj *), (qsort_comparator *) fn);
- if (info->unique && len > 1) {
- ListRemoveDuplicates(listObjPtr, fn);
- }
- Jim_InvalidateStringRep(listObjPtr);
- }
- sort_info = prev_info;
- return rc;
- }
- static void ListEnsureLength(Jim_Obj *listPtr, int idx)
- {
- assert(idx >= 0);
- if (idx >= listPtr->internalRep.listValue.maxLen) {
- if (idx < 4) {
- idx = 4;
- }
- listPtr->internalRep.listValue.ele = Jim_Realloc(listPtr->internalRep.listValue.ele,
- sizeof(Jim_Obj *) * idx);
- listPtr->internalRep.listValue.maxLen = idx;
- }
- }
- static void ListInsertElements(Jim_Obj *listPtr, int idx, int elemc, Jim_Obj *const *elemVec)
- {
- int currentLen = listPtr->internalRep.listValue.len;
- int requiredLen = currentLen + elemc;
- int i;
- Jim_Obj **point;
- if (elemc == 0) {
- return;
- }
- if (requiredLen > listPtr->internalRep.listValue.maxLen) {
- if (currentLen) {
- requiredLen *= 2;
- }
- ListEnsureLength(listPtr, requiredLen);
- }
- if (idx < 0) {
- idx = currentLen;
- }
- point = listPtr->internalRep.listValue.ele + idx;
- memmove(point + elemc, point, (currentLen - idx) * sizeof(Jim_Obj *));
- for (i = 0; i < elemc; ++i) {
- point[i] = elemVec[i];
- Jim_IncrRefCount(point[i]);
- }
- listPtr->internalRep.listValue.len += elemc;
- }
- static void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr)
- {
- ListInsertElements(listPtr, -1, 1, &objPtr);
- }
- static void ListAppendList(Jim_Obj *listPtr, Jim_Obj *appendListPtr)
- {
- ListInsertElements(listPtr, -1,
- appendListPtr->internalRep.listValue.len, appendListPtr->internalRep.listValue.ele);
- }
- void Jim_ListAppendElement(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *objPtr)
- {
- JimPanic((Jim_IsShared(listPtr), "Jim_ListAppendElement called with shared object"));
- SetListFromAny(interp, listPtr);
- Jim_InvalidateStringRep(listPtr);
- ListAppendElement(listPtr, objPtr);
- }
- void Jim_ListAppendList(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *appendListPtr)
- {
- JimPanic((Jim_IsShared(listPtr), "Jim_ListAppendList called with shared object"));
- SetListFromAny(interp, listPtr);
- SetListFromAny(interp, appendListPtr);
- Jim_InvalidateStringRep(listPtr);
- ListAppendList(listPtr, appendListPtr);
- }
- int Jim_ListLength(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- SetListFromAny(interp, objPtr);
- return objPtr->internalRep.listValue.len;
- }
- void Jim_ListInsertElements(Jim_Interp *interp, Jim_Obj *listPtr, int idx,
- int objc, Jim_Obj *const *objVec)
- {
- JimPanic((Jim_IsShared(listPtr), "Jim_ListInsertElement called with shared object"));
- SetListFromAny(interp, listPtr);
- if (idx >= 0 && idx > listPtr->internalRep.listValue.len)
- idx = listPtr->internalRep.listValue.len;
- else if (idx < 0)
- idx = 0;
- Jim_InvalidateStringRep(listPtr);
- ListInsertElements(listPtr, idx, objc, objVec);
- }
- Jim_Obj *Jim_ListGetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx)
- {
- SetListFromAny(interp, listPtr);
- if ((idx >= 0 && idx >= listPtr->internalRep.listValue.len) ||
- (idx < 0 && (-idx - 1) >= listPtr->internalRep.listValue.len)) {
- return NULL;
- }
- if (idx < 0)
- idx = listPtr->internalRep.listValue.len + idx;
- return listPtr->internalRep.listValue.ele[idx];
- }
- int Jim_ListIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx, Jim_Obj **objPtrPtr, int flags)
- {
- *objPtrPtr = Jim_ListGetIndex(interp, listPtr, idx);
- if (*objPtrPtr == NULL) {
- if (flags & JIM_ERRMSG) {
- Jim_SetResultString(interp, "list index out of range", -1);
- }
- return JIM_ERR;
- }
- return JIM_OK;
- }
- static int Jim_ListIndices(Jim_Interp *interp, Jim_Obj *listPtr,
- Jim_Obj *const *indexv, int indexc, Jim_Obj **resultObj, int flags)
- {
- int i;
- int static_idxes[5];
- int *idxes = static_idxes;
- int ret = JIM_OK;
- if (indexc > sizeof(static_idxes) / sizeof(*static_idxes)) {
- idxes = Jim_Alloc(indexc * sizeof(*idxes));
- }
- for (i = 0; i < indexc; i++) {
- ret = Jim_GetIndex(interp, indexv[i], &idxes[i]);
- if (ret != JIM_OK) {
- goto err;
- }
- }
- for (i = 0; i < indexc; i++) {
- Jim_Obj *objPtr = Jim_ListGetIndex(interp, listPtr, idxes[i]);
- if (!objPtr) {
- if (flags & JIM_ERRMSG) {
- if (idxes[i] < 0 || idxes[i] > Jim_ListLength(interp, listPtr)) {
- Jim_SetResultFormatted(interp, "index \"%#s\" out of range", indexv[i]);
- }
- else {
- Jim_SetResultFormatted(interp, "element %#s missing from sublist \"%#s\"", indexv[i], listPtr);
- }
- }
- return -1;
- }
- listPtr = objPtr;
- }
- *resultObj = listPtr;
- err:
- if (idxes != static_idxes)
- Jim_Free(idxes);
- return ret;
- }
- static int ListSetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx,
- Jim_Obj *newObjPtr, int flags)
- {
- SetListFromAny(interp, listPtr);
- if ((idx >= 0 && idx >= listPtr->internalRep.listValue.len) ||
- (idx < 0 && (-idx - 1) >= listPtr->internalRep.listValue.len)) {
- if (flags & JIM_ERRMSG) {
- Jim_SetResultString(interp, "list index out of range", -1);
- }
- return JIM_ERR;
- }
- if (idx < 0)
- idx = listPtr->internalRep.listValue.len + idx;
- Jim_DecrRefCount(interp, listPtr->internalRep.listValue.ele[idx]);
- listPtr->internalRep.listValue.ele[idx] = newObjPtr;
- Jim_IncrRefCount(newObjPtr);
- return JIM_OK;
- }
- int Jim_ListSetIndex(Jim_Interp *interp, Jim_Obj *varNamePtr,
- Jim_Obj *const *indexv, int indexc, Jim_Obj *newObjPtr)
- {
- Jim_Obj *varObjPtr, *objPtr, *listObjPtr;
- int shared, i, idx;
- varObjPtr = objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG | JIM_UNSHARED);
- if (objPtr == NULL)
- return JIM_ERR;
- if ((shared = Jim_IsShared(objPtr)))
- varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);
- for (i = 0; i < indexc - 1; i++) {
- listObjPtr = objPtr;
- if (Jim_GetIndex(interp, indexv[i], &idx) != JIM_OK)
- goto err;
- objPtr = Jim_ListGetIndex(interp, listObjPtr, idx);
- if (objPtr == NULL) {
- Jim_SetResultFormatted(interp, "index \"%#s\" out of range", indexv[i]);
- goto err;
- }
- if (Jim_IsShared(objPtr)) {
- objPtr = Jim_DuplicateObj(interp, objPtr);
- ListSetIndex(interp, listObjPtr, idx, objPtr, JIM_NONE);
- }
- Jim_InvalidateStringRep(listObjPtr);
- }
- if (Jim_GetIndex(interp, indexv[indexc - 1], &idx) != JIM_OK)
- goto err;
- if (ListSetIndex(interp, objPtr, idx, newObjPtr, JIM_ERRMSG) == JIM_ERR)
- goto err;
- Jim_InvalidateStringRep(objPtr);
- Jim_InvalidateStringRep(varObjPtr);
- if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK)
- goto err;
- Jim_SetResult(interp, varObjPtr);
- return JIM_OK;
- err:
- if (shared) {
- Jim_FreeNewObj(interp, varObjPtr);
- }
- return JIM_ERR;
- }
- Jim_Obj *Jim_ListJoin(Jim_Interp *interp, Jim_Obj *listObjPtr, const char *joinStr, int joinStrLen)
- {
- int i;
- int listLen = Jim_ListLength(interp, listObjPtr);
- Jim_Obj *resObjPtr = Jim_NewEmptyStringObj(interp);
- for (i = 0; i < listLen; ) {
- Jim_AppendObj(interp, resObjPtr, Jim_ListGetIndex(interp, listObjPtr, i));
- if (++i != listLen) {
- Jim_AppendString(interp, resObjPtr, joinStr, joinStrLen);
- }
- }
- return resObjPtr;
- }
- Jim_Obj *Jim_ConcatObj(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
- {
- int i;
- for (i = 0; i < objc; i++) {
- if (!Jim_IsList(objv[i]))
- break;
- }
- if (i == objc) {
- Jim_Obj *objPtr = Jim_NewListObj(interp, NULL, 0);
- for (i = 0; i < objc; i++)
- ListAppendList(objPtr, objv[i]);
- return objPtr;
- }
- else {
- int len = 0, objLen;
- char *bytes, *p;
- for (i = 0; i < objc; i++) {
- len += Jim_Length(objv[i]);
- }
- if (objc)
- len += objc - 1;
- p = bytes = Jim_Alloc(len + 1);
- for (i = 0; i < objc; i++) {
- const char *s = Jim_GetString(objv[i], &objLen);
- while (objLen && isspace(UCHAR(*s))) {
- s++;
- objLen--;
- len--;
- }
- while (objLen && isspace(UCHAR(s[objLen - 1]))) {
- if (objLen > 1 && s[objLen - 2] == '\\') {
- break;
- }
- objLen--;
- len--;
- }
- memcpy(p, s, objLen);
- p += objLen;
- if (i + 1 != objc) {
- if (objLen)
- *p++ = ' ';
- else {
- len--;
- }
- }
- }
- *p = '\0';
- return Jim_NewStringObjNoAlloc(interp, bytes, len);
- }
- }
- Jim_Obj *Jim_ListRange(Jim_Interp *interp, Jim_Obj *listObjPtr, Jim_Obj *firstObjPtr,
- Jim_Obj *lastObjPtr)
- {
- int first, last;
- int len, rangeLen;
- if (Jim_GetIndex(interp, firstObjPtr, &first) != JIM_OK ||
- Jim_GetIndex(interp, lastObjPtr, &last) != JIM_OK)
- return NULL;
- len = Jim_ListLength(interp, listObjPtr);
- first = JimRelToAbsIndex(len, first);
- last = JimRelToAbsIndex(len, last);
- JimRelToAbsRange(len, &first, &last, &rangeLen);
- if (first == 0 && last == len) {
- return listObjPtr;
- }
- return Jim_NewListObj(interp, listObjPtr->internalRep.listValue.ele + first, rangeLen);
- }
- static void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
- static void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
- static void UpdateStringOfDict(struct Jim_Obj *objPtr);
- static int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
- static const Jim_ObjType dictObjType = {
- "dict",
- FreeDictInternalRep,
- DupDictInternalRep,
- UpdateStringOfDict,
- JIM_TYPE_NONE,
- };
- static void JimFreeDict(Jim_Interp *interp, Jim_Dict *dict)
- {
- int i;
- for (i = 0; i < dict->len; i++) {
- Jim_DecrRefCount(interp, dict->table[i]);
- }
- Jim_Free(dict->table);
- Jim_Free(dict->ht);
- Jim_Free(dict);
- }
- enum {
- DICT_HASH_FIND = -1,
- DICT_HASH_REMOVE = -2,
- DICT_HASH_ADD = -3,
- };
- static int JimDictHashFind(Jim_Dict *dict, Jim_Obj *keyObjPtr, int op_tvoffset)
- {
- unsigned h = (JimObjectHTHashFunction(keyObjPtr) + dict->uniq);
- unsigned idx = h & dict->sizemask;
- int tvoffset = 0;
- unsigned peturb = h;
- unsigned first_removed = ~0;
- if (dict->len) {
- while ((tvoffset = dict->ht[idx].offset)) {
- if (tvoffset == -1) {
- if (first_removed == ~0) {
- first_removed = idx;
- }
- }
- else if (dict->ht[idx].hash == h) {
- if (Jim_StringEqObj(keyObjPtr, dict->table[tvoffset - 1])) {
- break;
- }
- }
- peturb >>= 5;
- idx = (5 * idx + 1 + peturb) & dict->sizemask;
- }
- }
- switch (op_tvoffset) {
- case DICT_HASH_FIND:
- break;
- case DICT_HASH_REMOVE:
- if (tvoffset) {
- dict->ht[idx].offset = -1;
- dict->dummy++;
- }
- break;
- case DICT_HASH_ADD:
- if (tvoffset == 0) {
- if (first_removed != ~0) {
- idx = first_removed;
- dict->dummy--;
- }
- dict->ht[idx].offset = dict->len + 1;
- dict->ht[idx].hash = h;
- }
- break;
- default:
- assert(tvoffset);
- dict->ht[idx].offset = op_tvoffset;
- break;
- }
- return tvoffset;
- }
- static void JimDictExpandHashTable(Jim_Dict *dict, unsigned int size)
- {
- int i;
- struct JimDictHashEntry *prevht = dict->ht;
- int prevsize = dict->size;
- dict->size = JimHashTableNextPower(size);
- dict->sizemask = dict->size - 1;
- dict->ht = Jim_Alloc(dict->size * sizeof(*dict->ht));
- memset(dict->ht, 0, dict->size * sizeof(*dict->ht));
- for (i = 0; i < prevsize; i++) {
- if (prevht[i].offset > 0) {
- unsigned h = prevht[i].hash;
- unsigned idx = h & dict->sizemask;
- unsigned peturb = h;
- while (dict->ht[idx].offset) {
- peturb >>= 5;
- idx = (5 * idx + 1 + peturb) & dict->sizemask;
- }
- dict->ht[idx].offset = prevht[i].offset;
- dict->ht[idx].hash = h;
- }
- }
- Jim_Free(prevht);
- }
- static int JimDictAdd(Jim_Dict *dict, Jim_Obj *keyObjPtr)
- {
- if (dict->size <= dict->len + dict->dummy) {
- JimDictExpandHashTable(dict, dict->size ? dict->size * 2 : 8);
- }
- return JimDictHashFind(dict, keyObjPtr, DICT_HASH_ADD);
- }
- static Jim_Dict *JimDictNew(Jim_Interp *interp, int table_size, int ht_size)
- {
- Jim_Dict *dict = Jim_Alloc(sizeof(*dict));
- memset(dict, 0, sizeof(*dict));
- if (ht_size) {
- JimDictExpandHashTable(dict, ht_size);
- }
- if (table_size) {
- dict->table = Jim_Alloc(table_size * sizeof(*dict->table));
- dict->maxLen = table_size;
- }
- #ifdef JIM_RANDOMISE_HASH
- dict->uniq = (rand() ^ time(NULL) ^ clock());
- #endif
- return dict;
- }
- static void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- JimFreeDict(interp, objPtr->internalRep.dictValue);
- }
- static void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
- {
- Jim_Dict *oldDict = srcPtr->internalRep.dictValue;
- int i;
- Jim_Dict *newDict = JimDictNew(interp, oldDict->maxLen, oldDict->size);
- for (i = 0; i < oldDict->len; i++) {
- newDict->table[i] = oldDict->table[i];
- Jim_IncrRefCount(newDict->table[i]);
- }
- newDict->len = oldDict->len;
- newDict->uniq = oldDict->uniq;
- memcpy(newDict->ht, oldDict->ht, sizeof(*oldDict->ht) * oldDict->size);
- dupPtr->internalRep.dictValue = newDict;
- dupPtr->typePtr = &dictObjType;
- }
- static void UpdateStringOfDict(struct Jim_Obj *objPtr)
- {
- JimMakeListStringRep(objPtr, objPtr->internalRep.dictValue->table, objPtr->internalRep.dictValue->len);
- }
- static int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
- {
- int listlen;
- if (objPtr->typePtr == &dictObjType) {
- return JIM_OK;
- }
- if (Jim_IsList(objPtr) && Jim_IsShared(objPtr)) {
- Jim_String(objPtr);
- }
- listlen = Jim_ListLength(interp, objPtr);
- if (listlen % 2) {
- Jim_SetResultString(interp, "missing value to go with key", -1);
- return JIM_ERR;
- }
- else {
- Jim_Dict *dict = JimDictNew(interp, 0, listlen);
- int i;
- dict->table = objPtr->internalRep.listValue.ele;
- dict->maxLen = objPtr->internalRep.listValue.maxLen;
- for (i = 0; i < listlen; i += 2) {
- int tvoffset = JimDictAdd(dict, dict->table[i]);
- if (tvoffset) {
- Jim_DecrRefCount(interp, dict->table[tvoffset]);
- dict->table[tvoffset] = dict->table[i + 1];
- Jim_DecrRefCount(interp, dict->table[i]);
- }
- else {
- if (dict->len != i) {
- dict->table[dict->len++] = dict->table[i];
- dict->table[dict->len++] = dict->table[i + 1];
- }
- else {
- dict->len += 2;
- }
- }
- }
- objPtr->typePtr = &dictObjType;
- objPtr->internalRep.dictValue = dict;
- return JIM_OK;
- }
- }
- static int DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
- Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr)
- {
- Jim_Dict *dict = objPtr->internalRep.dictValue;
- if (valueObjPtr == NULL) {
- int tvoffset = JimDictHashFind(dict, keyObjPtr, DICT_HASH_REMOVE);
- if (tvoffset) {
- Jim_DecrRefCount(interp, dict->table[tvoffset - 1]);
- Jim_DecrRefCount(interp, dict->table[tvoffset]);
- dict->len -= 2;
- if (tvoffset != dict->len + 1) {
- dict->table[tvoffset - 1] = dict->table[dict->len];
- dict->table[tvoffset] = dict->table[dict->len + 1];
- JimDictHashFind(dict, dict->table[tvoffset - 1], tvoffset);
- }
- return JIM_OK;
- }
- return JIM_ERR;
- }
- else {
- int tvoffset = JimDictAdd(dict, keyObjPtr);
- if (tvoffset) {
- Jim_IncrRefCount(valueObjPtr);
- Jim_DecrRefCount(interp, dict->table[tvoffset]);
- dict->table[tvoffset] = valueObjPtr;
- }
- else {
- if (dict->maxLen == dict->len) {
- if (dict->maxLen < 4) {
- dict->maxLen = 4;
- }
- else {
- dict->maxLen *= 2;
- }
- dict->table = Jim_Realloc(dict->table, dict->maxLen * sizeof(*dict->table));
- }
- Jim_IncrRefCount(keyObjPtr);
- Jim_IncrRefCount(valueObjPtr);
- dict->table[dict->len++] = keyObjPtr;
- dict->table[dict->len++] = valueObjPtr;
- }
- return JIM_OK;
- }
- }
- int Jim_DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
- Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr)
- {
- JimPanic((Jim_IsShared(objPtr), "Jim_DictAddElement called with shared object"));
- if (SetDictFromAny(interp, objPtr) != JIM_OK) {
- return JIM_ERR;
- }
- Jim_InvalidateStringRep(objPtr);
- return DictAddElement(interp, objPtr, keyObjPtr, valueObjPtr);
- }
- Jim_Obj *Jim_NewDictObj(Jim_Interp *interp, Jim_Obj *const *elements, int len)
- {
- Jim_Obj *objPtr;
- int i;
- JimPanic((len % 2, "Jim_NewDictObj() 'len' argument must be even"));
- objPtr = Jim_NewObj(interp);
- objPtr->typePtr = &dictObjType;
- objPtr->bytes = NULL;
- objPtr->internalRep.dictValue = JimDictNew(interp, len, len);
- for (i = 0; i < len; i += 2)
- DictAddElement(interp, objPtr, elements[i], elements[i + 1]);
- return objPtr;
- }
- int Jim_DictKey(Jim_Interp *interp, Jim_Obj *dictPtr, Jim_Obj *keyPtr,
- Jim_Obj **objPtrPtr, int flags)
- {
- int tvoffset;
- Jim_Dict *dict;
- if (SetDictFromAny(interp, dictPtr) != JIM_OK) {
- return -1;
- }
- dict = dictPtr->internalRep.dictValue;
- tvoffset = JimDictHashFind(dict, keyPtr, DICT_HASH_FIND);
- if (tvoffset == 0) {
- if (flags & JIM_ERRMSG) {
- Jim_SetResultFormatted(interp, "key \"%#s\" not known in dictionary", keyPtr);
- }
- return JIM_ERR;
- }
- *objPtrPtr = dict->table[tvoffset];
- return JIM_OK;
- }
- Jim_Obj **Jim_DictPairs(Jim_Interp *interp, Jim_Obj *dictPtr, int *len)
- {
- if (Jim_IsList(dictPtr)) {
- Jim_Obj **table;
- JimListGetElements(interp, dictPtr, len, &table);
- if (*len % 2 == 0) {
- return table;
- }
- }
- if (SetDictFromAny(interp, dictPtr) != JIM_OK) {
- *len = 1;
- return NULL;
- }
- *len = dictPtr->internalRep.dictValue->len;
- return dictPtr->internalRep.dictValue->table;
- }
- int Jim_DictKeysVector(Jim_Interp *interp, Jim_Obj *dictPtr,
- Jim_Obj *const *keyv, int keyc, Jim_Obj **objPtrPtr, int flags)
- {
- int i;
- if (keyc == 0) {
- *objPtrPtr = dictPtr;
- return JIM_OK;
- }
- for (i = 0; i < keyc; i++) {
- Jim_Obj *objPtr;
- int rc = Jim_DictKey(interp, dictPtr, keyv[i], &objPtr, flags);
- if (rc != JIM_OK) {
- return rc;
- }
- dictPtr = objPtr;
- }
- *objPtrPtr = dictPtr;
- return JIM_OK;
- }
- int Jim_SetDictKeysVector(Jim_Interp *interp, Jim_Obj *varNamePtr,
- Jim_Obj *const *keyv, int keyc, Jim_Obj *newObjPtr, int flags)
- {
- Jim_Obj *varObjPtr, *objPtr, *dictObjPtr;
- int shared, i;
- varObjPtr = objPtr = Jim_GetVariable(interp, varNamePtr, flags);
- if (objPtr == NULL) {
- if (newObjPtr == NULL && (flags & JIM_MUSTEXIST)) {
- return JIM_ERR;
- }
- varObjPtr = objPtr = Jim_NewDictObj(interp, NULL, 0);
- if (Jim_SetVariable(interp, varNamePtr, objPtr) != JIM_OK) {
- Jim_FreeNewObj(interp, varObjPtr);
- return JIM_ERR;
- }
- }
- if ((shared = Jim_IsShared(objPtr)))
- varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);
- for (i = 0; i < keyc; i++) {
- dictObjPtr = objPtr;
- if (SetDictFromAny(interp, dictObjPtr) != JIM_OK) {
- goto err;
- }
- if (i == keyc - 1) {
- if (Jim_DictAddElement(interp, objPtr, keyv[keyc - 1], newObjPtr) != JIM_OK) {
- if (newObjPtr || (flags & JIM_MUSTEXIST)) {
- goto err;
- }
- }
- break;
- }
- Jim_InvalidateStringRep(dictObjPtr);
- if (Jim_DictKey(interp, dictObjPtr, keyv[i], &objPtr,
- newObjPtr ? JIM_NONE : JIM_ERRMSG) == JIM_OK) {
- if (Jim_IsShared(objPtr)) {
- objPtr = Jim_DuplicateObj(interp, objPtr);
- DictAddElement(interp, dictObjPtr, keyv[i], objPtr);
- }
- }
- else {
- if (newObjPtr == NULL) {
- goto err;
- }
- objPtr = Jim_NewDictObj(interp, NULL, 0);
- DictAddElement(interp, dictObjPtr, keyv[i], objPtr);
- }
- }
- Jim_InvalidateStringRep(objPtr);
- Jim_InvalidateStringRep(varObjPtr);
- if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK) {
- goto err;
- }
- if (!(flags & JIM_NORESULT)) {
- Jim_SetResult(interp, varObjPtr);
- }
- return JIM_OK;
- err:
- if (shared) {
- Jim_FreeNewObj(interp, varObjPtr);
- }
- return JIM_ERR;
- }
- static void UpdateStringOfIndex(struct Jim_Obj *objPtr);
- static int SetIndexFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
- static const Jim_ObjType indexObjType = {
- "index",
- NULL,
- NULL,
- UpdateStringOfIndex,
- JIM_TYPE_NONE,
- };
- static void UpdateStringOfIndex(struct Jim_Obj *objPtr)
- {
- if (objPtr->internalRep.intValue == -1) {
- JimSetStringBytes(objPtr, "end");
- }
- else {
- char buf[JIM_INTEGER_SPACE + 1];
- if (objPtr->internalRep.intValue >= 0 || objPtr->internalRep.intValue == -INT_MAX) {
- sprintf(buf, "%d", objPtr->internalRep.intValue);
- }
- else {
- sprintf(buf, "end%d", objPtr->internalRep.intValue + 1);
- }
- JimSetStringBytes(objPtr, buf);
- }
- }
- static int SetIndexFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- jim_wide idx;
- int end = 0;
- const char *str;
- Jim_Obj *exprObj = objPtr;
- JimPanic((objPtr->refCount == 0, "SetIndexFromAny() called with zero refcount object"));
- str = Jim_String(objPtr);
- if (strncmp(str, "end", 3) == 0) {
- end = 1;
- str += 3;
- idx = 0;
- switch (*str) {
- case '\0':
- exprObj = NULL;
- break;
- case '-':
- case '+':
- exprObj = Jim_NewStringObj(interp, str, -1);
- break;
- default:
- goto badindex;
- }
- }
- if (exprObj) {
- int ret;
- Jim_IncrRefCount(exprObj);
- ret = Jim_GetWideExpr(interp, exprObj, &idx);
- Jim_DecrRefCount(interp, exprObj);
- if (ret != JIM_OK) {
- goto badindex;
- }
- }
- if (end) {
- if (idx > 0) {
- idx = INT_MAX;
- }
- else {
- idx--;
- }
- }
- else if (idx < 0) {
- idx = -INT_MAX;
- }
- Jim_FreeIntRep(interp, objPtr);
- objPtr->typePtr = &indexObjType;
- objPtr->internalRep.intValue = idx;
- return JIM_OK;
- badindex:
- Jim_SetResultFormatted(interp,
- "bad index \"%#s\": must be intexpr or end?[+-]intexpr?", objPtr);
- return JIM_ERR;
- }
- int Jim_GetIndex(Jim_Interp *interp, Jim_Obj *objPtr, int *indexPtr)
- {
- if (objPtr->typePtr == &intObjType) {
- jim_wide val = JimWideValue(objPtr);
- if (val < 0)
- *indexPtr = -INT_MAX;
- else if (val > INT_MAX)
- *indexPtr = INT_MAX;
- else
- *indexPtr = (int)val;
- return JIM_OK;
- }
- if (objPtr->typePtr != &indexObjType && SetIndexFromAny(interp, objPtr) == JIM_ERR)
- return JIM_ERR;
- *indexPtr = objPtr->internalRep.intValue;
- return JIM_OK;
- }
- static const char * const jimReturnCodes[] = {
- "ok",
- "error",
- "return",
- "break",
- "continue",
- "signal",
- "exit",
- "eval",
- NULL
- };
- #define jimReturnCodesSize (sizeof(jimReturnCodes)/sizeof(*jimReturnCodes) - 1)
- static const Jim_ObjType returnCodeObjType = {
- "return-code",
- NULL,
- NULL,
- NULL,
- JIM_TYPE_NONE,
- };
- const char *Jim_ReturnCode(int code)
- {
- if (code < 0 || code >= (int)jimReturnCodesSize) {
- return "?";
- }
- else {
- return jimReturnCodes[code];
- }
- }
- static int SetReturnCodeFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- int returnCode;
- jim_wide wideValue;
- if (JimGetWideNoErr(interp, objPtr, &wideValue) != JIM_ERR)
- returnCode = (int)wideValue;
- else if (Jim_GetEnum(interp, objPtr, jimReturnCodes, &returnCode, NULL, JIM_NONE) != JIM_OK) {
- Jim_SetResultFormatted(interp, "expected return code but got \"%#s\"", objPtr);
- return JIM_ERR;
- }
- Jim_FreeIntRep(interp, objPtr);
- objPtr->typePtr = &returnCodeObjType;
- objPtr->internalRep.intValue = returnCode;
- return JIM_OK;
- }
- int Jim_GetReturnCode(Jim_Interp *interp, Jim_Obj *objPtr, int *intPtr)
- {
- if (objPtr->typePtr != &returnCodeObjType && SetReturnCodeFromAny(interp, objPtr) == JIM_ERR)
- return JIM_ERR;
- *intPtr = objPtr->internalRep.intValue;
- return JIM_OK;
- }
- static int JimParseExprOperator(struct JimParserCtx *pc);
- static int JimParseExprNumber(struct JimParserCtx *pc);
- static int JimParseExprIrrational(struct JimParserCtx *pc);
- static int JimParseExprBoolean(struct JimParserCtx *pc);
- enum
- {
- JIM_EXPROP_MUL = JIM_TT_EXPR_OP,
- JIM_EXPROP_DIV,
- JIM_EXPROP_MOD,
- JIM_EXPROP_SUB,
- JIM_EXPROP_ADD,
- JIM_EXPROP_LSHIFT,
- JIM_EXPROP_RSHIFT,
- JIM_EXPROP_ROTL,
- JIM_EXPROP_ROTR,
- JIM_EXPROP_LT,
- JIM_EXPROP_GT,
- JIM_EXPROP_LTE,
- JIM_EXPROP_GTE,
- JIM_EXPROP_NUMEQ,
- JIM_EXPROP_NUMNE,
- JIM_EXPROP_BITAND,
- JIM_EXPROP_BITXOR,
- JIM_EXPROP_BITOR,
- JIM_EXPROP_LOGICAND,
- JIM_EXPROP_LOGICOR,
- JIM_EXPROP_TERNARY,
- JIM_EXPROP_COLON,
- JIM_EXPROP_POW,
- JIM_EXPROP_STREQ,
- JIM_EXPROP_STRNE,
- JIM_EXPROP_STRIN,
- JIM_EXPROP_STRNI,
- JIM_EXPROP_STRLT,
- JIM_EXPROP_STRGT,
- JIM_EXPROP_STRLE,
- JIM_EXPROP_STRGE,
- JIM_EXPROP_NOT,
- JIM_EXPROP_BITNOT,
- JIM_EXPROP_UNARYMINUS,
- JIM_EXPROP_UNARYPLUS,
- JIM_EXPROP_FUNC_INT,
- JIM_EXPROP_FUNC_WIDE,
- JIM_EXPROP_FUNC_ABS,
- JIM_EXPROP_FUNC_DOUBLE,
- JIM_EXPROP_FUNC_ROUND,
- JIM_EXPROP_FUNC_RAND,
- JIM_EXPROP_FUNC_SRAND,
- JIM_EXPROP_FUNC_SIN,
- JIM_EXPROP_FUNC_COS,
- JIM_EXPROP_FUNC_TAN,
- JIM_EXPROP_FUNC_ASIN,
- JIM_EXPROP_FUNC_ACOS,
- JIM_EXPROP_FUNC_ATAN,
- JIM_EXPROP_FUNC_ATAN2,
- JIM_EXPROP_FUNC_SINH,
- JIM_EXPROP_FUNC_COSH,
- JIM_EXPROP_FUNC_TANH,
- JIM_EXPROP_FUNC_CEIL,
- JIM_EXPROP_FUNC_FLOOR,
- JIM_EXPROP_FUNC_EXP,
- JIM_EXPROP_FUNC_LOG,
- JIM_EXPROP_FUNC_LOG10,
- JIM_EXPROP_FUNC_SQRT,
- JIM_EXPROP_FUNC_POW,
- JIM_EXPROP_FUNC_HYPOT,
- JIM_EXPROP_FUNC_FMOD,
- };
- struct JimExprNode {
- int type;
- struct Jim_Obj *objPtr;
- struct JimExprNode *left;
- struct JimExprNode *right;
- struct JimExprNode *ternary;
- };
- typedef struct Jim_ExprOperator
- {
- const char *name;
- int (*funcop) (Jim_Interp *interp, struct JimExprNode *opnode);
- unsigned char precedence;
- unsigned char arity;
- unsigned char attr;
- unsigned char namelen;
- } Jim_ExprOperator;
- static int JimExprGetTerm(Jim_Interp *interp, struct JimExprNode *node, Jim_Obj **objPtrPtr);
- static int JimExprGetTermBoolean(Jim_Interp *interp, struct JimExprNode *node);
- static int JimExprEvalTermNode(Jim_Interp *interp, struct JimExprNode *node);
- static int JimExprOpNumUnary(Jim_Interp *interp, struct JimExprNode *node)
- {
- int intresult = 1;
- int rc, bA = 0;
- double dA, dC = 0;
- jim_wide wA, wC = 0;
- Jim_Obj *A;
- if ((rc = JimExprGetTerm(interp, node->left, &A)) != JIM_OK) {
- return rc;
- }
- if ((A->typePtr != &doubleObjType || A->bytes) && JimGetWideNoErr(interp, A, &wA) == JIM_OK) {
- switch (node->type) {
- case JIM_EXPROP_FUNC_INT:
- case JIM_EXPROP_FUNC_WIDE:
- case JIM_EXPROP_FUNC_ROUND:
- case JIM_EXPROP_UNARYPLUS:
- wC = wA;
- break;
- case JIM_EXPROP_FUNC_DOUBLE:
- dC = wA;
- intresult = 0;
- break;
- case JIM_EXPROP_FUNC_ABS:
- wC = wA >= 0 ? wA : -wA;
- break;
- case JIM_EXPROP_UNARYMINUS:
- wC = -wA;
- break;
- case JIM_EXPROP_NOT:
- wC = !wA;
- break;
- default:
- abort();
- }
- }
- else if ((rc = Jim_GetDouble(interp, A, &dA)) == JIM_OK) {
- switch (node->type) {
- case JIM_EXPROP_FUNC_INT:
- case JIM_EXPROP_FUNC_WIDE:
- wC = dA;
- break;
- case JIM_EXPROP_FUNC_ROUND:
- wC = dA < 0 ? (dA - 0.5) : (dA + 0.5);
- break;
- case JIM_EXPROP_FUNC_DOUBLE:
- case JIM_EXPROP_UNARYPLUS:
- dC = dA;
- intresult = 0;
- break;
- case JIM_EXPROP_FUNC_ABS:
- #ifdef JIM_MATH_FUNCTIONS
- dC = fabs(dA);
- #else
- dC = dA >= 0 ? dA : -dA;
- #endif
- intresult = 0;
- break;
- case JIM_EXPROP_UNARYMINUS:
- dC = -dA;
- intresult = 0;
- break;
- case JIM_EXPROP_NOT:
- wC = !dA;
- break;
- default:
- abort();
- }
- }
- else if ((rc = Jim_GetBoolean(interp, A, &bA)) == JIM_OK) {
- switch (node->type) {
- case JIM_EXPROP_NOT:
- wC = !bA;
- break;
- default:
- abort();
- }
- }
- if (rc == JIM_OK) {
- if (intresult) {
- Jim_SetResultInt(interp, wC);
- }
- else {
- Jim_SetResult(interp, Jim_NewDoubleObj(interp, dC));
- }
- }
- Jim_DecrRefCount(interp, A);
- return rc;
- }
- static double JimRandDouble(Jim_Interp *interp)
- {
- unsigned long x;
- JimRandomBytes(interp, &x, sizeof(x));
- return (double)x / (double)~0UL;
- }
- static int JimExprOpIntUnary(Jim_Interp *interp, struct JimExprNode *node)
- {
- jim_wide wA;
- Jim_Obj *A;
- int rc;
- if ((rc = JimExprGetTerm(interp, node->left, &A)) != JIM_OK) {
- return rc;
- }
- rc = Jim_GetWide(interp, A, &wA);
- if (rc == JIM_OK) {
- switch (node->type) {
- case JIM_EXPROP_BITNOT:
- Jim_SetResultInt(interp, ~wA);
- break;
- case JIM_EXPROP_FUNC_SRAND:
- JimPrngSeed(interp, (unsigned char *)&wA, sizeof(wA));
- Jim_SetResult(interp, Jim_NewDoubleObj(interp, JimRandDouble(interp)));
- break;
- default:
- abort();
- }
- }
- Jim_DecrRefCount(interp, A);
- return rc;
- }
- static int JimExprOpNone(Jim_Interp *interp, struct JimExprNode *node)
- {
- JimPanic((node->type != JIM_EXPROP_FUNC_RAND, "JimExprOpNone only support rand()"));
- Jim_SetResult(interp, Jim_NewDoubleObj(interp, JimRandDouble(interp)));
- return JIM_OK;
- }
- #ifdef JIM_MATH_FUNCTIONS
- static int JimExprOpDoubleUnary(Jim_Interp *interp, struct JimExprNode *node)
- {
- int rc;
- double dA, dC;
- Jim_Obj *A;
- if ((rc = JimExprGetTerm(interp, node->left, &A)) != JIM_OK) {
- return rc;
- }
- rc = Jim_GetDouble(interp, A, &dA);
- if (rc == JIM_OK) {
- switch (node->type) {
- case JIM_EXPROP_FUNC_SIN:
- dC = sin(dA);
- break;
- case JIM_EXPROP_FUNC_COS:
- dC = cos(dA);
- break;
- case JIM_EXPROP_FUNC_TAN:
- dC = tan(dA);
- break;
- case JIM_EXPROP_FUNC_ASIN:
- dC = asin(dA);
- break;
- case JIM_EXPROP_FUNC_ACOS:
- dC = acos(dA);
- break;
- case JIM_EXPROP_FUNC_ATAN:
- dC = atan(dA);
- break;
- case JIM_EXPROP_FUNC_SINH:
- dC = sinh(dA);
- break;
- case JIM_EXPROP_FUNC_COSH:
- dC = cosh(dA);
- break;
- case JIM_EXPROP_FUNC_TANH:
- dC = tanh(dA);
- break;
- case JIM_EXPROP_FUNC_CEIL:
- dC = ceil(dA);
- break;
- case JIM_EXPROP_FUNC_FLOOR:
- dC = floor(dA);
- break;
- case JIM_EXPROP_FUNC_EXP:
- dC = exp(dA);
- break;
- case JIM_EXPROP_FUNC_LOG:
- dC = log(dA);
- break;
- case JIM_EXPROP_FUNC_LOG10:
- dC = log10(dA);
- break;
- case JIM_EXPROP_FUNC_SQRT:
- dC = sqrt(dA);
- break;
- default:
- abort();
- }
- Jim_SetResult(interp, Jim_NewDoubleObj(interp, dC));
- }
- Jim_DecrRefCount(interp, A);
- return rc;
- }
- #endif
- static int JimExprOpIntBin(Jim_Interp *interp, struct JimExprNode *node)
- {
- jim_wide wA, wB;
- int rc;
- Jim_Obj *A, *B;
- if ((rc = JimExprGetTerm(interp, node->left, &A)) != JIM_OK) {
- return rc;
- }
- if ((rc = JimExprGetTerm(interp, node->right, &B)) != JIM_OK) {
- Jim_DecrRefCount(interp, A);
- return rc;
- }
- rc = JIM_ERR;
- if (Jim_GetWide(interp, A, &wA) == JIM_OK && Jim_GetWide(interp, B, &wB) == JIM_OK) {
- jim_wide wC;
- rc = JIM_OK;
- switch (node->type) {
- case JIM_EXPROP_LSHIFT:
- wC = wA << wB;
- break;
- case JIM_EXPROP_RSHIFT:
- wC = wA >> wB;
- break;
- case JIM_EXPROP_BITAND:
- wC = wA & wB;
- break;
- case JIM_EXPROP_BITXOR:
- wC = wA ^ wB;
- break;
- case JIM_EXPROP_BITOR:
- wC = wA | wB;
- break;
- case JIM_EXPROP_MOD:
- if (wB == 0) {
- wC = 0;
- Jim_SetResultString(interp, "Division by zero", -1);
- rc = JIM_ERR;
- }
- else {
- int negative = 0;
- if (wB < 0) {
- wB = -wB;
- wA = -wA;
- negative = 1;
- }
- wC = wA % wB;
- if (wC < 0) {
- wC += wB;
- }
- if (negative) {
- wC = -wC;
- }
- }
- break;
- case JIM_EXPROP_ROTL:
- case JIM_EXPROP_ROTR:{
- unsigned long uA = (unsigned long)wA;
- unsigned long uB = (unsigned long)wB;
- const unsigned int S = sizeof(unsigned long) * 8;
- uB %= S;
- if (node->type == JIM_EXPROP_ROTR) {
- uB = S - uB;
- }
- wC = (unsigned long)(uA << uB) | (uA >> (S - uB));
- break;
- }
- default:
- abort();
- }
- Jim_SetResultInt(interp, wC);
- }
- Jim_DecrRefCount(interp, A);
- Jim_DecrRefCount(interp, B);
- return rc;
- }
- static int JimExprOpBin(Jim_Interp *interp, struct JimExprNode *node)
- {
- int rc = JIM_OK;
- double dA, dB, dC = 0;
- jim_wide wA, wB, wC = 0;
- Jim_Obj *A, *B;
- if ((rc = JimExprGetTerm(interp, node->left, &A)) != JIM_OK) {
- return rc;
- }
- if ((rc = JimExprGetTerm(interp, node->right, &B)) != JIM_OK) {
- Jim_DecrRefCount(interp, A);
- return rc;
- }
- if ((A->typePtr != &doubleObjType || A->bytes) &&
- (B->typePtr != &doubleObjType || B->bytes) &&
- JimGetWideNoErr(interp, A, &wA) == JIM_OK && JimGetWideNoErr(interp, B, &wB) == JIM_OK) {
- switch (node->type) {
- case JIM_EXPROP_POW:
- case JIM_EXPROP_FUNC_POW:
- if (wA == 0 && wB < 0) {
- Jim_SetResultString(interp, "exponentiation of zero by negative power", -1);
- rc = JIM_ERR;
- goto done;
- }
- wC = JimPowWide(wA, wB);
- goto intresult;
- case JIM_EXPROP_ADD:
- wC = wA + wB;
- goto intresult;
- case JIM_EXPROP_SUB:
- wC = wA - wB;
- goto intresult;
- case JIM_EXPROP_MUL:
- wC = wA * wB;
- goto intresult;
- case JIM_EXPROP_DIV:
- if (wB == 0) {
- Jim_SetResultString(interp, "Division by zero", -1);
- rc = JIM_ERR;
- goto done;
- }
- else {
- if (wB < 0) {
- wB = -wB;
- wA = -wA;
- }
- wC = wA / wB;
- if (wA % wB < 0) {
- wC--;
- }
- goto intresult;
- }
- case JIM_EXPROP_LT:
- wC = wA < wB;
- goto intresult;
- case JIM_EXPROP_GT:
- wC = wA > wB;
- goto intresult;
- case JIM_EXPROP_LTE:
- wC = wA <= wB;
- goto intresult;
- case JIM_EXPROP_GTE:
- wC = wA >= wB;
- goto intresult;
- case JIM_EXPROP_NUMEQ:
- wC = wA == wB;
- goto intresult;
- case JIM_EXPROP_NUMNE:
- wC = wA != wB;
- goto intresult;
- }
- }
- if (Jim_GetDouble(interp, A, &dA) == JIM_OK && Jim_GetDouble(interp, B, &dB) == JIM_OK) {
- switch (node->type) {
- #ifndef JIM_MATH_FUNCTIONS
- case JIM_EXPROP_POW:
- case JIM_EXPROP_FUNC_POW:
- case JIM_EXPROP_FUNC_ATAN2:
- case JIM_EXPROP_FUNC_HYPOT:
- case JIM_EXPROP_FUNC_FMOD:
- Jim_SetResultString(interp, "unsupported", -1);
- rc = JIM_ERR;
- goto done;
- #else
- case JIM_EXPROP_POW:
- case JIM_EXPROP_FUNC_POW:
- dC = pow(dA, dB);
- goto doubleresult;
- case JIM_EXPROP_FUNC_ATAN2:
- dC = atan2(dA, dB);
- goto doubleresult;
- case JIM_EXPROP_FUNC_HYPOT:
- dC = hypot(dA, dB);
- goto doubleresult;
- case JIM_EXPROP_FUNC_FMOD:
- dC = fmod(dA, dB);
- goto doubleresult;
- #endif
- case JIM_EXPROP_ADD:
- dC = dA + dB;
- goto doubleresult;
- case JIM_EXPROP_SUB:
- dC = dA - dB;
- goto doubleresult;
- case JIM_EXPROP_MUL:
- dC = dA * dB;
- goto doubleresult;
- case JIM_EXPROP_DIV:
- if (dB == 0) {
- #ifdef INFINITY
- dC = dA < 0 ? -INFINITY : INFINITY;
- #else
- dC = (dA < 0 ? -1.0 : 1.0) * strtod("Inf", NULL);
- #endif
- }
- else {
- dC = dA / dB;
- }
- goto doubleresult;
- case JIM_EXPROP_LT:
- wC = dA < dB;
- goto intresult;
- case JIM_EXPROP_GT:
- wC = dA > dB;
- goto intresult;
- case JIM_EXPROP_LTE:
- wC = dA <= dB;
- goto intresult;
- case JIM_EXPROP_GTE:
- wC = dA >= dB;
- goto intresult;
- case JIM_EXPROP_NUMEQ:
- wC = dA == dB;
- goto intresult;
- case JIM_EXPROP_NUMNE:
- wC = dA != dB;
- goto intresult;
- }
- }
- else {
- int i = Jim_StringCompareObj(interp, A, B, 0);
- switch (node->type) {
- case JIM_EXPROP_LT:
- wC = i < 0;
- goto intresult;
- case JIM_EXPROP_GT:
- wC = i > 0;
- goto intresult;
- case JIM_EXPROP_LTE:
- wC = i <= 0;
- goto intresult;
- case JIM_EXPROP_GTE:
- wC = i >= 0;
- goto intresult;
- case JIM_EXPROP_NUMEQ:
- wC = i == 0;
- goto intresult;
- case JIM_EXPROP_NUMNE:
- wC = i != 0;
- goto intresult;
- }
- }
- rc = JIM_ERR;
- done:
- Jim_DecrRefCount(interp, A);
- Jim_DecrRefCount(interp, B);
- return rc;
- intresult:
- Jim_SetResultInt(interp, wC);
- goto done;
- doubleresult:
- Jim_SetResult(interp, Jim_NewDoubleObj(interp, dC));
- goto done;
- }
- static int JimSearchList(Jim_Interp *interp, Jim_Obj *listObjPtr, Jim_Obj *valObj)
- {
- int listlen;
- int i;
- listlen = Jim_ListLength(interp, listObjPtr);
- for (i = 0; i < listlen; i++) {
- if (Jim_StringEqObj(Jim_ListGetIndex(interp, listObjPtr, i), valObj)) {
- return 1;
- }
- }
- return 0;
- }
- static int JimExprOpStrBin(Jim_Interp *interp, struct JimExprNode *node)
- {
- Jim_Obj *A, *B;
- jim_wide wC;
- int comp, rc;
- if ((rc = JimExprGetTerm(interp, node->left, &A)) != JIM_OK) {
- return rc;
- }
- if ((rc = JimExprGetTerm(interp, node->right, &B)) != JIM_OK) {
- Jim_DecrRefCount(interp, A);
- return rc;
- }
- switch (node->type) {
- case JIM_EXPROP_STREQ:
- case JIM_EXPROP_STRNE:
- wC = Jim_StringEqObj(A, B);
- if (node->type == JIM_EXPROP_STRNE) {
- wC = !wC;
- }
- break;
- case JIM_EXPROP_STRLT:
- case JIM_EXPROP_STRGT:
- case JIM_EXPROP_STRLE:
- case JIM_EXPROP_STRGE:
- comp = Jim_StringCompareObj(interp, A, B, 0);
- if (node->type == JIM_EXPROP_STRLT) {
- wC = comp == -1;
- } else if (node->type == JIM_EXPROP_STRGT) {
- wC = comp == 1;
- } else if (node->type == JIM_EXPROP_STRLE) {
- wC = comp == -1 || comp == 0;
- } else {
- wC = comp == 0 || comp == 1;
- }
- break;
- case JIM_EXPROP_STRIN:
- wC = JimSearchList(interp, B, A);
- break;
- case JIM_EXPROP_STRNI:
- wC = !JimSearchList(interp, B, A);
- break;
- default:
- abort();
- }
- Jim_SetResultInt(interp, wC);
- Jim_DecrRefCount(interp, A);
- Jim_DecrRefCount(interp, B);
- return rc;
- }
- static int ExprBool(Jim_Interp *interp, Jim_Obj *obj)
- {
- long l;
- double d;
- int b;
- int ret = -1;
- Jim_IncrRefCount(obj);
- if (Jim_GetLong(interp, obj, &l) == JIM_OK) {
- ret = (l != 0);
- }
- else if (Jim_GetDouble(interp, obj, &d) == JIM_OK) {
- ret = (d != 0);
- }
- else if (Jim_GetBoolean(interp, obj, &b) == JIM_OK) {
- ret = (b != 0);
- }
- Jim_DecrRefCount(interp, obj);
- return ret;
- }
- static int JimExprOpAnd(Jim_Interp *interp, struct JimExprNode *node)
- {
- int result = JimExprGetTermBoolean(interp, node->left);
- if (result == 1) {
- result = JimExprGetTermBoolean(interp, node->right);
- }
- if (result == -1) {
- return JIM_ERR;
- }
- Jim_SetResultInt(interp, result);
- return JIM_OK;
- }
- static int JimExprOpOr(Jim_Interp *interp, struct JimExprNode *node)
- {
- int result = JimExprGetTermBoolean(interp, node->left);
- if (result == 0) {
- result = JimExprGetTermBoolean(interp, node->right);
- }
- if (result == -1) {
- return JIM_ERR;
- }
- Jim_SetResultInt(interp, result);
- return JIM_OK;
- }
- static int JimExprOpTernary(Jim_Interp *interp, struct JimExprNode *node)
- {
- int result = JimExprGetTermBoolean(interp, node->left);
- if (result == 1) {
- return JimExprEvalTermNode(interp, node->right);
- }
- else if (result == 0) {
- return JimExprEvalTermNode(interp, node->ternary);
- }
- return JIM_ERR;
- }
- enum
- {
- OP_FUNC = 0x0001,
- OP_RIGHT_ASSOC = 0x0002,
- };
- #define OPRINIT_ATTR(N, P, ARITY, F, ATTR) {N, F, P, ARITY, ATTR, sizeof(N) - 1}
- #define OPRINIT(N, P, ARITY, F) OPRINIT_ATTR(N, P, ARITY, F, 0)
- static const struct Jim_ExprOperator Jim_ExprOperators[] = {
- OPRINIT("*", 110, 2, JimExprOpBin),
- OPRINIT("/", 110, 2, JimExprOpBin),
- OPRINIT("%", 110, 2, JimExprOpIntBin),
- OPRINIT("-", 100, 2, JimExprOpBin),
- OPRINIT("+", 100, 2, JimExprOpBin),
- OPRINIT("<<", 90, 2, JimExprOpIntBin),
- OPRINIT(">>", 90, 2, JimExprOpIntBin),
- OPRINIT("<<<", 90, 2, JimExprOpIntBin),
- OPRINIT(">>>", 90, 2, JimExprOpIntBin),
- OPRINIT("<", 80, 2, JimExprOpBin),
- OPRINIT(">", 80, 2, JimExprOpBin),
- OPRINIT("<=", 80, 2, JimExprOpBin),
- OPRINIT(">=", 80, 2, JimExprOpBin),
- OPRINIT("==", 70, 2, JimExprOpBin),
- OPRINIT("!=", 70, 2, JimExprOpBin),
- OPRINIT("&", 50, 2, JimExprOpIntBin),
- OPRINIT("^", 49, 2, JimExprOpIntBin),
- OPRINIT("|", 48, 2, JimExprOpIntBin),
- OPRINIT("&&", 10, 2, JimExprOpAnd),
- OPRINIT("||", 9, 2, JimExprOpOr),
- OPRINIT_ATTR("?", 5, 3, JimExprOpTernary, OP_RIGHT_ASSOC),
- OPRINIT_ATTR(":", 5, 3, NULL, OP_RIGHT_ASSOC),
- OPRINIT_ATTR("**", 120, 2, JimExprOpBin, OP_RIGHT_ASSOC),
- OPRINIT("eq", 60, 2, JimExprOpStrBin),
- OPRINIT("ne", 60, 2, JimExprOpStrBin),
- OPRINIT("in", 55, 2, JimExprOpStrBin),
- OPRINIT("ni", 55, 2, JimExprOpStrBin),
- OPRINIT("lt", 75, 2, JimExprOpStrBin),
- OPRINIT("gt", 75, 2, JimExprOpStrBin),
- OPRINIT("le", 75, 2, JimExprOpStrBin),
- OPRINIT("ge", 75, 2, JimExprOpStrBin),
- OPRINIT_ATTR("!", 150, 1, JimExprOpNumUnary, OP_RIGHT_ASSOC),
- OPRINIT_ATTR("~", 150, 1, JimExprOpIntUnary, OP_RIGHT_ASSOC),
- OPRINIT_ATTR(" -", 150, 1, JimExprOpNumUnary, OP_RIGHT_ASSOC),
- OPRINIT_ATTR(" +", 150, 1, JimExprOpNumUnary, OP_RIGHT_ASSOC),
- OPRINIT_ATTR("int", 200, 1, JimExprOpNumUnary, OP_FUNC),
- OPRINIT_ATTR("wide", 200, 1, JimExprOpNumUnary, OP_FUNC),
- OPRINIT_ATTR("abs", 200, 1, JimExprOpNumUnary, OP_FUNC),
- OPRINIT_ATTR("double", 200, 1, JimExprOpNumUnary, OP_FUNC),
- OPRINIT_ATTR("round", 200, 1, JimExprOpNumUnary, OP_FUNC),
- OPRINIT_ATTR("rand", 200, 0, JimExprOpNone, OP_FUNC),
- OPRINIT_ATTR("srand", 200, 1, JimExprOpIntUnary, OP_FUNC),
- #ifdef JIM_MATH_FUNCTIONS
- OPRINIT_ATTR("sin", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
- OPRINIT_ATTR("cos", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
- OPRINIT_ATTR("tan", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
- OPRINIT_ATTR("asin", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
- OPRINIT_ATTR("acos", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
- OPRINIT_ATTR("atan", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
- OPRINIT_ATTR("atan2", 200, 2, JimExprOpBin, OP_FUNC),
- OPRINIT_ATTR("sinh", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
- OPRINIT_ATTR("cosh", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
- OPRINIT_ATTR("tanh", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
- OPRINIT_ATTR("ceil", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
- OPRINIT_ATTR("floor", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
- OPRINIT_ATTR("exp", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
- OPRINIT_ATTR("log", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
- OPRINIT_ATTR("log10", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
- OPRINIT_ATTR("sqrt", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
- OPRINIT_ATTR("pow", 200, 2, JimExprOpBin, OP_FUNC),
- OPRINIT_ATTR("hypot", 200, 2, JimExprOpBin, OP_FUNC),
- OPRINIT_ATTR("fmod", 200, 2, JimExprOpBin, OP_FUNC),
- #endif
- };
- #undef OPRINIT
- #undef OPRINIT_ATTR
- #define JIM_EXPR_OPERATORS_NUM \
- (sizeof(Jim_ExprOperators)/sizeof(struct Jim_ExprOperator))
- static int JimParseExpression(struct JimParserCtx *pc)
- {
- pc->errmsg = NULL;
- while (1) {
- while (isspace(UCHAR(*pc->p)) || (*(pc->p) == '\\' && *(pc->p + 1) == '\n')) {
- if (*pc->p == '\n') {
- pc->linenr++;
- }
- pc->p++;
- pc->len--;
- }
- if (*pc->p == '#') {
- JimParseComment(pc);
- continue;
- }
- break;
- }
- pc->tline = pc->linenr;
- pc->tstart = pc->p;
- if (pc->len == 0) {
- pc->tend = pc->p;
- pc->tt = JIM_TT_EOL;
- pc->eof = 1;
- return JIM_OK;
- }
- switch (*(pc->p)) {
- case '(':
- pc->tt = JIM_TT_SUBEXPR_START;
- goto singlechar;
- case ')':
- pc->tt = JIM_TT_SUBEXPR_END;
- goto singlechar;
- case ',':
- pc->tt = JIM_TT_SUBEXPR_COMMA;
- singlechar:
- pc->tend = pc->p;
- pc->p++;
- pc->len--;
- break;
- case '[':
- return JimParseCmd(pc);
- case '$':
- if (JimParseVar(pc) == JIM_ERR)
- return JimParseExprOperator(pc);
- else {
- if (pc->tt == JIM_TT_EXPRSUGAR) {
- pc->errmsg = "nesting expr in expr is not allowed";
- return JIM_ERR;
- }
- return JIM_OK;
- }
- break;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- case '.':
- return JimParseExprNumber(pc);
- case '"':
- return JimParseQuote(pc);
- case '{':
- return JimParseBrace(pc);
- case 'N':
- case 'I':
- case 'n':
- case 'i':
- if (JimParseExprIrrational(pc) == JIM_ERR)
- if (JimParseExprBoolean(pc) == JIM_ERR)
- return JimParseExprOperator(pc);
- break;
- case 't':
- case 'f':
- case 'o':
- case 'y':
- if (JimParseExprBoolean(pc) == JIM_ERR)
- return JimParseExprOperator(pc);
- break;
- default:
- return JimParseExprOperator(pc);
- break;
- }
- return JIM_OK;
- }
- static int JimParseExprNumber(struct JimParserCtx *pc)
- {
- char *end;
- pc->tt = JIM_TT_EXPR_INT;
- jim_strtoull(pc->p, (char **)&pc->p);
- if (strchr("eENnIi.", *pc->p) || pc->p == pc->tstart) {
- if (strtod(pc->tstart, &end)) { }
- if (end == pc->tstart)
- return JIM_ERR;
- if (end > pc->p) {
- pc->tt = JIM_TT_EXPR_DOUBLE;
- pc->p = end;
- }
- }
- pc->tend = pc->p - 1;
- pc->len -= (pc->p - pc->tstart);
- return JIM_OK;
- }
- static int JimParseExprIrrational(struct JimParserCtx *pc)
- {
- const char *irrationals[] = { "NaN", "nan", "NAN", "Inf", "inf", "INF", NULL };
- int i;
- for (i = 0; irrationals[i]; i++) {
- const char *irr = irrationals[i];
- if (strncmp(irr, pc->p, 3) == 0) {
- pc->p += 3;
- pc->len -= 3;
- pc->tend = pc->p - 1;
- pc->tt = JIM_TT_EXPR_DOUBLE;
- return JIM_OK;
- }
- }
- return JIM_ERR;
- }
- static int JimParseExprBoolean(struct JimParserCtx *pc)
- {
- int i;
- for (i = 0; i < sizeof(jim_true_false_strings) / sizeof(*jim_true_false_strings); i++) {
- if (strncmp(pc->p, jim_true_false_strings[i], jim_true_false_lens[i]) == 0) {
- pc->p += jim_true_false_lens[i];
- pc->len -= jim_true_false_lens[i];
- pc->tend = pc->p - 1;
- pc->tt = JIM_TT_EXPR_BOOLEAN;
- return JIM_OK;
- }
- }
- return JIM_ERR;
- }
- static const struct Jim_ExprOperator *JimExprOperatorInfoByOpcode(int opcode)
- {
- static Jim_ExprOperator dummy_op;
- if (opcode < JIM_TT_EXPR_OP) {
- return &dummy_op;
- }
- return &Jim_ExprOperators[opcode - JIM_TT_EXPR_OP];
- }
- static int JimParseExprOperator(struct JimParserCtx *pc)
- {
- int i;
- const struct Jim_ExprOperator *bestOp = NULL;
- int bestLen = 0;
- for (i = 0; i < (signed)JIM_EXPR_OPERATORS_NUM; i++) {
- const struct Jim_ExprOperator *op = &Jim_ExprOperators[i];
- if (op->name[0] != pc->p[0]) {
- continue;
- }
- if (op->namelen > bestLen && strncmp(op->name, pc->p, op->namelen) == 0) {
- bestOp = op;
- bestLen = op->namelen;
- }
- }
- if (bestOp == NULL) {
- return JIM_ERR;
- }
- if (bestOp->attr & OP_FUNC) {
- const char *p = pc->p + bestLen;
- int len = pc->len - bestLen;
- while (len && isspace(UCHAR(*p))) {
- len--;
- p++;
- }
- if (*p != '(') {
- pc->errmsg = "function requires parentheses";
- return JIM_ERR;
- }
- }
- pc->tend = pc->p + bestLen - 1;
- pc->p += bestLen;
- pc->len -= bestLen;
- pc->tt = (bestOp - Jim_ExprOperators) + JIM_TT_EXPR_OP;
- return JIM_OK;
- }
- static void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
- static void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
- static int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
- static const Jim_ObjType exprObjType = {
- "expression",
- FreeExprInternalRep,
- DupExprInternalRep,
- NULL,
- JIM_TYPE_NONE,
- };
- struct ExprTree
- {
- struct JimExprNode *expr;
- struct JimExprNode *nodes;
- int len;
- int inUse;
- };
- static void ExprTreeFreeNodes(Jim_Interp *interp, struct JimExprNode *nodes, int num)
- {
- int i;
- for (i = 0; i < num; i++) {
- if (nodes[i].objPtr) {
- Jim_DecrRefCount(interp, nodes[i].objPtr);
- }
- }
- Jim_Free(nodes);
- }
- static void ExprTreeFree(Jim_Interp *interp, struct ExprTree *expr)
- {
- ExprTreeFreeNodes(interp, expr->nodes, expr->len);
- Jim_Free(expr);
- }
- static void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- struct ExprTree *expr = (void *)objPtr->internalRep.ptr;
- if (expr) {
- if (--expr->inUse != 0) {
- return;
- }
- ExprTreeFree(interp, expr);
- }
- }
- static void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
- {
- JIM_NOTUSED(interp);
- JIM_NOTUSED(srcPtr);
- dupPtr->typePtr = NULL;
- }
- struct ExprBuilder {
- int parencount;
- int level;
- ParseToken *token;
- ParseToken *first_token;
- Jim_Stack stack;
- Jim_Obj *exprObjPtr;
- Jim_Obj *fileNameObj;
- struct JimExprNode *nodes;
- struct JimExprNode *next;
- };
- #ifdef DEBUG_SHOW_EXPR
- static void JimShowExprNode(struct JimExprNode *node, int level)
- {
- int i;
- for (i = 0; i < level; i++) {
- printf(" ");
- }
- if (TOKEN_IS_EXPR_OP(node->type)) {
- printf("%s\n", jim_tt_name(node->type));
- if (node->left) {
- JimShowExprNode(node->left, level + 1);
- }
- if (node->right) {
- JimShowExprNode(node->right, level + 1);
- }
- if (node->ternary) {
- JimShowExprNode(node->ternary, level + 1);
- }
- }
- else {
- printf("[%s] %s\n", jim_tt_name(node->type), Jim_String(node->objPtr));
- }
- }
- #endif
- #define EXPR_UNTIL_CLOSE 0x0001
- #define EXPR_FUNC_ARGS 0x0002
- #define EXPR_TERNARY 0x0004
- static int ExprTreeBuildTree(Jim_Interp *interp, struct ExprBuilder *builder, int precedence, int flags, int exp_numterms) {
- int rc;
- struct JimExprNode *node;
- int exp_stacklen = builder->stack.len + exp_numterms;
- if (builder->level++ > 200) {
- Jim_SetResultString(interp, "Expression too complex", -1);
- return JIM_ERR;
- }
- while (builder->token->type != JIM_TT_EOL) {
- ParseToken *t = builder->token++;
- int prevtt;
- if (t == builder->first_token) {
- prevtt = JIM_TT_NONE;
- }
- else {
- prevtt = t[-1].type;
- }
- if (t->type == JIM_TT_SUBEXPR_START) {
- if (builder->stack.len == exp_stacklen) {
- Jim_SetResultFormatted(interp, "unexpected open parenthesis in expression: \"%#s\"", builder->exprObjPtr);
- return JIM_ERR;
- }
- builder->parencount++;
- rc = ExprTreeBuildTree(interp, builder, 0, EXPR_UNTIL_CLOSE, 1);
- if (rc != JIM_OK) {
- return rc;
- }
- }
- else if (t->type == JIM_TT_SUBEXPR_END) {
- if (!(flags & EXPR_UNTIL_CLOSE)) {
- if (builder->stack.len == exp_stacklen && builder->level > 1) {
- builder->token--;
- builder->level--;
- return JIM_OK;
- }
- Jim_SetResultFormatted(interp, "unexpected closing parenthesis in expression: \"%#s\"", builder->exprObjPtr);
- return JIM_ERR;
- }
- builder->parencount--;
- if (builder->stack.len == exp_stacklen) {
- break;
- }
- }
- else if (t->type == JIM_TT_SUBEXPR_COMMA) {
- if (!(flags & EXPR_FUNC_ARGS)) {
- if (builder->stack.len == exp_stacklen) {
- builder->token--;
- builder->level--;
- return JIM_OK;
- }
- Jim_SetResultFormatted(interp, "unexpected comma in expression: \"%#s\"", builder->exprObjPtr);
- return JIM_ERR;
- }
- else {
- if (builder->stack.len > exp_stacklen) {
- Jim_SetResultFormatted(interp, "too many arguments to math function");
- return JIM_ERR;
- }
- }
- }
- else if (t->type == JIM_EXPROP_COLON) {
- if (!(flags & EXPR_TERNARY)) {
- if (builder->level != 1) {
- builder->token--;
- builder->level--;
- return JIM_OK;
- }
- Jim_SetResultFormatted(interp, ": without ? in expression: \"%#s\"", builder->exprObjPtr);
- return JIM_ERR;
- }
- if (builder->stack.len == exp_stacklen) {
- builder->token--;
- builder->level--;
- return JIM_OK;
- }
- }
- else if (TOKEN_IS_EXPR_OP(t->type)) {
- const struct Jim_ExprOperator *op;
- if (TOKEN_IS_EXPR_OP(prevtt) || TOKEN_IS_EXPR_START(prevtt)) {
- if (t->type == JIM_EXPROP_SUB) {
- t->type = JIM_EXPROP_UNARYMINUS;
- }
- else if (t->type == JIM_EXPROP_ADD) {
- t->type = JIM_EXPROP_UNARYPLUS;
- }
- }
- op = JimExprOperatorInfoByOpcode(t->type);
- if (op->precedence < precedence || (!(op->attr & OP_RIGHT_ASSOC) && op->precedence == precedence)) {
- builder->token--;
- break;
- }
- if (op->attr & OP_FUNC) {
- if (builder->token->type != JIM_TT_SUBEXPR_START) {
- Jim_SetResultString(interp, "missing arguments for math function", -1);
- return JIM_ERR;
- }
- builder->token++;
- if (op->arity == 0) {
- if (builder->token->type != JIM_TT_SUBEXPR_END) {
- Jim_SetResultString(interp, "too many arguments for math function", -1);
- return JIM_ERR;
- }
- builder->token++;
- goto noargs;
- }
- builder->parencount++;
- rc = ExprTreeBuildTree(interp, builder, 0, EXPR_FUNC_ARGS | EXPR_UNTIL_CLOSE, op->arity);
- }
- else if (t->type == JIM_EXPROP_TERNARY) {
- rc = ExprTreeBuildTree(interp, builder, op->precedence, EXPR_TERNARY, 2);
- }
- else {
- rc = ExprTreeBuildTree(interp, builder, op->precedence, 0, 1);
- }
- if (rc != JIM_OK) {
- return rc;
- }
- noargs:
- node = builder->next++;
- node->type = t->type;
- if (op->arity >= 3) {
- node->ternary = Jim_StackPop(&builder->stack);
- if (node->ternary == NULL) {
- goto missingoperand;
- }
- }
- if (op->arity >= 2) {
- node->right = Jim_StackPop(&builder->stack);
- if (node->right == NULL) {
- goto missingoperand;
- }
- }
- if (op->arity >= 1) {
- node->left = Jim_StackPop(&builder->stack);
- if (node->left == NULL) {
- missingoperand:
- Jim_SetResultFormatted(interp, "missing operand to %s in expression: \"%#s\"", op->name, builder->exprObjPtr);
- builder->next--;
- return JIM_ERR;
- }
- }
- Jim_StackPush(&builder->stack, node);
- }
- else {
- Jim_Obj *objPtr = NULL;
- if (!TOKEN_IS_EXPR_START(prevtt) && !TOKEN_IS_EXPR_OP(prevtt)) {
- Jim_SetResultFormatted(interp, "missing operator in expression: \"%#s\"", builder->exprObjPtr);
- return JIM_ERR;
- }
- if (t->type == JIM_TT_EXPR_INT || t->type == JIM_TT_EXPR_DOUBLE) {
- char *endptr;
- if (t->type == JIM_TT_EXPR_INT) {
- objPtr = Jim_NewIntObj(interp, jim_strtoull(t->token, &endptr));
- }
- else {
- objPtr = Jim_NewDoubleObj(interp, strtod(t->token, &endptr));
- }
- if (endptr != t->token + t->len) {
- Jim_FreeNewObj(interp, objPtr);
- objPtr = NULL;
- }
- }
- if (!objPtr) {
- objPtr = Jim_NewStringObj(interp, t->token, t->len);
- if (t->type == JIM_TT_CMD) {
- Jim_SetSourceInfo(interp, objPtr, builder->fileNameObj, t->line);
- }
- }
- node = builder->next++;
- node->objPtr = objPtr;
- Jim_IncrRefCount(node->objPtr);
- node->type = t->type;
- Jim_StackPush(&builder->stack, node);
- }
- }
- if (builder->stack.len == exp_stacklen) {
- builder->level--;
- return JIM_OK;
- }
- if ((flags & EXPR_FUNC_ARGS)) {
- Jim_SetResultFormatted(interp, "too %s arguments for math function", (builder->stack.len < exp_stacklen) ? "few" : "many");
- }
- else {
- if (builder->stack.len < exp_stacklen) {
- if (builder->level == 0) {
- Jim_SetResultFormatted(interp, "empty expression");
- }
- else {
- Jim_SetResultFormatted(interp, "syntax error in expression \"%#s\": premature end of expression", builder->exprObjPtr);
- }
- }
- else {
- Jim_SetResultFormatted(interp, "extra terms after expression");
- }
- }
- return JIM_ERR;
- }
- static struct ExprTree *ExprTreeCreateTree(Jim_Interp *interp, const ParseTokenList *tokenlist, Jim_Obj *exprObjPtr, Jim_Obj *fileNameObj)
- {
- struct ExprTree *expr;
- struct ExprBuilder builder;
- int rc;
- struct JimExprNode *top = NULL;
- builder.parencount = 0;
- builder.level = 0;
- builder.token = builder.first_token = tokenlist->list;
- builder.exprObjPtr = exprObjPtr;
- builder.fileNameObj = fileNameObj;
- builder.nodes = Jim_Alloc(sizeof(struct JimExprNode) * (tokenlist->count - 1));
- memset(builder.nodes, 0, sizeof(struct JimExprNode) * (tokenlist->count - 1));
- builder.next = builder.nodes;
- Jim_InitStack(&builder.stack);
- rc = ExprTreeBuildTree(interp, &builder, 0, 0, 1);
- if (rc == JIM_OK) {
- top = Jim_StackPop(&builder.stack);
- if (builder.parencount) {
- Jim_SetResultString(interp, "missing close parenthesis", -1);
- rc = JIM_ERR;
- }
- }
- Jim_FreeStack(&builder.stack);
- if (rc != JIM_OK) {
- ExprTreeFreeNodes(interp, builder.nodes, builder.next - builder.nodes);
- return NULL;
- }
- expr = Jim_Alloc(sizeof(*expr));
- expr->inUse = 1;
- expr->expr = top;
- expr->nodes = builder.nodes;
- expr->len = builder.next - builder.nodes;
- assert(expr->len <= tokenlist->count - 1);
- return expr;
- }
- static int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
- {
- int exprTextLen;
- const char *exprText;
- struct JimParserCtx parser;
- struct ExprTree *expr;
- ParseTokenList tokenlist;
- int line;
- Jim_Obj *fileNameObj;
- int rc = JIM_ERR;
- fileNameObj = Jim_GetSourceInfo(interp, objPtr, &line);
- Jim_IncrRefCount(fileNameObj);
- exprText = Jim_GetString(objPtr, &exprTextLen);
- ScriptTokenListInit(&tokenlist);
- JimParserInit(&parser, exprText, exprTextLen, line);
- while (!parser.eof) {
- if (JimParseExpression(&parser) != JIM_OK) {
- ScriptTokenListFree(&tokenlist);
- Jim_SetResultFormatted(interp, "syntax error in expression: \"%#s\"", objPtr);
- if (parser.errmsg) {
- Jim_AppendStrings(interp, Jim_GetResult(interp), ": ", parser.errmsg, NULL);
- }
- expr = NULL;
- goto err;
- }
- ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
- parser.tline);
- }
- #ifdef DEBUG_SHOW_EXPR_TOKENS
- {
- int i;
- printf("==== Expr Tokens (%s) ====\n", Jim_String(fileNameObj));
- for (i = 0; i < tokenlist.count; i++) {
- printf("[%2d]@%d %s '%.*s'\n", i, tokenlist.list[i].line, jim_tt_name(tokenlist.list[i].type),
- tokenlist.list[i].len, tokenlist.list[i].token);
- }
- }
- #endif
- if (tokenlist.count <= 1) {
- Jim_SetResultString(interp, "empty expression", -1);
- rc = JIM_ERR;
- }
- else {
- rc = JimParseCheckMissing(interp, parser.missing.ch);
- }
- if (rc != JIM_OK) {
- ScriptTokenListFree(&tokenlist);
- Jim_DecrRefCount(interp, fileNameObj);
- return rc;
- }
- expr = ExprTreeCreateTree(interp, &tokenlist, objPtr, fileNameObj);
- ScriptTokenListFree(&tokenlist);
- if (!expr) {
- goto err;
- }
- #ifdef DEBUG_SHOW_EXPR
- printf("==== Expr ====\n");
- JimShowExprNode(expr->expr, 0);
- #endif
- rc = JIM_OK;
- err:
- Jim_DecrRefCount(interp, fileNameObj);
- Jim_FreeIntRep(interp, objPtr);
- Jim_SetIntRepPtr(objPtr, expr);
- objPtr->typePtr = &exprObjType;
- return rc;
- }
- static struct ExprTree *JimGetExpression(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- if (objPtr->typePtr != &exprObjType) {
- if (SetExprFromAny(interp, objPtr) != JIM_OK) {
- return NULL;
- }
- }
- return (struct ExprTree *) Jim_GetIntRepPtr(objPtr);
- }
- #ifdef JIM_OPTIMIZATION
- static Jim_Obj *JimExprIntValOrVar(Jim_Interp *interp, struct JimExprNode *node)
- {
- if (node->type == JIM_TT_EXPR_INT)
- return node->objPtr;
- else if (node->type == JIM_TT_VAR)
- return Jim_GetVariable(interp, node->objPtr, JIM_NONE);
- else if (node->type == JIM_TT_DICTSUGAR)
- return JimExpandDictSugar(interp, node->objPtr);
- else
- return NULL;
- }
- #endif
- static int JimExprEvalTermNode(Jim_Interp *interp, struct JimExprNode *node)
- {
- if (TOKEN_IS_EXPR_OP(node->type)) {
- const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(node->type);
- return op->funcop(interp, node);
- }
- else {
- Jim_Obj *objPtr;
- switch (node->type) {
- case JIM_TT_EXPR_INT:
- case JIM_TT_EXPR_DOUBLE:
- case JIM_TT_EXPR_BOOLEAN:
- case JIM_TT_STR:
- Jim_SetResult(interp, node->objPtr);
- return JIM_OK;
- case JIM_TT_VAR:
- objPtr = Jim_GetVariable(interp, node->objPtr, JIM_ERRMSG);
- if (objPtr) {
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- return JIM_ERR;
- case JIM_TT_DICTSUGAR:
- objPtr = JimExpandDictSugar(interp, node->objPtr);
- if (objPtr) {
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- return JIM_ERR;
- case JIM_TT_ESC:
- if (interp->safeexpr) {
- return JIM_ERR;
- }
- if (Jim_SubstObj(interp, node->objPtr, &objPtr, JIM_NONE) == JIM_OK) {
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- return JIM_ERR;
- case JIM_TT_CMD:
- if (interp->safeexpr) {
- return JIM_ERR;
- }
- return Jim_EvalObj(interp, node->objPtr);
- default:
- return JIM_ERR;
- }
- }
- }
- static int JimExprGetTerm(Jim_Interp *interp, struct JimExprNode *node, Jim_Obj **objPtrPtr)
- {
- int rc = JimExprEvalTermNode(interp, node);
- if (rc == JIM_OK) {
- *objPtrPtr = Jim_GetResult(interp);
- Jim_IncrRefCount(*objPtrPtr);
- }
- return rc;
- }
- static int JimExprGetTermBoolean(Jim_Interp *interp, struct JimExprNode *node)
- {
- if (JimExprEvalTermNode(interp, node) == JIM_OK) {
- return ExprBool(interp, Jim_GetResult(interp));
- }
- return -1;
- }
- int Jim_EvalExpression(Jim_Interp *interp, Jim_Obj *exprObjPtr)
- {
- struct ExprTree *expr;
- int retcode = JIM_OK;
- Jim_IncrRefCount(exprObjPtr);
- expr = JimGetExpression(interp, exprObjPtr);
- if (!expr) {
- retcode = JIM_ERR;
- goto done;
- }
- #ifdef JIM_OPTIMIZATION
- if (!interp->safeexpr) {
- Jim_Obj *objPtr;
- switch (expr->len) {
- case 1:
- objPtr = JimExprIntValOrVar(interp, expr->expr);
- if (objPtr) {
- Jim_SetResult(interp, objPtr);
- goto done;
- }
- break;
- case 2:
- if (expr->expr->type == JIM_EXPROP_NOT) {
- objPtr = JimExprIntValOrVar(interp, expr->expr->left);
- if (objPtr && JimIsWide(objPtr)) {
- Jim_SetResult(interp, JimWideValue(objPtr) ? interp->falseObj : interp->trueObj);
- goto done;
- }
- }
- break;
- case 3:
- objPtr = JimExprIntValOrVar(interp, expr->expr->left);
- if (objPtr && JimIsWide(objPtr)) {
- Jim_Obj *objPtr2 = JimExprIntValOrVar(interp, expr->expr->right);
- if (objPtr2 && JimIsWide(objPtr2)) {
- jim_wide wideValueA = JimWideValue(objPtr);
- jim_wide wideValueB = JimWideValue(objPtr2);
- int cmpRes;
- switch (expr->expr->type) {
- case JIM_EXPROP_LT:
- cmpRes = wideValueA < wideValueB;
- break;
- case JIM_EXPROP_LTE:
- cmpRes = wideValueA <= wideValueB;
- break;
- case JIM_EXPROP_GT:
- cmpRes = wideValueA > wideValueB;
- break;
- case JIM_EXPROP_GTE:
- cmpRes = wideValueA >= wideValueB;
- break;
- case JIM_EXPROP_NUMEQ:
- cmpRes = wideValueA == wideValueB;
- break;
- case JIM_EXPROP_NUMNE:
- cmpRes = wideValueA != wideValueB;
- break;
- default:
- goto noopt;
- }
- Jim_SetResult(interp, cmpRes ? interp->trueObj : interp->falseObj);
- goto done;
- }
- }
- break;
- }
- }
- noopt:
- #endif
- expr->inUse++;
- retcode = JimExprEvalTermNode(interp, expr->expr);
- Jim_FreeIntRep(interp, exprObjPtr);
- exprObjPtr->typePtr = &exprObjType;
- Jim_SetIntRepPtr(exprObjPtr, expr);
- done:
- Jim_DecrRefCount(interp, exprObjPtr);
- return retcode;
- }
- int Jim_GetBoolFromExpr(Jim_Interp *interp, Jim_Obj *exprObjPtr, int *boolPtr)
- {
- int retcode = Jim_EvalExpression(interp, exprObjPtr);
- if (retcode == JIM_OK) {
- switch (ExprBool(interp, Jim_GetResult(interp))) {
- case 0:
- *boolPtr = 0;
- break;
- case 1:
- *boolPtr = 1;
- break;
- case -1:
- retcode = JIM_ERR;
- break;
- }
- }
- return retcode;
- }
- typedef struct ScanFmtPartDescr
- {
- const char *arg;
- const char *prefix;
- size_t width;
- int pos;
- char type;
- char modifier;
- } ScanFmtPartDescr;
- typedef struct ScanFmtStringObj
- {
- jim_wide size;
- char *stringRep;
- size_t count;
- size_t convCount;
- size_t maxPos;
- const char *error;
- char *scratch;
- ScanFmtPartDescr descr[1];
- } ScanFmtStringObj;
- static void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
- static void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
- static void UpdateStringOfScanFmt(Jim_Obj *objPtr);
- static const Jim_ObjType scanFmtStringObjType = {
- "scanformatstring",
- FreeScanFmtInternalRep,
- DupScanFmtInternalRep,
- UpdateStringOfScanFmt,
- JIM_TYPE_NONE,
- };
- void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- JIM_NOTUSED(interp);
- Jim_Free((char *)objPtr->internalRep.ptr);
- objPtr->internalRep.ptr = 0;
- }
- void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
- {
- size_t size = (size_t) ((ScanFmtStringObj *) srcPtr->internalRep.ptr)->size;
- ScanFmtStringObj *newVec = (ScanFmtStringObj *) Jim_Alloc(size);
- JIM_NOTUSED(interp);
- memcpy(newVec, srcPtr->internalRep.ptr, size);
- dupPtr->internalRep.ptr = newVec;
- dupPtr->typePtr = &scanFmtStringObjType;
- }
- static void UpdateStringOfScanFmt(Jim_Obj *objPtr)
- {
- JimSetStringBytes(objPtr, ((ScanFmtStringObj *) objPtr->internalRep.ptr)->stringRep);
- }
- static int SetScanFmtFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- ScanFmtStringObj *fmtObj;
- char *buffer;
- int maxCount, i, approxSize, lastPos = -1;
- const char *fmt = Jim_String(objPtr);
- int maxFmtLen = Jim_Length(objPtr);
- const char *fmtEnd = fmt + maxFmtLen;
- int curr;
- Jim_FreeIntRep(interp, objPtr);
- for (i = 0, maxCount = 0; i < maxFmtLen; ++i)
- if (fmt[i] == '%')
- ++maxCount;
- approxSize = sizeof(ScanFmtStringObj)
- +(maxCount + 1) * sizeof(ScanFmtPartDescr)
- +maxFmtLen * sizeof(char) + 3 + 1
- + maxFmtLen * sizeof(char) + 1
- + maxFmtLen * sizeof(char)
- +(maxCount + 1) * sizeof(char)
- +1;
- fmtObj = (ScanFmtStringObj *) Jim_Alloc(approxSize);
- memset(fmtObj, 0, approxSize);
- fmtObj->size = approxSize;
- fmtObj->maxPos = 0;
- fmtObj->scratch = (char *)&fmtObj->descr[maxCount + 1];
- fmtObj->stringRep = fmtObj->scratch + maxFmtLen + 3 + 1;
- memcpy(fmtObj->stringRep, fmt, maxFmtLen);
- buffer = fmtObj->stringRep + maxFmtLen + 1;
- objPtr->internalRep.ptr = fmtObj;
- objPtr->typePtr = &scanFmtStringObjType;
- for (i = 0, curr = 0; fmt < fmtEnd; ++fmt) {
- int width = 0, skip;
- ScanFmtPartDescr *descr = &fmtObj->descr[curr];
- fmtObj->count++;
- descr->width = 0;
- if (*fmt != '%' || fmt[1] == '%') {
- descr->type = 0;
- descr->prefix = &buffer[i];
- for (; fmt < fmtEnd; ++fmt) {
- if (*fmt == '%') {
- if (fmt[1] != '%')
- break;
- ++fmt;
- }
- buffer[i++] = *fmt;
- }
- buffer[i++] = 0;
- }
- ++fmt;
- if (fmt >= fmtEnd)
- goto done;
- descr->pos = 0;
- if (*fmt == '*') {
- descr->pos = -1;
- ++fmt;
- }
- else
- fmtObj->convCount++;
- if (sscanf(fmt, "%d%n", &width, &skip) == 1) {
- fmt += skip;
- if (descr->pos != -1 && *fmt == '$') {
- int prev;
- ++fmt;
- descr->pos = width;
- width = 0;
- if ((lastPos == 0 && descr->pos > 0)
- || (lastPos > 0 && descr->pos == 0)) {
- fmtObj->error = "cannot mix \"%\" and \"%n$\" conversion specifiers";
- return JIM_ERR;
- }
- for (prev = 0; prev < curr; ++prev) {
- if (fmtObj->descr[prev].pos == -1)
- continue;
- if (fmtObj->descr[prev].pos == descr->pos) {
- fmtObj->error =
- "variable is assigned by multiple \"%n$\" conversion specifiers";
- return JIM_ERR;
- }
- }
- if (descr->pos < 0) {
- fmtObj->error =
- "\"%n$\" conversion specifier is negative";
- return JIM_ERR;
- }
- if (sscanf(fmt, "%d%n", &width, &skip) == 1) {
- descr->width = width;
- fmt += skip;
- }
- if (descr->pos > 0 && (size_t) descr->pos > fmtObj->maxPos)
- fmtObj->maxPos = descr->pos;
- }
- else {
- descr->width = width;
- }
- }
- if (lastPos == -1)
- lastPos = descr->pos;
- if (*fmt == '[') {
- int swapped = 1, beg = i, end, j;
- descr->type = '[';
- descr->arg = &buffer[i];
- ++fmt;
- if (*fmt == '^')
- buffer[i++] = *fmt++;
- if (*fmt == ']')
- buffer[i++] = *fmt++;
- while (*fmt && *fmt != ']')
- buffer[i++] = *fmt++;
- if (*fmt != ']') {
- fmtObj->error = "unmatched [ in format string";
- return JIM_ERR;
- }
- end = i;
- buffer[i++] = 0;
- while (swapped) {
- swapped = 0;
- for (j = beg + 1; j < end - 1; ++j) {
- if (buffer[j] == '-' && buffer[j - 1] > buffer[j + 1]) {
- char tmp = buffer[j - 1];
- buffer[j - 1] = buffer[j + 1];
- buffer[j + 1] = tmp;
- swapped = 1;
- }
- }
- }
- }
- else {
- if (fmt < fmtEnd && strchr("hlL", *fmt))
- descr->modifier = tolower((int)*fmt++);
- if (fmt >= fmtEnd) {
- fmtObj->error = "missing scan conversion character";
- return JIM_ERR;
- }
- descr->type = *fmt;
- if (strchr("efgcsndoxui", *fmt) == 0) {
- fmtObj->error = "bad scan conversion character";
- return JIM_ERR;
- }
- else if (*fmt == 'c' && descr->width != 0) {
- fmtObj->error = "field width may not be specified in %c " "conversion";
- return JIM_ERR;
- }
- else if (*fmt == 'u' && descr->modifier == 'l') {
- fmtObj->error = "unsigned wide not supported";
- return JIM_ERR;
- }
- }
- curr++;
- }
- done:
- return JIM_OK;
- }
- #define FormatGetCnvCount(_fo_) \
- ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->convCount
- #define FormatGetMaxPos(_fo_) \
- ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->maxPos
- #define FormatGetError(_fo_) \
- ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->error
- static Jim_Obj *JimScanAString(Jim_Interp *interp, const char *sdescr, const char *str)
- {
- char *buffer = Jim_StrDup(str);
- char *p = buffer;
- while (*str) {
- int c;
- int n;
- if (!sdescr && isspace(UCHAR(*str)))
- break;
- n = utf8_tounicode(str, &c);
- if (sdescr && !JimCharsetMatch(sdescr, strlen(sdescr), c, JIM_CHARSET_SCAN))
- break;
- while (n--)
- *p++ = *str++;
- }
- *p = 0;
- return Jim_NewStringObjNoAlloc(interp, buffer, p - buffer);
- }
- static int ScanOneEntry(Jim_Interp *interp, const char *str, int pos, int str_bytelen,
- ScanFmtStringObj * fmtObj, long idx, Jim_Obj **valObjPtr)
- {
- const char *tok;
- const ScanFmtPartDescr *descr = &fmtObj->descr[idx];
- size_t scanned = 0;
- size_t anchor = pos;
- int i;
- Jim_Obj *tmpObj = NULL;
- *valObjPtr = 0;
- if (descr->prefix) {
- for (i = 0; pos < str_bytelen && descr->prefix[i]; ++i) {
- if (isspace(UCHAR(descr->prefix[i])))
- while (pos < str_bytelen && isspace(UCHAR(str[pos])))
- ++pos;
- else if (descr->prefix[i] != str[pos])
- break;
- else
- ++pos;
- }
- if (pos >= str_bytelen) {
- return -1;
- }
- else if (descr->prefix[i] != 0)
- return 0;
- }
- if (descr->type != 'c' && descr->type != '[' && descr->type != 'n')
- while (isspace(UCHAR(str[pos])))
- ++pos;
- scanned = pos - anchor;
- if (descr->type == 'n') {
- *valObjPtr = Jim_NewIntObj(interp, anchor + scanned);
- }
- else if (pos >= str_bytelen) {
- return -1;
- }
- else if (descr->type == 'c') {
- int c;
- scanned += utf8_tounicode(&str[pos], &c);
- *valObjPtr = Jim_NewIntObj(interp, c);
- return scanned;
- }
- else {
- if (descr->width > 0) {
- size_t sLen = utf8_strlen(&str[pos], str_bytelen - pos);
- size_t tLen = descr->width > sLen ? sLen : descr->width;
- tmpObj = Jim_NewStringObjUtf8(interp, str + pos, tLen);
- tok = tmpObj->bytes;
- }
- else {
- tok = &str[pos];
- }
- switch (descr->type) {
- case 'd':
- case 'o':
- case 'x':
- case 'u':
- case 'i':{
- char *endp;
- jim_wide w;
- int base = descr->type == 'o' ? 8
- : descr->type == 'x' ? 16 : descr->type == 'i' ? 0 : 10;
- if (base == 0) {
- w = jim_strtoull(tok, &endp);
- }
- else {
- w = strtoull(tok, &endp, base);
- }
- if (endp != tok) {
- *valObjPtr = Jim_NewIntObj(interp, w);
- scanned += endp - tok;
- }
- else {
- scanned = *tok ? 0 : -1;
- }
- break;
- }
- case 's':
- case '[':{
- *valObjPtr = JimScanAString(interp, descr->arg, tok);
- scanned += Jim_Length(*valObjPtr);
- break;
- }
- case 'e':
- case 'f':
- case 'g':{
- char *endp;
- double value = strtod(tok, &endp);
- if (endp != tok) {
- *valObjPtr = Jim_NewDoubleObj(interp, value);
- scanned += endp - tok;
- }
- else {
- scanned = *tok ? 0 : -1;
- }
- break;
- }
- }
- if (tmpObj) {
- Jim_FreeNewObj(interp, tmpObj);
- }
- }
- return scanned;
- }
- Jim_Obj *Jim_ScanString(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *fmtObjPtr, int flags)
- {
- size_t i, pos;
- int scanned = 1;
- const char *str = Jim_String(strObjPtr);
- int str_bytelen = Jim_Length(strObjPtr);
- Jim_Obj *resultList = 0;
- Jim_Obj **resultVec = 0;
- int resultc;
- Jim_Obj *emptyStr = 0;
- ScanFmtStringObj *fmtObj;
- JimPanic((fmtObjPtr->typePtr != &scanFmtStringObjType, "Jim_ScanString() for non-scan format"));
- fmtObj = (ScanFmtStringObj *) fmtObjPtr->internalRep.ptr;
- if (fmtObj->error != 0) {
- if (flags & JIM_ERRMSG)
- Jim_SetResultString(interp, fmtObj->error, -1);
- return 0;
- }
- emptyStr = Jim_NewEmptyStringObj(interp);
- Jim_IncrRefCount(emptyStr);
- resultList = Jim_NewListObj(interp, NULL, 0);
- if (fmtObj->maxPos > 0) {
- for (i = 0; i < fmtObj->maxPos; ++i)
- Jim_ListAppendElement(interp, resultList, emptyStr);
- JimListGetElements(interp, resultList, &resultc, &resultVec);
- }
- for (i = 0, pos = 0; i < fmtObj->count; ++i) {
- ScanFmtPartDescr *descr = &(fmtObj->descr[i]);
- Jim_Obj *value = 0;
- if (descr->type == 0)
- continue;
- if (scanned > 0)
- scanned = ScanOneEntry(interp, str, pos, str_bytelen, fmtObj, i, &value);
- if (scanned == -1 && i == 0)
- goto eof;
- pos += scanned;
- if (value == 0)
- value = Jim_NewEmptyStringObj(interp);
- if (descr->pos == -1) {
- Jim_FreeNewObj(interp, value);
- }
- else if (descr->pos == 0)
- Jim_ListAppendElement(interp, resultList, value);
- else if (resultVec[descr->pos - 1] == emptyStr) {
- Jim_DecrRefCount(interp, resultVec[descr->pos - 1]);
- Jim_IncrRefCount(value);
- resultVec[descr->pos - 1] = value;
- }
- else {
- Jim_FreeNewObj(interp, value);
- goto err;
- }
- }
- Jim_DecrRefCount(interp, emptyStr);
- return resultList;
- eof:
- Jim_DecrRefCount(interp, emptyStr);
- Jim_FreeNewObj(interp, resultList);
- return (Jim_Obj *)EOF;
- err:
- Jim_DecrRefCount(interp, emptyStr);
- Jim_FreeNewObj(interp, resultList);
- return 0;
- }
- static void JimPrngInit(Jim_Interp *interp)
- {
- #define PRNG_SEED_SIZE 256
- int i;
- unsigned int *seed;
- time_t t = time(NULL);
- interp->prngState = Jim_Alloc(sizeof(Jim_PrngState));
- seed = Jim_Alloc(PRNG_SEED_SIZE * sizeof(*seed));
- for (i = 0; i < PRNG_SEED_SIZE; i++) {
- seed[i] = (rand() ^ t ^ clock());
- }
- JimPrngSeed(interp, (unsigned char *)seed, PRNG_SEED_SIZE * sizeof(*seed));
- Jim_Free(seed);
- }
- static void JimRandomBytes(Jim_Interp *interp, void *dest, unsigned int len)
- {
- Jim_PrngState *prng;
- unsigned char *destByte = (unsigned char *)dest;
- unsigned int si, sj, x;
- if (interp->prngState == NULL)
- JimPrngInit(interp);
- prng = interp->prngState;
- for (x = 0; x < len; x++) {
- prng->i = (prng->i + 1) & 0xff;
- si = prng->sbox[prng->i];
- prng->j = (prng->j + si) & 0xff;
- sj = prng->sbox[prng->j];
- prng->sbox[prng->i] = sj;
- prng->sbox[prng->j] = si;
- *destByte++ = prng->sbox[(si + sj) & 0xff];
- }
- }
- static void JimPrngSeed(Jim_Interp *interp, unsigned char *seed, int seedLen)
- {
- int i;
- Jim_PrngState *prng;
- if (interp->prngState == NULL)
- JimPrngInit(interp);
- prng = interp->prngState;
- for (i = 0; i < 256; i++)
- prng->sbox[i] = i;
- for (i = 0; i < seedLen; i++) {
- unsigned char t;
- t = prng->sbox[i & 0xFF];
- prng->sbox[i & 0xFF] = prng->sbox[seed[i]];
- prng->sbox[seed[i]] = t;
- }
- prng->i = prng->j = 0;
- for (i = 0; i < 256; i += seedLen) {
- JimRandomBytes(interp, seed, seedLen);
- }
- }
- static int Jim_IncrCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- jim_wide wideValue, increment = 1;
- Jim_Obj *intObjPtr;
- if (argc != 2 && argc != 3) {
- Jim_WrongNumArgs(interp, 1, argv, "varName ?increment?");
- return JIM_ERR;
- }
- if (argc == 3) {
- if (Jim_GetWideExpr(interp, argv[2], &increment) != JIM_OK)
- return JIM_ERR;
- }
- intObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
- if (!intObjPtr) {
- wideValue = 0;
- }
- else if (Jim_GetWide(interp, intObjPtr, &wideValue) != JIM_OK) {
- return JIM_ERR;
- }
- if (!intObjPtr || Jim_IsShared(intObjPtr)) {
- intObjPtr = Jim_NewIntObj(interp, wideValue + increment);
- if (Jim_SetVariable(interp, argv[1], intObjPtr) != JIM_OK) {
- Jim_FreeNewObj(interp, intObjPtr);
- return JIM_ERR;
- }
- }
- else {
- Jim_InvalidateStringRep(intObjPtr);
- JimWideValue(intObjPtr) = wideValue + increment;
- if (argv[1]->typePtr != &variableObjType) {
- Jim_SetVariable(interp, argv[1], intObjPtr);
- }
- }
- Jim_SetResult(interp, intObjPtr);
- return JIM_OK;
- }
- #define JIM_EVAL_SARGV_LEN 8
- #define JIM_EVAL_SINTV_LEN 8
- static int JimTraceCallback(Jim_Interp *interp, const char *type, int argc, Jim_Obj *const *argv)
- {
- JimPanic((interp->traceCmdObj == NULL, "xtrace invoked with no object"));
- int ret;
- Jim_Obj *nargv[7];
- Jim_Obj *traceCmdObj = interp->traceCmdObj;
- Jim_Obj *resultObj = Jim_GetResult(interp);
- ScriptObj *script = NULL;
- if (interp->evalFrame->scriptObj) {
- script = JimGetScript(interp, interp->evalFrame->scriptObj);
- }
- nargv[0] = traceCmdObj;
- nargv[1] = Jim_NewStringObj(interp, type, -1);
- nargv[2] = script ? script->fileNameObj : interp->emptyObj;
- nargv[3] = Jim_NewIntObj(interp, script ? script->linenr : 1);
- nargv[4] = resultObj;
- nargv[5] = argv[0];
- nargv[6] = Jim_NewListObj(interp, argv + 1, argc - 1);
- interp->traceCmdObj = NULL;
- Jim_IncrRefCount(resultObj);
- ret = Jim_EvalObjVector(interp, 7, nargv);
- Jim_DecrRefCount(interp, resultObj);
- if (ret == JIM_OK || ret == JIM_RETURN) {
- interp->traceCmdObj = traceCmdObj;
- Jim_SetEmptyResult(interp);
- ret = JIM_OK;
- }
- else {
- Jim_DecrRefCount(interp, traceCmdObj);
- }
- return ret;
- }
- static int JimUnknown(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int retcode;
- if (interp->unknown_called > 50) {
- return JIM_ERR;
- }
- if (Jim_GetCommand(interp, interp->unknown, JIM_NONE) == NULL)
- return JIM_ERR;
- interp->unknown_called++;
- retcode = Jim_EvalObjPrefix(interp, interp->unknown, argc, argv);
- interp->unknown_called--;
- return retcode;
- }
- static void JimPushEvalFrame(Jim_Interp *interp, Jim_EvalFrame *frame, Jim_Obj *scriptObj)
- {
- memset(frame, 0, sizeof(*frame));
- frame->parent = interp->evalFrame;
- frame->level = frame->parent->level + 1;
- frame->procLevel = interp->procLevel;
- frame->framePtr = interp->framePtr;
- if (scriptObj) {
- frame->scriptObj = scriptObj;
- }
- else {
- frame->scriptObj = frame->parent->scriptObj;
- }
- interp->evalFrame = frame;
- #if 0
- if (frame->scriptObj) {
- printf("script: %.*s\n", 20, Jim_String(frame->scriptObj));
- }
- #endif
- }
- static void JimPopEvalFrame(Jim_Interp *interp)
- {
- interp->evalFrame = interp->evalFrame->parent;
- }
- static int JimInvokeCommand(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
- {
- int retcode;
- Jim_Cmd *cmdPtr;
- void *prevPrivData;
- Jim_Obj *tailcallObj = NULL;
- #if 0
- printf("invoke");
- int j;
- for (j = 0; j < objc; j++) {
- printf(" '%s'", Jim_String(objv[j]));
- }
- printf("\n");
- #endif
- cmdPtr = Jim_GetCommand(interp, objv[0], JIM_ERRMSG);
- if (cmdPtr == NULL) {
- return JimUnknown(interp, objc, objv);
- }
- JimIncrCmdRefCount(cmdPtr);
- if (interp->evalDepth == interp->maxEvalDepth) {
- Jim_SetResultString(interp, "Infinite eval recursion", -1);
- retcode = JIM_ERR;
- goto out;
- }
- interp->evalDepth++;
- prevPrivData = interp->cmdPrivData;
- tailcall:
- interp->evalFrame->argc = objc;
- interp->evalFrame->argv = objv;
- interp->evalFrame->cmd = cmdPtr;
- if (!interp->traceCmdObj ||
- (retcode = JimTraceCallback(interp, "cmd", objc, objv)) == JIM_OK) {
- Jim_SetEmptyResult(interp);
- if (cmdPtr->isproc) {
- retcode = JimCallProcedure(interp, cmdPtr, objc, objv);
- }
- else {
- interp->cmdPrivData = cmdPtr->u.native.privData;
- retcode = cmdPtr->u.native.cmdProc(interp, objc, objv);
- }
- if (retcode == JIM_ERR) {
- JimSetErrorStack(interp, NULL);
- }
- }
- if (tailcallObj) {
- Jim_DecrRefCount(interp, tailcallObj);
- tailcallObj = NULL;
- }
- interp->evalFrame->argc = 0;
- interp->evalFrame->argv = NULL;
- if (retcode == JIM_EVAL && interp->framePtr->tailcallObj) {
- JimDecrCmdRefCount(interp, cmdPtr);
- cmdPtr = interp->framePtr->tailcallCmd;
- interp->framePtr->tailcallCmd = NULL;
- tailcallObj = interp->framePtr->tailcallObj;
- interp->framePtr->tailcallObj = NULL;
- objc = tailcallObj->internalRep.listValue.len;
- objv = tailcallObj->internalRep.listValue.ele;
- goto tailcall;
- }
- interp->cmdPrivData = prevPrivData;
- interp->evalDepth--;
- out:
- JimDecrCmdRefCount(interp, cmdPtr);
- if (retcode == JIM_ERR) {
- JimSetErrorStack(interp, NULL);
- }
- if (interp->framePtr->tailcallObj) {
- JimDecrCmdRefCount(interp, interp->framePtr->tailcallCmd);
- Jim_DecrRefCount(interp, interp->framePtr->tailcallObj);
- interp->framePtr->tailcallCmd = NULL;
- interp->framePtr->tailcallObj = NULL;
- }
- return retcode;
- }
- int Jim_EvalObjVector(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
- {
- int i, retcode;
- Jim_EvalFrame frame;
- for (i = 0; i < objc; i++)
- Jim_IncrRefCount(objv[i]);
- JimPushEvalFrame(interp, &frame, NULL);
- retcode = JimInvokeCommand(interp, objc, objv);
- JimPopEvalFrame(interp);
- for (i = 0; i < objc; i++)
- Jim_DecrRefCount(interp, objv[i]);
- return retcode;
- }
- int Jim_EvalObjPrefix(Jim_Interp *interp, Jim_Obj *prefix, int objc, Jim_Obj *const *objv)
- {
- int ret;
- Jim_Obj **nargv = Jim_Alloc((objc + 1) * sizeof(*nargv));
- nargv[0] = prefix;
- memcpy(&nargv[1], &objv[0], sizeof(nargv[0]) * objc);
- ret = Jim_EvalObjVector(interp, objc + 1, nargv);
- Jim_Free(nargv);
- return ret;
- }
- static int JimSubstOneToken(Jim_Interp *interp, const ScriptToken *token, Jim_Obj **objPtrPtr)
- {
- Jim_Obj *objPtr;
- int ret = JIM_ERR;
- switch (token->type) {
- case JIM_TT_STR:
- case JIM_TT_ESC:
- objPtr = token->objPtr;
- break;
- case JIM_TT_VAR:
- objPtr = Jim_GetVariable(interp, token->objPtr, JIM_ERRMSG);
- break;
- case JIM_TT_DICTSUGAR:
- objPtr = JimExpandDictSugar(interp, token->objPtr);
- break;
- case JIM_TT_EXPRSUGAR:
- ret = Jim_EvalExpression(interp, token->objPtr);
- if (ret == JIM_OK) {
- objPtr = Jim_GetResult(interp);
- }
- else {
- objPtr = NULL;
- }
- break;
- case JIM_TT_CMD:
- ret = Jim_EvalObj(interp, token->objPtr);
- if (ret == JIM_OK || ret == JIM_RETURN) {
- objPtr = interp->result;
- } else {
- objPtr = NULL;
- }
- break;
- default:
- JimPanic((1,
- "default token type (%d) reached " "in Jim_SubstObj().", token->type));
- objPtr = NULL;
- break;
- }
- if (objPtr) {
- *objPtrPtr = objPtr;
- return JIM_OK;
- }
- return ret;
- }
- static Jim_Obj *JimInterpolateTokens(Jim_Interp *interp, const ScriptToken * token, int tokens, int flags)
- {
- int totlen = 0, i;
- Jim_Obj **intv;
- Jim_Obj *sintv[JIM_EVAL_SINTV_LEN];
- Jim_Obj *objPtr;
- char *s;
- if (tokens <= JIM_EVAL_SINTV_LEN)
- intv = sintv;
- else
- intv = Jim_Alloc(sizeof(Jim_Obj *) * tokens);
- for (i = 0; i < tokens; i++) {
- switch (JimSubstOneToken(interp, &token[i], &intv[i])) {
- case JIM_OK:
- case JIM_RETURN:
- break;
- case JIM_BREAK:
- if (flags & JIM_SUBST_FLAG) {
- tokens = i;
- continue;
- }
- case JIM_CONTINUE:
- if (flags & JIM_SUBST_FLAG) {
- intv[i] = NULL;
- continue;
- }
- default:
- while (i--) {
- Jim_DecrRefCount(interp, intv[i]);
- }
- if (intv != sintv) {
- Jim_Free(intv);
- }
- return NULL;
- }
- Jim_IncrRefCount(intv[i]);
- Jim_String(intv[i]);
- totlen += intv[i]->length;
- }
- if (tokens == 1 && intv[0] && intv == sintv) {
- intv[0]->refCount--;
- return intv[0];
- }
- objPtr = Jim_NewStringObjNoAlloc(interp, NULL, 0);
- if (tokens == 4 && token[0].type == JIM_TT_ESC && token[1].type == JIM_TT_ESC
- && token[2].type == JIM_TT_VAR) {
- objPtr->typePtr = &interpolatedObjType;
- objPtr->internalRep.dictSubstValue.varNameObjPtr = token[0].objPtr;
- objPtr->internalRep.dictSubstValue.indexObjPtr = intv[2];
- Jim_IncrRefCount(intv[2]);
- }
- else if (tokens && intv[0] && intv[0]->typePtr == &sourceObjType) {
- int line;
- Jim_Obj *fileNameObj = Jim_GetSourceInfo(interp, intv[0], &line);
- Jim_SetSourceInfo(interp, objPtr, fileNameObj, line);
- }
- s = objPtr->bytes = Jim_Alloc(totlen + 1);
- objPtr->length = totlen;
- for (i = 0; i < tokens; i++) {
- if (intv[i]) {
- memcpy(s, intv[i]->bytes, intv[i]->length);
- s += intv[i]->length;
- Jim_DecrRefCount(interp, intv[i]);
- }
- }
- objPtr->bytes[totlen] = '\0';
- if (intv != sintv) {
- Jim_Free(intv);
- }
- return objPtr;
- }
- static int JimEvalObjList(Jim_Interp *interp, Jim_Obj *listPtr)
- {
- int retcode = JIM_OK;
- Jim_EvalFrame frame;
- JimPanic((Jim_IsList(listPtr) == 0, "JimEvalObjList() invoked on non-list."));
- JimPushEvalFrame(interp, &frame, NULL);
- if (listPtr->internalRep.listValue.len) {
- Jim_IncrRefCount(listPtr);
- retcode = JimInvokeCommand(interp,
- listPtr->internalRep.listValue.len,
- listPtr->internalRep.listValue.ele);
- Jim_DecrRefCount(interp, listPtr);
- }
- JimPopEvalFrame(interp);
- return retcode;
- }
- int Jim_EvalObjList(Jim_Interp *interp, Jim_Obj *listPtr)
- {
- SetListFromAny(interp, listPtr);
- return JimEvalObjList(interp, listPtr);
- }
- int Jim_EvalObj(Jim_Interp *interp, Jim_Obj *scriptObjPtr)
- {
- int i;
- ScriptObj *script;
- ScriptToken *token;
- int retcode = JIM_OK;
- Jim_Obj *sargv[JIM_EVAL_SARGV_LEN], **argv = NULL;
- Jim_EvalFrame frame;
- if (Jim_IsList(scriptObjPtr) && scriptObjPtr->bytes == NULL) {
- return JimEvalObjList(interp, scriptObjPtr);
- }
- Jim_IncrRefCount(scriptObjPtr);
- script = JimGetScript(interp, scriptObjPtr);
- if (JimParseCheckMissing(interp, script->missing) == JIM_ERR) {
- JimSetErrorStack(interp, script);
- Jim_DecrRefCount(interp, scriptObjPtr);
- return JIM_ERR;
- }
- Jim_SetEmptyResult(interp);
- token = script->token;
- #ifdef JIM_OPTIMIZATION
- if (script->len == 0) {
- Jim_DecrRefCount(interp, scriptObjPtr);
- return JIM_OK;
- }
- if (script->len == 3
- && token[1].objPtr->typePtr == &commandObjType
- && token[1].objPtr->internalRep.cmdValue.cmdPtr->isproc == 0
- && token[1].objPtr->internalRep.cmdValue.cmdPtr->u.native.cmdProc == Jim_IncrCoreCommand
- && token[2].objPtr->typePtr == &variableObjType) {
- Jim_Obj *objPtr = Jim_GetVariable(interp, token[2].objPtr, JIM_NONE);
- if (objPtr && !Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
- JimWideValue(objPtr)++;
- Jim_InvalidateStringRep(objPtr);
- Jim_DecrRefCount(interp, scriptObjPtr);
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- }
- #endif
- script->inUse++;
- JimPushEvalFrame(interp, &frame, scriptObjPtr);
- interp->errorFlag = 0;
- argv = sargv;
- for (i = 0; i < script->len && retcode == JIM_OK; ) {
- int argc;
- int j;
- argc = token[i].objPtr->internalRep.scriptLineValue.argc;
- script->linenr = token[i].objPtr->internalRep.scriptLineValue.line;
- if (argc > JIM_EVAL_SARGV_LEN)
- argv = Jim_Alloc(sizeof(Jim_Obj *) * argc);
- i++;
- for (j = 0; j < argc; j++) {
- long wordtokens = 1;
- int expand = 0;
- Jim_Obj *wordObjPtr = NULL;
- if (token[i].type == JIM_TT_WORD) {
- wordtokens = JimWideValue(token[i++].objPtr);
- if (wordtokens < 0) {
- expand = 1;
- wordtokens = -wordtokens;
- }
- }
- if (wordtokens == 1) {
- switch (token[i].type) {
- case JIM_TT_ESC:
- case JIM_TT_STR:
- wordObjPtr = token[i].objPtr;
- break;
- case JIM_TT_VAR:
- wordObjPtr = Jim_GetVariable(interp, token[i].objPtr, JIM_ERRMSG);
- break;
- case JIM_TT_EXPRSUGAR:
- retcode = Jim_EvalExpression(interp, token[i].objPtr);
- if (retcode == JIM_OK) {
- wordObjPtr = Jim_GetResult(interp);
- }
- else {
- wordObjPtr = NULL;
- }
- break;
- case JIM_TT_DICTSUGAR:
- wordObjPtr = JimExpandDictSugar(interp, token[i].objPtr);
- break;
- case JIM_TT_CMD:
- retcode = Jim_EvalObj(interp, token[i].objPtr);
- if (retcode == JIM_OK) {
- wordObjPtr = Jim_GetResult(interp);
- }
- break;
- default:
- JimPanic((1, "default token type reached " "in Jim_EvalObj()."));
- }
- }
- else {
- wordObjPtr = JimInterpolateTokens(interp, token + i, wordtokens, JIM_NONE);
- }
- if (!wordObjPtr) {
- if (retcode == JIM_OK) {
- retcode = JIM_ERR;
- }
- break;
- }
- Jim_IncrRefCount(wordObjPtr);
- i += wordtokens;
- if (!expand) {
- argv[j] = wordObjPtr;
- }
- else {
- int len = Jim_ListLength(interp, wordObjPtr);
- int newargc = argc + len - 1;
- int k;
- if (len > 1) {
- if (argv == sargv) {
- if (newargc > JIM_EVAL_SARGV_LEN) {
- argv = Jim_Alloc(sizeof(*argv) * newargc);
- memcpy(argv, sargv, sizeof(*argv) * j);
- }
- }
- else {
- argv = Jim_Realloc(argv, sizeof(*argv) * newargc);
- }
- }
- for (k = 0; k < len; k++) {
- argv[j++] = wordObjPtr->internalRep.listValue.ele[k];
- Jim_IncrRefCount(wordObjPtr->internalRep.listValue.ele[k]);
- }
- Jim_DecrRefCount(interp, wordObjPtr);
- j--;
- argc += len - 1;
- }
- }
- if (retcode == JIM_OK && argc) {
- retcode = JimInvokeCommand(interp, argc, argv);
- if (Jim_CheckSignal(interp)) {
- retcode = JIM_SIGNAL;
- }
- }
- while (j-- > 0) {
- Jim_DecrRefCount(interp, argv[j]);
- }
- if (argv != sargv) {
- Jim_Free(argv);
- argv = sargv;
- }
- }
- if (retcode == JIM_ERR) {
- JimSetErrorStack(interp, NULL);
- }
- JimPopEvalFrame(interp);
- Jim_FreeIntRep(interp, scriptObjPtr);
- scriptObjPtr->typePtr = &scriptObjType;
- Jim_SetIntRepPtr(scriptObjPtr, script);
- Jim_DecrRefCount(interp, scriptObjPtr);
- return retcode;
- }
- static int JimSetProcArg(Jim_Interp *interp, Jim_Obj *argNameObj, Jim_Obj *argValObj)
- {
- int retcode;
- const char *varname = Jim_String(argNameObj);
- if (*varname == '&') {
- Jim_Obj *objPtr;
- Jim_CallFrame *savedCallFrame = interp->framePtr;
- interp->framePtr = interp->framePtr->parent;
- objPtr = Jim_GetVariable(interp, argValObj, JIM_ERRMSG);
- interp->framePtr = savedCallFrame;
- if (!objPtr) {
- return JIM_ERR;
- }
- objPtr = Jim_NewStringObj(interp, varname + 1, -1);
- Jim_IncrRefCount(objPtr);
- retcode = Jim_SetVariableLink(interp, objPtr, argValObj, interp->framePtr->parent);
- Jim_DecrRefCount(interp, objPtr);
- }
- else {
- retcode = Jim_SetVariable(interp, argNameObj, argValObj);
- }
- return retcode;
- }
- static void JimSetProcWrongArgs(Jim_Interp *interp, Jim_Obj *procNameObj, Jim_Cmd *cmd)
- {
- Jim_Obj *argmsg = Jim_NewStringObj(interp, "", 0);
- int i;
- for (i = 0; i < cmd->u.proc.argListLen; i++) {
- Jim_AppendString(interp, argmsg, " ", 1);
- if (i == cmd->u.proc.argsPos) {
- if (cmd->u.proc.arglist[i].defaultObjPtr) {
- Jim_AppendString(interp, argmsg, "?", 1);
- Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].defaultObjPtr);
- Jim_AppendString(interp, argmsg, " ...?", -1);
- }
- else {
- Jim_AppendString(interp, argmsg, "?arg ...?", -1);
- }
- }
- else {
- if (cmd->u.proc.arglist[i].defaultObjPtr) {
- Jim_AppendString(interp, argmsg, "?", 1);
- Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].nameObjPtr);
- Jim_AppendString(interp, argmsg, "?", 1);
- }
- else {
- const char *arg = Jim_String(cmd->u.proc.arglist[i].nameObjPtr);
- if (*arg == '&') {
- arg++;
- }
- Jim_AppendString(interp, argmsg, arg, -1);
- }
- }
- }
- Jim_SetResultFormatted(interp, "wrong # args: should be \"%#s%#s\"", procNameObj, argmsg);
- }
- #ifdef jim_ext_namespace
- int Jim_EvalNamespace(Jim_Interp *interp, Jim_Obj *scriptObj, Jim_Obj *nsObj)
- {
- Jim_CallFrame *callFramePtr;
- int retcode;
- callFramePtr = JimCreateCallFrame(interp, interp->framePtr, nsObj);
- callFramePtr->argv = interp->evalFrame->argv;
- callFramePtr->argc = interp->evalFrame->argc;
- callFramePtr->procArgsObjPtr = NULL;
- callFramePtr->procBodyObjPtr = scriptObj;
- callFramePtr->staticVars = NULL;
- Jim_IncrRefCount(scriptObj);
- interp->framePtr = callFramePtr;
- if (interp->framePtr->level == interp->maxCallFrameDepth) {
- Jim_SetResultString(interp, "Too many nested calls. Infinite recursion?", -1);
- retcode = JIM_ERR;
- }
- else {
- retcode = Jim_EvalObj(interp, scriptObj);
- }
- interp->framePtr = interp->framePtr->parent;
- JimFreeCallFrame(interp, callFramePtr, JIM_FCF_REUSE);
- return retcode;
- }
- #endif
- static int JimCallProcedure(Jim_Interp *interp, Jim_Cmd *cmd, int argc, Jim_Obj *const *argv)
- {
- Jim_CallFrame *callFramePtr;
- int i, d, retcode, optargs;
- if (argc - 1 < cmd->u.proc.reqArity ||
- (cmd->u.proc.argsPos < 0 && argc - 1 > cmd->u.proc.reqArity + cmd->u.proc.optArity)) {
- JimSetProcWrongArgs(interp, argv[0], cmd);
- return JIM_ERR;
- }
- if (Jim_Length(cmd->u.proc.bodyObjPtr) == 0) {
- return JIM_OK;
- }
- if (interp->framePtr->level == interp->maxCallFrameDepth) {
- Jim_SetResultString(interp, "Too many nested calls. Infinite recursion?", -1);
- return JIM_ERR;
- }
- callFramePtr = JimCreateCallFrame(interp, interp->framePtr, cmd->u.proc.nsObj);
- callFramePtr->argv = argv;
- callFramePtr->argc = argc;
- callFramePtr->procArgsObjPtr = cmd->u.proc.argListObjPtr;
- callFramePtr->procBodyObjPtr = cmd->u.proc.bodyObjPtr;
- callFramePtr->staticVars = cmd->u.proc.staticVars;
- interp->procLevel++;
- Jim_IncrRefCount(cmd->u.proc.argListObjPtr);
- Jim_IncrRefCount(cmd->u.proc.bodyObjPtr);
- interp->framePtr = callFramePtr;
- optargs = (argc - 1 - cmd->u.proc.reqArity);
- i = 1;
- for (d = 0; d < cmd->u.proc.argListLen; d++) {
- Jim_Obj *nameObjPtr = cmd->u.proc.arglist[d].nameObjPtr;
- if (d == cmd->u.proc.argsPos) {
- Jim_Obj *listObjPtr;
- int argsLen = 0;
- if (cmd->u.proc.reqArity + cmd->u.proc.optArity < argc - 1) {
- argsLen = argc - 1 - (cmd->u.proc.reqArity + cmd->u.proc.optArity);
- }
- listObjPtr = Jim_NewListObj(interp, &argv[i], argsLen);
- if (cmd->u.proc.arglist[d].defaultObjPtr) {
- nameObjPtr =cmd->u.proc.arglist[d].defaultObjPtr;
- }
- retcode = Jim_SetVariable(interp, nameObjPtr, listObjPtr);
- if (retcode != JIM_OK) {
- goto badargset;
- }
- i += argsLen;
- continue;
- }
- if (cmd->u.proc.arglist[d].defaultObjPtr == NULL || optargs-- > 0) {
- retcode = JimSetProcArg(interp, nameObjPtr, argv[i++]);
- }
- else {
- retcode = Jim_SetVariable(interp, nameObjPtr, cmd->u.proc.arglist[d].defaultObjPtr);
- }
- if (retcode != JIM_OK) {
- goto badargset;
- }
- }
- if (interp->traceCmdObj == NULL ||
- (retcode = JimTraceCallback(interp, "proc", argc, argv)) == JIM_OK) {
- retcode = Jim_EvalObj(interp, cmd->u.proc.bodyObjPtr);
- }
- badargset:
- retcode = JimInvokeDefer(interp, retcode);
- interp->framePtr = interp->framePtr->parent;
- JimFreeCallFrame(interp, callFramePtr, JIM_FCF_REUSE);
- if (retcode == JIM_RETURN) {
- if (--interp->returnLevel <= 0) {
- retcode = interp->returnCode;
- interp->returnCode = JIM_OK;
- interp->returnLevel = 0;
- }
- }
- interp->procLevel--;
- return retcode;
- }
- int Jim_EvalSource(Jim_Interp *interp, const char *filename, int lineno, const char *script)
- {
- int retval;
- Jim_Obj *scriptObjPtr;
- scriptObjPtr = Jim_NewStringObj(interp, script, -1);
- Jim_IncrRefCount(scriptObjPtr);
- if (filename) {
- Jim_SetSourceInfo(interp, scriptObjPtr, Jim_NewStringObj(interp, filename, -1), lineno);
- }
- retval = Jim_EvalObj(interp, scriptObjPtr);
- Jim_DecrRefCount(interp, scriptObjPtr);
- return retval;
- }
- int Jim_Eval(Jim_Interp *interp, const char *script)
- {
- return Jim_EvalObj(interp, Jim_NewStringObj(interp, script, -1));
- }
- int Jim_EvalGlobal(Jim_Interp *interp, const char *script)
- {
- int retval;
- Jim_CallFrame *savedFramePtr = interp->framePtr;
- interp->framePtr = interp->topFramePtr;
- retval = Jim_Eval(interp, script);
- interp->framePtr = savedFramePtr;
- return retval;
- }
- int Jim_EvalFileGlobal(Jim_Interp *interp, const char *filename)
- {
- int retval;
- Jim_CallFrame *savedFramePtr = interp->framePtr;
- interp->framePtr = interp->topFramePtr;
- retval = Jim_EvalFile(interp, filename);
- interp->framePtr = savedFramePtr;
- return retval;
- }
- #include <sys/stat.h>
- static Jim_Obj *JimReadTextFile(Jim_Interp *interp, const char *filename)
- {
- jim_stat_t sb;
- int fd;
- char *buf;
- int readlen;
- if (Jim_Stat(filename, &sb) == -1 || (fd = open(filename, O_RDONLY | O_TEXT, 0666)) < 0) {
- Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", filename, strerror(errno));
- return NULL;
- }
- buf = Jim_Alloc(sb.st_size + 1);
- readlen = read(fd, buf, sb.st_size);
- close(fd);
- if (readlen < 0) {
- Jim_Free(buf);
- Jim_SetResultFormatted(interp, "failed to load file \"%s\": %s", filename, strerror(errno));
- return NULL;
- }
- else {
- Jim_Obj *objPtr;
- buf[readlen] = 0;
- objPtr = Jim_NewStringObjNoAlloc(interp, buf, readlen);
- return objPtr;
- }
- }
- int Jim_EvalFile(Jim_Interp *interp, const char *filename)
- {
- Jim_Obj *filenameObj;
- Jim_Obj *oldFilenameObj;
- Jim_Obj *scriptObjPtr;
- int retcode;
- scriptObjPtr = JimReadTextFile(interp, filename);
- if (!scriptObjPtr) {
- return JIM_ERR;
- }
- filenameObj = Jim_NewStringObj(interp, filename, -1);
- Jim_SetSourceInfo(interp, scriptObjPtr, filenameObj, 1);
- oldFilenameObj = JimPushInterpObj(interp->currentFilenameObj, filenameObj);
- retcode = Jim_EvalObj(interp, scriptObjPtr);
- JimPopInterpObj(interp, interp->currentFilenameObj, oldFilenameObj);
- if (retcode == JIM_RETURN) {
- if (--interp->returnLevel <= 0) {
- retcode = interp->returnCode;
- interp->returnCode = JIM_OK;
- interp->returnLevel = 0;
- }
- }
- return retcode;
- }
- static void JimParseSubst(struct JimParserCtx *pc, int flags)
- {
- pc->tstart = pc->p;
- pc->tline = pc->linenr;
- if (pc->len == 0) {
- pc->tend = pc->p;
- pc->tt = JIM_TT_EOL;
- pc->eof = 1;
- return;
- }
- if (*pc->p == '[' && !(flags & JIM_SUBST_NOCMD)) {
- JimParseCmd(pc);
- return;
- }
- if (*pc->p == '$' && !(flags & JIM_SUBST_NOVAR)) {
- if (JimParseVar(pc) == JIM_OK) {
- return;
- }
- pc->tstart = pc->p;
- pc->p++;
- pc->len--;
- }
- while (pc->len) {
- if (*pc->p == '$' && !(flags & JIM_SUBST_NOVAR)) {
- break;
- }
- if (*pc->p == '[' && !(flags & JIM_SUBST_NOCMD)) {
- break;
- }
- if (*pc->p == '\\' && pc->len > 1) {
- pc->p++;
- pc->len--;
- }
- pc->p++;
- pc->len--;
- }
- pc->tend = pc->p - 1;
- pc->tt = (flags & JIM_SUBST_NOESC) ? JIM_TT_STR : JIM_TT_ESC;
- }
- static int SetSubstFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr, int flags)
- {
- int scriptTextLen;
- const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);
- struct JimParserCtx parser;
- struct ScriptObj *script = Jim_Alloc(sizeof(*script));
- ParseTokenList tokenlist;
- ScriptTokenListInit(&tokenlist);
- JimParserInit(&parser, scriptText, scriptTextLen, 1);
- while (1) {
- JimParseSubst(&parser, flags);
- if (parser.eof) {
- break;
- }
- ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
- parser.tline);
- }
- script->inUse = 1;
- script->substFlags = flags;
- script->fileNameObj = interp->emptyObj;
- Jim_IncrRefCount(script->fileNameObj);
- SubstObjAddTokens(interp, script, &tokenlist);
- ScriptTokenListFree(&tokenlist);
- #ifdef DEBUG_SHOW_SUBST
- {
- int i;
- printf("==== Subst ====\n");
- for (i = 0; i < script->len; i++) {
- printf("[%2d] %s '%s'\n", i, jim_tt_name(script->token[i].type),
- Jim_String(script->token[i].objPtr));
- }
- }
- #endif
- Jim_FreeIntRep(interp, objPtr);
- Jim_SetIntRepPtr(objPtr, script);
- objPtr->typePtr = &scriptObjType;
- return JIM_OK;
- }
- static ScriptObj *Jim_GetSubst(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
- {
- if (objPtr->typePtr != &scriptObjType || ((ScriptObj *)Jim_GetIntRepPtr(objPtr))->substFlags != flags)
- SetSubstFromAny(interp, objPtr, flags);
- return (ScriptObj *) Jim_GetIntRepPtr(objPtr);
- }
- int Jim_SubstObj(Jim_Interp *interp, Jim_Obj *substObjPtr, Jim_Obj **resObjPtrPtr, int flags)
- {
- ScriptObj *script;
- JimPanic((substObjPtr->refCount == 0, "Jim_SubstObj() called with zero refcount object"));
- script = Jim_GetSubst(interp, substObjPtr, flags);
- Jim_IncrRefCount(substObjPtr);
- script->inUse++;
- *resObjPtrPtr = JimInterpolateTokens(interp, script->token, script->len, flags);
- script->inUse--;
- Jim_DecrRefCount(interp, substObjPtr);
- if (*resObjPtrPtr == NULL) {
- return JIM_ERR;
- }
- return JIM_OK;
- }
- void Jim_WrongNumArgs(Jim_Interp *interp, int argc, Jim_Obj *const *argv, const char *msg)
- {
- Jim_Obj *objPtr;
- Jim_Obj *listObjPtr;
- JimPanic((argc == 0, "Jim_WrongNumArgs() called with argc=0"));
- listObjPtr = Jim_NewListObj(interp, argv, argc);
- if (msg && *msg) {
- Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, msg, -1));
- }
- Jim_IncrRefCount(listObjPtr);
- objPtr = Jim_ListJoin(interp, listObjPtr, " ", 1);
- Jim_DecrRefCount(interp, listObjPtr);
- Jim_SetResultFormatted(interp, "wrong # args: should be \"%#s\"", objPtr);
- }
- typedef void JimHashtableIteratorCallbackType(Jim_Interp *interp, Jim_Obj *listObjPtr,
- Jim_Obj *keyObjPtr, void *value, Jim_Obj *patternObjPtr, int type);
- #define JimTrivialMatch(pattern) (strpbrk((pattern), "*[?\\") == NULL)
- static Jim_Obj *JimHashtablePatternMatch(Jim_Interp *interp, Jim_HashTable *ht, Jim_Obj *patternObjPtr,
- JimHashtableIteratorCallbackType *callback, int type)
- {
- Jim_HashEntry *he;
- Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
- if (patternObjPtr && JimTrivialMatch(Jim_String(patternObjPtr))) {
- he = Jim_FindHashEntry(ht, patternObjPtr);
- if (he) {
- callback(interp, listObjPtr, Jim_GetHashEntryKey(he), Jim_GetHashEntryVal(he),
- patternObjPtr, type);
- }
- }
- else {
- Jim_HashTableIterator htiter;
- JimInitHashTableIterator(ht, &htiter);
- while ((he = Jim_NextHashEntry(&htiter)) != NULL) {
- callback(interp, listObjPtr, Jim_GetHashEntryKey(he), Jim_GetHashEntryVal(he),
- patternObjPtr, type);
- }
- }
- return listObjPtr;
- }
- #define JIM_CMDLIST_COMMANDS 0
- #define JIM_CMDLIST_PROCS 1
- #define JIM_CMDLIST_CHANNELS 2
- static void JimCommandMatch(Jim_Interp *interp, Jim_Obj *listObjPtr,
- Jim_Obj *keyObj, void *value, Jim_Obj *patternObj, int type)
- {
- Jim_Cmd *cmdPtr = (Jim_Cmd *)value;
- if (type == JIM_CMDLIST_PROCS && !cmdPtr->isproc) {
- return;
- }
- Jim_IncrRefCount(keyObj);
- if (type != JIM_CMDLIST_CHANNELS || Jim_AioFilehandle(interp, keyObj) >= 0) {
- int match = 1;
- if (patternObj) {
- int plen, slen;
- const char *pattern = Jim_GetStringNoQualifier(patternObj, &plen);
- const char *str = Jim_GetStringNoQualifier(keyObj, &slen);
- #ifdef JIM_NO_INTROSPECTION
- match = (JimStringCompareUtf8(pattern, plen, str, slen, 0) == 0);
- #else
- match = JimGlobMatch(pattern, plen, str, slen, 0);
- #endif
- }
- if (match) {
- Jim_ListAppendElement(interp, listObjPtr, keyObj);
- }
- }
- Jim_DecrRefCount(interp, keyObj);
- }
- static Jim_Obj *JimCommandsList(Jim_Interp *interp, Jim_Obj *patternObjPtr, int type)
- {
- return JimHashtablePatternMatch(interp, &interp->commands, patternObjPtr, JimCommandMatch, type);
- }
- #define JIM_VARLIST_GLOBALS 0
- #define JIM_VARLIST_LOCALS 1
- #define JIM_VARLIST_VARS 2
- #define JIM_VARLIST_MASK 0x000f
- #define JIM_VARLIST_VALUES 0x1000
- static void JimVariablesMatch(Jim_Interp *interp, Jim_Obj *listObjPtr,
- Jim_Obj *keyObj, void *value, Jim_Obj *patternObj, int type)
- {
- Jim_VarVal *vv = (Jim_VarVal *)value;
- if ((type & JIM_VARLIST_MASK) != JIM_VARLIST_LOCALS || vv->linkFramePtr == NULL) {
- if (patternObj == NULL || Jim_StringMatchObj(interp, patternObj, keyObj, 0)) {
- Jim_ListAppendElement(interp, listObjPtr, keyObj);
- if (type & JIM_VARLIST_VALUES) {
- Jim_ListAppendElement(interp, listObjPtr, vv->objPtr);
- }
- }
- }
- }
- static Jim_Obj *JimVariablesList(Jim_Interp *interp, Jim_Obj *patternObjPtr, int mode)
- {
- if (mode == JIM_VARLIST_LOCALS && interp->framePtr == interp->topFramePtr) {
- return interp->emptyObj;
- }
- else {
- Jim_CallFrame *framePtr = (mode == JIM_VARLIST_GLOBALS) ? interp->topFramePtr : interp->framePtr;
- return JimHashtablePatternMatch(interp, &framePtr->vars, patternObjPtr, JimVariablesMatch,
- mode);
- }
- }
- static int JimInfoLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr, Jim_Obj **objPtrPtr)
- {
- long level;
- if (Jim_GetLong(interp, levelObjPtr, &level) == JIM_OK) {
- Jim_CallFrame *targetCallFrame = JimGetCallFrameByInteger(interp, level);
- if (targetCallFrame && targetCallFrame != interp->topFramePtr) {
- #ifdef JIM_NO_INTROSPECTION
- *objPtrPtr = Jim_NewListObj(interp, targetCallFrame->argv, 1);
- #else
- *objPtrPtr = Jim_NewListObj(interp, targetCallFrame->argv, targetCallFrame->argc);
- #endif
- return JIM_OK;
- }
- }
- Jim_SetResultFormatted(interp, "bad level \"%#s\"", levelObjPtr);
- return JIM_ERR;
- }
- static int JimInfoFrame(Jim_Interp *interp, Jim_Obj *levelObjPtr, Jim_Obj **objPtrPtr)
- {
- long level;
- if (Jim_GetLong(interp, levelObjPtr, &level) == JIM_OK) {
- Jim_EvalFrame *frame = JimGetEvalFrameByProcLevel(interp, level);
- if (frame) {
- Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
- Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "type", -1));
- Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "source", -1));
- if (frame->scriptObj) {
- ScriptObj *script = JimGetScript(interp, frame->scriptObj);
- Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "line", -1));
- Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, script->linenr));
- Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "file", -1));
- Jim_ListAppendElement(interp, listObj, script->fileNameObj);
- }
- #ifndef JIM_NO_INTROSPECTION
- {
- Jim_Obj *cmdObj = Jim_NewListObj(interp, frame->argv, frame->argc);
- Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "cmd", -1));
- Jim_ListAppendElement(interp, listObj, cmdObj);
- }
- #endif
- {
- Jim_Obj *procNameObj = JimProcForEvalFrame(interp, frame);
- if (procNameObj) {
- Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "proc", -1));
- Jim_ListAppendElement(interp, listObj, procNameObj);
- }
- }
- Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "level", -1));
- Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, interp->framePtr->level - frame->framePtr->level));
- *objPtrPtr = listObj;
- return JIM_OK;
- }
- }
- Jim_SetResultFormatted(interp, "bad level \"%#s\"", levelObjPtr);
- return JIM_ERR;
- }
- static int Jim_PutsCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- if (argc != 2 && argc != 3) {
- Jim_WrongNumArgs(interp, 1, argv, "?-nonewline? string");
- return JIM_ERR;
- }
- if (argc == 3) {
- if (!Jim_CompareStringImmediate(interp, argv[1], "-nonewline")) {
- Jim_SetResultString(interp, "The second argument must " "be -nonewline", -1);
- return JIM_ERR;
- }
- else {
- fputs(Jim_String(argv[2]), stdout);
- }
- }
- else {
- puts(Jim_String(argv[1]));
- }
- return JIM_OK;
- }
- static int JimAddMulHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int op)
- {
- jim_wide wideValue, res;
- double doubleValue, doubleRes;
- int i;
- res = (op == JIM_EXPROP_ADD) ? 0 : 1;
- for (i = 1; i < argc; i++) {
- if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK)
- goto trydouble;
- if (op == JIM_EXPROP_ADD)
- res += wideValue;
- else
- res *= wideValue;
- }
- Jim_SetResultInt(interp, res);
- return JIM_OK;
- trydouble:
- doubleRes = (double)res;
- for (; i < argc; i++) {
- if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)
- return JIM_ERR;
- if (op == JIM_EXPROP_ADD)
- doubleRes += doubleValue;
- else
- doubleRes *= doubleValue;
- }
- Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
- return JIM_OK;
- }
- static int JimSubDivHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int op)
- {
- jim_wide wideValue, res = 0;
- double doubleValue, doubleRes = 0;
- int i = 2;
- if (argc < 2) {
- Jim_WrongNumArgs(interp, 1, argv, "number ?number ... number?");
- return JIM_ERR;
- }
- else if (argc == 2) {
- if (Jim_GetWide(interp, argv[1], &wideValue) != JIM_OK) {
- if (Jim_GetDouble(interp, argv[1], &doubleValue) != JIM_OK) {
- return JIM_ERR;
- }
- else {
- if (op == JIM_EXPROP_SUB)
- doubleRes = -doubleValue;
- else
- doubleRes = 1.0 / doubleValue;
- Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
- return JIM_OK;
- }
- }
- if (op == JIM_EXPROP_SUB) {
- res = -wideValue;
- Jim_SetResultInt(interp, res);
- }
- else {
- doubleRes = 1.0 / wideValue;
- Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
- }
- return JIM_OK;
- }
- else {
- if (Jim_GetWide(interp, argv[1], &res) != JIM_OK) {
- if (Jim_GetDouble(interp, argv[1], &doubleRes)
- != JIM_OK) {
- return JIM_ERR;
- }
- else {
- goto trydouble;
- }
- }
- }
- for (i = 2; i < argc; i++) {
- if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK) {
- doubleRes = (double)res;
- goto trydouble;
- }
- if (op == JIM_EXPROP_SUB)
- res -= wideValue;
- else {
- if (wideValue == 0) {
- Jim_SetResultString(interp, "Division by zero", -1);
- return JIM_ERR;
- }
- res /= wideValue;
- }
- }
- Jim_SetResultInt(interp, res);
- return JIM_OK;
- trydouble:
- for (; i < argc; i++) {
- if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)
- return JIM_ERR;
- if (op == JIM_EXPROP_SUB)
- doubleRes -= doubleValue;
- else
- doubleRes /= doubleValue;
- }
- Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
- return JIM_OK;
- }
- static int Jim_AddCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- return JimAddMulHelper(interp, argc, argv, JIM_EXPROP_ADD);
- }
- static int Jim_MulCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- return JimAddMulHelper(interp, argc, argv, JIM_EXPROP_MUL);
- }
- static int Jim_SubCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- return JimSubDivHelper(interp, argc, argv, JIM_EXPROP_SUB);
- }
- static int Jim_DivCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- return JimSubDivHelper(interp, argc, argv, JIM_EXPROP_DIV);
- }
- static int Jim_SetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- if (argc != 2 && argc != 3) {
- Jim_WrongNumArgs(interp, 1, argv, "varName ?newValue?");
- return JIM_ERR;
- }
- if (argc == 2) {
- Jim_Obj *objPtr;
- objPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
- if (!objPtr)
- return JIM_ERR;
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)
- return JIM_ERR;
- Jim_SetResult(interp, argv[2]);
- return JIM_OK;
- }
- static int Jim_UnsetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int i = 1;
- int complain = 1;
- while (i < argc) {
- if (Jim_CompareStringImmediate(interp, argv[i], "--")) {
- i++;
- break;
- }
- if (Jim_CompareStringImmediate(interp, argv[i], "-nocomplain")) {
- complain = 0;
- i++;
- continue;
- }
- break;
- }
- while (i < argc) {
- if (Jim_UnsetVariable(interp, argv[i], complain ? JIM_ERRMSG : JIM_NONE) != JIM_OK
- && complain) {
- return JIM_ERR;
- }
- i++;
- }
- Jim_SetEmptyResult(interp);
- return JIM_OK;
- }
- static int JimCheckLoopRetcode(Jim_Interp *interp, int retval)
- {
- if (retval == JIM_BREAK || retval == JIM_CONTINUE) {
- if (--interp->break_level > 0) {
- return 1;
- }
- }
- return 0;
- }
- static int Jim_WhileCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- if (argc != 3) {
- Jim_WrongNumArgs(interp, 1, argv, "condition body");
- return JIM_ERR;
- }
- while (1) {
- int boolean = 0, retval;
- if ((retval = Jim_GetBoolFromExpr(interp, argv[1], &boolean)) != JIM_OK)
- return retval;
- if (!boolean)
- break;
- if ((retval = Jim_EvalObj(interp, argv[2])) != JIM_OK) {
- if (JimCheckLoopRetcode(interp, retval)) {
- return retval;
- }
- switch (retval) {
- case JIM_BREAK:
- goto out;
- case JIM_CONTINUE:
- continue;
- default:
- return retval;
- }
- }
- }
- out:
- Jim_SetEmptyResult(interp);
- return JIM_OK;
- }
- static int Jim_ForCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int retval;
- int boolean = 1;
- int immediate = 0;
- Jim_Obj *varNamePtr = NULL;
- Jim_Obj *stopVarNamePtr = NULL;
- if (argc != 5) {
- Jim_WrongNumArgs(interp, 1, argv, "start test next body");
- return JIM_ERR;
- }
- if ((retval = Jim_EvalObj(interp, argv[1])) != JIM_OK) {
- return retval;
- }
- retval = Jim_GetBoolFromExpr(interp, argv[2], &boolean);
- #ifdef JIM_OPTIMIZATION
- if (retval == JIM_OK && boolean) {
- ScriptObj *incrScript;
- struct ExprTree *expr;
- jim_wide stop, currentVal;
- Jim_Obj *objPtr;
- int cmpOffset;
- expr = JimGetExpression(interp, argv[2]);
- incrScript = JimGetScript(interp, argv[3]);
- if (incrScript == NULL || incrScript->len != 3 || !expr || expr->len != 3) {
- goto evalstart;
- }
- if (incrScript->token[1].type != JIM_TT_ESC) {
- goto evalstart;
- }
- if (expr->expr->type == JIM_EXPROP_LT) {
- cmpOffset = 0;
- }
- else if (expr->expr->type == JIM_EXPROP_LTE) {
- cmpOffset = 1;
- }
- else {
- goto evalstart;
- }
- if (expr->expr->left->type != JIM_TT_VAR) {
- goto evalstart;
- }
- if (expr->expr->right->type != JIM_TT_VAR && expr->expr->right->type != JIM_TT_EXPR_INT) {
- goto evalstart;
- }
- if (!Jim_CompareStringImmediate(interp, incrScript->token[1].objPtr, "incr")) {
- goto evalstart;
- }
- if (!Jim_StringEqObj(incrScript->token[2].objPtr, expr->expr->left->objPtr)) {
- goto evalstart;
- }
- if (expr->expr->right->type == JIM_TT_EXPR_INT) {
- if (Jim_GetWideExpr(interp, expr->expr->right->objPtr, &stop) == JIM_ERR) {
- goto evalstart;
- }
- }
- else {
- stopVarNamePtr = expr->expr->right->objPtr;
- Jim_IncrRefCount(stopVarNamePtr);
- stop = 0;
- }
- varNamePtr = expr->expr->left->objPtr;
- Jim_IncrRefCount(varNamePtr);
- objPtr = Jim_GetVariable(interp, varNamePtr, JIM_NONE);
- if (objPtr == NULL || Jim_GetWide(interp, objPtr, ¤tVal) != JIM_OK) {
- goto testcond;
- }
- while (retval == JIM_OK) {
- if (stopVarNamePtr) {
- objPtr = Jim_GetVariable(interp, stopVarNamePtr, JIM_NONE);
- if (objPtr == NULL || Jim_GetWide(interp, objPtr, &stop) != JIM_OK) {
- goto testcond;
- }
- }
- if (currentVal >= stop + cmpOffset) {
- break;
- }
- retval = Jim_EvalObj(interp, argv[4]);
- if (JimCheckLoopRetcode(interp, retval)) {
- immediate++;
- goto out;
- }
- if (retval == JIM_OK || retval == JIM_CONTINUE) {
- retval = JIM_OK;
- objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG);
- if (objPtr == NULL) {
- retval = JIM_ERR;
- goto out;
- }
- if (!Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
- currentVal = ++JimWideValue(objPtr);
- Jim_InvalidateStringRep(objPtr);
- }
- else {
- if (Jim_GetWide(interp, objPtr, ¤tVal) != JIM_OK ||
- Jim_SetVariable(interp, varNamePtr, Jim_NewIntObj(interp,
- ++currentVal)) != JIM_OK) {
- goto evalnext;
- }
- }
- }
- }
- goto out;
- }
- evalstart:
- #endif
- while (boolean && (retval == JIM_OK || retval == JIM_CONTINUE)) {
- retval = Jim_EvalObj(interp, argv[4]);
- if (JimCheckLoopRetcode(interp, retval)) {
- immediate++;
- break;
- }
- if (retval == JIM_OK || retval == JIM_CONTINUE) {
- JIM_IF_OPTIM(evalnext:)
- retval = Jim_EvalObj(interp, argv[3]);
- if (retval == JIM_OK || retval == JIM_CONTINUE) {
- JIM_IF_OPTIM(testcond:)
- retval = Jim_GetBoolFromExpr(interp, argv[2], &boolean);
- }
- }
- }
- JIM_IF_OPTIM(out:)
- if (stopVarNamePtr) {
- Jim_DecrRefCount(interp, stopVarNamePtr);
- }
- if (varNamePtr) {
- Jim_DecrRefCount(interp, varNamePtr);
- }
- if (!immediate) {
- if (retval == JIM_CONTINUE || retval == JIM_BREAK || retval == JIM_OK) {
- Jim_SetEmptyResult(interp);
- return JIM_OK;
- }
- }
- return retval;
- }
- static int Jim_LoopCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int retval;
- jim_wide i;
- jim_wide limit = 0;
- jim_wide incr = 1;
- Jim_Obj *bodyObjPtr;
- if (argc < 4 || argc > 6) {
- Jim_WrongNumArgs(interp, 1, argv, "var ?first? limit ?incr? body");
- return JIM_ERR;
- }
- retval = Jim_GetWideExpr(interp, argv[2], &i);
- if (argc > 4 && retval == JIM_OK) {
- retval = Jim_GetWideExpr(interp, argv[3], &limit);
- }
- if (argc > 5 && retval == JIM_OK) {
- Jim_GetWideExpr(interp, argv[4], &incr);
- }
- if (retval != JIM_OK) {
- return retval;
- }
- if (argc == 4) {
- limit = i;
- i = 0;
- }
- bodyObjPtr = argv[argc - 1];
- retval = Jim_SetVariable(interp, argv[1], Jim_NewIntObj(interp, i));
- while (((i < limit && incr > 0) || (i > limit && incr < 0)) && retval == JIM_OK) {
- retval = Jim_EvalObj(interp, bodyObjPtr);
- if (JimCheckLoopRetcode(interp, retval)) {
- return retval;
- }
- if (retval == JIM_OK || retval == JIM_CONTINUE) {
- Jim_Obj *objPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
- retval = JIM_OK;
- i += incr;
- if (objPtr && !Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
- if (argv[1]->typePtr != &variableObjType) {
- if (Jim_SetVariable(interp, argv[1], objPtr) != JIM_OK) {
- return JIM_ERR;
- }
- }
- JimWideValue(objPtr) = i;
- Jim_InvalidateStringRep(objPtr);
- if (argv[1]->typePtr != &variableObjType) {
- if (Jim_SetVariable(interp, argv[1], objPtr) != JIM_OK) {
- retval = JIM_ERR;
- break;
- }
- }
- }
- else {
- objPtr = Jim_NewIntObj(interp, i);
- retval = Jim_SetVariable(interp, argv[1], objPtr);
- if (retval != JIM_OK) {
- Jim_FreeNewObj(interp, objPtr);
- }
- }
- }
- }
- if (retval == JIM_OK || retval == JIM_CONTINUE || retval == JIM_BREAK) {
- Jim_SetEmptyResult(interp);
- return JIM_OK;
- }
- return retval;
- }
- typedef struct {
- Jim_Obj *objPtr;
- int idx;
- } Jim_ListIter;
- static void JimListIterInit(Jim_ListIter *iter, Jim_Obj *objPtr)
- {
- iter->objPtr = objPtr;
- iter->idx = 0;
- }
- static Jim_Obj *JimListIterNext(Jim_Interp *interp, Jim_ListIter *iter)
- {
- if (iter->idx >= Jim_ListLength(interp, iter->objPtr)) {
- return NULL;
- }
- return iter->objPtr->internalRep.listValue.ele[iter->idx++];
- }
- static int JimListIterDone(Jim_Interp *interp, Jim_ListIter *iter)
- {
- return iter->idx >= Jim_ListLength(interp, iter->objPtr);
- }
- static int JimForeachMapHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int doMap)
- {
- int result = JIM_OK;
- int i, numargs;
- Jim_ListIter twoiters[2];
- Jim_ListIter *iters;
- Jim_Obj *script;
- Jim_Obj *resultObj;
- if (argc < 4 || argc % 2 != 0) {
- Jim_WrongNumArgs(interp, 1, argv, "varList list ?varList list ...? script");
- return JIM_ERR;
- }
- script = argv[argc - 1];
- numargs = (argc - 1 - 1);
- if (numargs == 2) {
- iters = twoiters;
- }
- else {
- iters = Jim_Alloc(numargs * sizeof(*iters));
- }
- for (i = 0; i < numargs; i++) {
- JimListIterInit(&iters[i], argv[i + 1]);
- if (i % 2 == 0 && JimListIterDone(interp, &iters[i])) {
- result = JIM_ERR;
- }
- }
- if (result != JIM_OK) {
- Jim_SetResultString(interp, "foreach varlist is empty", -1);
- goto empty_varlist;
- }
- if (doMap) {
- resultObj = Jim_NewListObj(interp, NULL, 0);
- }
- else {
- resultObj = interp->emptyObj;
- }
- Jim_IncrRefCount(resultObj);
- while (1) {
- for (i = 0; i < numargs; i += 2) {
- if (!JimListIterDone(interp, &iters[i + 1])) {
- break;
- }
- }
- if (i == numargs) {
- break;
- }
- for (i = 0; i < numargs; i += 2) {
- Jim_Obj *varName;
- JimListIterInit(&iters[i], argv[i + 1]);
- while ((varName = JimListIterNext(interp, &iters[i])) != NULL) {
- Jim_Obj *valObj = JimListIterNext(interp, &iters[i + 1]);
- if (!valObj) {
- valObj = interp->emptyObj;
- }
- Jim_IncrRefCount(valObj);
- result = Jim_SetVariable(interp, varName, valObj);
- Jim_DecrRefCount(interp, valObj);
- if (result != JIM_OK) {
- goto err;
- }
- }
- }
- result = Jim_EvalObj(interp, script);
- if (JimCheckLoopRetcode(interp, result)) {
- goto err;
- }
- switch (result) {
- case JIM_OK:
- if (doMap) {
- Jim_ListAppendElement(interp, resultObj, interp->result);
- }
- break;
- case JIM_CONTINUE:
- break;
- case JIM_BREAK:
- goto out;
- default:
- goto err;
- }
- }
- out:
- result = JIM_OK;
- Jim_SetResult(interp, resultObj);
- err:
- Jim_DecrRefCount(interp, resultObj);
- empty_varlist:
- if (numargs > 2) {
- Jim_Free(iters);
- }
- return result;
- }
- static int Jim_ForeachCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- return JimForeachMapHelper(interp, argc, argv, 0);
- }
- static int Jim_LmapCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- return JimForeachMapHelper(interp, argc, argv, 1);
- }
- static int Jim_LassignCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int result = JIM_ERR;
- int i;
- Jim_ListIter iter;
- Jim_Obj *resultObj;
- if (argc < 2) {
- Jim_WrongNumArgs(interp, 1, argv, "varList list ?varName ...?");
- return JIM_ERR;
- }
- JimListIterInit(&iter, argv[1]);
- for (i = 2; i < argc; i++) {
- Jim_Obj *valObj = JimListIterNext(interp, &iter);
- result = Jim_SetVariable(interp, argv[i], valObj ? valObj : interp->emptyObj);
- if (result != JIM_OK) {
- return result;
- }
- }
- resultObj = Jim_NewListObj(interp, NULL, 0);
- while (!JimListIterDone(interp, &iter)) {
- Jim_ListAppendElement(interp, resultObj, JimListIterNext(interp, &iter));
- }
- Jim_SetResult(interp, resultObj);
- return JIM_OK;
- }
- static int Jim_IfCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int boolean, retval, current = 1, falsebody = 0;
- if (argc >= 3) {
- while (1) {
- if (current >= argc)
- goto err;
- if ((retval = Jim_GetBoolFromExpr(interp, argv[current++], &boolean))
- != JIM_OK)
- return retval;
- if (current >= argc)
- goto err;
- if (Jim_CompareStringImmediate(interp, argv[current], "then"))
- current++;
- if (current >= argc)
- goto err;
- if (boolean)
- return Jim_EvalObj(interp, argv[current]);
- if (++current >= argc) {
- Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
- return JIM_OK;
- }
- falsebody = current++;
- if (Jim_CompareStringImmediate(interp, argv[falsebody], "else")) {
- if (current != argc - 1)
- goto err;
- return Jim_EvalObj(interp, argv[current]);
- }
- else if (Jim_CompareStringImmediate(interp, argv[falsebody], "elseif"))
- continue;
- else if (falsebody != argc - 1)
- goto err;
- return Jim_EvalObj(interp, argv[falsebody]);
- }
- return JIM_OK;
- }
- err:
- Jim_WrongNumArgs(interp, 1, argv, "condition ?then? trueBody ?elseif ...? ?else? falseBody");
- return JIM_ERR;
- }
- int Jim_CommandMatchObj(Jim_Interp *interp, Jim_Obj *commandObj, Jim_Obj *patternObj,
- Jim_Obj *stringObj, int flags)
- {
- Jim_Obj *parms[5];
- int argc = 0;
- long eq;
- int rc;
- parms[argc++] = commandObj;
- if (flags & JIM_NOCASE) {
- parms[argc++] = Jim_NewStringObj(interp, "-nocase", -1);
- }
- if (flags & JIM_OPT_END) {
- parms[argc++] = Jim_NewStringObj(interp, "--", -1);
- }
- parms[argc++] = patternObj;
- parms[argc++] = stringObj;
- rc = Jim_EvalObjVector(interp, argc, parms);
- if (rc != JIM_OK || Jim_GetLong(interp, Jim_GetResult(interp), &eq) != JIM_OK) {
- eq = -rc;
- }
- return eq;
- }
- static int Jim_SwitchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- enum { SWITCH_EXACT, SWITCH_GLOB, SWITCH_RE, SWITCH_CMD };
- int matchOpt = SWITCH_EXACT, opt = 1, patCount, i;
- int match_flags = 0;
- Jim_Obj *command = NULL, *scriptObj = NULL, *strObj;
- Jim_Obj **caseList;
- if (argc < 3) {
- wrongnumargs:
- Jim_WrongNumArgs(interp, 1, argv, "?options? string "
- "pattern body ... ?default body? or " "{pattern body ?pattern body ...?}");
- return JIM_ERR;
- }
- for (opt = 1; opt < argc; ++opt) {
- const char *option = Jim_String(argv[opt]);
- if (*option != '-')
- break;
- else if (strncmp(option, "--", 2) == 0) {
- ++opt;
- break;
- }
- else if (strncmp(option, "-exact", 2) == 0)
- matchOpt = SWITCH_EXACT;
- else if (strncmp(option, "-glob", 2) == 0)
- matchOpt = SWITCH_GLOB;
- else if (strncmp(option, "-regexp", 2) == 0) {
- matchOpt = SWITCH_RE;
- match_flags |= JIM_OPT_END;
- }
- else if (strncmp(option, "-command", 2) == 0) {
- matchOpt = SWITCH_CMD;
- if ((argc - opt) < 2)
- goto wrongnumargs;
- command = argv[++opt];
- }
- else {
- Jim_SetResultFormatted(interp,
- "bad option \"%#s\": must be -exact, -glob, -regexp, -command procname or --",
- argv[opt]);
- return JIM_ERR;
- }
- if ((argc - opt) < 2)
- goto wrongnumargs;
- }
- strObj = argv[opt++];
- patCount = argc - opt;
- if (patCount == 1) {
- JimListGetElements(interp, argv[opt], &patCount, &caseList);
- }
- else
- caseList = (Jim_Obj **)&argv[opt];
- if (patCount == 0 || patCount % 2 != 0)
- goto wrongnumargs;
- for (i = 0; scriptObj == NULL && i < patCount; i += 2) {
- Jim_Obj *patObj = caseList[i];
- if (!Jim_CompareStringImmediate(interp, patObj, "default")
- || i < (patCount - 2)) {
- switch (matchOpt) {
- case SWITCH_EXACT:
- if (Jim_StringEqObj(strObj, patObj))
- scriptObj = caseList[i + 1];
- break;
- case SWITCH_GLOB:
- if (Jim_StringMatchObj(interp, patObj, strObj, 0))
- scriptObj = caseList[i + 1];
- break;
- case SWITCH_RE:
- command = Jim_NewStringObj(interp, "regexp", -1);
- case SWITCH_CMD:{
- int rc = Jim_CommandMatchObj(interp, command, patObj, strObj, match_flags);
- if (argc - opt == 1) {
- JimListGetElements(interp, argv[opt], &patCount, &caseList);
- }
- if (rc < 0) {
- return -rc;
- }
- if (rc)
- scriptObj = caseList[i + 1];
- break;
- }
- }
- }
- else {
- scriptObj = caseList[i + 1];
- }
- }
- for (; i < patCount && Jim_CompareStringImmediate(interp, scriptObj, "-"); i += 2)
- scriptObj = caseList[i + 1];
- if (scriptObj && Jim_CompareStringImmediate(interp, scriptObj, "-")) {
- Jim_SetResultFormatted(interp, "no body specified for pattern \"%#s\"", caseList[i - 2]);
- return JIM_ERR;
- }
- Jim_SetEmptyResult(interp);
- if (scriptObj) {
- return Jim_EvalObj(interp, scriptObj);
- }
- return JIM_OK;
- }
- static int Jim_ListCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *listObjPtr;
- listObjPtr = Jim_NewListObj(interp, argv + 1, argc - 1);
- Jim_SetResult(interp, listObjPtr);
- return JIM_OK;
- }
- static int Jim_LindexCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *objPtr;
- int ret;
- if (argc < 2) {
- Jim_WrongNumArgs(interp, 1, argv, "list ?index ...?");
- return JIM_ERR;
- }
- ret = Jim_ListIndices(interp, argv[1], argv + 2, argc - 2, &objPtr, JIM_NONE);
- if (ret < 0) {
- ret = JIM_OK;
- Jim_SetEmptyResult(interp);
- }
- else if (ret == JIM_OK) {
- Jim_SetResult(interp, objPtr);
- }
- return ret;
- }
- static int Jim_LlengthCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- if (argc != 2) {
- Jim_WrongNumArgs(interp, 1, argv, "list");
- return JIM_ERR;
- }
- Jim_SetResultInt(interp, Jim_ListLength(interp, argv[1]));
- return JIM_OK;
- }
- static int Jim_LsearchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- static const char * const options[] = {
- "-bool", "-not", "-nocase", "-exact", "-glob", "-regexp", "-all", "-inline", "-command",
- "-stride", "-index", NULL
- };
- enum
- { OPT_BOOL, OPT_NOT, OPT_NOCASE, OPT_EXACT, OPT_GLOB, OPT_REGEXP, OPT_ALL, OPT_INLINE,
- OPT_COMMAND, OPT_STRIDE, OPT_INDEX };
- int i;
- int opt_bool = 0;
- int opt_not = 0;
- int opt_all = 0;
- int opt_inline = 0;
- int opt_match = OPT_EXACT;
- int listlen;
- int rc = JIM_OK;
- Jim_Obj *listObjPtr = NULL;
- Jim_Obj *commandObj = NULL;
- Jim_Obj *indexObj = NULL;
- int match_flags = 0;
- long stride = 1;
- if (argc < 3) {
- wrongargs:
- Jim_WrongNumArgs(interp, 1, argv,
- "?-exact|-glob|-regexp|-command 'command'? ?-bool|-inline? ?-not? ?-nocase? ?-all? ?-stride len? ?-index val? list value");
- return JIM_ERR;
- }
- for (i = 1; i < argc - 2; i++) {
- int option;
- if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ERRMSG) != JIM_OK) {
- return JIM_ERR;
- }
- switch (option) {
- case OPT_BOOL:
- opt_bool = 1;
- opt_inline = 0;
- break;
- case OPT_NOT:
- opt_not = 1;
- break;
- case OPT_NOCASE:
- match_flags |= JIM_NOCASE;
- break;
- case OPT_INLINE:
- opt_inline = 1;
- opt_bool = 0;
- break;
- case OPT_ALL:
- opt_all = 1;
- break;
- case OPT_REGEXP:
- opt_match = option;
- match_flags |= JIM_OPT_END;
- break;
- case OPT_COMMAND:
- if (i >= argc - 2) {
- goto wrongargs;
- }
- commandObj = argv[++i];
- case OPT_EXACT:
- case OPT_GLOB:
- opt_match = option;
- break;
- case OPT_INDEX:
- if (i >= argc - 2) {
- goto wrongargs;
- }
- indexObj = argv[++i];
- break;
- case OPT_STRIDE:
- if (i >= argc - 2) {
- goto wrongargs;
- }
- if (Jim_GetLong(interp, argv[++i], &stride) != JIM_OK) {
- return JIM_ERR;
- }
- if (stride < 1) {
- Jim_SetResultString(interp, "stride length must be at least 1", -1);
- return JIM_ERR;
- }
- break;
- }
- }
- argc -= i;
- if (argc < 2) {
- goto wrongargs;
- }
- argv += i;
- listlen = Jim_ListLength(interp, argv[0]);
- if (listlen % stride) {
- Jim_SetResultString(interp, "list size must be a multiple of the stride length", -1);
- return JIM_ERR;
- }
- if (opt_all) {
- listObjPtr = Jim_NewListObj(interp, NULL, 0);
- }
- if (opt_match == OPT_REGEXP) {
- commandObj = Jim_NewStringObj(interp, "regexp", -1);
- }
- if (commandObj) {
- Jim_IncrRefCount(commandObj);
- }
- for (i = 0; i < listlen; i += stride) {
- int eq = 0;
- Jim_Obj *searchListObj;
- Jim_Obj *objPtr;
- int offset;
- if (indexObj) {
- int indexlen = Jim_ListLength(interp, indexObj);
- if (stride == 1) {
- searchListObj = Jim_ListGetIndex(interp, argv[0], i);
- }
- else {
- searchListObj = Jim_NewListObj(interp, argv[0]->internalRep.listValue.ele + i, stride);
- }
- Jim_IncrRefCount(searchListObj);
- rc = Jim_ListIndices(interp, searchListObj, indexObj->internalRep.listValue.ele, indexlen, &objPtr, JIM_ERRMSG);
- if (rc != JIM_OK) {
- Jim_DecrRefCount(interp, searchListObj);
- rc = JIM_ERR;
- goto done;
- }
- offset = 0;
- }
- else {
- searchListObj = argv[0];
- offset = i;
- objPtr = Jim_ListGetIndex(interp, searchListObj, i);
- Jim_IncrRefCount(searchListObj);
- }
- switch (opt_match) {
- case OPT_EXACT:
- eq = Jim_StringCompareObj(interp, argv[1], objPtr, match_flags) == 0;
- break;
- case OPT_GLOB:
- eq = Jim_StringMatchObj(interp, argv[1], objPtr, match_flags);
- break;
- case OPT_REGEXP:
- case OPT_COMMAND:
- eq = Jim_CommandMatchObj(interp, commandObj, argv[1], objPtr, match_flags);
- if (eq < 0) {
- Jim_DecrRefCount(interp, searchListObj);
- rc = JIM_ERR;
- goto done;
- }
- break;
- }
- if ((!opt_bool && eq == !opt_not) || (opt_bool && (eq || opt_all))) {
- Jim_Obj *resultObj;
- if (opt_bool) {
- resultObj = Jim_NewIntObj(interp, eq ^ opt_not);
- }
- else if (!opt_inline) {
- resultObj = Jim_NewIntObj(interp, i);
- }
- else if (stride == 1) {
- resultObj = objPtr;
- }
- else if (opt_all) {
- ListInsertElements(listObjPtr, -1, stride,
- searchListObj->internalRep.listValue.ele + offset);
- resultObj = NULL;
- }
- else {
- resultObj = Jim_NewListObj(interp, searchListObj->internalRep.listValue.ele + offset, stride);
- }
- if (opt_all) {
- if (stride == 1) {
- Jim_ListAppendElement(interp, listObjPtr, resultObj);
- }
- }
- else {
- Jim_SetResult(interp, resultObj);
- Jim_DecrRefCount(interp, searchListObj);
- goto done;
- }
- }
- Jim_DecrRefCount(interp, searchListObj);
- }
- if (opt_all) {
- Jim_SetResult(interp, listObjPtr);
- listObjPtr = NULL;
- }
- else {
- if (opt_bool) {
- Jim_SetResultBool(interp, opt_not);
- }
- else if (!opt_inline) {
- Jim_SetResultInt(interp, -1);
- }
- }
- done:
- if (listObjPtr) {
- Jim_FreeNewObj(interp, listObjPtr);
- }
- if (commandObj) {
- Jim_DecrRefCount(interp, commandObj);
- }
- return rc;
- }
- static int Jim_LappendCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *listObjPtr;
- int new_obj = 0;
- int i;
- if (argc < 2) {
- Jim_WrongNumArgs(interp, 1, argv, "varName ?value value ...?");
- return JIM_ERR;
- }
- listObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
- if (!listObjPtr) {
- listObjPtr = Jim_NewListObj(interp, NULL, 0);
- new_obj = 1;
- }
- else if (Jim_IsShared(listObjPtr)) {
- listObjPtr = Jim_DuplicateObj(interp, listObjPtr);
- new_obj = 1;
- }
- for (i = 2; i < argc; i++)
- Jim_ListAppendElement(interp, listObjPtr, argv[i]);
- if (Jim_SetVariable(interp, argv[1], listObjPtr) != JIM_OK) {
- if (new_obj)
- Jim_FreeNewObj(interp, listObjPtr);
- return JIM_ERR;
- }
- Jim_SetResult(interp, listObjPtr);
- return JIM_OK;
- }
- static int Jim_LinsertCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int idx, len;
- Jim_Obj *listPtr;
- if (argc < 3) {
- Jim_WrongNumArgs(interp, 1, argv, "list index ?element ...?");
- return JIM_ERR;
- }
- listPtr = argv[1];
- if (Jim_IsShared(listPtr))
- listPtr = Jim_DuplicateObj(interp, listPtr);
- if (Jim_GetIndex(interp, argv[2], &idx) != JIM_OK)
- goto err;
- len = Jim_ListLength(interp, listPtr);
- if (idx >= len)
- idx = len;
- else if (idx < 0)
- idx = len + idx + 1;
- Jim_ListInsertElements(interp, listPtr, idx, argc - 3, &argv[3]);
- Jim_SetResult(interp, listPtr);
- return JIM_OK;
- err:
- if (listPtr != argv[1]) {
- Jim_FreeNewObj(interp, listPtr);
- }
- return JIM_ERR;
- }
- static int Jim_LreplaceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int first, last, len, rangeLen;
- Jim_Obj *listObj;
- Jim_Obj *newListObj;
- if (argc < 4) {
- Jim_WrongNumArgs(interp, 1, argv, "list first last ?element ...?");
- return JIM_ERR;
- }
- if (Jim_GetIndex(interp, argv[2], &first) != JIM_OK ||
- Jim_GetIndex(interp, argv[3], &last) != JIM_OK) {
- return JIM_ERR;
- }
- listObj = argv[1];
- len = Jim_ListLength(interp, listObj);
- first = JimRelToAbsIndex(len, first);
- last = JimRelToAbsIndex(len, last);
- JimRelToAbsRange(len, &first, &last, &rangeLen);
- if (first > len) {
- first = len;
- }
- newListObj = Jim_NewListObj(interp, listObj->internalRep.listValue.ele, first);
- ListInsertElements(newListObj, -1, argc - 4, argv + 4);
- ListInsertElements(newListObj, -1, len - first - rangeLen, listObj->internalRep.listValue.ele + first + rangeLen);
- Jim_SetResult(interp, newListObj);
- return JIM_OK;
- }
- static int Jim_LsetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- if (argc < 3) {
- Jim_WrongNumArgs(interp, 1, argv, "listVar ?index ...? value");
- return JIM_ERR;
- }
- else if (argc == 3) {
- if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)
- return JIM_ERR;
- Jim_SetResult(interp, argv[2]);
- return JIM_OK;
- }
- return Jim_ListSetIndex(interp, argv[1], argv + 2, argc - 3, argv[argc - 1]);
- }
- static int Jim_LsortCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const argv[])
- {
- static const char * const options[] = {
- "-ascii", "-nocase", "-increasing", "-decreasing", "-command", "-integer", "-real", "-index", "-unique",
- "-stride", "-dictionary", NULL
- };
- enum {
- OPT_ASCII, OPT_NOCASE, OPT_INCREASING, OPT_DECREASING, OPT_COMMAND, OPT_INTEGER, OPT_REAL, OPT_INDEX, OPT_UNIQUE,
- OPT_STRIDE, OPT_DICT
- };
- Jim_Obj *resObj;
- int i;
- int retCode;
- int shared;
- long stride = 1;
- Jim_Obj **elements;
- int listlen;
- struct lsort_info info;
- if (argc < 2) {
- wrongargs:
- Jim_WrongNumArgs(interp, 1, argv, "?options? list");
- return JIM_ERR;
- }
- info.type = JIM_LSORT_ASCII;
- info.order = 1;
- info.indexc = 0;
- info.unique = 0;
- info.command = NULL;
- info.interp = interp;
- for (i = 1; i < (argc - 1); i++) {
- int option;
- if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ENUM_ABBREV | JIM_ERRMSG)
- != JIM_OK)
- return JIM_ERR;
- switch (option) {
- case OPT_ASCII:
- info.type = JIM_LSORT_ASCII;
- break;
- case OPT_DICT:
- info.type = JIM_LSORT_DICT;
- break;
- case OPT_NOCASE:
- info.type = JIM_LSORT_NOCASE;
- break;
- case OPT_INTEGER:
- info.type = JIM_LSORT_INTEGER;
- break;
- case OPT_REAL:
- info.type = JIM_LSORT_REAL;
- break;
- case OPT_INCREASING:
- info.order = 1;
- break;
- case OPT_DECREASING:
- info.order = -1;
- break;
- case OPT_UNIQUE:
- info.unique = 1;
- break;
- case OPT_COMMAND:
- if (i >= (argc - 2)) {
- Jim_SetResultString(interp, "\"-command\" option must be followed by comparison command", -1);
- return JIM_ERR;
- }
- info.type = JIM_LSORT_COMMAND;
- info.command = argv[i + 1];
- i++;
- break;
- case OPT_STRIDE:
- if (i >= argc - 2) {
- goto wrongargs;
- }
- if (Jim_GetLong(interp, argv[++i], &stride) != JIM_OK) {
- return JIM_ERR;
- }
- if (stride < 2) {
- Jim_SetResultString(interp, "stride length must be at least 2", -1);
- return JIM_ERR;
- }
- break;
- case OPT_INDEX:
- if (i >= (argc - 2)) {
- badindex:
- Jim_SetResultString(interp, "\"-index\" option must be followed by list index", -1);
- return JIM_ERR;
- }
- JimListGetElements(interp, argv[i + 1], &info.indexc, &info.indexv);
- if (info.indexc == 0) {
- goto badindex;
- }
- i++;
- break;
- }
- }
- resObj = argv[argc - 1];
- JimListGetElements(interp, resObj, &listlen, &elements);
- if (listlen <= 1) {
- Jim_SetResult(interp, resObj);
- return JIM_OK;
- }
- if (stride > 1) {
- Jim_Obj *tmpListObj;
- int i;
- if (listlen % stride) {
- Jim_SetResultString(interp, "list size must be a multiple of the stride length", -1);
- return JIM_ERR;
- }
- tmpListObj = Jim_NewListObj(interp, NULL, 0);
- Jim_IncrRefCount(tmpListObj);
- for (i = 0; i < listlen; i += stride) {
- Jim_ListAppendElement(interp, tmpListObj, Jim_NewListObj(interp, elements + i, stride));
- }
- retCode = ListSortElements(interp, tmpListObj, &info);
- if (retCode == JIM_OK) {
- resObj = Jim_NewListObj(interp, NULL, 0);
- for (i = 0; i < listlen; i += stride) {
- Jim_ListAppendList(interp, resObj, Jim_ListGetIndex(interp, tmpListObj, i / stride));
- }
- Jim_SetResult(interp, resObj);
- }
- Jim_DecrRefCount(interp, tmpListObj);
- }
- else {
- if ((shared = Jim_IsShared(resObj))) {
- resObj = Jim_DuplicateObj(interp, resObj);
- }
- retCode = ListSortElements(interp, resObj, &info);
- if (retCode == JIM_OK) {
- Jim_SetResult(interp, resObj);
- }
- else if (shared) {
- Jim_FreeNewObj(interp, resObj);
- }
- }
- return retCode;
- }
- static int Jim_AppendCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *stringObjPtr;
- int i;
- if (argc < 2) {
- Jim_WrongNumArgs(interp, 1, argv, "varName ?value ...?");
- return JIM_ERR;
- }
- if (argc == 2) {
- stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
- if (!stringObjPtr)
- return JIM_ERR;
- }
- else {
- int new_obj = 0;
- stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
- if (!stringObjPtr) {
- stringObjPtr = Jim_NewEmptyStringObj(interp);
- new_obj = 1;
- }
- else if (Jim_IsShared(stringObjPtr)) {
- new_obj = 1;
- stringObjPtr = Jim_DuplicateObj(interp, stringObjPtr);
- }
- for (i = 2; i < argc; i++) {
- Jim_AppendObj(interp, stringObjPtr, argv[i]);
- }
- if (Jim_SetVariable(interp, argv[1], stringObjPtr) != JIM_OK) {
- if (new_obj) {
- Jim_FreeNewObj(interp, stringObjPtr);
- }
- return JIM_ERR;
- }
- }
- Jim_SetResult(interp, stringObjPtr);
- return JIM_OK;
- }
- static int Jim_EvalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int rc;
- if (argc < 2) {
- Jim_WrongNumArgs(interp, 1, argv, "arg ?arg ...?");
- return JIM_ERR;
- }
- if (argc == 2) {
- rc = Jim_EvalObj(interp, argv[1]);
- }
- else {
- rc = Jim_EvalObj(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
- }
- return rc;
- }
- static int Jim_UplevelCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- if (argc >= 2) {
- int retcode;
- Jim_CallFrame *savedCallFrame, *targetCallFrame;
- const char *str;
- savedCallFrame = interp->framePtr;
- str = Jim_String(argv[1]);
- if ((str[0] >= '0' && str[0] <= '9') || str[0] == '#') {
- targetCallFrame = Jim_GetCallFrameByLevel(interp, argv[1]);
- argc--;
- argv++;
- }
- else {
- targetCallFrame = Jim_GetCallFrameByLevel(interp, NULL);
- }
- if (targetCallFrame == NULL) {
- return JIM_ERR;
- }
- if (argc < 2) {
- Jim_WrongNumArgs(interp, 1, argv - 1, "?level? command ?arg ...?");
- return JIM_ERR;
- }
- interp->framePtr = targetCallFrame;
- if (argc == 2) {
- retcode = Jim_EvalObj(interp, argv[1]);
- }
- else {
- retcode = Jim_EvalObj(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
- }
- interp->framePtr = savedCallFrame;
- return retcode;
- }
- else {
- Jim_WrongNumArgs(interp, 1, argv, "?level? command ?arg ...?");
- return JIM_ERR;
- }
- }
- static int Jim_ExprCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int retcode;
- if (argc == 2) {
- retcode = Jim_EvalExpression(interp, argv[1]);
- }
- #ifndef JIM_COMPAT
- else {
- Jim_WrongNumArgs(interp, 1, argv, "expression");
- retcode = JIM_ERR;
- }
- #else
- else if (argc > 2) {
- Jim_Obj *objPtr;
- objPtr = Jim_ConcatObj(interp, argc - 1, argv + 1);
- Jim_IncrRefCount(objPtr);
- retcode = Jim_EvalExpression(interp, objPtr);
- Jim_DecrRefCount(interp, objPtr);
- }
- else {
- Jim_WrongNumArgs(interp, 1, argv, "expression ?...?");
- return JIM_ERR;
- }
- #endif
- return retcode;
- }
- static int JimBreakContinueHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int retcode)
- {
- if (argc != 1 && argc != 2) {
- Jim_WrongNumArgs(interp, 1, argv, "?level?");
- return JIM_ERR;
- }
- if (argc == 2) {
- long level;
- int ret = Jim_GetLong(interp, argv[1], &level);
- if (ret != JIM_OK) {
- return ret;
- }
- interp->break_level = level;
- }
- return retcode;
- }
- static int Jim_BreakCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- return JimBreakContinueHelper(interp, argc, argv, JIM_BREAK);
- }
- static int Jim_ContinueCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- return JimBreakContinueHelper(interp, argc, argv, JIM_CONTINUE);
- }
- static int Jim_StacktraceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *listObj;
- int i;
- jim_wide skip = 0;
- jim_wide last = 0;
- if (argc > 1) {
- if (Jim_GetWideExpr(interp, argv[1], &skip) != JIM_OK) {
- return JIM_ERR;
- }
- }
- if (argc > 2) {
- if (Jim_GetWideExpr(interp, argv[2], &last) != JIM_OK) {
- return JIM_ERR;
- }
- }
- listObj = Jim_NewListObj(interp, NULL, 0);
- for (i = skip; i <= interp->procLevel; i++) {
- Jim_EvalFrame *frame = JimGetEvalFrameByProcLevel(interp, -i);
- if (frame->procLevel < last) {
- break;
- }
- JimAddStackFrame(interp, frame, listObj);
- }
- Jim_SetResult(interp, listObj);
- return JIM_OK;
- }
- static int Jim_ReturnCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int i;
- Jim_Obj *stackTraceObj = NULL;
- Jim_Obj *errorCodeObj = NULL;
- int returnCode = JIM_OK;
- long level = 1;
- for (i = 1; i < argc - 1; i += 2) {
- if (Jim_CompareStringImmediate(interp, argv[i], "-code")) {
- if (Jim_GetReturnCode(interp, argv[i + 1], &returnCode) == JIM_ERR) {
- return JIM_ERR;
- }
- }
- else if (Jim_CompareStringImmediate(interp, argv[i], "-errorinfo")) {
- stackTraceObj = argv[i + 1];
- }
- else if (Jim_CompareStringImmediate(interp, argv[i], "-errorcode")) {
- errorCodeObj = argv[i + 1];
- }
- else if (Jim_CompareStringImmediate(interp, argv[i], "-level")) {
- if (Jim_GetLong(interp, argv[i + 1], &level) != JIM_OK || level < 0) {
- Jim_SetResultFormatted(interp, "bad level \"%#s\"", argv[i + 1]);
- return JIM_ERR;
- }
- }
- else {
- break;
- }
- }
- if (i != argc - 1 && i != argc) {
- Jim_WrongNumArgs(interp, 1, argv,
- "?-code code? ?-errorinfo stacktrace? ?-level level? ?result?");
- }
- if (stackTraceObj && returnCode == JIM_ERR) {
- JimSetStackTrace(interp, stackTraceObj);
- }
- if (errorCodeObj && returnCode == JIM_ERR) {
- Jim_SetGlobalVariableStr(interp, "errorCode", errorCodeObj);
- }
- interp->returnCode = returnCode;
- interp->returnLevel = level;
- if (i == argc - 1) {
- Jim_SetResult(interp, argv[i]);
- }
- return level == 0 ? returnCode : JIM_RETURN;
- }
- static int Jim_TailcallCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- if (interp->framePtr->level == 0) {
- Jim_SetResultString(interp, "tailcall can only be called from a proc or lambda", -1);
- return JIM_ERR;
- }
- else if (argc >= 2) {
- Jim_CallFrame *cf = interp->framePtr->parent;
- Jim_Cmd *cmdPtr = Jim_GetCommand(interp, argv[1], JIM_ERRMSG);
- if (cmdPtr == NULL) {
- return JIM_ERR;
- }
- JimPanic((cf->tailcallCmd != NULL, "Already have a tailcallCmd"));
- JimIncrCmdRefCount(cmdPtr);
- cf->tailcallCmd = cmdPtr;
- JimPanic((cf->tailcallObj != NULL, "Already have a tailcallobj"));
- cf->tailcallObj = Jim_NewListObj(interp, argv + 1, argc - 1);
- Jim_IncrRefCount(cf->tailcallObj);
- return JIM_EVAL;
- }
- return JIM_OK;
- }
- static int JimAliasCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *cmdList;
- Jim_Obj *prefixListObj = Jim_CmdPrivData(interp);
- cmdList = Jim_DuplicateObj(interp, prefixListObj);
- Jim_ListInsertElements(interp, cmdList, Jim_ListLength(interp, cmdList), argc - 1, argv + 1);
- return JimEvalObjList(interp, cmdList);
- }
- static void JimAliasCmdDelete(Jim_Interp *interp, void *privData)
- {
- Jim_Obj *prefixListObj = privData;
- Jim_DecrRefCount(interp, prefixListObj);
- }
- static int Jim_AliasCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *prefixListObj;
- if (argc < 3) {
- Jim_WrongNumArgs(interp, 1, argv, "newname command ?args ...?");
- return JIM_ERR;
- }
- prefixListObj = Jim_NewListObj(interp, argv + 2, argc - 2);
- Jim_IncrRefCount(prefixListObj);
- Jim_SetResult(interp, argv[1]);
- return Jim_CreateCommandObj(interp, argv[1], JimAliasCmd, prefixListObj, JimAliasCmdDelete);
- }
- static int Jim_ProcCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Cmd *cmd;
- if (argc != 4 && argc != 5) {
- Jim_WrongNumArgs(interp, 1, argv, "name arglist ?statics? body");
- return JIM_ERR;
- }
- if (argc == 4) {
- cmd = JimCreateProcedureCmd(interp, argv[2], NULL, argv[3], NULL);
- }
- else {
- cmd = JimCreateProcedureCmd(interp, argv[2], argv[3], argv[4], NULL);
- }
- if (cmd) {
- Jim_Obj *nameObjPtr = JimQualifyName(interp, argv[1]);
- JimCreateCommand(interp, nameObjPtr, cmd);
- JimUpdateProcNamespace(interp, cmd, nameObjPtr);
- Jim_DecrRefCount(interp, nameObjPtr);
- Jim_SetResult(interp, argv[1]);
- return JIM_OK;
- }
- return JIM_ERR;
- }
- static int Jim_XtraceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- if (argc != 2) {
- Jim_WrongNumArgs(interp, 1, argv, "callback");
- return JIM_ERR;
- }
- if (interp->traceCmdObj) {
- Jim_DecrRefCount(interp, interp->traceCmdObj);
- interp->traceCmdObj = NULL;
- }
- if (Jim_Length(argv[1])) {
- interp->traceCmdObj = argv[1];
- Jim_IncrRefCount(interp->traceCmdObj);
- }
- return JIM_OK;
- }
- static int Jim_LocalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int retcode;
- if (argc < 2) {
- Jim_WrongNumArgs(interp, 1, argv, "cmd ?args ...?");
- return JIM_ERR;
- }
- interp->local++;
- retcode = Jim_EvalObjVector(interp, argc - 1, argv + 1);
- interp->local--;
- if (retcode == 0) {
- Jim_Obj *cmdNameObj = Jim_GetResult(interp);
- if (Jim_GetCommand(interp, cmdNameObj, JIM_ERRMSG) == NULL) {
- return JIM_ERR;
- }
- if (interp->framePtr->localCommands == NULL) {
- interp->framePtr->localCommands = Jim_Alloc(sizeof(*interp->framePtr->localCommands));
- Jim_InitStack(interp->framePtr->localCommands);
- }
- Jim_IncrRefCount(cmdNameObj);
- Jim_StackPush(interp->framePtr->localCommands, cmdNameObj);
- }
- return retcode;
- }
- static int Jim_UpcallCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- if (argc < 2) {
- Jim_WrongNumArgs(interp, 1, argv, "cmd ?args ...?");
- return JIM_ERR;
- }
- else {
- int retcode;
- Jim_Cmd *cmdPtr = Jim_GetCommand(interp, argv[1], JIM_ERRMSG);
- if (cmdPtr == NULL || !cmdPtr->isproc || !cmdPtr->prevCmd) {
- Jim_SetResultFormatted(interp, "no previous command: \"%#s\"", argv[1]);
- return JIM_ERR;
- }
- cmdPtr->u.proc.upcall++;
- JimIncrCmdRefCount(cmdPtr);
- retcode = Jim_EvalObjVector(interp, argc - 1, argv + 1);
- cmdPtr->u.proc.upcall--;
- JimDecrCmdRefCount(interp, cmdPtr);
- return retcode;
- }
- }
- static int Jim_ApplyCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- if (argc < 2) {
- Jim_WrongNumArgs(interp, 1, argv, "lambdaExpr ?arg ...?");
- return JIM_ERR;
- }
- else {
- int ret;
- Jim_Cmd *cmd;
- Jim_Obj *argListObjPtr;
- Jim_Obj *bodyObjPtr;
- Jim_Obj *nsObj = NULL;
- Jim_Obj **nargv;
- int len = Jim_ListLength(interp, argv[1]);
- if (len != 2 && len != 3) {
- Jim_SetResultFormatted(interp, "can't interpret \"%#s\" as a lambda expression", argv[1]);
- return JIM_ERR;
- }
- if (len == 3) {
- #ifdef jim_ext_namespace
- nsObj = Jim_ListGetIndex(interp, argv[1], 2);
- #else
- Jim_SetResultString(interp, "namespaces not enabled", -1);
- return JIM_ERR;
- #endif
- }
- argListObjPtr = Jim_ListGetIndex(interp, argv[1], 0);
- bodyObjPtr = Jim_ListGetIndex(interp, argv[1], 1);
- cmd = JimCreateProcedureCmd(interp, argListObjPtr, NULL, bodyObjPtr, nsObj);
- if (cmd) {
- nargv = Jim_Alloc((argc - 2 + 1) * sizeof(*nargv));
- nargv[0] = Jim_NewStringObj(interp, "apply lambdaExpr", -1);
- Jim_IncrRefCount(nargv[0]);
- memcpy(&nargv[1], argv + 2, (argc - 2) * sizeof(*nargv));
- ret = JimCallProcedure(interp, cmd, argc - 2 + 1, nargv);
- Jim_DecrRefCount(interp, nargv[0]);
- Jim_Free(nargv);
- JimDecrCmdRefCount(interp, cmd);
- return ret;
- }
- return JIM_ERR;
- }
- }
- static int Jim_ConcatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_SetResult(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
- return JIM_OK;
- }
- static int Jim_UpvarCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int i;
- Jim_CallFrame *targetCallFrame;
- if (argc > 3 && (argc % 2 == 0)) {
- targetCallFrame = Jim_GetCallFrameByLevel(interp, argv[1]);
- argc--;
- argv++;
- }
- else {
- targetCallFrame = Jim_GetCallFrameByLevel(interp, NULL);
- }
- if (targetCallFrame == NULL) {
- return JIM_ERR;
- }
- if (argc < 3) {
- Jim_WrongNumArgs(interp, 1, argv, "?level? otherVar localVar ?otherVar localVar ...?");
- return JIM_ERR;
- }
- for (i = 1; i < argc; i += 2) {
- if (Jim_SetVariableLink(interp, argv[i + 1], argv[i], targetCallFrame) != JIM_OK)
- return JIM_ERR;
- }
- return JIM_OK;
- }
- static int Jim_GlobalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int i;
- if (argc < 2) {
- Jim_WrongNumArgs(interp, 1, argv, "varName ?varName ...?");
- return JIM_ERR;
- }
- if (interp->framePtr->level == 0)
- return JIM_OK;
- for (i = 1; i < argc; i++) {
- const char *name = Jim_String(argv[i]);
- if (name[0] != ':' || name[1] != ':') {
- if (Jim_SetVariableLink(interp, argv[i], argv[i], interp->topFramePtr) != JIM_OK)
- return JIM_ERR;
- }
- }
- return JIM_OK;
- }
- static Jim_Obj *JimStringMap(Jim_Interp *interp, Jim_Obj *mapListObjPtr,
- Jim_Obj *objPtr, int nocase)
- {
- int numMaps;
- const char *str, *noMatchStart = NULL;
- int strLen, i;
- Jim_Obj *resultObjPtr;
- numMaps = Jim_ListLength(interp, mapListObjPtr);
- if (numMaps % 2) {
- Jim_SetResultString(interp, "list must contain an even number of elements", -1);
- return NULL;
- }
- str = Jim_String(objPtr);
- strLen = Jim_Utf8Length(interp, objPtr);
- resultObjPtr = Jim_NewStringObj(interp, "", 0);
- while (strLen) {
- for (i = 0; i < numMaps; i += 2) {
- Jim_Obj *eachObjPtr;
- const char *k;
- int kl;
- eachObjPtr = Jim_ListGetIndex(interp, mapListObjPtr, i);
- k = Jim_String(eachObjPtr);
- kl = Jim_Utf8Length(interp, eachObjPtr);
- if (strLen >= kl && kl) {
- int rc;
- rc = JimStringCompareUtf8(str, kl, k, kl, nocase);
- if (rc == 0) {
- if (noMatchStart) {
- Jim_AppendString(interp, resultObjPtr, noMatchStart, str - noMatchStart);
- noMatchStart = NULL;
- }
- Jim_AppendObj(interp, resultObjPtr, Jim_ListGetIndex(interp, mapListObjPtr, i + 1));
- str += utf8_index(str, kl);
- strLen -= kl;
- break;
- }
- }
- }
- if (i == numMaps) {
- int c;
- if (noMatchStart == NULL)
- noMatchStart = str;
- str += utf8_tounicode(str, &c);
- strLen--;
- }
- }
- if (noMatchStart) {
- Jim_AppendString(interp, resultObjPtr, noMatchStart, str - noMatchStart);
- }
- return resultObjPtr;
- }
- static int Jim_StringCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int len;
- int opt_case = 1;
- int option;
- static const char * const nocase_options[] = {
- "-nocase", NULL
- };
- static const char * const nocase_length_options[] = {
- "-nocase", "-length", NULL
- };
- enum {
- OPT_BYTELENGTH,
- OPT_BYTERANGE,
- OPT_CAT,
- OPT_COMPARE,
- OPT_EQUAL,
- OPT_FIRST,
- OPT_INDEX,
- OPT_IS,
- OPT_LAST,
- OPT_LENGTH,
- OPT_MAP,
- OPT_MATCH,
- OPT_RANGE,
- OPT_REPEAT,
- OPT_REPLACE,
- OPT_REVERSE,
- OPT_TOLOWER,
- OPT_TOTITLE,
- OPT_TOUPPER,
- OPT_TRIM,
- OPT_TRIMLEFT,
- OPT_TRIMRIGHT,
- OPT_COUNT
- };
- static const jim_subcmd_type cmds[OPT_COUNT + 1] = {
- JIM_DEF_SUBCMD("bytelength", "string", 1, 1),
- JIM_DEF_SUBCMD("byterange", "string first last", 3, 3),
- JIM_DEF_SUBCMD("cat", "?...?", 0, -1),
- JIM_DEF_SUBCMD("compare", "?-nocase? ?-length int? string1 string2", 2, 5),
- JIM_DEF_SUBCMD("equal", "?-nocase? ?-length int? string1 string2", 2, 5),
- JIM_DEF_SUBCMD("first", "subString string ?index?", 2, 3),
- JIM_DEF_SUBCMD("index", "string index", 2, 2),
- JIM_DEF_SUBCMD("is", "class ?-strict? str", 2, 3),
- JIM_DEF_SUBCMD("last", "subString string ?index?", 2, 3),
- JIM_DEF_SUBCMD("length","string", 1, 1),
- JIM_DEF_SUBCMD("map", "?-nocase? mapList string", 2, 3),
- JIM_DEF_SUBCMD("match", "?-nocase? pattern string", 2, 3),
- JIM_DEF_SUBCMD("range", "string first last", 3, 3),
- JIM_DEF_SUBCMD("repeat", "string count", 2, 2),
- JIM_DEF_SUBCMD("replace", "string first last ?string?", 3, 4),
- JIM_DEF_SUBCMD("reverse", "string", 1, 1),
- JIM_DEF_SUBCMD("tolower", "string", 1, 1),
- JIM_DEF_SUBCMD("totitle", "string", 1, 1),
- JIM_DEF_SUBCMD("toupper", "string", 1, 1),
- JIM_DEF_SUBCMD("trim", "string ?trimchars?", 1, 2),
- JIM_DEF_SUBCMD("trimleft", "string ?trimchars?", 1, 2),
- JIM_DEF_SUBCMD("trimright", "string ?trimchars?", 1, 2),
- { NULL }
- };
- const jim_subcmd_type *ct = Jim_ParseSubCmd(interp, cmds, argc, argv);
- if (!ct) {
- return JIM_ERR;
- }
- if (ct->function) {
- return ct->function(interp, argc, argv);
- }
- option = ct - cmds;
- switch (option) {
- case OPT_LENGTH:
- Jim_SetResultInt(interp, Jim_Utf8Length(interp, argv[2]));
- return JIM_OK;
- case OPT_BYTELENGTH:
- Jim_SetResultInt(interp, Jim_Length(argv[2]));
- return JIM_OK;
- case OPT_CAT:{
- Jim_Obj *objPtr;
- if (argc == 3) {
- objPtr = argv[2];
- }
- else {
- int i;
- objPtr = Jim_NewStringObj(interp, "", 0);
- for (i = 2; i < argc; i++) {
- Jim_AppendObj(interp, objPtr, argv[i]);
- }
- }
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- case OPT_COMPARE:
- case OPT_EQUAL:
- {
- long opt_length = -1;
- int n = argc - 4;
- int i = 2;
- while (n > 0) {
- int subopt;
- if (Jim_GetEnum(interp, argv[i++], nocase_length_options, &subopt, NULL,
- JIM_ENUM_ABBREV) != JIM_OK) {
- badcompareargs:
- Jim_SubCmdArgError(interp, ct, argv[0]);
- return JIM_ERR;
- }
- if (subopt == 0) {
- opt_case = 0;
- n--;
- }
- else {
- if (n < 2) {
- goto badcompareargs;
- }
- if (Jim_GetLong(interp, argv[i++], &opt_length) != JIM_OK) {
- return JIM_ERR;
- }
- n -= 2;
- }
- }
- if (n) {
- goto badcompareargs;
- }
- argv += argc - 2;
- if (opt_length < 0 && option != OPT_COMPARE && opt_case) {
- Jim_SetResultBool(interp, Jim_StringEqObj(argv[0], argv[1]));
- }
- else {
- const char *s1 = Jim_String(argv[0]);
- int l1 = Jim_Utf8Length(interp, argv[0]);
- const char *s2 = Jim_String(argv[1]);
- int l2 = Jim_Utf8Length(interp, argv[1]);
- if (opt_length >= 0) {
- if (l1 > opt_length) {
- l1 = opt_length;
- }
- if (l2 > opt_length) {
- l2 = opt_length;
- }
- }
- n = JimStringCompareUtf8(s1, l1, s2, l2, !opt_case);
- Jim_SetResultInt(interp, option == OPT_COMPARE ? n : n == 0);
- }
- return JIM_OK;
- }
- case OPT_MATCH:
- if (argc != 4 &&
- (argc != 5 ||
- Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
- JIM_ENUM_ABBREV) != JIM_OK)) {
- Jim_WrongNumArgs(interp, 2, argv, "?-nocase? pattern string");
- return JIM_ERR;
- }
- if (opt_case == 0) {
- argv++;
- }
- Jim_SetResultBool(interp, Jim_StringMatchObj(interp, argv[2], argv[3], !opt_case));
- return JIM_OK;
- case OPT_MAP:{
- Jim_Obj *objPtr;
- if (argc != 4 &&
- (argc != 5 ||
- Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
- JIM_ENUM_ABBREV) != JIM_OK)) {
- Jim_WrongNumArgs(interp, 2, argv, "?-nocase? mapList string");
- return JIM_ERR;
- }
- if (opt_case == 0) {
- argv++;
- }
- objPtr = JimStringMap(interp, argv[2], argv[3], !opt_case);
- if (objPtr == NULL) {
- return JIM_ERR;
- }
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- case OPT_RANGE:{
- Jim_Obj *objPtr = Jim_StringRangeObj(interp, argv[2], argv[3], argv[4]);
- if (objPtr == NULL) {
- return JIM_ERR;
- }
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- case OPT_BYTERANGE:{
- Jim_Obj *objPtr = Jim_StringByteRangeObj(interp, argv[2], argv[3], argv[4]);
- if (objPtr == NULL) {
- return JIM_ERR;
- }
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- case OPT_REPLACE:{
- Jim_Obj *objPtr = JimStringReplaceObj(interp, argv[2], argv[3], argv[4], argc == 6 ? argv[5] : NULL);
- if (objPtr == NULL) {
- return JIM_ERR;
- }
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- case OPT_REPEAT:{
- Jim_Obj *objPtr;
- jim_wide count;
- if (Jim_GetWideExpr(interp, argv[3], &count) != JIM_OK) {
- return JIM_ERR;
- }
- objPtr = Jim_NewStringObj(interp, "", 0);
- if (count > 0) {
- while (count--) {
- Jim_AppendObj(interp, objPtr, argv[2]);
- }
- }
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- case OPT_REVERSE:{
- char *buf, *p;
- const char *str;
- int i;
- str = Jim_GetString(argv[2], &len);
- buf = Jim_Alloc(len + 1);
- assert(buf);
- p = buf + len;
- *p = 0;
- for (i = 0; i < len; ) {
- int c;
- int l = utf8_tounicode(str, &c);
- memcpy(p - l, str, l);
- p -= l;
- i += l;
- str += l;
- }
- Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, buf, len));
- return JIM_OK;
- }
- case OPT_INDEX:{
- int idx;
- const char *str;
- if (Jim_GetIndex(interp, argv[3], &idx) != JIM_OK) {
- return JIM_ERR;
- }
- str = Jim_String(argv[2]);
- len = Jim_Utf8Length(interp, argv[2]);
- idx = JimRelToAbsIndex(len, idx);
- if (idx < 0 || idx >= len || str == NULL) {
- Jim_SetResultString(interp, "", 0);
- }
- else if (len == Jim_Length(argv[2])) {
- Jim_SetResultString(interp, str + idx, 1);
- }
- else {
- int c;
- int i = utf8_index(str, idx);
- Jim_SetResultString(interp, str + i, utf8_tounicode(str + i, &c));
- }
- return JIM_OK;
- }
- case OPT_FIRST:
- case OPT_LAST:{
- int idx = 0, l1, l2;
- const char *s1, *s2;
- s1 = Jim_String(argv[2]);
- s2 = Jim_String(argv[3]);
- l1 = Jim_Utf8Length(interp, argv[2]);
- l2 = Jim_Utf8Length(interp, argv[3]);
- if (argc == 5) {
- if (Jim_GetIndex(interp, argv[4], &idx) != JIM_OK) {
- return JIM_ERR;
- }
- idx = JimRelToAbsIndex(l2, idx);
- if (idx < 0) {
- idx = 0;
- }
- }
- else if (option == OPT_LAST) {
- idx = l2;
- }
- if (option == OPT_FIRST) {
- Jim_SetResultInt(interp, JimStringFirst(s1, l1, s2, l2, idx));
- }
- else {
- #ifdef JIM_UTF8
- Jim_SetResultInt(interp, JimStringLastUtf8(s1, l1, s2, idx));
- #else
- Jim_SetResultInt(interp, JimStringLast(s1, l1, s2, idx));
- #endif
- }
- return JIM_OK;
- }
- case OPT_TRIM:
- Jim_SetResult(interp, JimStringTrim(interp, argv[2], argc == 4 ? argv[3] : NULL));
- return JIM_OK;
- case OPT_TRIMLEFT:
- Jim_SetResult(interp, JimStringTrimLeft(interp, argv[2], argc == 4 ? argv[3] : NULL));
- return JIM_OK;
- case OPT_TRIMRIGHT:{
- Jim_SetResult(interp, JimStringTrimRight(interp, argv[2], argc == 4 ? argv[3] : NULL));
- return JIM_OK;
- }
- case OPT_TOLOWER:
- Jim_SetResult(interp, JimStringToLower(interp, argv[2]));
- return JIM_OK;
- case OPT_TOUPPER:
- Jim_SetResult(interp, JimStringToUpper(interp, argv[2]));
- return JIM_OK;
- case OPT_TOTITLE:
- Jim_SetResult(interp, JimStringToTitle(interp, argv[2]));
- return JIM_OK;
- case OPT_IS:
- if (argc == 5 && !Jim_CompareStringImmediate(interp, argv[3], "-strict")) {
- Jim_SubCmdArgError(interp, ct, argv[0]);
- return JIM_ERR;
- }
- return JimStringIs(interp, argv[argc - 1], argv[2], argc == 5);
- }
- return JIM_OK;
- }
- static int Jim_TimeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- long i, count = 1;
- jim_wide start, elapsed;
- if (argc < 2) {
- Jim_WrongNumArgs(interp, 1, argv, "script ?count?");
- return JIM_ERR;
- }
- if (argc == 3) {
- if (Jim_GetLong(interp, argv[2], &count) != JIM_OK)
- return JIM_ERR;
- }
- if (count < 0)
- return JIM_OK;
- i = count;
- start = Jim_GetTimeUsec(CLOCK_MONOTONIC_RAW);
- while (i-- > 0) {
- int retval;
- retval = Jim_EvalObj(interp, argv[1]);
- if (retval != JIM_OK) {
- return retval;
- }
- }
- elapsed = Jim_GetTimeUsec(CLOCK_MONOTONIC_RAW) - start;
- if (elapsed < count * 10) {
- Jim_SetResult(interp, Jim_NewDoubleObj(interp, elapsed * 1.0 / count));
- }
- else {
- Jim_SetResultInt(interp, count == 0 ? 0 : elapsed / count);
- }
- Jim_AppendString(interp, Jim_GetResult(interp)," microseconds per iteration", -1);
- return JIM_OK;
- }
- static int Jim_TimeRateCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- long us = 0;
- jim_wide start, delta, overhead;
- Jim_Obj *objPtr;
- double us_per_iter;
- int count;
- int n;
- if (argc < 2) {
- Jim_WrongNumArgs(interp, 1, argv, "script ?milliseconds?");
- return JIM_ERR;
- }
- if (argc == 3) {
- if (Jim_GetLong(interp, argv[2], &us) != JIM_OK)
- return JIM_ERR;
- us *= 1000;
- }
- if (us < 1) {
- us = 1000 * 1000;
- }
- start = Jim_GetTimeUsec(CLOCK_MONOTONIC_RAW);
- count = 0;
- do {
- int retval = Jim_EvalObj(interp, argv[1]);
- delta = Jim_GetTimeUsec(CLOCK_MONOTONIC_RAW) - start;
- if (retval != JIM_OK) {
- return retval;
- }
- count++;
- } while (delta < us);
- start = Jim_GetTimeUsec(CLOCK_MONOTONIC_RAW);
- n = 0;
- do {
- int retval = Jim_EvalObj(interp, interp->nullScriptObj);
- overhead = Jim_GetTimeUsec(CLOCK_MONOTONIC_RAW) - start;
- if (retval != JIM_OK) {
- return retval;
- }
- n++;
- } while (n < count);
- delta -= overhead;
- us_per_iter = (double)delta / count;
- objPtr = Jim_NewListObj(interp, NULL, 0);
- Jim_ListAppendElement(interp, objPtr, Jim_NewStringObj(interp, "us_per_iter", -1));
- Jim_ListAppendElement(interp, objPtr, Jim_NewDoubleObj(interp, us_per_iter));
- Jim_ListAppendElement(interp, objPtr, Jim_NewStringObj(interp, "iters_per_sec", -1));
- Jim_ListAppendElement(interp, objPtr, Jim_NewDoubleObj(interp, 1e6 / us_per_iter));
- Jim_ListAppendElement(interp, objPtr, Jim_NewStringObj(interp, "count", -1));
- Jim_ListAppendElement(interp, objPtr, Jim_NewIntObj(interp, count));
- Jim_ListAppendElement(interp, objPtr, Jim_NewStringObj(interp, "elapsed_us", -1));
- Jim_ListAppendElement(interp, objPtr, Jim_NewIntObj(interp, delta));
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- static int Jim_ExitCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- long exitCode = 0;
- if (argc > 2) {
- Jim_WrongNumArgs(interp, 1, argv, "?exitCode?");
- return JIM_ERR;
- }
- if (argc == 2) {
- if (Jim_GetLong(interp, argv[1], &exitCode) != JIM_OK)
- return JIM_ERR;
- Jim_SetResult(interp, argv[1]);
- }
- interp->exitCode = exitCode;
- return JIM_EXIT;
- }
- static int JimMatchReturnCodes(Jim_Interp *interp, Jim_Obj *retcodeListObj, int rc)
- {
- int len = Jim_ListLength(interp, retcodeListObj);
- int i;
- for (i = 0; i < len; i++) {
- int returncode;
- if (Jim_GetReturnCode(interp, Jim_ListGetIndex(interp, retcodeListObj, i), &returncode) != JIM_OK) {
- return JIM_ERR;
- }
- if (rc == returncode) {
- return JIM_OK;
- }
- }
- return -1;
- }
- static int JimCatchTryHelper(Jim_Interp *interp, int istry, int argc, Jim_Obj *const *argv)
- {
- static const char * const wrongargs_catchtry[2] = {
- "?-?no?code ... --? script ?resultVarName? ?optionVarName?",
- "?-?no?code ... --? script ?on|trap codes vars script? ... ?finally script?"
- };
- int exitCode = 0;
- int i;
- int sig = 0;
- int ok;
- Jim_Obj *finallyScriptObj = NULL;
- Jim_Obj *msgVarObj = NULL;
- Jim_Obj *optsVarObj = NULL;
- Jim_Obj *handlerScriptObj = NULL;
- Jim_Obj *errorCodeObj;
- int idx;
- jim_wide ignore_mask = (1 << JIM_EXIT) | (1 << JIM_EVAL) | (1 << JIM_SIGNAL);
- static const int max_ignore_code = sizeof(ignore_mask) * 8;
- JimPanic((istry != 0 && istry != 1, "wrong args to JimCatchTryHelper"));
- Jim_SetGlobalVariableStr(interp, "errorCode", Jim_NewStringObj(interp, "NONE", -1));
- for (i = 1; i < argc - 1; i++) {
- const char *arg = Jim_String(argv[i]);
- jim_wide option;
- int ignore;
- if (strcmp(arg, "--") == 0) {
- i++;
- break;
- }
- if (*arg != '-') {
- break;
- }
- if (strncmp(arg, "-no", 3) == 0) {
- arg += 3;
- ignore = 1;
- }
- else {
- arg++;
- ignore = 0;
- }
- if (Jim_StringToWide(arg, &option, 10) != JIM_OK) {
- option = -1;
- }
- if (option < 0) {
- option = Jim_FindByName(arg, jimReturnCodes, jimReturnCodesSize);
- }
- if (option < 0) {
- goto wrongargs;
- }
- if (ignore) {
- ignore_mask |= ((jim_wide)1 << option);
- }
- else {
- ignore_mask &= (~((jim_wide)1 << option));
- }
- }
- idx = i;
- if (argc - idx < 1) {
- wrongargs:
- Jim_WrongNumArgs(interp, 1, argv, wrongargs_catchtry[istry]);
- return JIM_ERR;
- }
- if ((ignore_mask & (1 << JIM_SIGNAL)) == 0) {
- sig++;
- }
- interp->signal_level += sig;
- if (Jim_CheckSignal(interp)) {
- exitCode = JIM_SIGNAL;
- }
- else {
- exitCode = Jim_EvalObj(interp, argv[idx]);
- interp->errorFlag = 0;
- }
- interp->signal_level -= sig;
- errorCodeObj = Jim_GetGlobalVariableStr(interp, "errorCode", JIM_NONE);
- idx++;
- if (istry) {
- while (idx < argc) {
- int option;
- int ret;
- static const char * const try_options[] = { "on", "trap", "finally", NULL };
- enum { TRY_ON, TRY_TRAP, TRY_FINALLY, };
- if (Jim_GetEnum(interp, argv[idx], try_options, &option, "handler", JIM_ERRMSG) != JIM_OK) {
- return JIM_ERR;
- }
- switch (option) {
- case TRY_ON:
- case TRY_TRAP:
- if (idx + 4 > argc) {
- goto wrongargs;
- }
- if (option == TRY_ON) {
- ret = JimMatchReturnCodes(interp, argv[idx + 1], exitCode);
- if (ret > JIM_OK) {
- goto wrongargs;
- }
- }
- else if (errorCodeObj) {
- int len = Jim_ListLength(interp, argv[idx + 1]);
- int i;
- ret = JIM_OK;
- for (i = 0; i < len; i++) {
- Jim_Obj *matchObj = Jim_ListGetIndex(interp, argv[idx + 1], i);
- Jim_Obj *objPtr = Jim_ListGetIndex(interp, errorCodeObj, i);
- if (Jim_StringCompareObj(interp, matchObj, objPtr, 0) != 0) {
- ret = -1;
- break;
- }
- }
- }
- else {
- ret = -1;
- }
- if (ret == JIM_OK && handlerScriptObj == NULL) {
- msgVarObj = Jim_ListGetIndex(interp, argv[idx + 2], 0);
- optsVarObj = Jim_ListGetIndex(interp, argv[idx + 2], 1);
- handlerScriptObj = argv[idx + 3];
- }
- idx += 4;
- break;
- case TRY_FINALLY:
- if (idx + 2 != argc) {
- goto wrongargs;
- }
- finallyScriptObj = argv[idx + 1];
- idx += 2;
- break;
- }
- }
- }
- else {
- if (argc - idx >= 1) {
- msgVarObj = argv[idx];
- idx++;
- if (argc - idx >= 1) {
- optsVarObj = argv[idx];
- idx++;
- }
- }
- }
- if (exitCode >= 0 && exitCode < max_ignore_code && (((unsigned jim_wide)1 << exitCode) & ignore_mask)) {
- if (finallyScriptObj) {
- Jim_EvalObj(interp, finallyScriptObj);
- }
- return exitCode;
- }
- if (sig && exitCode == JIM_SIGNAL) {
- if (interp->signal_set_result) {
- interp->signal_set_result(interp, interp->sigmask);
- }
- else if (!istry) {
- Jim_SetResultInt(interp, interp->sigmask);
- }
- interp->sigmask = 0;
- }
- ok = 1;
- if (msgVarObj && Jim_Length(msgVarObj)) {
- if (Jim_SetVariable(interp, msgVarObj, Jim_GetResult(interp)) != JIM_OK) {
- ok = 0;
- }
- }
- if (ok && optsVarObj && Jim_Length(optsVarObj)) {
- Jim_Obj *optListObj = Jim_NewListObj(interp, NULL, 0);
- Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-code", -1));
- Jim_ListAppendElement(interp, optListObj,
- Jim_NewIntObj(interp, exitCode == JIM_RETURN ? interp->returnCode : exitCode));
- Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-level", -1));
- Jim_ListAppendElement(interp, optListObj, Jim_NewIntObj(interp, interp->returnLevel));
- if (exitCode == JIM_ERR) {
- Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-errorinfo",
- -1));
- Jim_ListAppendElement(interp, optListObj, interp->stackTrace);
- if (errorCodeObj) {
- Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-errorcode", -1));
- Jim_ListAppendElement(interp, optListObj, errorCodeObj);
- }
- }
- if (Jim_SetVariable(interp, optsVarObj, optListObj) != JIM_OK) {
- ok = 0;
- }
- }
- if (ok && handlerScriptObj) {
- exitCode = Jim_EvalObj(interp, handlerScriptObj);
- }
- if (finallyScriptObj) {
- Jim_Obj *prevResultObj = Jim_GetResult(interp);
- Jim_IncrRefCount(prevResultObj);
- int ret = Jim_EvalObj(interp, finallyScriptObj);
- if (ret == JIM_OK) {
- Jim_SetResult(interp, prevResultObj);
- }
- else {
- exitCode = ret;
- }
- Jim_DecrRefCount(interp, prevResultObj);
- }
- if (!istry) {
- Jim_SetResultInt(interp, exitCode);
- exitCode = JIM_OK;
- }
- return exitCode;
- }
- static int Jim_CatchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- return JimCatchTryHelper(interp, 0, argc, argv);
- }
- static int Jim_TryCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- return JimCatchTryHelper(interp, 1, argc, argv);
- }
- static int Jim_RenameCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- if (argc != 3) {
- Jim_WrongNumArgs(interp, 1, argv, "oldName newName");
- return JIM_ERR;
- }
- return Jim_RenameCommand(interp, argv[1], argv[2]);
- }
- #define JIM_DICTMATCH_KEYS 0x0001
- #define JIM_DICTMATCH_VALUES 0x002
- int Jim_DictMatchTypes(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *patternObj, int match_type, int return_types)
- {
- Jim_Obj *listObjPtr;
- Jim_Dict *dict;
- int i;
- if (SetDictFromAny(interp, objPtr) != JIM_OK) {
- return JIM_ERR;
- }
- dict = objPtr->internalRep.dictValue;
- listObjPtr = Jim_NewListObj(interp, NULL, 0);
- for (i = 0; i < dict->len; i += 2 ) {
- Jim_Obj *keyObj = dict->table[i];
- Jim_Obj *valObj = dict->table[i + 1];
- if (patternObj) {
- Jim_Obj *matchObj = (match_type == JIM_DICTMATCH_KEYS) ? keyObj : valObj;
- if (!Jim_StringMatchObj(interp, patternObj, matchObj, 0)) {
- continue;
- }
- }
- if (return_types & JIM_DICTMATCH_KEYS) {
- Jim_ListAppendElement(interp, listObjPtr, keyObj);
- }
- if (return_types & JIM_DICTMATCH_VALUES) {
- Jim_ListAppendElement(interp, listObjPtr, valObj);
- }
- }
- Jim_SetResult(interp, listObjPtr);
- return JIM_OK;
- }
- int Jim_DictSize(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- if (SetDictFromAny(interp, objPtr) != JIM_OK) {
- return -1;
- }
- return objPtr->internalRep.dictValue->len / 2;
- }
- Jim_Obj *Jim_DictMerge(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
- {
- Jim_Obj *objPtr = Jim_NewDictObj(interp, NULL, 0);
- int i;
- JimPanic((objc == 0, "Jim_DictMerge called with objc=0"));
- for (i = 0; i < objc; i++) {
- Jim_Obj **table;
- int tablelen;
- int j;
- table = Jim_DictPairs(interp, objv[i], &tablelen);
- if (tablelen && !table) {
- Jim_FreeNewObj(interp, objPtr);
- return NULL;
- }
- for (j = 0; j < tablelen; j += 2) {
- DictAddElement(interp, objPtr, table[j], table[j + 1]);
- }
- }
- return objPtr;
- }
- int Jim_DictInfo(Jim_Interp *interp, Jim_Obj *objPtr)
- {
- char buffer[100];
- Jim_Obj *output;
- Jim_Dict *dict;
- if (SetDictFromAny(interp, objPtr) != JIM_OK) {
- return JIM_ERR;
- }
- dict = objPtr->internalRep.dictValue;
- snprintf(buffer, sizeof(buffer), "%d entries in table, %d buckets", dict->len, dict->size);
- output = Jim_NewStringObj(interp, buffer, -1);
- Jim_SetResult(interp, output);
- return JIM_OK;
- }
- static int Jim_EvalEnsemble(Jim_Interp *interp, const char *basecmd, const char *subcmd, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *prefixObj = Jim_NewStringObj(interp, basecmd, -1);
- Jim_AppendString(interp, prefixObj, " ", 1);
- Jim_AppendString(interp, prefixObj, subcmd, -1);
- return Jim_EvalObjPrefix(interp, prefixObj, argc, argv);
- }
- static int JimDictWith(Jim_Interp *interp, Jim_Obj *dictVarName, Jim_Obj *const *keyv, int keyc, Jim_Obj *scriptObj)
- {
- int i;
- Jim_Obj *objPtr;
- Jim_Obj *dictObj;
- Jim_Obj **dictValues;
- int len;
- int ret = JIM_OK;
- dictObj = Jim_GetVariable(interp, dictVarName, JIM_ERRMSG);
- if (dictObj == NULL || Jim_DictKeysVector(interp, dictObj, keyv, keyc, &objPtr, JIM_ERRMSG) != JIM_OK) {
- return JIM_ERR;
- }
- dictValues = Jim_DictPairs(interp, objPtr, &len);
- if (len && dictValues == NULL) {
- return JIM_ERR;
- }
- for (i = 0; i < len; i += 2) {
- if (Jim_SetVariable(interp, dictValues[i], dictValues[i + 1]) == JIM_ERR) {
- return JIM_ERR;
- }
- }
- if (Jim_Length(scriptObj)) {
- ret = Jim_EvalObj(interp, scriptObj);
- if (ret == JIM_OK && Jim_GetVariable(interp, dictVarName, 0) != NULL) {
- Jim_Obj **newkeyv = Jim_Alloc(sizeof(*newkeyv) * (keyc + 1));
- for (i = 0; i < keyc; i++) {
- newkeyv[i] = keyv[i];
- }
- for (i = 0; i < len; i += 2) {
- if (Jim_StringCompareObj(interp, dictVarName, dictValues[i], 0) != 0) {
- objPtr = Jim_GetVariable(interp, dictValues[i], 0);
- newkeyv[keyc] = dictValues[i];
- Jim_SetDictKeysVector(interp, dictVarName, newkeyv, keyc + 1, objPtr, JIM_NORESULT);
- }
- }
- Jim_Free(newkeyv);
- }
- }
- return ret;
- }
- static int Jim_DictCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *objPtr;
- int types = JIM_DICTMATCH_KEYS;
- enum {
- OPT_CREATE,
- OPT_GET,
- OPT_GETDEF,
- OPT_GETWITHDEFAULT,
- OPT_SET,
- OPT_UNSET,
- OPT_EXISTS,
- OPT_KEYS,
- OPT_SIZE,
- OPT_INFO,
- OPT_MERGE,
- OPT_WITH,
- OPT_APPEND,
- OPT_LAPPEND,
- OPT_INCR,
- OPT_REMOVE,
- OPT_VALUES,
- OPT_FOR,
- OPT_REPLACE,
- OPT_UPDATE,
- OPT_COUNT
- };
- static const jim_subcmd_type cmds[OPT_COUNT + 1] = {
- JIM_DEF_SUBCMD("create", "?key value ...?", 0, -2),
- JIM_DEF_SUBCMD("get", "dictionary ?key ...?", 1, -1),
- JIM_DEF_SUBCMD_HIDDEN("getdef", "dictionary ?key ...? key default", 3, -1),
- JIM_DEF_SUBCMD("getwithdefault", "dictionary ?key ...? key default", 3, -1),
- JIM_DEF_SUBCMD("set", "varName key ?key ...? value", 3, -1),
- JIM_DEF_SUBCMD("unset", "varName key ?key ...?", 2, -1),
- JIM_DEF_SUBCMD("exists", "dictionary key ?key ...?", 2, -1),
- JIM_DEF_SUBCMD("keys", "dictionary ?pattern?", 1, 2),
- JIM_DEF_SUBCMD("size", "dictionary", 1, 1),
- JIM_DEF_SUBCMD("info", "dictionary", 1, 1),
- JIM_DEF_SUBCMD("merge", "?...?", 0, -1),
- JIM_DEF_SUBCMD("with", "dictVar ?key ...? script", 2, -1),
- JIM_DEF_SUBCMD("append", "varName key ?value ...?", 2, -1),
- JIM_DEF_SUBCMD("lappend", "varName key ?value ...?", 2, -1),
- JIM_DEF_SUBCMD("incr", "varName key ?increment?", 2, 3),
- JIM_DEF_SUBCMD("remove", "dictionary ?key ...?", 1, -1),
- JIM_DEF_SUBCMD("values", "dictionary ?pattern?", 1, 2),
- JIM_DEF_SUBCMD("for", "vars dictionary script", 3, 3),
- JIM_DEF_SUBCMD("replace", "dictionary ?key value ...?", 1, -1),
- JIM_DEF_SUBCMD("update", "varName ?arg ...? script", 2, -1),
- { NULL }
- };
- const jim_subcmd_type *ct = Jim_ParseSubCmd(interp, cmds, argc, argv);
- if (!ct) {
- return JIM_ERR;
- }
- if (ct->function) {
- return ct->function(interp, argc, argv);
- }
- switch (ct - cmds) {
- case OPT_GET:
- if (Jim_DictKeysVector(interp, argv[2], argv + 3, argc - 3, &objPtr,
- JIM_ERRMSG) != JIM_OK) {
- return JIM_ERR;
- }
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- case OPT_GETDEF:
- case OPT_GETWITHDEFAULT:{
- int rc = Jim_DictKeysVector(interp, argv[2], argv + 3, argc - 4, &objPtr, JIM_ERRMSG);
- if (rc == -1) {
- return JIM_ERR;
- }
- if (rc == JIM_ERR) {
- Jim_SetResult(interp, argv[argc - 1]);
- }
- else {
- Jim_SetResult(interp, objPtr);
- }
- return JIM_OK;
- }
- case OPT_SET:
- return Jim_SetDictKeysVector(interp, argv[2], argv + 3, argc - 4, argv[argc - 1], JIM_ERRMSG);
- case OPT_EXISTS:{
- int rc = Jim_DictKeysVector(interp, argv[2], argv + 3, argc - 3, &objPtr, JIM_NONE);
- if (rc < 0) {
- return JIM_ERR;
- }
- Jim_SetResultBool(interp, rc == JIM_OK);
- return JIM_OK;
- }
- case OPT_UNSET:
- if (Jim_SetDictKeysVector(interp, argv[2], argv + 3, argc - 3, NULL, JIM_NONE) != JIM_OK) {
- return JIM_ERR;
- }
- return JIM_OK;
- case OPT_VALUES:
- types = JIM_DICTMATCH_VALUES;
- case OPT_KEYS:
- return Jim_DictMatchTypes(interp, argv[2], argc == 4 ? argv[3] : NULL, types, types);
- case OPT_SIZE:
- if (Jim_DictSize(interp, argv[2]) < 0) {
- return JIM_ERR;
- }
- Jim_SetResultInt(interp, Jim_DictSize(interp, argv[2]));
- return JIM_OK;
- case OPT_MERGE:
- if (argc == 2) {
- return JIM_OK;
- }
- objPtr = Jim_DictMerge(interp, argc - 2, argv + 2);
- if (objPtr == NULL) {
- return JIM_ERR;
- }
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- case OPT_CREATE:
- objPtr = Jim_NewDictObj(interp, argv + 2, argc - 2);
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- case OPT_INFO:
- return Jim_DictInfo(interp, argv[2]);
- case OPT_WITH:
- return JimDictWith(interp, argv[2], argv + 3, argc - 4, argv[argc - 1]);
- case OPT_UPDATE:
- if (argc < 6 || argc % 2) {
- argc = 2;
- }
- default:
- return Jim_EvalEnsemble(interp, "dict", Jim_String(argv[1]), argc - 2, argv + 2);
- }
- }
- static int Jim_SubstCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- static const char * const options[] = {
- "-nobackslashes", "-nocommands", "-novariables", NULL
- };
- enum
- { OPT_NOBACKSLASHES, OPT_NOCOMMANDS, OPT_NOVARIABLES };
- int i;
- int flags = JIM_SUBST_FLAG;
- Jim_Obj *objPtr;
- if (argc < 2) {
- Jim_WrongNumArgs(interp, 1, argv, "?options? string");
- return JIM_ERR;
- }
- for (i = 1; i < (argc - 1); i++) {
- int option;
- if (Jim_GetEnum(interp, argv[i], options, &option, NULL,
- JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
- return JIM_ERR;
- }
- switch (option) {
- case OPT_NOBACKSLASHES:
- flags |= JIM_SUBST_NOESC;
- break;
- case OPT_NOCOMMANDS:
- flags |= JIM_SUBST_NOCMD;
- break;
- case OPT_NOVARIABLES:
- flags |= JIM_SUBST_NOVAR;
- break;
- }
- }
- if (Jim_SubstObj(interp, argv[argc - 1], &objPtr, flags) != JIM_OK) {
- return JIM_ERR;
- }
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- #ifdef jim_ext_namespace
- static int JimIsGlobalNamespace(Jim_Obj *objPtr)
- {
- int len;
- const char *str = Jim_GetString(objPtr, &len);
- return len >= 2 && str[0] == ':' && str[1] == ':';
- }
- #endif
- static int Jim_InfoCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *objPtr;
- int mode = 0;
- enum {
- INFO_ALIAS,
- INFO_ARGS,
- INFO_BODY,
- INFO_CHANNELS,
- INFO_COMMANDS,
- INFO_COMPLETE,
- INFO_EXISTS,
- INFO_FRAME,
- INFO_GLOBALS,
- INFO_HOSTNAME,
- INFO_LEVEL,
- INFO_LOCALS,
- INFO_NAMEOFEXECUTABLE,
- INFO_PATCHLEVEL,
- INFO_PROCS,
- INFO_REFERENCES,
- INFO_RETURNCODES,
- INFO_SCRIPT,
- INFO_SOURCE,
- INFO_STACKTRACE,
- INFO_STATICS,
- INFO_VARS,
- INFO_VERSION,
- INFO_COUNT
- };
- static const jim_subcmd_type cmds[INFO_COUNT + 1] = {
- JIM_DEF_SUBCMD("alias", "command", 1, 1),
- JIM_DEF_SUBCMD("args", "procname", 1, 1),
- JIM_DEF_SUBCMD("body", "procname", 1, 1),
- JIM_DEF_SUBCMD("channels", "?pattern?", 0, 1),
- JIM_DEF_SUBCMD("commands", "?pattern?", 0, 1),
- JIM_DEF_SUBCMD("complete", "script ?missing?", 1, 2),
- JIM_DEF_SUBCMD("exists", "varName", 1, 1),
- JIM_DEF_SUBCMD("frame", "?levelNum?", 0, 1),
- JIM_DEF_SUBCMD("globals", "?pattern?", 0, 1),
- JIM_DEF_SUBCMD("hostname", NULL, 0, 0),
- JIM_DEF_SUBCMD("level", "?levelNum?", 0, 1),
- JIM_DEF_SUBCMD("locals", "?pattern?", 0, 1),
- JIM_DEF_SUBCMD("nameofexecutable", NULL, 0, 0),
- JIM_DEF_SUBCMD("patchlevel", NULL, 0, 0),
- JIM_DEF_SUBCMD("procs", "?pattern?", 0, 1),
- JIM_DEF_SUBCMD("references", NULL, 0, 0),
- JIM_DEF_SUBCMD("returncodes", "?code?", 0, 1),
- JIM_DEF_SUBCMD("script", "?filename?", 0, 1),
- JIM_DEF_SUBCMD("source", "source ?filename line?", 1, 3),
- JIM_DEF_SUBCMD("stacktrace", NULL, 0, 0),
- JIM_DEF_SUBCMD("statics", "procname", 1, 1),
- JIM_DEF_SUBCMD("vars", "?pattern?", 0, 1),
- JIM_DEF_SUBCMD("version", NULL, 0, 0),
- { NULL }
- };
- const jim_subcmd_type *ct;
- #ifdef jim_ext_namespace
- int nons = 0;
- if (argc > 2 && Jim_CompareStringImmediate(interp, argv[1], "-nons")) {
- argc--;
- argv++;
- nons = 1;
- }
- #endif
- ct = Jim_ParseSubCmd(interp, cmds, argc, argv);
- if (!ct) {
- return JIM_ERR;
- }
- if (ct->function) {
- return ct->function(interp, argc, argv);
- }
- int option = ct - cmds;
- switch (option) {
- case INFO_EXISTS:
- Jim_SetResultBool(interp, Jim_GetVariable(interp, argv[2], 0) != NULL);
- return JIM_OK;
- case INFO_ALIAS:{
- Jim_Cmd *cmdPtr;
- if ((cmdPtr = Jim_GetCommand(interp, argv[2], JIM_ERRMSG)) == NULL) {
- return JIM_ERR;
- }
- if (cmdPtr->isproc || cmdPtr->u.native.cmdProc != JimAliasCmd) {
- Jim_SetResultFormatted(interp, "command \"%#s\" is not an alias", argv[2]);
- return JIM_ERR;
- }
- Jim_SetResult(interp, (Jim_Obj *)cmdPtr->u.native.privData);
- return JIM_OK;
- }
- case INFO_CHANNELS:
- mode++;
- #ifndef jim_ext_aio
- Jim_SetResultString(interp, "aio not enabled", -1);
- return JIM_ERR;
- #endif
- case INFO_PROCS:
- mode++;
- case INFO_COMMANDS:
- #ifdef jim_ext_namespace
- if (!nons) {
- if (Jim_Length(interp->framePtr->nsObj) || (argc == 3 && JimIsGlobalNamespace(argv[2]))) {
- return Jim_EvalPrefix(interp, "namespace info", argc - 1, argv + 1);
- }
- }
- #endif
- Jim_SetResult(interp, JimCommandsList(interp, (argc == 3) ? argv[2] : NULL, mode));
- return JIM_OK;
- case INFO_VARS:
- mode++;
- case INFO_LOCALS:
- mode++;
- case INFO_GLOBALS:
- #ifdef jim_ext_namespace
- if (!nons) {
- if (Jim_Length(interp->framePtr->nsObj) || (argc == 3 && JimIsGlobalNamespace(argv[2]))) {
- return Jim_EvalPrefix(interp, "namespace info", argc - 1, argv + 1);
- }
- }
- #endif
- Jim_SetResult(interp, JimVariablesList(interp, argc == 3 ? argv[2] : NULL, mode));
- return JIM_OK;
- case INFO_SCRIPT:
- if (argc == 3) {
- Jim_IncrRefCount(argv[2]);
- Jim_DecrRefCount(interp, interp->currentFilenameObj);
- interp->currentFilenameObj = argv[2];
- }
- Jim_SetResult(interp, interp->currentFilenameObj);
- return JIM_OK;
- case INFO_SOURCE:{
- Jim_Obj *resObjPtr;
- Jim_Obj *fileNameObj;
- if (argc == 4) {
- Jim_SubCmdArgError(interp, ct, argv[0]);
- return JIM_ERR;
- }
- if (argc == 5) {
- jim_wide line;
- if (Jim_GetWide(interp, argv[4], &line) != JIM_OK) {
- return JIM_ERR;
- }
- resObjPtr = Jim_NewStringObj(interp, Jim_String(argv[2]), Jim_Length(argv[2]));
- Jim_SetSourceInfo(interp, resObjPtr, argv[3], line);
- }
- else {
- int line;
- fileNameObj = Jim_GetSourceInfo(interp, argv[2], &line);
- resObjPtr = Jim_NewListObj(interp, NULL, 0);
- Jim_ListAppendElement(interp, resObjPtr, fileNameObj);
- Jim_ListAppendElement(interp, resObjPtr, Jim_NewIntObj(interp, line));
- }
- Jim_SetResult(interp, resObjPtr);
- return JIM_OK;
- }
- case INFO_STACKTRACE:
- Jim_SetResult(interp, interp->stackTrace);
- return JIM_OK;
- case INFO_LEVEL:
- if (argc == 2) {
- Jim_SetResultInt(interp, interp->framePtr->level);
- }
- else {
- if (JimInfoLevel(interp, argv[2], &objPtr) != JIM_OK) {
- return JIM_ERR;
- }
- Jim_SetResult(interp, objPtr);
- }
- return JIM_OK;
- case INFO_FRAME:
- if (argc == 2) {
- Jim_SetResultInt(interp, interp->procLevel + 1);
- }
- else {
- if (JimInfoFrame(interp, argv[2], &objPtr) != JIM_OK) {
- return JIM_ERR;
- }
- Jim_SetResult(interp, objPtr);
- }
- return JIM_OK;
- case INFO_BODY:
- case INFO_STATICS:
- case INFO_ARGS:{
- Jim_Cmd *cmdPtr;
- if ((cmdPtr = Jim_GetCommand(interp, argv[2], JIM_ERRMSG)) == NULL) {
- return JIM_ERR;
- }
- if (!cmdPtr->isproc) {
- Jim_SetResultFormatted(interp, "command \"%#s\" is not a procedure", argv[2]);
- return JIM_ERR;
- }
- switch (option) {
- #ifdef JIM_NO_INTROSPECTION
- default:
- Jim_SetResultString(interp, "unsupported", -1);
- return JIM_ERR;
- #else
- case INFO_BODY:
- Jim_SetResult(interp, cmdPtr->u.proc.bodyObjPtr);
- break;
- case INFO_ARGS:
- Jim_SetResult(interp, cmdPtr->u.proc.argListObjPtr);
- break;
- #endif
- case INFO_STATICS:
- if (cmdPtr->u.proc.staticVars) {
- Jim_SetResult(interp, JimHashtablePatternMatch(interp, cmdPtr->u.proc.staticVars,
- NULL, JimVariablesMatch, JIM_VARLIST_LOCALS | JIM_VARLIST_VALUES));
- }
- break;
- }
- return JIM_OK;
- }
- case INFO_VERSION:
- case INFO_PATCHLEVEL:{
- char buf[(JIM_INTEGER_SPACE * 2) + 1];
- sprintf(buf, "%d.%d", JIM_VERSION / 100, JIM_VERSION % 100);
- Jim_SetResultString(interp, buf, -1);
- return JIM_OK;
- }
- case INFO_COMPLETE: {
- char missing;
- Jim_SetResultBool(interp, Jim_ScriptIsComplete(interp, argv[2], &missing));
- if (missing != ' ' && argc == 4) {
- Jim_SetVariable(interp, argv[3], Jim_NewStringObj(interp, &missing, 1));
- }
- return JIM_OK;
- }
- case INFO_HOSTNAME:
- return Jim_Eval(interp, "os.gethostname");
- case INFO_NAMEOFEXECUTABLE:
- return Jim_Eval(interp, "{info nameofexecutable}");
- case INFO_RETURNCODES:
- if (argc == 2) {
- int i;
- Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
- for (i = 0; jimReturnCodes[i]; i++) {
- Jim_ListAppendElement(interp, listObjPtr, Jim_NewIntObj(interp, i));
- Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp,
- jimReturnCodes[i], -1));
- }
- Jim_SetResult(interp, listObjPtr);
- }
- else if (argc == 3) {
- long code;
- const char *name;
- if (Jim_GetLong(interp, argv[2], &code) != JIM_OK) {
- return JIM_ERR;
- }
- name = Jim_ReturnCode(code);
- if (*name == '?') {
- Jim_SetResultInt(interp, code);
- }
- else {
- Jim_SetResultString(interp, name, -1);
- }
- }
- return JIM_OK;
- case INFO_REFERENCES:
- #ifdef JIM_REFERENCES
- return JimInfoReferences(interp, argc, argv);
- #else
- Jim_SetResultString(interp, "not supported", -1);
- return JIM_ERR;
- #endif
- default:
- abort();
- }
- }
- static int Jim_ExistsCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *objPtr;
- int result = 0;
- static const char * const options[] = {
- "-command", "-proc", "-alias", "-var", NULL
- };
- enum
- {
- OPT_COMMAND, OPT_PROC, OPT_ALIAS, OPT_VAR
- };
- int option;
- if (argc == 2) {
- option = OPT_VAR;
- objPtr = argv[1];
- }
- else if (argc == 3) {
- if (Jim_GetEnum(interp, argv[1], options, &option, NULL, JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
- return JIM_ERR;
- }
- objPtr = argv[2];
- }
- else {
- Jim_WrongNumArgs(interp, 1, argv, "?option? name");
- return JIM_ERR;
- }
- if (option == OPT_VAR) {
- result = Jim_GetVariable(interp, objPtr, 0) != NULL;
- }
- else {
- Jim_Cmd *cmd = Jim_GetCommand(interp, objPtr, JIM_NONE);
- if (cmd) {
- switch (option) {
- case OPT_COMMAND:
- result = 1;
- break;
- case OPT_ALIAS:
- result = cmd->isproc == 0 && cmd->u.native.cmdProc == JimAliasCmd;
- break;
- case OPT_PROC:
- result = cmd->isproc;
- break;
- }
- }
- }
- Jim_SetResultBool(interp, result);
- return JIM_OK;
- }
- static int Jim_SplitCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- const char *str, *splitChars, *noMatchStart;
- int splitLen, strLen;
- Jim_Obj *resObjPtr;
- int c;
- int len;
- if (argc != 2 && argc != 3) {
- Jim_WrongNumArgs(interp, 1, argv, "string ?splitChars?");
- return JIM_ERR;
- }
- str = Jim_GetString(argv[1], &len);
- if (len == 0) {
- return JIM_OK;
- }
- strLen = Jim_Utf8Length(interp, argv[1]);
- if (argc == 2) {
- splitChars = " \n\t\r";
- splitLen = 4;
- }
- else {
- splitChars = Jim_String(argv[2]);
- splitLen = Jim_Utf8Length(interp, argv[2]);
- }
- noMatchStart = str;
- resObjPtr = Jim_NewListObj(interp, NULL, 0);
- if (splitLen) {
- Jim_Obj *objPtr;
- while (strLen--) {
- const char *sc = splitChars;
- int scLen = splitLen;
- int sl = utf8_tounicode(str, &c);
- while (scLen--) {
- int pc;
- sc += utf8_tounicode(sc, &pc);
- if (c == pc) {
- objPtr = Jim_NewStringObj(interp, noMatchStart, (str - noMatchStart));
- Jim_ListAppendElement(interp, resObjPtr, objPtr);
- noMatchStart = str + sl;
- break;
- }
- }
- str += sl;
- }
- objPtr = Jim_NewStringObj(interp, noMatchStart, (str - noMatchStart));
- Jim_ListAppendElement(interp, resObjPtr, objPtr);
- }
- else {
- Jim_Obj **commonObj = NULL;
- #define NUM_COMMON (128 - 9)
- while (strLen--) {
- int n = utf8_tounicode(str, &c);
- #ifdef JIM_OPTIMIZATION
- if (c >= 9 && c < 128) {
- c -= 9;
- if (!commonObj) {
- commonObj = Jim_Alloc(sizeof(*commonObj) * NUM_COMMON);
- memset(commonObj, 0, sizeof(*commonObj) * NUM_COMMON);
- }
- if (!commonObj[c]) {
- commonObj[c] = Jim_NewStringObj(interp, str, 1);
- }
- Jim_ListAppendElement(interp, resObjPtr, commonObj[c]);
- str++;
- continue;
- }
- #endif
- Jim_ListAppendElement(interp, resObjPtr, Jim_NewStringObjUtf8(interp, str, 1));
- str += n;
- }
- Jim_Free(commonObj);
- }
- Jim_SetResult(interp, resObjPtr);
- return JIM_OK;
- }
- static int Jim_JoinCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- const char *joinStr;
- int joinStrLen;
- if (argc != 2 && argc != 3) {
- Jim_WrongNumArgs(interp, 1, argv, "list ?joinString?");
- return JIM_ERR;
- }
- if (argc == 2) {
- joinStr = " ";
- joinStrLen = 1;
- }
- else {
- joinStr = Jim_GetString(argv[2], &joinStrLen);
- }
- Jim_SetResult(interp, Jim_ListJoin(interp, argv[1], joinStr, joinStrLen));
- return JIM_OK;
- }
- static int Jim_FormatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *objPtr;
- if (argc < 2) {
- Jim_WrongNumArgs(interp, 1, argv, "formatString ?arg arg ...?");
- return JIM_ERR;
- }
- objPtr = Jim_FormatString(interp, argv[1], argc - 2, argv + 2);
- if (objPtr == NULL)
- return JIM_ERR;
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- static int Jim_ScanCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *listPtr, **outVec;
- int outc, i;
- if (argc < 3) {
- Jim_WrongNumArgs(interp, 1, argv, "string format ?varName varName ...?");
- return JIM_ERR;
- }
- if (argv[2]->typePtr != &scanFmtStringObjType)
- SetScanFmtFromAny(interp, argv[2]);
- if (FormatGetError(argv[2]) != 0) {
- Jim_SetResultString(interp, FormatGetError(argv[2]), -1);
- return JIM_ERR;
- }
- if (argc > 3) {
- int maxPos = FormatGetMaxPos(argv[2]);
- int count = FormatGetCnvCount(argv[2]);
- if (maxPos > argc - 3) {
- Jim_SetResultString(interp, "\"%n$\" argument index out of range", -1);
- return JIM_ERR;
- }
- else if (count > argc - 3) {
- Jim_SetResultString(interp, "different numbers of variable names and "
- "field specifiers", -1);
- return JIM_ERR;
- }
- else if (count < argc - 3) {
- Jim_SetResultString(interp, "variable is not assigned by any "
- "conversion specifiers", -1);
- return JIM_ERR;
- }
- }
- listPtr = Jim_ScanString(interp, argv[1], argv[2], JIM_ERRMSG);
- if (listPtr == 0)
- return JIM_ERR;
- if (argc > 3) {
- int rc = JIM_OK;
- int count = 0;
- if (listPtr != 0 && listPtr != (Jim_Obj *)EOF) {
- int len = Jim_ListLength(interp, listPtr);
- if (len != 0) {
- JimListGetElements(interp, listPtr, &outc, &outVec);
- for (i = 0; i < outc; ++i) {
- if (Jim_Length(outVec[i]) > 0) {
- ++count;
- if (Jim_SetVariable(interp, argv[3 + i], outVec[i]) != JIM_OK) {
- rc = JIM_ERR;
- }
- }
- }
- }
- Jim_FreeNewObj(interp, listPtr);
- }
- else {
- count = -1;
- }
- if (rc == JIM_OK) {
- Jim_SetResultInt(interp, count);
- }
- return rc;
- }
- else {
- if (listPtr == (Jim_Obj *)EOF) {
- Jim_SetResult(interp, Jim_NewListObj(interp, 0, 0));
- return JIM_OK;
- }
- Jim_SetResult(interp, listPtr);
- }
- return JIM_OK;
- }
- static int Jim_ErrorCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- if (argc != 2 && argc != 3) {
- Jim_WrongNumArgs(interp, 1, argv, "message ?stacktrace?");
- return JIM_ERR;
- }
- Jim_SetResult(interp, argv[1]);
- if (argc == 3) {
- JimSetStackTrace(interp, argv[2]);
- return JIM_ERR;
- }
- return JIM_ERR;
- }
- static int Jim_LrangeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *objPtr;
- if (argc != 4) {
- Jim_WrongNumArgs(interp, 1, argv, "list first last");
- return JIM_ERR;
- }
- if ((objPtr = Jim_ListRange(interp, argv[1], argv[2], argv[3])) == NULL)
- return JIM_ERR;
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- static int Jim_LrepeatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *objPtr;
- jim_wide count;
- if (argc < 2 || Jim_GetWideExpr(interp, argv[1], &count) != JIM_OK || count < 0) {
- Jim_WrongNumArgs(interp, 1, argv, "count ?value ...?");
- return JIM_ERR;
- }
- if (count == 0 || argc == 2) {
- Jim_SetEmptyResult(interp);
- return JIM_OK;
- }
- argc -= 2;
- argv += 2;
- objPtr = Jim_NewListObj(interp, NULL, 0);
- ListEnsureLength(objPtr, argc * count);
- while (count--) {
- ListInsertElements(objPtr, -1, argc, argv);
- }
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- char **Jim_GetEnviron(void)
- {
- #if defined(HAVE__NSGETENVIRON)
- return *_NSGetEnviron();
- #elif defined(_environ)
- return _environ;
- #else
- #if !defined(NO_ENVIRON_EXTERN)
- extern char **environ;
- #endif
- return environ;
- #endif
- }
- void Jim_SetEnviron(char **env)
- {
- #if defined(HAVE__NSGETENVIRON)
- *_NSGetEnviron() = env;
- #elif defined(_environ)
- _environ = env;
- #else
- #if !defined(NO_ENVIRON_EXTERN)
- extern char **environ;
- #endif
- environ = env;
- #endif
- }
- static int Jim_EnvCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- const char *key;
- const char *val;
- if (argc == 1) {
- char **e = Jim_GetEnviron();
- int i;
- Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
- for (i = 0; e[i]; i++) {
- const char *equals = strchr(e[i], '=');
- if (equals) {
- Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, e[i],
- equals - e[i]));
- Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, equals + 1, -1));
- }
- }
- Jim_SetResult(interp, listObjPtr);
- return JIM_OK;
- }
- if (argc > 3) {
- Jim_WrongNumArgs(interp, 1, argv, "varName ?default?");
- return JIM_ERR;
- }
- key = Jim_String(argv[1]);
- val = getenv(key);
- if (val == NULL) {
- if (argc < 3) {
- Jim_SetResultFormatted(interp, "environment variable \"%#s\" does not exist", argv[1]);
- return JIM_ERR;
- }
- val = Jim_String(argv[2]);
- }
- Jim_SetResult(interp, Jim_NewStringObj(interp, val, -1));
- return JIM_OK;
- }
- static int Jim_SourceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- int retval;
- if (argc != 2) {
- Jim_WrongNumArgs(interp, 1, argv, "fileName");
- return JIM_ERR;
- }
- retval = Jim_EvalFile(interp, Jim_String(argv[1]));
- if (retval == JIM_RETURN)
- return JIM_OK;
- return retval;
- }
- static int Jim_LreverseCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- Jim_Obj *revObjPtr, **ele;
- int len;
- if (argc != 2) {
- Jim_WrongNumArgs(interp, 1, argv, "list");
- return JIM_ERR;
- }
- JimListGetElements(interp, argv[1], &len, &ele);
- revObjPtr = Jim_NewListObj(interp, NULL, 0);
- ListEnsureLength(revObjPtr, len);
- len--;
- while (len >= 0)
- ListAppendElement(revObjPtr, ele[len--]);
- Jim_SetResult(interp, revObjPtr);
- return JIM_OK;
- }
- static int JimRangeLen(jim_wide start, jim_wide end, jim_wide step)
- {
- jim_wide len;
- if (step == 0)
- return -1;
- if (start == end)
- return 0;
- else if (step > 0 && start > end)
- return -1;
- else if (step < 0 && end > start)
- return -1;
- len = end - start;
- if (len < 0)
- len = -len;
- if (step < 0)
- step = -step;
- len = 1 + ((len - 1) / step);
- if (len > INT_MAX)
- len = INT_MAX;
- return (int)((len < 0) ? -1 : len);
- }
- static int Jim_RangeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- jim_wide start = 0, end, step = 1;
- int len, i;
- Jim_Obj *objPtr;
- if (argc < 2 || argc > 4) {
- Jim_WrongNumArgs(interp, 1, argv, "?start? end ?step?");
- return JIM_ERR;
- }
- if (argc == 2) {
- if (Jim_GetWideExpr(interp, argv[1], &end) != JIM_OK)
- return JIM_ERR;
- }
- else {
- if (Jim_GetWideExpr(interp, argv[1], &start) != JIM_OK ||
- Jim_GetWideExpr(interp, argv[2], &end) != JIM_OK)
- return JIM_ERR;
- if (argc == 4 && Jim_GetWideExpr(interp, argv[3], &step) != JIM_OK)
- return JIM_ERR;
- }
- if ((len = JimRangeLen(start, end, step)) == -1) {
- Jim_SetResultString(interp, "Invalid (infinite?) range specified", -1);
- return JIM_ERR;
- }
- objPtr = Jim_NewListObj(interp, NULL, 0);
- ListEnsureLength(objPtr, len);
- for (i = 0; i < len; i++)
- ListAppendElement(objPtr, Jim_NewIntObj(interp, start + i * step));
- Jim_SetResult(interp, objPtr);
- return JIM_OK;
- }
- static int Jim_RandCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- jim_wide min = 0, max = 0, len, maxMul;
- if (argc < 1 || argc > 3) {
- Jim_WrongNumArgs(interp, 1, argv, "?min? max");
- return JIM_ERR;
- }
- if (argc == 1) {
- max = JIM_WIDE_MAX;
- } else if (argc == 2) {
- if (Jim_GetWideExpr(interp, argv[1], &max) != JIM_OK)
- return JIM_ERR;
- } else if (argc == 3) {
- if (Jim_GetWideExpr(interp, argv[1], &min) != JIM_OK ||
- Jim_GetWideExpr(interp, argv[2], &max) != JIM_OK)
- return JIM_ERR;
- }
- len = max-min;
- if (len < 0) {
- Jim_SetResultString(interp, "Invalid arguments (max < min)", -1);
- return JIM_ERR;
- }
- maxMul = JIM_WIDE_MAX - (len ? (JIM_WIDE_MAX%len) : 0);
- while (1) {
- jim_wide r;
- JimRandomBytes(interp, &r, sizeof(jim_wide));
- if (r < 0 || r >= maxMul) continue;
- r = (len == 0) ? 0 : r%len;
- Jim_SetResultInt(interp, min+r);
- return JIM_OK;
- }
- }
- static const struct {
- const char *name;
- Jim_CmdProc *cmdProc;
- } Jim_CoreCommandsTable[] = {
- {"alias", Jim_AliasCoreCommand},
- {"set", Jim_SetCoreCommand},
- {"unset", Jim_UnsetCoreCommand},
- {"puts", Jim_PutsCoreCommand},
- {"+", Jim_AddCoreCommand},
- {"*", Jim_MulCoreCommand},
- {"-", Jim_SubCoreCommand},
- {"/", Jim_DivCoreCommand},
- {"incr", Jim_IncrCoreCommand},
- {"while", Jim_WhileCoreCommand},
- {"loop", Jim_LoopCoreCommand},
- {"for", Jim_ForCoreCommand},
- {"foreach", Jim_ForeachCoreCommand},
- {"lmap", Jim_LmapCoreCommand},
- {"lassign", Jim_LassignCoreCommand},
- {"if", Jim_IfCoreCommand},
- {"switch", Jim_SwitchCoreCommand},
- {"list", Jim_ListCoreCommand},
- {"lindex", Jim_LindexCoreCommand},
- {"lset", Jim_LsetCoreCommand},
- {"lsearch", Jim_LsearchCoreCommand},
- {"llength", Jim_LlengthCoreCommand},
- {"lappend", Jim_LappendCoreCommand},
- {"linsert", Jim_LinsertCoreCommand},
- {"lreplace", Jim_LreplaceCoreCommand},
- {"lsort", Jim_LsortCoreCommand},
- {"append", Jim_AppendCoreCommand},
- {"eval", Jim_EvalCoreCommand},
- {"uplevel", Jim_UplevelCoreCommand},
- {"expr", Jim_ExprCoreCommand},
- {"break", Jim_BreakCoreCommand},
- {"continue", Jim_ContinueCoreCommand},
- {"proc", Jim_ProcCoreCommand},
- {"xtrace", Jim_XtraceCoreCommand},
- {"concat", Jim_ConcatCoreCommand},
- {"return", Jim_ReturnCoreCommand},
- {"upvar", Jim_UpvarCoreCommand},
- {"global", Jim_GlobalCoreCommand},
- {"string", Jim_StringCoreCommand},
- {"time", Jim_TimeCoreCommand},
- {"timerate", Jim_TimeRateCoreCommand},
- {"exit", Jim_ExitCoreCommand},
- {"catch", Jim_CatchCoreCommand},
- {"try", Jim_TryCoreCommand},
- #ifdef JIM_REFERENCES
- {"ref", Jim_RefCoreCommand},
- {"getref", Jim_GetrefCoreCommand},
- {"setref", Jim_SetrefCoreCommand},
- {"finalize", Jim_FinalizeCoreCommand},
- {"collect", Jim_CollectCoreCommand},
- #endif
- {"rename", Jim_RenameCoreCommand},
- {"dict", Jim_DictCoreCommand},
- {"subst", Jim_SubstCoreCommand},
- {"info", Jim_InfoCoreCommand},
- {"exists", Jim_ExistsCoreCommand},
- {"split", Jim_SplitCoreCommand},
- {"join", Jim_JoinCoreCommand},
- {"format", Jim_FormatCoreCommand},
- {"scan", Jim_ScanCoreCommand},
- {"error", Jim_ErrorCoreCommand},
- {"lrange", Jim_LrangeCoreCommand},
- {"lrepeat", Jim_LrepeatCoreCommand},
- {"env", Jim_EnvCoreCommand},
- {"source", Jim_SourceCoreCommand},
- {"lreverse", Jim_LreverseCoreCommand},
- {"range", Jim_RangeCoreCommand},
- {"rand", Jim_RandCoreCommand},
- {"tailcall", Jim_TailcallCoreCommand},
- {"local", Jim_LocalCoreCommand},
- {"upcall", Jim_UpcallCoreCommand},
- {"apply", Jim_ApplyCoreCommand},
- {"stacktrace", Jim_StacktraceCoreCommand},
- {NULL, NULL},
- };
- void Jim_RegisterCoreCommands(Jim_Interp *interp)
- {
- int i = 0;
- while (Jim_CoreCommandsTable[i].name != NULL) {
- Jim_CreateCommand(interp,
- Jim_CoreCommandsTable[i].name, Jim_CoreCommandsTable[i].cmdProc, NULL, NULL);
- i++;
- }
- }
- void Jim_MakeErrorMessage(Jim_Interp *interp)
- {
- Jim_Obj *argv[2];
- argv[0] = Jim_NewStringObj(interp, "errorInfo", -1);
- argv[1] = interp->result;
- Jim_EvalObjVector(interp, 2, argv);
- }
- static char **JimSortStringTable(const char *const *tablePtr)
- {
- int count;
- char **tablePtrSorted;
- for (count = 0; tablePtr[count]; count++) {
- }
- tablePtrSorted = Jim_Alloc(sizeof(char *) * (count + 1));
- memcpy(tablePtrSorted, tablePtr, sizeof(char *) * count);
- qsort(tablePtrSorted, count, sizeof(char *), qsortCompareStringPointers);
- tablePtrSorted[count] = NULL;
- return tablePtrSorted;
- }
- static void JimSetFailedEnumResult(Jim_Interp *interp, const char *arg, const char *badtype,
- const char *prefix, const char *const *tablePtr, const char *name)
- {
- char **tablePtrSorted;
- int i;
- if (name == NULL) {
- name = "option";
- }
- Jim_SetResultFormatted(interp, "%s%s \"%s\": must be ", badtype, name, arg);
- tablePtrSorted = JimSortStringTable(tablePtr);
- for (i = 0; tablePtrSorted[i]; i++) {
- if (tablePtrSorted[i + 1] == NULL && i > 0) {
- Jim_AppendString(interp, Jim_GetResult(interp), "or ", -1);
- }
- Jim_AppendStrings(interp, Jim_GetResult(interp), prefix, tablePtrSorted[i], NULL);
- if (tablePtrSorted[i + 1]) {
- Jim_AppendString(interp, Jim_GetResult(interp), ", ", -1);
- }
- }
- Jim_Free(tablePtrSorted);
- }
- int Jim_CheckShowCommands(Jim_Interp *interp, Jim_Obj *objPtr, const char *const *tablePtr)
- {
- if (Jim_CompareStringImmediate(interp, objPtr, "-commands")) {
- int i;
- char **tablePtrSorted = JimSortStringTable(tablePtr);
- Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
- for (i = 0; tablePtrSorted[i]; i++) {
- Jim_ListAppendElement(interp, Jim_GetResult(interp), Jim_NewStringObj(interp, tablePtrSorted[i], -1));
- }
- Jim_Free(tablePtrSorted);
- return JIM_OK;
- }
- return JIM_ERR;
- }
- static const Jim_ObjType getEnumObjType = {
- "get-enum",
- NULL,
- NULL,
- NULL,
- JIM_TYPE_REFERENCES
- };
- int Jim_GetEnum(Jim_Interp *interp, Jim_Obj *objPtr,
- const char *const *tablePtr, int *indexPtr, const char *name, int flags)
- {
- const char *bad = "bad ";
- const char *const *entryPtr = NULL;
- int i;
- int match = -1;
- int arglen;
- const char *arg;
- if (objPtr->typePtr == &getEnumObjType) {
- if (objPtr->internalRep.ptrIntValue.ptr == tablePtr && objPtr->internalRep.ptrIntValue.int1 == flags) {
- *indexPtr = objPtr->internalRep.ptrIntValue.int2;
- return JIM_OK;
- }
- }
- arg = Jim_GetString(objPtr, &arglen);
- *indexPtr = -1;
- for (entryPtr = tablePtr, i = 0; *entryPtr != NULL; entryPtr++, i++) {
- if (Jim_CompareStringImmediate(interp, objPtr, *entryPtr)) {
- match = i;
- goto found;
- }
- if (flags & JIM_ENUM_ABBREV) {
- if (strncmp(arg, *entryPtr, arglen) == 0) {
- if (*arg == '-' && arglen == 1) {
- break;
- }
- if (match >= 0) {
- bad = "ambiguous ";
- goto ambiguous;
- }
- match = i;
- }
- }
- }
- if (match >= 0) {
- found:
- Jim_FreeIntRep(interp, objPtr);
- objPtr->typePtr = &getEnumObjType;
- objPtr->internalRep.ptrIntValue.ptr = (void *)tablePtr;
- objPtr->internalRep.ptrIntValue.int1 = flags;
- objPtr->internalRep.ptrIntValue.int2 = match;
- *indexPtr = match;
- return JIM_OK;
- }
- ambiguous:
- if (flags & JIM_ERRMSG) {
- JimSetFailedEnumResult(interp, arg, bad, "", tablePtr, name);
- }
- return JIM_ERR;
- }
- int Jim_FindByName(const char *name, const char * const array[], size_t len)
- {
- int i;
- for (i = 0; i < (int)len; i++) {
- if (array[i] && strcmp(array[i], name) == 0) {
- return i;
- }
- }
- return -1;
- }
- int Jim_IsDict(Jim_Obj *objPtr)
- {
- return objPtr->typePtr == &dictObjType;
- }
- int Jim_IsList(Jim_Obj *objPtr)
- {
- return objPtr->typePtr == &listObjType;
- }
- void Jim_SetResultFormatted(Jim_Interp *interp, const char *format, ...)
- {
- int len = strlen(format);
- int extra = 0;
- int n = 0;
- const char *params[5];
- int nobjparam = 0;
- Jim_Obj *objparam[5];
- char *buf;
- va_list args;
- int i;
- va_start(args, format);
- for (i = 0; i < len && n < 5; i++) {
- int l;
- if (strncmp(format + i, "%s", 2) == 0) {
- params[n] = va_arg(args, char *);
- l = strlen(params[n]);
- }
- else if (strncmp(format + i, "%#s", 3) == 0) {
- Jim_Obj *objPtr = va_arg(args, Jim_Obj *);
- params[n] = Jim_GetString(objPtr, &l);
- objparam[nobjparam++] = objPtr;
- Jim_IncrRefCount(objPtr);
- }
- else {
- if (format[i] == '%') {
- i++;
- }
- continue;
- }
- n++;
- extra += l;
- }
- len += extra;
- buf = Jim_Alloc(len + 1);
- len = snprintf(buf, len + 1, format, params[0], params[1], params[2], params[3], params[4]);
- va_end(args);
- Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, buf, len));
- for (i = 0; i < nobjparam; i++) {
- Jim_DecrRefCount(interp, objparam[i]);
- }
- }
- int Jim_CheckAbiVersion(Jim_Interp *interp, int abi_version)
- {
- if (abi_version != JIM_ABI_VERSION) {
- Jim_SetResultString(interp, "ABI version mismatch", -1);
- return JIM_ERR;
- }
- return JIM_OK;
- }
- #ifndef jim_ext_package
- int Jim_PackageProvide(Jim_Interp *interp, const char *name, const char *ver, int flags)
- {
- return JIM_OK;
- }
- #endif
- #ifndef jim_ext_aio
- int Jim_AioFilehandle(Jim_Interp *interp, Jim_Obj *fhObj)
- {
- return -1;
- }
- #endif
- #include <stdio.h>
- #include <string.h>
- static int subcmd_null(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- return JIM_OK;
- }
- static const jim_subcmd_type dummy_subcmd = {
- "dummy", NULL, subcmd_null, 0, 0, JIM_MODFLAG_HIDDEN
- };
- static Jim_Obj *subcmd_cmd_list(Jim_Interp *interp, const jim_subcmd_type * ct, const char *sep)
- {
- Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
- Jim_Obj *sortCmd[2];
- for (; ct->cmd; ct++) {
- if (!(ct->flags & JIM_MODFLAG_HIDDEN)) {
- Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, ct->cmd, -1));
- }
- }
- sortCmd[0] = Jim_NewStringObj(interp, "lsort", -1);
- sortCmd[1] = listObj;
- if (Jim_EvalObjVector(interp, 2, sortCmd) == JIM_OK) {
- return Jim_ListJoin(interp, Jim_GetResult(interp), sep, strlen(sep));
- }
- return Jim_GetResult(interp);
- }
- static void bad_subcmd(Jim_Interp *interp, const jim_subcmd_type * command_table, const char *type,
- Jim_Obj *cmd, Jim_Obj *subcmd)
- {
- Jim_SetResultFormatted(interp, "%#s, %s command \"%#s\": should be %#s", cmd, type,
- subcmd, subcmd_cmd_list(interp, command_table, ", "));
- }
- static void show_cmd_usage(Jim_Interp *interp, const jim_subcmd_type * command_table, int argc,
- Jim_Obj *const *argv)
- {
- Jim_SetResultFormatted(interp, "Usage: \"%#s command ... \", where command is one of: %#s",
- argv[0], subcmd_cmd_list(interp, command_table, ", "));
- }
- static void add_cmd_usage(Jim_Interp *interp, const jim_subcmd_type * ct, Jim_Obj *cmd)
- {
- if (cmd) {
- Jim_AppendStrings(interp, Jim_GetResult(interp), Jim_String(cmd), " ", NULL);
- }
- Jim_AppendStrings(interp, Jim_GetResult(interp), ct->cmd, NULL);
- if (ct->args && *ct->args) {
- Jim_AppendStrings(interp, Jim_GetResult(interp), " ", ct->args, NULL);
- }
- }
- void Jim_SubCmdArgError(Jim_Interp *interp, const jim_subcmd_type * ct, Jim_Obj *subcmd)
- {
- Jim_SetResultString(interp, "wrong # args: should be \"", -1);
- add_cmd_usage(interp, ct, subcmd);
- Jim_AppendStrings(interp, Jim_GetResult(interp), "\"", NULL);
- }
- static const Jim_ObjType subcmdLookupObjType = {
- "subcmd-lookup",
- NULL,
- NULL,
- NULL,
- JIM_TYPE_REFERENCES
- };
- const jim_subcmd_type *Jim_ParseSubCmd(Jim_Interp *interp, const jim_subcmd_type * command_table,
- int argc, Jim_Obj *const *argv)
- {
- const jim_subcmd_type *ct;
- const jim_subcmd_type *partial = 0;
- int cmdlen;
- Jim_Obj *cmd;
- const char *cmdstr;
- int help = 0;
- int argsok = 1;
- if (argc < 2) {
- Jim_SetResultFormatted(interp, "wrong # args: should be \"%#s command ...\"\n"
- "Use \"%#s -help ?command?\" for help", argv[0], argv[0]);
- return 0;
- }
- cmd = argv[1];
- if (cmd->typePtr == &subcmdLookupObjType) {
- if (cmd->internalRep.ptrIntValue.ptr == command_table) {
- ct = command_table + cmd->internalRep.ptrIntValue.int1;
- goto found;
- }
- }
- if (Jim_CompareStringImmediate(interp, cmd, "-help")) {
- if (argc == 2) {
- show_cmd_usage(interp, command_table, argc, argv);
- return &dummy_subcmd;
- }
- help = 1;
- cmd = argv[2];
- }
- if (Jim_CompareStringImmediate(interp, cmd, "-commands")) {
- Jim_SetResult(interp, subcmd_cmd_list(interp, command_table, " "));
- return &dummy_subcmd;
- }
- cmdstr = Jim_GetString(cmd, &cmdlen);
- for (ct = command_table; ct->cmd; ct++) {
- if (Jim_CompareStringImmediate(interp, cmd, ct->cmd)) {
- break;
- }
- if (strncmp(cmdstr, ct->cmd, cmdlen) == 0) {
- if (partial) {
- if (help) {
- show_cmd_usage(interp, command_table, argc, argv);
- return &dummy_subcmd;
- }
- bad_subcmd(interp, command_table, "ambiguous", argv[0], argv[1 + help]);
- return 0;
- }
- partial = ct;
- }
- continue;
- }
- if (partial && !ct->cmd) {
- ct = partial;
- }
- if (!ct->cmd) {
- if (help) {
- show_cmd_usage(interp, command_table, argc, argv);
- return &dummy_subcmd;
- }
- bad_subcmd(interp, command_table, "unknown", argv[0], argv[1 + help]);
- return 0;
- }
- if (help) {
- Jim_SetResultString(interp, "Usage: ", -1);
- add_cmd_usage(interp, ct, argv[0]);
- return &dummy_subcmd;
- }
- Jim_FreeIntRep(interp, cmd);
- cmd->typePtr = &subcmdLookupObjType;
- cmd->internalRep.ptrIntValue.ptr = (void *)command_table;
- cmd->internalRep.ptrIntValue.int1 = ct - command_table;
- found:
- if (argc - 2 < ct->minargs) {
- argsok = 0;
- }
- else if (ct->maxargs >= 0 && argc - 2 > ct->maxargs) {
- argsok = 0;
- }
- else if (ct->maxargs < -1 && (argc - 2) % -ct->maxargs != 0) {
- argsok = 0;
- }
- if (!argsok) {
- Jim_SetResultString(interp, "wrong # args: should be \"", -1);
- add_cmd_usage(interp, ct, argv[0]);
- Jim_AppendStrings(interp, Jim_GetResult(interp), "\"", NULL);
- return 0;
- }
- return ct;
- }
- int Jim_CallSubCmd(Jim_Interp *interp, const jim_subcmd_type * ct, int argc, Jim_Obj *const *argv)
- {
- int ret = JIM_ERR;
- if (ct) {
- if (ct->flags & JIM_MODFLAG_FULLARGV) {
- ret = ct->function(interp, argc, argv);
- }
- else {
- ret = ct->function(interp, argc - 2, argv + 2);
- }
- if (ret < 0) {
- Jim_SubCmdArgError(interp, ct, argv[0]);
- ret = JIM_ERR;
- }
- }
- return ret;
- }
- int Jim_SubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
- {
- const jim_subcmd_type *ct =
- Jim_ParseSubCmd(interp, (const jim_subcmd_type *)Jim_CmdPrivData(interp), argc, argv);
- return Jim_CallSubCmd(interp, ct, argc, argv);
- }
- #include <ctype.h>
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- #include <assert.h>
- int utf8_fromunicode(char *p, unsigned uc)
- {
- if (uc <= 0x7f) {
- *p = uc;
- return 1;
- }
- else if (uc <= 0x7ff) {
- *p++ = 0xc0 | ((uc & 0x7c0) >> 6);
- *p = 0x80 | (uc & 0x3f);
- return 2;
- }
- else if (uc <= 0xffff) {
- *p++ = 0xe0 | ((uc & 0xf000) >> 12);
- *p++ = 0x80 | ((uc & 0xfc0) >> 6);
- *p = 0x80 | (uc & 0x3f);
- return 3;
- }
- else {
- *p++ = 0xf0 | ((uc & 0x1c0000) >> 18);
- *p++ = 0x80 | ((uc & 0x3f000) >> 12);
- *p++ = 0x80 | ((uc & 0xfc0) >> 6);
- *p = 0x80 | (uc & 0x3f);
- return 4;
- }
- }
- #include <ctype.h>
- #include <string.h>
- #include <stdio.h>
- #define JIM_INTEGER_SPACE 24
- #define MAX_FLOAT_WIDTH 320
- Jim_Obj *Jim_FormatString(Jim_Interp *interp, Jim_Obj *fmtObjPtr, int objc, Jim_Obj *const *objv)
- {
- const char *span, *format, *formatEnd, *msg;
- int numBytes = 0, objIndex = 0, gotXpg = 0, gotSequential = 0;
- static const char * const mixedXPG =
- "cannot mix \"%\" and \"%n$\" conversion specifiers";
- static const char * const badIndex[2] = {
- "not enough arguments for all format specifiers",
- "\"%n$\" argument index out of range"
- };
- int formatLen;
- Jim_Obj *resultPtr;
- char *num_buffer = NULL;
- int num_buffer_size = 0;
- span = format = Jim_GetString(fmtObjPtr, &formatLen);
- formatEnd = format + formatLen;
- resultPtr = Jim_NewEmptyStringObj(interp);
- while (format != formatEnd) {
- char *end;
- int gotMinus, sawFlag;
- int gotPrecision, useShort;
- long width, precision;
- int newXpg;
- int ch;
- int step;
- int doubleType;
- char pad = ' ';
- char spec[2*JIM_INTEGER_SPACE + 12];
- char *p;
- int formatted_chars;
- int formatted_bytes;
- const char *formatted_buf;
- step = utf8_tounicode(format, &ch);
- format += step;
- if (ch != '%') {
- numBytes += step;
- continue;
- }
- if (numBytes) {
- Jim_AppendString(interp, resultPtr, span, numBytes);
- numBytes = 0;
- }
- step = utf8_tounicode(format, &ch);
- if (ch == '%') {
- span = format;
- numBytes = step;
- format += step;
- continue;
- }
- newXpg = 0;
- if (isdigit(ch)) {
- int position = strtoul(format, &end, 10);
- if (*end == '$') {
- newXpg = 1;
- objIndex = position - 1;
- format = end + 1;
- step = utf8_tounicode(format, &ch);
- }
- }
- if (newXpg) {
- if (gotSequential) {
- msg = mixedXPG;
- goto errorMsg;
- }
- gotXpg = 1;
- } else {
- if (gotXpg) {
- msg = mixedXPG;
- goto errorMsg;
- }
- gotSequential = 1;
- }
- if ((objIndex < 0) || (objIndex >= objc)) {
- msg = badIndex[gotXpg];
- goto errorMsg;
- }
- p = spec;
- *p++ = '%';
- gotMinus = 0;
- sawFlag = 1;
- do {
- switch (ch) {
- case '-':
- gotMinus = 1;
- break;
- case '0':
- pad = ch;
- break;
- case ' ':
- case '+':
- case '#':
- break;
- default:
- sawFlag = 0;
- continue;
- }
- *p++ = ch;
- format += step;
- step = utf8_tounicode(format, &ch);
- } while (sawFlag && (p - spec <= 5));
- width = 0;
- if (isdigit(ch)) {
- width = strtoul(format, &end, 10);
- format = end;
- step = utf8_tounicode(format, &ch);
- } else if (ch == '*') {
- if (objIndex >= objc - 1) {
- msg = badIndex[gotXpg];
- goto errorMsg;
- }
- if (Jim_GetLong(interp, objv[objIndex], &width) != JIM_OK) {
- goto error;
- }
- if (width < 0) {
- width = -width;
- if (!gotMinus) {
- *p++ = '-';
- gotMinus = 1;
- }
- }
- objIndex++;
- format += step;
- step = utf8_tounicode(format, &ch);
- }
- gotPrecision = precision = 0;
- if (ch == '.') {
- gotPrecision = 1;
- format += step;
- step = utf8_tounicode(format, &ch);
- }
- if (isdigit(ch)) {
- precision = strtoul(format, &end, 10);
- format = end;
- step = utf8_tounicode(format, &ch);
- } else if (ch == '*') {
- if (objIndex >= objc - 1) {
- msg = badIndex[gotXpg];
- goto errorMsg;
- }
- if (Jim_GetLong(interp, objv[objIndex], &precision) != JIM_OK) {
- goto error;
- }
- if (precision < 0) {
- precision = 0;
- }
- objIndex++;
- format += step;
- step = utf8_tounicode(format, &ch);
- }
- useShort = 0;
- if (ch == 'h') {
- useShort = 1;
- format += step;
- step = utf8_tounicode(format, &ch);
- } else if (ch == 'l') {
- format += step;
- step = utf8_tounicode(format, &ch);
- if (ch == 'l') {
- format += step;
- step = utf8_tounicode(format, &ch);
- }
- }
- format += step;
- span = format;
- if (ch == 'i') {
- ch = 'd';
- }
- doubleType = 0;
- switch (ch) {
- case '\0':
- msg = "format string ended in middle of field specifier";
- goto errorMsg;
- case 's': {
- formatted_buf = Jim_GetString(objv[objIndex], &formatted_bytes);
- formatted_chars = Jim_Utf8Length(interp, objv[objIndex]);
- if (gotPrecision && (precision < formatted_chars)) {
- formatted_chars = precision;
- formatted_bytes = utf8_index(formatted_buf, precision);
- }
- break;
- }
- case 'c': {
- jim_wide code;
- if (Jim_GetWide(interp, objv[objIndex], &code) != JIM_OK) {
- goto error;
- }
- formatted_bytes = utf8_getchars(spec, code);
- formatted_buf = spec;
- formatted_chars = 1;
- break;
- }
- case 'b': {
- unsigned jim_wide w;
- int length;
- int i;
- int j;
- if (Jim_GetWide(interp, objv[objIndex], (jim_wide *)&w) != JIM_OK) {
- goto error;
- }
- length = sizeof(w) * 8;
- if (num_buffer_size < length + 1) {
- num_buffer_size = length + 1;
- num_buffer = Jim_Realloc(num_buffer, num_buffer_size);
- }
- j = 0;
- for (i = length; i > 0; ) {
- i--;
- if (w & ((unsigned jim_wide)1 << i)) {
- num_buffer[j++] = '1';
- }
- else if (j || i == 0) {
- num_buffer[j++] = '0';
- }
- }
- num_buffer[j] = 0;
- formatted_chars = formatted_bytes = j;
- formatted_buf = num_buffer;
- break;
- }
- case 'e':
- case 'E':
- case 'f':
- case 'g':
- case 'G':
- doubleType = 1;
- case 'd':
- case 'u':
- case 'o':
- case 'x':
- case 'X': {
- jim_wide w;
- double d;
- int length;
- if (width) {
- p += sprintf(p, "%ld", width);
- }
- if (gotPrecision) {
- p += sprintf(p, ".%ld", precision);
- }
- if (doubleType) {
- if (Jim_GetDouble(interp, objv[objIndex], &d) != JIM_OK) {
- goto error;
- }
- length = MAX_FLOAT_WIDTH;
- }
- else {
- if (Jim_GetWide(interp, objv[objIndex], &w) != JIM_OK) {
- goto error;
- }
- length = JIM_INTEGER_SPACE;
- if (useShort) {
- if (ch == 'd') {
- w = (short)w;
- }
- else {
- w = (unsigned short)w;
- }
- }
- *p++ = 'l';
- #ifdef HAVE_LONG_LONG
- if (sizeof(long long) == sizeof(jim_wide)) {
- *p++ = 'l';
- }
- #endif
- }
- *p++ = (char) ch;
- *p = '\0';
- if (width > 10000 || length > 10000 || precision > 10000) {
- Jim_SetResultString(interp, "format too long", -1);
- goto error;
- }
- if (width > length) {
- length = width;
- }
- if (gotPrecision) {
- length += precision;
- }
- if (num_buffer_size < length + 1) {
- num_buffer_size = length + 1;
- num_buffer = Jim_Realloc(num_buffer, num_buffer_size);
- }
- if (doubleType) {
- snprintf(num_buffer, length + 1, spec, d);
- }
- else {
- formatted_bytes = snprintf(num_buffer, length + 1, spec, w);
- }
- formatted_chars = formatted_bytes = strlen(num_buffer);
- formatted_buf = num_buffer;
- break;
- }
- default: {
- spec[0] = ch;
- spec[1] = '\0';
- Jim_SetResultFormatted(interp, "bad field specifier \"%s\"", spec);
- goto error;
- }
- }
- if (!gotMinus) {
- while (formatted_chars < width) {
- Jim_AppendString(interp, resultPtr, &pad, 1);
- formatted_chars++;
- }
- }
- Jim_AppendString(interp, resultPtr, formatted_buf, formatted_bytes);
- while (formatted_chars < width) {
- Jim_AppendString(interp, resultPtr, &pad, 1);
- formatted_chars++;
- }
- objIndex += gotSequential;
- }
- if (numBytes) {
- Jim_AppendString(interp, resultPtr, span, numBytes);
- }
- Jim_Free(num_buffer);
- return resultPtr;
- errorMsg:
- Jim_SetResultString(interp, msg, -1);
- error:
- Jim_FreeNewObj(interp, resultPtr);
- Jim_Free(num_buffer);
- return NULL;
- }
- #if defined(JIM_REGEXP)
- #include <stdio.h>
- #include <ctype.h>
- #include <stdlib.h>
- #include <string.h>
- #define REG_MAX_PAREN 100
- #define END 0
- #define BOL 1
- #define EOL 2
- #define ANY 3
- #define ANYOF 4
- #define ANYBUT 5
- #define BRANCH 6
- #define BACK 7
- #define EXACTLY 8
- #define NOTHING 9
- #define REP 10
- #define REPMIN 11
- #define REPX 12
- #define REPXMIN 13
- #define BOLX 14
- #define EOLX 15
- #define WORDA 16
- #define WORDZ 17
- #define OPENNC 1000
- #define OPEN 1001
- #define CLOSENC 2000
- #define CLOSE 2001
- #define CLOSE_END (CLOSE+REG_MAX_PAREN)
- #define REG_MAGIC 0xFADED00D
- #define OP(preg, p) (preg->program[p])
- #define NEXT(preg, p) (preg->program[p + 1])
- #define OPERAND(p) ((p) + 2)
- #define FAIL(R,M) { (R)->err = (M); return (M); }
- #define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?' || (c) == '{')
- #define META "^$.[()|?{+*"
- #define HASWIDTH 1
- #define SIMPLE 2
- #define SPSTART 4
- #define WORST 0
- #define MAX_REP_COUNT 1000000
- static int reg(regex_t *preg, int paren, int *flagp );
- static int regpiece(regex_t *preg, int *flagp );
- static int regbranch(regex_t *preg, int *flagp );
- static int regatom(regex_t *preg, int *flagp );
- static int regnode(regex_t *preg, int op );
- static int regnext(regex_t *preg, int p );
- static void regc(regex_t *preg, int b );
- static int reginsert(regex_t *preg, int op, int size, int opnd );
- static void regtail(regex_t *preg, int p, int val);
- static void regoptail(regex_t *preg, int p, int val );
- static int regopsize(regex_t *preg, int p );
- static int reg_range_find(const int *string, int c);
- static const char *str_find(const char *string, int c, int nocase);
- static int prefix_cmp(const int *prog, int proglen, const char *string, int nocase);
- #ifdef DEBUG
- static int regnarrate = 0;
- static void regdump(regex_t *preg);
- static const char *regprop( int op );
- #endif
- static int str_int_len(const int *seq)
- {
- int n = 0;
- while (*seq++) {
- n++;
- }
- return n;
- }
- int jim_regcomp(regex_t *preg, const char *exp, int cflags)
- {
- int scan;
- int longest;
- unsigned len;
- int flags;
- #ifdef DEBUG
- fprintf(stderr, "Compiling: '%s'\n", exp);
- #endif
- memset(preg, 0, sizeof(*preg));
- if (exp == NULL)
- FAIL(preg, REG_ERR_NULL_ARGUMENT);
- preg->cflags = cflags;
- preg->regparse = exp;
- preg->proglen = (strlen(exp) + 1) * 5;
- preg->program = malloc(preg->proglen * sizeof(int));
- if (preg->program == NULL)
- FAIL(preg, REG_ERR_NOMEM);
- regc(preg, REG_MAGIC);
- if (reg(preg, 0, &flags) == 0) {
- return preg->err;
- }
- if (preg->re_nsub >= REG_MAX_PAREN)
- FAIL(preg,REG_ERR_TOO_BIG);
- preg->regstart = 0;
- preg->reganch = 0;
- preg->regmust = 0;
- preg->regmlen = 0;
- scan = 1;
- if (OP(preg, regnext(preg, scan)) == END) {
- scan = OPERAND(scan);
- if (OP(preg, scan) == EXACTLY) {
- preg->regstart = preg->program[OPERAND(scan)];
- }
- else if (OP(preg, scan) == BOL)
- preg->reganch++;
- if (flags&SPSTART) {
- longest = 0;
- len = 0;
- for (; scan != 0; scan = regnext(preg, scan)) {
- if (OP(preg, scan) == EXACTLY) {
- int plen = str_int_len(preg->program + OPERAND(scan));
- if (plen >= len) {
- longest = OPERAND(scan);
- len = plen;
- }
- }
- }
- preg->regmust = longest;
- preg->regmlen = len;
- }
- }
- #ifdef DEBUG
- regdump(preg);
- #endif
- return 0;
- }
- static int reg(regex_t *preg, int paren, int *flagp )
- {
- int ret;
- int br;
- int ender;
- int parno = 0;
- int flags;
- *flagp = HASWIDTH;
- if (paren) {
- if (preg->regparse[0] == '?' && preg->regparse[1] == ':') {
- preg->regparse += 2;
- parno = -1;
- }
- else {
- parno = ++preg->re_nsub;
- }
- ret = regnode(preg, OPEN+parno);
- } else
- ret = 0;
- br = regbranch(preg, &flags);
- if (br == 0)
- return 0;
- if (ret != 0)
- regtail(preg, ret, br);
- else
- ret = br;
- if (!(flags&HASWIDTH))
- *flagp &= ~HASWIDTH;
- *flagp |= flags&SPSTART;
- while (*preg->regparse == '|') {
- preg->regparse++;
- br = regbranch(preg, &flags);
- if (br == 0)
- return 0;
- regtail(preg, ret, br);
- if (!(flags&HASWIDTH))
- *flagp &= ~HASWIDTH;
- *flagp |= flags&SPSTART;
- }
- ender = regnode(preg, (paren) ? CLOSE+parno : END);
- regtail(preg, ret, ender);
- for (br = ret; br != 0; br = regnext(preg, br))
- regoptail(preg, br, ender);
- if (paren && *preg->regparse++ != ')') {
- preg->err = REG_ERR_UNMATCHED_PAREN;
- return 0;
- } else if (!paren && *preg->regparse != '\0') {
- if (*preg->regparse == ')') {
- preg->err = REG_ERR_UNMATCHED_PAREN;
- return 0;
- } else {
- preg->err = REG_ERR_JUNK_ON_END;
- return 0;
- }
- }
- return(ret);
- }
- static int regbranch(regex_t *preg, int *flagp )
- {
- int ret;
- int chain;
- int latest;
- int flags;
- *flagp = WORST;
- ret = regnode(preg, BRANCH);
- chain = 0;
- while (*preg->regparse != '\0' && *preg->regparse != ')' &&
- *preg->regparse != '|') {
- latest = regpiece(preg, &flags);
- if (latest == 0)
- return 0;
- *flagp |= flags&HASWIDTH;
- if (chain == 0) {
- *flagp |= flags&SPSTART;
- }
- else {
- regtail(preg, chain, latest);
- }
- chain = latest;
- }
- if (chain == 0)
- (void) regnode(preg, NOTHING);
- return(ret);
- }
- static int regpiece(regex_t *preg, int *flagp)
- {
- int ret;
- char op;
- int next;
- int flags;
- int min;
- int max;
- ret = regatom(preg, &flags);
- if (ret == 0)
- return 0;
- op = *preg->regparse;
- if (!ISMULT(op)) {
- *flagp = flags;
- return(ret);
- }
- if (!(flags&HASWIDTH) && op != '?') {
- preg->err = REG_ERR_OPERAND_COULD_BE_EMPTY;
- return 0;
- }
- if (op == '{') {
- char *end;
- min = strtoul(preg->regparse + 1, &end, 10);
- if (end == preg->regparse + 1) {
- preg->err = REG_ERR_BAD_COUNT;
- return 0;
- }
- if (*end == '}') {
- max = min;
- }
- else if (*end == '\0') {
- preg->err = REG_ERR_UNMATCHED_BRACES;
- return 0;
- }
- else {
- preg->regparse = end;
- max = strtoul(preg->regparse + 1, &end, 10);
- if (*end != '}') {
- preg->err = REG_ERR_UNMATCHED_BRACES;
- return 0;
- }
- }
- if (end == preg->regparse + 1) {
- max = MAX_REP_COUNT;
- }
- else if (max < min || max >= 100) {
- preg->err = REG_ERR_BAD_COUNT;
- return 0;
- }
- if (min >= 100) {
- preg->err = REG_ERR_BAD_COUNT;
- return 0;
- }
- preg->regparse = strchr(preg->regparse, '}');
- }
- else {
- min = (op == '+');
- max = (op == '?' ? 1 : MAX_REP_COUNT);
- }
- if (preg->regparse[1] == '?') {
- preg->regparse++;
- next = reginsert(preg, flags & SIMPLE ? REPMIN : REPXMIN, 5, ret);
- }
- else {
- next = reginsert(preg, flags & SIMPLE ? REP: REPX, 5, ret);
- }
- preg->program[ret + 2] = max;
- preg->program[ret + 3] = min;
- preg->program[ret + 4] = 0;
- *flagp = (min) ? (WORST|HASWIDTH) : (WORST|SPSTART);
- if (!(flags & SIMPLE)) {
- int back = regnode(preg, BACK);
- regtail(preg, back, ret);
- regtail(preg, next, back);
- }
- preg->regparse++;
- if (ISMULT(*preg->regparse)) {
- preg->err = REG_ERR_NESTED_COUNT;
- return 0;
- }
- return ret;
- }
- static void reg_addrange(regex_t *preg, int lower, int upper)
- {
- if (lower > upper) {
- reg_addrange(preg, upper, lower);
- }
- regc(preg, upper - lower + 1);
- regc(preg, lower);
- }
- static void reg_addrange_str(regex_t *preg, const char *str)
- {
- while (*str) {
- reg_addrange(preg, *str, *str);
- str++;
- }
- }
- static int reg_utf8_tounicode_case(const char *s, int *uc, int upper)
- {
- int l = utf8_tounicode(s, uc);
- if (upper) {
- *uc = utf8_upper(*uc);
- }
- return l;
- }
- static int hexdigitval(int c)
- {
- if (c >= '0' && c <= '9')
- return c - '0';
- if (c >= 'a' && c <= 'f')
- return c - 'a' + 10;
- if (c >= 'A' && c <= 'F')
- return c - 'A' + 10;
- return -1;
- }
- static int parse_hex(const char *s, int n, int *uc)
- {
- int val = 0;
- int k;
- for (k = 0; k < n; k++) {
- int c = hexdigitval(*s++);
- if (c == -1) {
- break;
- }
- val = (val << 4) | c;
- }
- if (k) {
- *uc = val;
- }
- return k;
- }
- static int reg_decode_escape(const char *s, int *ch)
- {
- int n;
- const char *s0 = s;
- *ch = *s++;
- switch (*ch) {
- case 'b': *ch = '\b'; break;
- case 'e': *ch = 27; break;
- case 'f': *ch = '\f'; break;
- case 'n': *ch = '\n'; break;
- case 'r': *ch = '\r'; break;
- case 't': *ch = '\t'; break;
- case 'v': *ch = '\v'; break;
- case 'u':
- if (*s == '{') {
- n = parse_hex(s + 1, 6, ch);
- if (n > 0 && s[n + 1] == '}' && *ch >= 0 && *ch <= 0x1fffff) {
- s += n + 2;
- }
- else {
- *ch = 'u';
- }
- }
- else if ((n = parse_hex(s, 4, ch)) > 0) {
- s += n;
- }
- break;
- case 'U':
- if ((n = parse_hex(s, 8, ch)) > 0) {
- s += n;
- }
- break;
- case 'x':
- if ((n = parse_hex(s, 2, ch)) > 0) {
- s += n;
- }
- break;
- case '\0':
- s--;
- *ch = '\\';
- break;
- }
- return s - s0;
- }
- static int regatom(regex_t *preg, int *flagp)
- {
- int ret;
- int flags;
- int nocase = (preg->cflags & REG_ICASE);
- int ch;
- int n = reg_utf8_tounicode_case(preg->regparse, &ch, nocase);
- *flagp = WORST;
- preg->regparse += n;
- switch (ch) {
- case '^':
- ret = regnode(preg, BOL);
- break;
- case '$':
- ret = regnode(preg, EOL);
- break;
- case '.':
- ret = regnode(preg, ANY);
- *flagp |= HASWIDTH|SIMPLE;
- break;
- case '[': {
- const char *pattern = preg->regparse;
- if (*pattern == '^') {
- ret = regnode(preg, ANYBUT);
- pattern++;
- } else
- ret = regnode(preg, ANYOF);
- if (*pattern == ']' || *pattern == '-') {
- reg_addrange(preg, *pattern, *pattern);
- pattern++;
- }
- while (*pattern != ']') {
- int start;
- int end;
- enum {
- CC_ALPHA, CC_ALNUM, CC_SPACE, CC_BLANK, CC_UPPER, CC_LOWER,
- CC_DIGIT, CC_XDIGIT, CC_CNTRL, CC_GRAPH, CC_PRINT, CC_PUNCT,
- CC_NUM
- };
- int cc;
- if (!*pattern) {
- preg->err = REG_ERR_UNMATCHED_BRACKET;
- return 0;
- }
- pattern += reg_utf8_tounicode_case(pattern, &start, nocase);
- if (start == '\\') {
- switch (*pattern) {
- case 's':
- pattern++;
- cc = CC_SPACE;
- goto cc_switch;
- case 'd':
- pattern++;
- cc = CC_DIGIT;
- goto cc_switch;
- case 'w':
- pattern++;
- reg_addrange(preg, '_', '_');
- cc = CC_ALNUM;
- goto cc_switch;
- }
- pattern += reg_decode_escape(pattern, &start);
- if (start == 0) {
- preg->err = REG_ERR_NULL_CHAR;
- return 0;
- }
- if (start == '\\' && *pattern == 0) {
- preg->err = REG_ERR_INVALID_ESCAPE;
- return 0;
- }
- }
- if (pattern[0] == '-' && pattern[1] && pattern[1] != ']') {
- pattern += utf8_tounicode(pattern, &end);
- pattern += reg_utf8_tounicode_case(pattern, &end, nocase);
- if (end == '\\') {
- pattern += reg_decode_escape(pattern, &end);
- if (end == 0) {
- preg->err = REG_ERR_NULL_CHAR;
- return 0;
- }
- if (end == '\\' && *pattern == 0) {
- preg->err = REG_ERR_INVALID_ESCAPE;
- return 0;
- }
- }
- reg_addrange(preg, start, end);
- continue;
- }
- if (start == '[' && pattern[0] == ':') {
- static const char *character_class[] = {
- ":alpha:", ":alnum:", ":space:", ":blank:", ":upper:", ":lower:",
- ":digit:", ":xdigit:", ":cntrl:", ":graph:", ":print:", ":punct:",
- };
- for (cc = 0; cc < CC_NUM; cc++) {
- n = strlen(character_class[cc]);
- if (strncmp(pattern, character_class[cc], n) == 0) {
- if (pattern[n] != ']') {
- preg->err = REG_ERR_UNMATCHED_BRACKET;
- return 0;
- }
- pattern += n + 1;
- break;
- }
- }
- if (cc != CC_NUM) {
- cc_switch:
- switch (cc) {
- case CC_ALNUM:
- reg_addrange(preg, '0', '9');
- case CC_ALPHA:
- if ((preg->cflags & REG_ICASE) == 0) {
- reg_addrange(preg, 'a', 'z');
- }
- reg_addrange(preg, 'A', 'Z');
- break;
- case CC_SPACE:
- reg_addrange_str(preg, " \t\r\n\f\v");
- break;
- case CC_BLANK:
- reg_addrange_str(preg, " \t");
- break;
- case CC_UPPER:
- reg_addrange(preg, 'A', 'Z');
- break;
- case CC_LOWER:
- reg_addrange(preg, 'a', 'z');
- break;
- case CC_XDIGIT:
- reg_addrange(preg, 'a', 'f');
- reg_addrange(preg, 'A', 'F');
- case CC_DIGIT:
- reg_addrange(preg, '0', '9');
- break;
- case CC_CNTRL:
- reg_addrange(preg, 0, 31);
- reg_addrange(preg, 127, 127);
- break;
- case CC_PRINT:
- reg_addrange(preg, ' ', '~');
- break;
- case CC_GRAPH:
- reg_addrange(preg, '!', '~');
- break;
- case CC_PUNCT:
- reg_addrange(preg, '!', '/');
- reg_addrange(preg, ':', '@');
- reg_addrange(preg, '[', '`');
- reg_addrange(preg, '{', '~');
- break;
- }
- continue;
- }
- }
- reg_addrange(preg, start, start);
- }
- regc(preg, '\0');
- if (*pattern) {
- pattern++;
- }
- preg->regparse = pattern;
- *flagp |= HASWIDTH|SIMPLE;
- }
- break;
- case '(':
- ret = reg(preg, 1, &flags);
- if (ret == 0)
- return 0;
- *flagp |= flags&(HASWIDTH|SPSTART);
- break;
- case '\0':
- case '|':
- case ')':
- preg->err = REG_ERR_INTERNAL;
- return 0;
- case '?':
- case '+':
- case '*':
- case '{':
- preg->err = REG_ERR_COUNT_FOLLOWS_NOTHING;
- return 0;
- case '\\':
- ch = *preg->regparse++;
- switch (ch) {
- case '\0':
- preg->err = REG_ERR_INVALID_ESCAPE;
- return 0;
- case 'A':
- ret = regnode(preg, BOLX);
- break;
- case 'Z':
- ret = regnode(preg, EOLX);
- break;
- case '<':
- case 'm':
- ret = regnode(preg, WORDA);
- break;
- case '>':
- case 'M':
- ret = regnode(preg, WORDZ);
- break;
- case 'd':
- case 'D':
- ret = regnode(preg, ch == 'd' ? ANYOF : ANYBUT);
- reg_addrange(preg, '0', '9');
- regc(preg, '\0');
- *flagp |= HASWIDTH|SIMPLE;
- break;
- case 'w':
- case 'W':
- ret = regnode(preg, ch == 'w' ? ANYOF : ANYBUT);
- if ((preg->cflags & REG_ICASE) == 0) {
- reg_addrange(preg, 'a', 'z');
- }
- reg_addrange(preg, 'A', 'Z');
- reg_addrange(preg, '0', '9');
- reg_addrange(preg, '_', '_');
- regc(preg, '\0');
- *flagp |= HASWIDTH|SIMPLE;
- break;
- case 's':
- case 'S':
- ret = regnode(preg, ch == 's' ? ANYOF : ANYBUT);
- reg_addrange_str(preg," \t\r\n\f\v");
- regc(preg, '\0');
- *flagp |= HASWIDTH|SIMPLE;
- break;
- default:
- preg->regparse--;
- goto de_fault;
- }
- break;
- de_fault:
- default: {
- int added = 0;
- preg->regparse -= n;
- ret = regnode(preg, EXACTLY);
- while (*preg->regparse && strchr(META, *preg->regparse) == NULL) {
- n = reg_utf8_tounicode_case(preg->regparse, &ch, (preg->cflags & REG_ICASE));
- if (ch == '\\' && preg->regparse[n]) {
- if (strchr("<>mMwWdDsSAZ", preg->regparse[n])) {
- break;
- }
- n += reg_decode_escape(preg->regparse + n, &ch);
- if (ch == 0) {
- preg->err = REG_ERR_NULL_CHAR;
- return 0;
- }
- }
- if (ISMULT(preg->regparse[n])) {
- if (added) {
- break;
- }
- regc(preg, ch);
- added++;
- preg->regparse += n;
- break;
- }
- regc(preg, ch);
- added++;
- preg->regparse += n;
- }
- regc(preg, '\0');
- *flagp |= HASWIDTH;
- if (added == 1)
- *flagp |= SIMPLE;
- break;
- }
- break;
- }
- return(ret);
- }
- static void reg_grow(regex_t *preg, int n)
- {
- if (preg->p + n >= preg->proglen) {
- preg->proglen = (preg->p + n) * 2;
- preg->program = realloc(preg->program, preg->proglen * sizeof(int));
- }
- }
- static int regnode(regex_t *preg, int op)
- {
- reg_grow(preg, 2);
- preg->program[preg->p++] = op;
- preg->program[preg->p++] = 0;
- return preg->p - 2;
- }
- static void regc(regex_t *preg, int b )
- {
- reg_grow(preg, 1);
- preg->program[preg->p++] = b;
- }
- static int reginsert(regex_t *preg, int op, int size, int opnd )
- {
- reg_grow(preg, size);
- memmove(preg->program + opnd + size, preg->program + opnd, sizeof(int) * (preg->p - opnd));
- memset(preg->program + opnd, 0, sizeof(int) * size);
- preg->program[opnd] = op;
- preg->p += size;
- return opnd + size;
- }
- static void regtail(regex_t *preg, int p, int val)
- {
- int scan;
- int temp;
- int offset;
- scan = p;
- for (;;) {
- temp = regnext(preg, scan);
- if (temp == 0)
- break;
- scan = temp;
- }
- if (OP(preg, scan) == BACK)
- offset = scan - val;
- else
- offset = val - scan;
- preg->program[scan + 1] = offset;
- }
- static void regoptail(regex_t *preg, int p, int val )
- {
- if (p != 0 && OP(preg, p) == BRANCH) {
- regtail(preg, OPERAND(p), val);
- }
- }
- static int regtry(regex_t *preg, const char *string );
- static int regmatch(regex_t *preg, int prog);
- static int regrepeat(regex_t *preg, int p, int max);
- int jim_regexec(regex_t *preg, const char *string, size_t nmatch, regmatch_t pmatch[], int eflags)
- {
- const char *s;
- int scan;
- if (preg == NULL || preg->program == NULL || string == NULL) {
- return REG_ERR_NULL_ARGUMENT;
- }
- if (*preg->program != REG_MAGIC) {
- return REG_ERR_CORRUPTED;
- }
- #ifdef DEBUG
- fprintf(stderr, "regexec: %s\n", string);
- regdump(preg);
- #endif
- preg->eflags = eflags;
- preg->pmatch = pmatch;
- preg->nmatch = nmatch;
- preg->start = string;
- for (scan = OPERAND(1); scan != 0; scan += regopsize(preg, scan)) {
- int op = OP(preg, scan);
- if (op == END)
- break;
- if (op == REPX || op == REPXMIN)
- preg->program[scan + 4] = 0;
- }
- if (preg->regmust != 0) {
- s = string;
- while ((s = str_find(s, preg->program[preg->regmust], preg->cflags & REG_ICASE)) != NULL) {
- if (prefix_cmp(preg->program + preg->regmust, preg->regmlen, s, preg->cflags & REG_ICASE) >= 0) {
- break;
- }
- s++;
- }
- if (s == NULL)
- return REG_NOMATCH;
- }
- preg->regbol = string;
- if (preg->reganch) {
- if (eflags & REG_NOTBOL) {
- goto nextline;
- }
- while (1) {
- if (regtry(preg, string)) {
- return REG_NOERROR;
- }
- if (*string) {
- nextline:
- if (preg->cflags & REG_NEWLINE) {
- string = strchr(string, '\n');
- if (string) {
- preg->regbol = ++string;
- continue;
- }
- }
- }
- return REG_NOMATCH;
- }
- }
- s = string;
- if (preg->regstart != '\0') {
- while ((s = str_find(s, preg->regstart, preg->cflags & REG_ICASE)) != NULL) {
- if (regtry(preg, s))
- return REG_NOERROR;
- s++;
- }
- }
- else
- while (1) {
- if (regtry(preg, s))
- return REG_NOERROR;
- if (*s == '\0') {
- break;
- }
- else {
- int c;
- s += utf8_tounicode(s, &c);
- }
- }
- return REG_NOMATCH;
- }
- static int regtry( regex_t *preg, const char *string )
- {
- int i;
- preg->reginput = string;
- for (i = 0; i < preg->nmatch; i++) {
- preg->pmatch[i].rm_so = -1;
- preg->pmatch[i].rm_eo = -1;
- }
- if (regmatch(preg, 1)) {
- preg->pmatch[0].rm_so = string - preg->start;
- preg->pmatch[0].rm_eo = preg->reginput - preg->start;
- return(1);
- } else
- return(0);
- }
- static int prefix_cmp(const int *prog, int proglen, const char *string, int nocase)
- {
- const char *s = string;
- while (proglen && *s) {
- int ch;
- int n = reg_utf8_tounicode_case(s, &ch, nocase);
- if (ch != *prog) {
- return -1;
- }
- prog++;
- s += n;
- proglen--;
- }
- if (proglen == 0) {
- return s - string;
- }
- return -1;
- }
- static int reg_range_find(const int *range, int c)
- {
- while (*range) {
- if (c >= range[1] && c <= (range[0] + range[1] - 1)) {
- return 1;
- }
- range += 2;
- }
- return 0;
- }
- static const char *str_find(const char *string, int c, int nocase)
- {
- if (nocase) {
- c = utf8_upper(c);
- }
- while (*string) {
- int ch;
- int n = reg_utf8_tounicode_case(string, &ch, nocase);
- if (c == ch) {
- return string;
- }
- string += n;
- }
- return NULL;
- }
- static int reg_iseol(regex_t *preg, int ch)
- {
- if (preg->cflags & REG_NEWLINE) {
- return ch == '\0' || ch == '\n';
- }
- else {
- return ch == '\0';
- }
- }
- static int regmatchsimplerepeat(regex_t *preg, int scan, int matchmin)
- {
- int nextch = '\0';
- const char *save;
- int no;
- int c;
- int max = preg->program[scan + 2];
- int min = preg->program[scan + 3];
- int next = regnext(preg, scan);
- if (OP(preg, next) == EXACTLY) {
- nextch = preg->program[OPERAND(next)];
- }
- save = preg->reginput;
- no = regrepeat(preg, scan + 5, max);
- if (no < min) {
- return 0;
- }
- if (matchmin) {
- max = no;
- no = min;
- }
- while (1) {
- if (matchmin) {
- if (no > max) {
- break;
- }
- }
- else {
- if (no < min) {
- break;
- }
- }
- preg->reginput = save + utf8_index(save, no);
- reg_utf8_tounicode_case(preg->reginput, &c, (preg->cflags & REG_ICASE));
- if (reg_iseol(preg, nextch) || c == nextch) {
- if (regmatch(preg, next)) {
- return(1);
- }
- }
- if (matchmin) {
- no++;
- }
- else {
- no--;
- }
- }
- return(0);
- }
- static int regmatchrepeat(regex_t *preg, int scan, int matchmin)
- {
- int *scanpt = preg->program + scan;
- int max = scanpt[2];
- int min = scanpt[3];
- if (scanpt[4] < min) {
- scanpt[4]++;
- if (regmatch(preg, scan + 5)) {
- return 1;
- }
- scanpt[4]--;
- return 0;
- }
- if (scanpt[4] > max) {
- return 0;
- }
- if (matchmin) {
- if (regmatch(preg, regnext(preg, scan))) {
- return 1;
- }
- scanpt[4]++;
- if (regmatch(preg, scan + 5)) {
- return 1;
- }
- scanpt[4]--;
- return 0;
- }
- if (scanpt[4] < max) {
- scanpt[4]++;
- if (regmatch(preg, scan + 5)) {
- return 1;
- }
- scanpt[4]--;
- }
- return regmatch(preg, regnext(preg, scan));
- }
- static int regmatch(regex_t *preg, int prog)
- {
- int scan;
- int next;
- const char *save;
- scan = prog;
- #ifdef DEBUG
- if (scan != 0 && regnarrate)
- fprintf(stderr, "%s(\n", regprop(scan));
- #endif
- while (scan != 0) {
- int n;
- int c;
- #ifdef DEBUG
- if (regnarrate) {
- fprintf(stderr, "%3d: %s...\n", scan, regprop(OP(preg, scan)));
- }
- #endif
- next = regnext(preg, scan);
- n = reg_utf8_tounicode_case(preg->reginput, &c, (preg->cflags & REG_ICASE));
- switch (OP(preg, scan)) {
- case BOLX:
- if ((preg->eflags & REG_NOTBOL)) {
- return(0);
- }
- case BOL:
- if (preg->reginput != preg->regbol) {
- return(0);
- }
- break;
- case EOLX:
- if (c != 0) {
- return 0;
- }
- break;
- case EOL:
- if (!reg_iseol(preg, c)) {
- return(0);
- }
- break;
- case WORDA:
- if ((!isalnum(UCHAR(c))) && c != '_')
- return(0);
- if (preg->reginput > preg->regbol &&
- (isalnum(UCHAR(preg->reginput[-1])) || preg->reginput[-1] == '_'))
- return(0);
- break;
- case WORDZ:
- if (preg->reginput > preg->regbol) {
- if (reg_iseol(preg, c) || !(isalnum(UCHAR(c)) || c == '_')) {
- c = preg->reginput[-1];
- if (isalnum(UCHAR(c)) || c == '_') {
- break;
- }
- }
- }
- return(0);
- case ANY:
- if (reg_iseol(preg, c))
- return 0;
- preg->reginput += n;
- break;
- case EXACTLY: {
- int opnd;
- int len;
- int slen;
- opnd = OPERAND(scan);
- len = str_int_len(preg->program + opnd);
- slen = prefix_cmp(preg->program + opnd, len, preg->reginput, preg->cflags & REG_ICASE);
- if (slen < 0) {
- return(0);
- }
- preg->reginput += slen;
- }
- break;
- case ANYOF:
- if (reg_iseol(preg, c) || reg_range_find(preg->program + OPERAND(scan), c) == 0) {
- return(0);
- }
- preg->reginput += n;
- break;
- case ANYBUT:
- if (reg_iseol(preg, c) || reg_range_find(preg->program + OPERAND(scan), c) != 0) {
- return(0);
- }
- preg->reginput += n;
- break;
- case NOTHING:
- break;
- case BACK:
- break;
- case BRANCH:
- if (OP(preg, next) != BRANCH)
- next = OPERAND(scan);
- else {
- do {
- save = preg->reginput;
- if (regmatch(preg, OPERAND(scan))) {
- return(1);
- }
- preg->reginput = save;
- scan = regnext(preg, scan);
- } while (scan != 0 && OP(preg, scan) == BRANCH);
- return(0);
- }
- break;
- case REP:
- case REPMIN:
- return regmatchsimplerepeat(preg, scan, OP(preg, scan) == REPMIN);
- case REPX:
- case REPXMIN:
- return regmatchrepeat(preg, scan, OP(preg, scan) == REPXMIN);
- case END:
- return 1;
- case OPENNC:
- case CLOSENC:
- return regmatch(preg, next);
- default:
- if (OP(preg, scan) >= OPEN+1 && OP(preg, scan) < CLOSE_END) {
- save = preg->reginput;
- if (regmatch(preg, next)) {
- if (OP(preg, scan) < CLOSE) {
- int no = OP(preg, scan) - OPEN;
- if (no < preg->nmatch && preg->pmatch[no].rm_so == -1) {
- preg->pmatch[no].rm_so = save - preg->start;
- }
- }
- else {
- int no = OP(preg, scan) - CLOSE;
- if (no < preg->nmatch && preg->pmatch[no].rm_eo == -1) {
- preg->pmatch[no].rm_eo = save - preg->start;
- }
- }
- return(1);
- }
- preg->reginput = save;
- return(0);
- }
- return REG_ERR_INTERNAL;
- }
- scan = next;
- }
- return REG_ERR_INTERNAL;
- }
- static int regrepeat(regex_t *preg, int p, int max)
- {
- int count = 0;
- const char *scan;
- int opnd;
- int ch;
- int n;
- scan = preg->reginput;
- opnd = OPERAND(p);
- switch (OP(preg, p)) {
- case ANY:
- while (!reg_iseol(preg, *scan) && count < max) {
- count++;
- scan += utf8_charlen(*scan);
- }
- break;
- case EXACTLY:
- while (count < max) {
- n = reg_utf8_tounicode_case(scan, &ch, preg->cflags & REG_ICASE);
- if (preg->program[opnd] != ch) {
- break;
- }
- count++;
- scan += n;
- }
- break;
- case ANYOF:
- while (count < max) {
- n = reg_utf8_tounicode_case(scan, &ch, preg->cflags & REG_ICASE);
- if (reg_iseol(preg, ch) || reg_range_find(preg->program + opnd, ch) == 0) {
- break;
- }
- count++;
- scan += n;
- }
- break;
- case ANYBUT:
- while (count < max) {
- n = reg_utf8_tounicode_case(scan, &ch, preg->cflags & REG_ICASE);
- if (reg_iseol(preg, ch) || reg_range_find(preg->program + opnd, ch) != 0) {
- break;
- }
- count++;
- scan += n;
- }
- break;
- default:
- preg->err = REG_ERR_INTERNAL;
- count = 0;
- break;
- }
- preg->reginput = scan;
- return(count);
- }
- static int regnext(regex_t *preg, int p )
- {
- int offset;
- offset = NEXT(preg, p);
- if (offset == 0)
- return 0;
- if (OP(preg, p) == BACK)
- return(p-offset);
- else
- return(p+offset);
- }
- static int regopsize(regex_t *preg, int p )
- {
- switch (OP(preg, p)) {
- case REP:
- case REPMIN:
- case REPX:
- case REPXMIN:
- return 5;
- case ANYOF:
- case ANYBUT:
- case EXACTLY: {
- int s = p + 2;
- while (preg->program[s++]) {
- }
- return s - p;
- }
- }
- return 2;
- }
- size_t jim_regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
- {
- static const char *error_strings[] = {
- "success",
- "no match",
- "bad pattern",
- "null argument",
- "unknown error",
- "too big",
- "out of memory",
- "too many ()",
- "parentheses () not balanced",
- "braces {} not balanced",
- "invalid repetition count(s)",
- "extra characters",
- "*+ of empty atom",
- "nested count",
- "internal error",
- "count follows nothing",
- "invalid escape \\ sequence",
- "corrupted program",
- "contains null char",
- "brackets [] not balanced",
- };
- const char *err;
- if (errcode < 0 || errcode >= REG_ERR_NUM) {
- err = "Bad error code";
- }
- else {
- err = error_strings[errcode];
- }
- return snprintf(errbuf, errbuf_size, "%s", err);
- }
- void jim_regfree(regex_t *preg)
- {
- free(preg->program);
- }
- #endif
- #include <string.h>
- void Jim_SetResultErrno(Jim_Interp *interp, const char *msg)
- {
- Jim_SetResultFormatted(interp, "%s: %s", msg, strerror(Jim_Errno()));
- }
- #if defined(_WIN32) || defined(WIN32)
- #include <sys/stat.h>
- int Jim_Errno(void)
- {
- switch (GetLastError()) {
- case ERROR_FILE_NOT_FOUND: return ENOENT;
- case ERROR_PATH_NOT_FOUND: return ENOENT;
- case ERROR_TOO_MANY_OPEN_FILES: return EMFILE;
- case ERROR_ACCESS_DENIED: return EACCES;
- case ERROR_INVALID_HANDLE: return EBADF;
- case ERROR_BAD_ENVIRONMENT: return E2BIG;
- case ERROR_BAD_FORMAT: return ENOEXEC;
- case ERROR_INVALID_ACCESS: return EACCES;
- case ERROR_INVALID_DRIVE: return ENOENT;
- case ERROR_CURRENT_DIRECTORY: return EACCES;
- case ERROR_NOT_SAME_DEVICE: return EXDEV;
- case ERROR_NO_MORE_FILES: return ENOENT;
- case ERROR_WRITE_PROTECT: return EROFS;
- case ERROR_BAD_UNIT: return ENXIO;
- case ERROR_NOT_READY: return EBUSY;
- case ERROR_BAD_COMMAND: return EIO;
- case ERROR_CRC: return EIO;
- case ERROR_BAD_LENGTH: return EIO;
- case ERROR_SEEK: return EIO;
- case ERROR_WRITE_FAULT: return EIO;
- case ERROR_READ_FAULT: return EIO;
- case ERROR_GEN_FAILURE: return EIO;
- case ERROR_SHARING_VIOLATION: return EACCES;
- case ERROR_LOCK_VIOLATION: return EACCES;
- case ERROR_SHARING_BUFFER_EXCEEDED: return ENFILE;
- case ERROR_HANDLE_DISK_FULL: return ENOSPC;
- case ERROR_NOT_SUPPORTED: return ENODEV;
- case ERROR_REM_NOT_LIST: return EBUSY;
- case ERROR_DUP_NAME: return EEXIST;
- case ERROR_BAD_NETPATH: return ENOENT;
- case ERROR_NETWORK_BUSY: return EBUSY;
- case ERROR_DEV_NOT_EXIST: return ENODEV;
- case ERROR_TOO_MANY_CMDS: return EAGAIN;
- case ERROR_ADAP_HDW_ERR: return EIO;
- case ERROR_BAD_NET_RESP: return EIO;
- case ERROR_UNEXP_NET_ERR: return EIO;
- case ERROR_NETNAME_DELETED: return ENOENT;
- case ERROR_NETWORK_ACCESS_DENIED: return EACCES;
- case ERROR_BAD_DEV_TYPE: return ENODEV;
- case ERROR_BAD_NET_NAME: return ENOENT;
- case ERROR_TOO_MANY_NAMES: return ENFILE;
- case ERROR_TOO_MANY_SESS: return EIO;
- case ERROR_SHARING_PAUSED: return EAGAIN;
- case ERROR_REDIR_PAUSED: return EAGAIN;
- case ERROR_FILE_EXISTS: return EEXIST;
- case ERROR_CANNOT_MAKE: return ENOSPC;
- case ERROR_OUT_OF_STRUCTURES: return ENFILE;
- case ERROR_ALREADY_ASSIGNED: return EEXIST;
- case ERROR_INVALID_PASSWORD: return EPERM;
- case ERROR_NET_WRITE_FAULT: return EIO;
- case ERROR_NO_PROC_SLOTS: return EAGAIN;
- case ERROR_DISK_CHANGE: return EXDEV;
- case ERROR_BROKEN_PIPE: return EPIPE;
- case ERROR_OPEN_FAILED: return ENOENT;
- case ERROR_DISK_FULL: return ENOSPC;
- case ERROR_NO_MORE_SEARCH_HANDLES: return EMFILE;
- case ERROR_INVALID_TARGET_HANDLE: return EBADF;
- case ERROR_INVALID_NAME: return ENOENT;
- case ERROR_PROC_NOT_FOUND: return ESRCH;
- case ERROR_WAIT_NO_CHILDREN: return ECHILD;
- case ERROR_CHILD_NOT_COMPLETE: return ECHILD;
- case ERROR_DIRECT_ACCESS_HANDLE: return EBADF;
- case ERROR_SEEK_ON_DEVICE: return ESPIPE;
- case ERROR_BUSY_DRIVE: return EAGAIN;
- case ERROR_DIR_NOT_EMPTY: return EEXIST;
- case ERROR_NOT_LOCKED: return EACCES;
- case ERROR_BAD_PATHNAME: return ENOENT;
- case ERROR_LOCK_FAILED: return EACCES;
- case ERROR_ALREADY_EXISTS: return EEXIST;
- case ERROR_FILENAME_EXCED_RANGE: return ENAMETOOLONG;
- case ERROR_BAD_PIPE: return EPIPE;
- case ERROR_PIPE_BUSY: return EAGAIN;
- case ERROR_PIPE_NOT_CONNECTED: return EPIPE;
- case ERROR_DIRECTORY: return ENOTDIR;
- }
- return EINVAL;
- }
- long JimProcessPid(phandle_t pid)
- {
- if (pid == INVALID_HANDLE_VALUE) {
- return -1;
- }
- return GetProcessId(pid);
- }
- phandle_t JimWaitPid(long pid, int *status, int nohang)
- {
- if (pid > 0) {
- HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION | SYNCHRONIZE, FALSE, pid);
- if (h) {
- long pid = waitpid(h, status, nohang);
- CloseHandle(h);
- if (pid > 0) {
- return h;
- }
- }
- }
- return JIM_BAD_PHANDLE;
- }
- long waitpid(phandle_t phandle, int *status, int nohang)
- {
- long pid;
- DWORD ret = WaitForSingleObject(phandle, nohang ? 0 : INFINITE);
- if (ret == WAIT_TIMEOUT || ret == WAIT_FAILED) {
- return -1;
- }
- GetExitCodeProcess(phandle, &ret);
- *status = ret;
- pid = GetProcessId(phandle);
- CloseHandle(phandle);
- return pid;
- }
- int Jim_MakeTempFile(Jim_Interp *interp, const char *filename_template, int unlink_file)
- {
- char name[MAX_PATH];
- HANDLE handle;
- if (!GetTempPath(MAX_PATH, name) || !GetTempFileName(name, filename_template ? filename_template : "JIM", 0, name)) {
- return -1;
- }
- handle = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, NULL,
- CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | (unlink_file ? FILE_FLAG_DELETE_ON_CLOSE : 0),
- NULL);
- if (handle == INVALID_HANDLE_VALUE) {
- goto error;
- }
- Jim_SetResultString(interp, name, -1);
- return _open_osfhandle((intptr_t)handle, _O_RDWR | _O_TEXT);
- error:
- Jim_SetResultErrno(interp, name);
- DeleteFile(name);
- return -1;
- }
- int Jim_OpenForWrite(const char *filename, int append)
- {
- if (strcmp(filename, "/dev/null") == 0) {
- filename = "nul:";
- }
- int fd = _open(filename, _O_WRONLY | _O_CREAT | _O_TEXT | (append ? _O_APPEND : _O_TRUNC), _S_IREAD | _S_IWRITE);
- if (fd >= 0 && append) {
- _lseek(fd, 0L, SEEK_END);
- }
- return fd;
- }
- int Jim_OpenForRead(const char *filename)
- {
- if (strcmp(filename, "/dev/null") == 0) {
- filename = "nul:";
- }
- return _open(filename, _O_RDONLY | _O_TEXT, 0);
- }
- #elif defined(HAVE_UNISTD_H)
- int Jim_MakeTempFile(Jim_Interp *interp, const char *filename_template, int unlink_file)
- {
- int fd;
- mode_t mask;
- Jim_Obj *filenameObj;
- if (filename_template == NULL) {
- const char *tmpdir = getenv("TMPDIR");
- if (tmpdir == NULL || *tmpdir == '\0' || access(tmpdir, W_OK) != 0) {
- tmpdir = "/tmp/";
- }
- filenameObj = Jim_NewStringObj(interp, tmpdir, -1);
- if (tmpdir[0] && tmpdir[strlen(tmpdir) - 1] != '/') {
- Jim_AppendString(interp, filenameObj, "/", 1);
- }
- Jim_AppendString(interp, filenameObj, "tcl.tmp.XXXXXX", -1);
- }
- else {
- filenameObj = Jim_NewStringObj(interp, filename_template, -1);
- }
- #ifdef HAVE_UMASK
- mask = umask(S_IXUSR | S_IRWXG | S_IRWXO);
- #endif
- #ifdef HAVE_MKSTEMP
- fd = mkstemp(filenameObj->bytes);
- #else
- if (mktemp(filenameObj->bytes) == NULL) {
- fd = -1;
- }
- else {
- fd = open(filenameObj->bytes, O_RDWR | O_CREAT | O_TRUNC);
- }
- #endif
- #ifdef HAVE_UMASK
- umask(mask);
- #endif
- if (fd < 0) {
- Jim_SetResultErrno(interp, Jim_String(filenameObj));
- Jim_FreeNewObj(interp, filenameObj);
- return -1;
- }
- if (unlink_file) {
- remove(Jim_String(filenameObj));
- }
- Jim_SetResult(interp, filenameObj);
- return fd;
- }
- int Jim_OpenForWrite(const char *filename, int append)
- {
- return open(filename, O_WRONLY | O_CREAT | (append ? O_APPEND : O_TRUNC), 0666);
- }
- int Jim_OpenForRead(const char *filename)
- {
- return open(filename, O_RDONLY, 0);
- }
- #endif
- #if defined(_WIN32) || defined(WIN32)
- #ifndef STRICT
- #define STRICT
- #endif
- #define WIN32_LEAN_AND_MEAN
- #include <windows.h>
- #if defined(HAVE_DLOPEN_COMPAT)
- void *dlopen(const char *path, int mode)
- {
- JIM_NOTUSED(mode);
- return (void *)LoadLibraryA(path);
- }
- int dlclose(void *handle)
- {
- FreeLibrary((HANDLE)handle);
- return 0;
- }
- void *dlsym(void *handle, const char *symbol)
- {
- return GetProcAddress((HMODULE)handle, symbol);
- }
- char *dlerror(void)
- {
- static char msg[121];
- FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),
- LANG_NEUTRAL, msg, sizeof(msg) - 1, NULL);
- return msg;
- }
- #endif
- #ifdef _MSC_VER
- #include <sys/timeb.h>
- int gettimeofday(struct timeval *tv, void *unused)
- {
- struct _timeb tb;
- _ftime(&tb);
- tv->tv_sec = tb.time;
- tv->tv_usec = tb.millitm * 1000;
- return 0;
- }
- DIR *opendir(const char *name)
- {
- DIR *dir = 0;
- if (name && name[0]) {
- size_t base_length = strlen(name);
- const char *all =
- strchr("/\\", name[base_length - 1]) ? "*" : "/*";
- if ((dir = (DIR *) Jim_Alloc(sizeof *dir)) != 0 &&
- (dir->name = (char *)Jim_Alloc(base_length + strlen(all) + 1)) != 0) {
- strcat(strcpy(dir->name, name), all);
- if ((dir->handle = (long)_findfirst(dir->name, &dir->info)) != -1)
- dir->result.d_name = 0;
- else {
- Jim_Free(dir->name);
- Jim_Free(dir);
- dir = 0;
- }
- }
- else {
- Jim_Free(dir);
- dir = 0;
- errno = ENOMEM;
- }
- }
- else {
- errno = EINVAL;
- }
- return dir;
- }
- int closedir(DIR * dir)
- {
- int result = -1;
- if (dir) {
- if (dir->handle != -1)
- result = _findclose(dir->handle);
- Jim_Free(dir->name);
- Jim_Free(dir);
- }
- if (result == -1)
- errno = EBADF;
- return result;
- }
- struct dirent *readdir(DIR * dir)
- {
- struct dirent *result = 0;
- if (dir && dir->handle != -1) {
- if (!dir->result.d_name || _findnext(dir->handle, &dir->info) != -1) {
- result = &dir->result;
- result->d_name = dir->info.name;
- }
- }
- else {
- errno = EBADF;
- }
- return result;
- }
- #endif
- #endif
- #include <stdio.h>
- #include <signal.h>
- #ifndef SIGPIPE
- #define SIGPIPE 13
- #endif
- #ifndef SIGINT
- #define SIGINT 2
- #endif
- const char *Jim_SignalId(int sig)
- {
- static char buf[10];
- switch (sig) {
- case SIGINT: return "SIGINT";
- case SIGPIPE: return "SIGPIPE";
- }
- snprintf(buf, sizeof(buf), "%d", sig);
- return buf;
- }
- #ifndef JIM_BOOTSTRAP_LIB_ONLY
- #include <errno.h>
- #include <string.h>
- #include <stdio.h>
- #ifdef USE_LINENOISE
- #ifdef HAVE_UNISTD_H
- #include <unistd.h>
- #endif
- #ifdef HAVE_SYS_STAT_H
- #include <sys/stat.h>
- #endif
- #include "linenoise.h"
- #else
- #define MAX_LINE_LEN 512
- #endif
- #ifdef USE_LINENOISE
- struct JimCompletionInfo {
- Jim_Interp *interp;
- Jim_Obj *completion_command;
- Jim_Obj *hints_command;
- };
- static struct JimCompletionInfo *JimGetCompletionInfo(Jim_Interp *interp);
- static void JimCompletionCallback(const char *prefix, linenoiseCompletions *comp, void *userdata);
- static const char completion_callback_assoc_key[] = "interactive-completion";
- static char *JimHintsCallback(const char *prefix, int *color, int *bold, void *userdata);
- static void JimFreeHintsCallback(void *hint, void *userdata);
- #endif
- char *Jim_HistoryGetline(Jim_Interp *interp, const char *prompt)
- {
- #ifdef USE_LINENOISE
- struct JimCompletionInfo *compinfo = JimGetCompletionInfo(interp);
- char *result;
- Jim_Obj *objPtr;
- long mlmode = 0;
- if (compinfo->completion_command) {
- linenoiseSetCompletionCallback(JimCompletionCallback, compinfo);
- }
- if (compinfo->hints_command) {
- linenoiseSetHintsCallback(JimHintsCallback, compinfo);
- linenoiseSetFreeHintsCallback(JimFreeHintsCallback);
- }
- objPtr = Jim_GetVariableStr(interp, "history::multiline", JIM_NONE);
- if (objPtr && Jim_GetLong(interp, objPtr, &mlmode) == JIM_NONE) {
- linenoiseSetMultiLine(mlmode);
- }
- result = linenoise(prompt);
- linenoiseSetCompletionCallback(NULL, NULL);
- linenoiseSetHintsCallback(NULL, NULL);
- linenoiseSetFreeHintsCallback(NULL);
- return result;
- #else
- int len;
- char *line = Jim_Alloc(MAX_LINE_LEN);
- fputs(prompt, stdout);
- fflush(stdout);
- if (fgets(line, MAX_LINE_LEN, stdin) == NULL) {
- Jim_Free(line);
- return NULL;
- }
- len = strlen(line);
- if (len && line[len - 1] == '\n') {
- line[len - 1] = '\0';
- }
- return line;
- #endif
- }
- void Jim_HistoryLoad(const char *filename)
- {
- #ifdef USE_LINENOISE
- linenoiseHistoryLoad(filename);
- #endif
- }
- void Jim_HistoryAdd(const char *line)
- {
- #ifdef USE_LINENOISE
- linenoiseHistoryAdd(line);
- #endif
- }
- void Jim_HistorySave(const char *filename)
- {
- #ifdef USE_LINENOISE
- #ifdef HAVE_UMASK
- mode_t mask;
- mask = umask(S_IXUSR | S_IRWXG | S_IRWXO);
- #endif
- linenoiseHistorySave(filename);
- #ifdef HAVE_UMASK
- umask(mask);
- #endif
- #endif
- }
- void Jim_HistoryShow(void)
- {
- #ifdef USE_LINENOISE
- int i;
- int len;
- char **history = linenoiseHistory(&len);
- for (i = 0; i < len; i++) {
- printf("%4d %s\n", i + 1, history[i]);
- }
- #endif
- }
- void Jim_HistorySetMaxLen(int length)
- {
- #ifdef USE_LINENOISE
- linenoiseHistorySetMaxLen(length);
- #endif
- }
- int Jim_HistoryGetMaxLen(void)
- {
- #ifdef USE_LINENOISE
- return linenoiseHistoryGetMaxLen();
- #endif
- return 0;
- }
- #ifdef USE_LINENOISE
- static void JimCompletionCallback(const char *prefix, linenoiseCompletions *comp, void *userdata)
- {
- struct JimCompletionInfo *info = (struct JimCompletionInfo *)userdata;
- Jim_Obj *objv[2];
- int ret;
- objv[0] = info->completion_command;
- objv[1] = Jim_NewStringObj(info->interp, prefix, -1);
- ret = Jim_EvalObjVector(info->interp, 2, objv);
- if (ret == JIM_OK) {
- int i;
- Jim_Obj *listObj = Jim_GetResult(info->interp);
- int len = Jim_ListLength(info->interp, listObj);
- for (i = 0; i < len; i++) {
- linenoiseAddCompletion(comp, Jim_String(Jim_ListGetIndex(info->interp, listObj, i)));
- }
- }
- }
- static char *JimHintsCallback(const char *prefix, int *color, int *bold, void *userdata)
- {
- struct JimCompletionInfo *info = (struct JimCompletionInfo *)userdata;
- Jim_Obj *objv[2];
- int ret;
- char *result = NULL;
- objv[0] = info->hints_command;
- objv[1] = Jim_NewStringObj(info->interp, prefix, -1);
- ret = Jim_EvalObjVector(info->interp, 2, objv);
- if (ret == JIM_OK) {
- Jim_Obj *listObj = Jim_GetResult(info->interp);
- Jim_IncrRefCount(listObj);
- int len = Jim_ListLength(info->interp, listObj);
- if (len >= 1) {
- long x;
- result = Jim_StrDup(Jim_String(Jim_ListGetIndex(info->interp, listObj, 0)));
- if (len >= 2 && Jim_GetLong(info->interp, Jim_ListGetIndex(info->interp, listObj, 1), &x) == JIM_OK) {
- *color = x;
- }
- if (len >= 3 && Jim_GetLong(info->interp, Jim_ListGetIndex(info->interp, listObj, 2), &x) == JIM_OK) {
- *bold = x;
- }
- }
- Jim_DecrRefCount(info->interp, listObj);
- }
- return result;
- }
- static void JimFreeHintsCallback(void *hint, void *userdata)
- {
- Jim_Free(hint);
- }
- static void JimHistoryFreeCompletion(Jim_Interp *interp, void *data)
- {
- struct JimCompletionInfo *compinfo = data;
- if (compinfo->completion_command) {
- Jim_DecrRefCount(interp, compinfo->completion_command);
- }
- if (compinfo->hints_command) {
- Jim_DecrRefCount(interp, compinfo->hints_command);
- }
- Jim_Free(compinfo);
- }
- static struct JimCompletionInfo *JimGetCompletionInfo(Jim_Interp *interp)
- {
- struct JimCompletionInfo *compinfo = Jim_GetAssocData(interp, completion_callback_assoc_key);
- if (compinfo == NULL) {
- compinfo = Jim_Alloc(sizeof(*compinfo));
- compinfo->interp = interp;
- compinfo->completion_command = NULL;
- compinfo->hints_command = NULL;
- Jim_SetAssocData(interp, completion_callback_assoc_key, JimHistoryFreeCompletion, compinfo);
- }
- return compinfo;
- }
- #endif
- void Jim_HistorySetCompletion(Jim_Interp *interp, Jim_Obj *completionCommandObj)
- {
- #ifdef USE_LINENOISE
- struct JimCompletionInfo *compinfo = JimGetCompletionInfo(interp);
- if (completionCommandObj) {
- Jim_IncrRefCount(completionCommandObj);
- }
- if (compinfo->completion_command) {
- Jim_DecrRefCount(interp, compinfo->completion_command);
- }
- compinfo->completion_command = completionCommandObj;
- #endif
- }
- void Jim_HistorySetHints(Jim_Interp *interp, Jim_Obj *hintsCommandObj)
- {
- #ifdef USE_LINENOISE
- struct JimCompletionInfo *compinfo = JimGetCompletionInfo(interp);
- if (hintsCommandObj) {
- Jim_IncrRefCount(hintsCommandObj);
- }
- if (compinfo->hints_command) {
- Jim_DecrRefCount(interp, compinfo->hints_command);
- }
- compinfo->hints_command = hintsCommandObj;
- #endif
- }
- int Jim_InteractivePrompt(Jim_Interp *interp)
- {
- int retcode = JIM_OK;
- char *history_file = NULL;
- #ifdef USE_LINENOISE
- const char *home;
- home = getenv("HOME");
- if (home && isatty(STDIN_FILENO)) {
- int history_len = strlen(home) + sizeof("/.jim_history");
- history_file = Jim_Alloc(history_len);
- snprintf(history_file, history_len, "%s/.jim_history", home);
- Jim_HistoryLoad(history_file);
- }
- Jim_HistorySetCompletion(interp, Jim_NewStringObj(interp, "tcl::autocomplete", -1));
- Jim_HistorySetHints(interp, Jim_NewStringObj(interp, "tcl::stdhint", -1));
- #endif
- printf("Welcome to Jim version %d.%d\n",
- JIM_VERSION / 100, JIM_VERSION % 100);
- Jim_SetVariableStrWithStr(interp, JIM_INTERACTIVE, "1");
- while (1) {
- Jim_Obj *scriptObjPtr;
- const char *result;
- int reslen;
- char prompt[20];
- if (retcode != JIM_OK) {
- const char *retcodestr = Jim_ReturnCode(retcode);
- if (*retcodestr == '?') {
- snprintf(prompt, sizeof(prompt) - 3, "[%d] . ", retcode);
- }
- else {
- snprintf(prompt, sizeof(prompt) - 3, "[%s] . ", retcodestr);
- }
- }
- else {
- strcpy(prompt, ". ");
- }
- scriptObjPtr = Jim_NewStringObj(interp, "", 0);
- Jim_IncrRefCount(scriptObjPtr);
- while (1) {
- char state;
- char *line;
- line = Jim_HistoryGetline(interp, prompt);
- if (line == NULL) {
- if (errno == EINTR) {
- continue;
- }
- Jim_DecrRefCount(interp, scriptObjPtr);
- retcode = JIM_OK;
- goto out;
- }
- if (Jim_Length(scriptObjPtr) != 0) {
- Jim_AppendString(interp, scriptObjPtr, "\n", 1);
- }
- Jim_AppendString(interp, scriptObjPtr, line, -1);
- Jim_Free(line);
- if (Jim_ScriptIsComplete(interp, scriptObjPtr, &state))
- break;
- snprintf(prompt, sizeof(prompt), "%c> ", state);
- }
- #ifdef USE_LINENOISE
- if (strcmp(Jim_String(scriptObjPtr), "h") == 0) {
- Jim_HistoryShow();
- Jim_DecrRefCount(interp, scriptObjPtr);
- continue;
- }
- Jim_HistoryAdd(Jim_String(scriptObjPtr));
- if (history_file) {
- Jim_HistorySave(history_file);
- }
- #endif
- retcode = Jim_EvalObj(interp, scriptObjPtr);
- Jim_DecrRefCount(interp, scriptObjPtr);
- if (retcode == JIM_EXIT) {
- break;
- }
- if (retcode == JIM_ERR) {
- Jim_MakeErrorMessage(interp);
- }
- result = Jim_GetString(Jim_GetResult(interp), &reslen);
- if (reslen) {
- if (fwrite(result, reslen, 1, stdout) == 0) {
- }
- putchar('\n');
- }
- }
- out:
- Jim_Free(history_file);
- return retcode;
- }
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- extern int Jim_initjimshInit(Jim_Interp *interp);
- static void JimSetArgv(Jim_Interp *interp, int argc, char *const argv[])
- {
- int n;
- Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
- for (n = 0; n < argc; n++) {
- Jim_Obj *obj = Jim_NewStringObj(interp, argv[n], -1);
- Jim_ListAppendElement(interp, listObj, obj);
- }
- Jim_SetVariableStr(interp, "argv", listObj);
- Jim_SetVariableStr(interp, "argc", Jim_NewIntObj(interp, argc));
- }
- static void JimPrintErrorMessage(Jim_Interp *interp)
- {
- Jim_MakeErrorMessage(interp);
- fprintf(stderr, "%s\n", Jim_String(Jim_GetResult(interp)));
- }
- void usage(const char* executable_name)
- {
- printf("jimsh version %d.%d\n", JIM_VERSION / 100, JIM_VERSION % 100);
- printf("Usage: %s\n", executable_name);
- printf("or : %s [options] [filename]\n", executable_name);
- printf("\n");
- printf("Without options: Interactive mode\n");
- printf("\n");
- printf("Options:\n");
- printf(" --version : prints the version string\n");
- printf(" --help : prints this text\n");
- printf(" -e CMD : executes command CMD\n");
- printf(" NOTE: all subsequent options will be passed as arguments to the command\n");
- printf(" [filename|-] : executes the script contained in the named file, or from stdin if \"-\"\n");
- printf(" NOTE: all subsequent options will be passed to the script\n\n");
- }
- int main(int argc, char *const argv[])
- {
- int retcode;
- Jim_Interp *interp;
- char *const orig_argv0 = argv[0];
- if (argc > 1 && strcmp(argv[1], "--version") == 0) {
- printf("%d.%d\n", JIM_VERSION / 100, JIM_VERSION % 100);
- return 0;
- }
- else if (argc > 1 && strcmp(argv[1], "--help") == 0) {
- usage(argv[0]);
- return 0;
- }
- interp = Jim_CreateInterp();
- Jim_RegisterCoreCommands(interp);
- if (Jim_InitStaticExtensions(interp) != JIM_OK) {
- JimPrintErrorMessage(interp);
- }
- Jim_SetVariableStrWithStr(interp, "jim::argv0", orig_argv0);
- Jim_SetVariableStrWithStr(interp, JIM_INTERACTIVE, argc == 1 ? "1" : "0");
- #ifdef USE_LINENOISE
- Jim_SetVariableStrWithStr(interp, "jim::lineedit", "1");
- #else
- Jim_SetVariableStrWithStr(interp, "jim::lineedit", "0");
- #endif
- retcode = Jim_initjimshInit(interp);
- if (argc == 1) {
- if (retcode == JIM_ERR) {
- JimPrintErrorMessage(interp);
- }
- if (retcode != JIM_EXIT) {
- JimSetArgv(interp, 0, NULL);
- retcode = Jim_InteractivePrompt(interp);
- }
- }
- else {
- if (argc > 2 && strcmp(argv[1], "-e") == 0) {
- JimSetArgv(interp, argc - 3, argv + 3);
- retcode = Jim_Eval(interp, argv[2]);
- if (retcode != JIM_ERR) {
- int len;
- const char *msg = Jim_GetString(Jim_GetResult(interp), &len);
- if (fwrite(msg, len, 1, stdout) == 0) {
- }
- putchar('\n');
- }
- }
- else {
- Jim_SetVariableStr(interp, "argv0", Jim_NewStringObj(interp, argv[1], -1));
- JimSetArgv(interp, argc - 2, argv + 2);
- if (strcmp(argv[1], "-") == 0) {
- retcode = Jim_Eval(interp, "eval [info source [stdin read] stdin 1]");
- } else {
- retcode = Jim_EvalFile(interp, argv[1]);
- }
- }
- if (retcode == JIM_ERR) {
- JimPrintErrorMessage(interp);
- }
- }
- if (retcode == JIM_EXIT) {
- retcode = Jim_GetExitCode(interp);
- }
- else if (retcode == JIM_ERR) {
- retcode = 1;
- }
- else {
- retcode = 0;
- }
- Jim_FreeInterp(interp);
- return retcode;
- }
- #endif
|