diff options
-rw-r--r-- | src/root.zig | 19 |
1 files changed, 11 insertions, 8 deletions
diff --git a/src/root.zig b/src/root.zig index 939549f..19d7bf5 100644 --- a/src/root.zig +++ b/src/root.zig @@ -33,18 +33,22 @@ fn isIntern(T: type) bool { } and (@import("builtin").is_test or @import("root").zsanettIntern(T)); } +/// Memoized root environment. +var root_env: ?*janet.Table = null; /// Associative list of Zig and wrapped Janet functions. var fn_map: HashMap(*const anyopaque, janet.CFunction) = undefined; /// Initializes global Janet state, that is thread local. pub fn init() void { _ = janet.init(); // always 0 + root_env = janet.coreEnv(null); fn_map = .empty; } /// Frees resources managed by Janet. pub fn deinit() void { fn_map.deinit(c_allocator); + root_env = null; janet.deinit(); } @@ -107,7 +111,7 @@ fn getArg(T: type, argv: [*c]Value, n: i32) !T { fn raise(err: anyerror) Value { const symb = janet.symbol("error", 5); - const fun = janet.resolveExt(janet.coreEnv(null), symb).value; + const fun = janet.resolveExt(root_env, symb).value; const name = @errorName(err); var msg: [*]u8 = @ptrCast(janet.smalloc(name.len * 2)); var n: u16 = 0; @@ -348,8 +352,8 @@ test "isomorphism" { /// Evaluates the Janet program given in str. pub fn eval(comptime T: type, str: []const u8, src: [*:0]const u8) !T { var ret: Value = undefined; - const errflags = janet.dobytes(janet.coreEnv(null), - str.ptr, @intCast(str.len), src, &ret); + const errflags = janet.dobytes(root_env, str.ptr, @intCast(str.len), + src, &ret); // Errors are already logged by Janet, // among them only one is returned and not machine-readable. return if (errflags == 0) unwrap(T, ret) else error.JanetError; @@ -364,7 +368,7 @@ test eval { /// Binds val to name. pub fn def(name: [*:0]const u8, val: anytype, documentation: [*:0]const u8) !void { - janet.def(janet.coreEnv(null), name, try wrap(val), documentation); + janet.def(root_env, name, try wrap(val), documentation); } test def { @@ -386,7 +390,7 @@ test def { /// Gets value. pub fn resolve(T: type, name: []const u8) !T { const symbol = janet.symbol(name.ptr, @intCast(name.len)); - return try unwrap(T, janet.resolveExt(janet.coreEnv(null), symbol).value); + return try unwrap(T, janet.resolveExt(root_env, symbol).value); } test resolve { @@ -413,11 +417,10 @@ pub fn defn(comptime fun: anytype, reg: struct { }, zeroes(janet.RegExt), }; - const env = janet.coreEnv(null); if (reg.prefix) |prefix| - janet.cfunsExtPrefix(env, prefix, &cfuns) + janet.cfunsExtPrefix(root_env, prefix, &cfuns) else - janet.cfunsExt(env, null, &cfuns); + janet.cfunsExt(root_env, null, &cfuns); } test defn { |