1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
|
//! Top-level module
// SPDX-FileCopyrightText: 2024-2025 Nguyễn Gia Phong
// SPDX-License-Identifier: GPL-3.0-or-later
const Allocator = std.mem.Allocator;
const ArgsTuple = std.meta.ArgsTuple;
const HashMap = std.AutoHashMapUnmanaged;
const SourceLocation = std.builtin.SourceLocation;
const assert = std.debug.assert;
const c_allocator = std.heap.c_allocator;
const declarations = std.meta.declarations;
const eql = std.mem.eql;
const expectEqual = std.testing.expectEqual;
const expectEqualDeep = std.testing.expectEqualDeep;
const expectError = std.testing.expectError;
const std = @import("std");
const toLower = std.ascii.toLower;
const zeroes = std.mem.zeroes;
pub const janet = rename.janet;
pub const kebabCase = rename.kebabCase;
const rename = @import("rename.zig");
pub const renamespace = rename.space;
test {
_ = rename;
}
fn isIntern(T: type) bool {
return switch (@typeInfo(T)) {
.@"struct", .@"enum", .@"union", .@"opaque" => true,
else => false,
} 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();
}
/// Janet value structure.
pub const Value = janet.Janet;
/// Creates a Janet keyword in kebab-case.
fn keyword(comptime name: [:0]const u8) Value {
const kebab = kebabCase(name);
return janet.keywordv(kebab.ptr, @as(i32, @intCast(kebab.len)));
}
fn structWithMethods(T: type, fields_len: usize) !*janet.KV {
if (!comptime isIntern(T))
return janet.structBegin(@intCast(fields_len));
const decls = comptime declarations(T);
var cfuns: [decls.len]struct { Value, Value } = undefined;
var count: usize = 0;
inline for (decls) |decl_info| {
const decl = @field(T, decl_info.name);
switch (@typeInfo(@TypeOf(decl))) {
.@"fn" => |fn_info| if (!fn_info.is_generic) {
cfuns[count] = .{
keyword(decl_info.name),
try wrap(decl),
};
count += 1;
},
else => {},
}
}
const kv = janet.structBegin(@intCast(fields_len + count));
for (cfuns[0..count]) |cfun| {
const k, const v = cfun;
janet.structPut(kv, k, v);
}
return kv;
}
/// Gets function argument.
fn getArg(T: type, argv: [*c]Value, n: i32) !T {
return switch (@typeInfo(T)) {
.bool => janet.getboolean(argv, n) != 0,
.int => |int| @intCast(switch (int.signedness) {
.signed => switch (int.bits) {
0...16 => janet.getinteger16,
17...32 => janet.getinteger,
else => janet.getinteger64,
},
.unsigned => if (T != usize) switch (int.bits) {
0...16 => janet.getuinteger16,
17...32 => janet.getuinteger,
else => janet.getuinteger64,
} else janet.getsize,
}(argv, n)),
.float => @floatCast(janet.getnumber(argv, n)),
else => unwrap(T, argv[@intCast(n)]),
};
}
fn raise(err: anyerror) noreturn {
const name = @errorName(err);
var msg: [*:0]u8 = @ptrCast(janet.smalloc(name.len * 2));
var n: usize = 0;
for (name) |char| {
switch (char) {
'A'...'Z' => if (n > 0) {
msg[n] = ' ';
n += 1;
},
else => {},
}
msg[n] = toLower(char);
n += 1;
}
msg[n] = 0;
n += 1;
msg = @ptrCast(janet.srealloc(msg, n));
janet.panic(msg);
unreachable;
}
pub fn wrapFn(f: anytype) Allocator.Error!janet.CFunction {
const F = @TypeOf(f);
const info = @typeInfo(F).@"fn";
assert(!info.is_generic);
const entry = try fn_map.getOrPut(c_allocator, &f);
if (!entry.found_existing)
entry.value_ptr.* = struct {
fn cfun(argc: i32, argv: [*c]Value) callconv(.C) Value {
janet.fixarity(argc, info.params.len);
var args: ArgsTuple(F) = undefined;
inline for (&args, info.params, 0..) |*arg, param, i| {
const P = param.type.?;
arg.* = getArg(P, argv, i) catch |err|
raise(err);
}
const result = @call(.auto, f, args);
return if (@typeInfo(@TypeOf(result)) != .error_union)
wrap(result) catch unreachable
else if (result) |res|
wrap(res) catch unreachable
else |err|
raise(err);
}
}.cfun;
return entry.value_ptr.*;
}
/// Wraps native type in Janet value.
pub fn wrap(x: anytype) !Value {
const T = @TypeOf(x);
return switch (@typeInfo(T)) {
.void => janet.wrapNil(),
.bool => janet.wrapBoolean(@intFromBool(x)),
.int => janet.wrapInteger(@intCast(x)),
.comptime_int => janet.wrapInteger(x),
.float => janet.wrapNumber(@floatCast(x)),
.comptime_float => janet.wrapNumber(x),
.enum_literal => keyword(@tagName(x)),
.array => |info| y: {
var tuple: [info.len]Value = undefined;
for (x, &tuple) |src, *dest|
dest.* = try wrap(src);
break :y janet.wrapTuple(janet.tupleN(&tuple, tuple.len));
},
.@"enum" => switch (x) {
inline else => |tag| keyword(@tagName(tag)),
},
.@"fn" => janet.wrapCfunction(try wrapFn(x)),
.optional => if (x) |child| try wrap(child) else try wrap({}),
.pointer => |info| switch (info.size) {
.one => if (isIntern(info.child)) y: {
const kv = try structWithMethods(info.child, 1);
const ptr = janet.wrapPointer(@constCast(@ptrCast(x)));
janet.structPut(kv, keyword(@typeName(info.child)), ptr);
break :y janet.wrapStruct(janet.structEnd(kv));
} else janet.wrapPointer(@constCast(@ptrCast(x))),
.many, .c => janet.wrapPointer(@constCast(@ptrCast(x))),
.slice => y: {
const len: i32 = @intCast(x.len * @sizeOf(info.child));
if (info.is_const) {
const string = janet.string(@ptrCast(x.ptr), len);
break :y janet.wrapString(string);
} else {
const memory: *anyopaque = @ptrCast(x.ptr);
const buffer = janet.pointerBufferUnsafe(memory, len, len);
break :y janet.wrapBuffer(buffer);
}
},
},
.@"struct" => |info| y: {
const kv = try structWithMethods(T, info.fields.len);
inline for (info.fields) |field| {
const k = keyword(field.name);
const v = @field(x, field.name);
janet.structPut(kv, k, try wrap(v));
}
break :y janet.wrapStruct(janet.structEnd(kv));
},
.@"union" => |info| if (info.tag_type != null) switch (x) {
inline else => |v, tag| janet.wrapTuple(y: {
const k = keyword(@tagName(tag));
const tuple = [_]Value{ k, try wrap(v) };
break :y janet.tupleN(&tuple, tuple.len);
}),
} else @compileError("can't wrap untagged union"),
.vector => |info| try wrap(@as([info.len]info.child, x)),
else => @compileError(@typeName(@TypeOf(x))),
};
}
/// Accesses Janet tuple data type-safely.
fn tupleData(len: comptime_int,
head: *const janet.TupleHead) *const [len]Value {
assert(head.length == len);
return @ptrCast(head.data());
}
/// Compares given Janet values for equality.
fn equal(x: Value, y: Value) bool {
return janet.equals(x, y) != 0;
}
/// Checks for Janet nil.
fn isNil(x: Value) bool {
return janet.checktype(x, janet.NIL) != 0;
}
/// Unwraps to native type.
pub fn unwrap(T: type, x: Value) !T {
return switch (@typeInfo(T)) {
.void => {},
.bool => janet.unwrapBoolean(x) != 0,
.int => @intCast(janet.unwrapInteger(x)),
.float => @floatCast(janet.unwrapNumber(x)),
inline .array, .vector => |info| y: {
const head = janet.tupleHead(janet.unwrapTuple(x));
var array: [info.len]info.child = undefined;
for (tupleData(info.len, head).*, &array) |src, *dest|
dest.* = try unwrap(info.child, src);
break :y array;
},
.@"enum" => |info| inline for (info.fields) |field| {
if (equal(keyword(field.name), x))
break @field(T, field.name);
} else error.NoCorrespodingEnum,
.optional => |info| if (isNil(x)) null else try unwrap(info.child, x),
.pointer => |info| switch (info.size) {
.one => if (@typeInfo(info.child) == .@"fn") y: {
var iterator = fn_map.iterator();
while (iterator.next()) |entry|
if (entry.value_ptr.* == janet.unwrapCfunction(x))
break :y @ptrCast(entry.key_ptr.*);
break :y error.UnknownFunction;
} else if (isIntern(info.child)) y: {
const ptr = janet.structGet(janet.unwrapStruct(x),
keyword(@typeName(info.child)));
break :y @alignCast(@ptrCast(janet.unwrapPointer(ptr)));
} else @alignCast(@ptrCast(janet.unwrapPointer(x))),
.many, .c => @alignCast(@ptrCast(janet.unwrapPointer(x))),
.slice => slice: {
const ptr = if (info.is_const)
janet.unwrapString(x)
else
janet.unwrapBuffer(x).*.data;
comptime var many_info = info;
many_info.size = .many;
const Many = @Type(.{ .pointer = many_info });
const many: Many = @alignCast(@ptrCast(ptr));
const size = if (info.is_const)
janet.stringLength(ptr)
else
janet.unwrapBuffer(x).*.count;
const len = @divExact(size, @sizeOf(info.child));
break :slice if (info.sentinel()) |sentinel|
many[0..@intCast(len):sentinel]
else
many[0..@intCast(len)];
},
},
.@"struct" => |info| y: {
const src = janet.unwrapStruct(x);
var dest: T = undefined;
break :y inline for (info.fields) |field| {
const k = keyword(field.name);
const v = janet.structGet(src, k);
@field(dest, field.name) = if (isNil(v))
field.defaultValue() orelse break error.MissingStructField
else
try unwrap(field.type, v);
} else dest;
},
.@"union" => |info| if (info.tag_type != null) y: {
const head = janet.tupleHead(janet.unwrapTuple(x));
const k, const v = tupleData(2, head).*;
break :y inline for (info.fields) |field| {
if (equal(keyword(field.name), k))
break @unionInit(T, field.name, try unwrap(field.type, v));
} else error.UnionTagNotFound;
} else @compileError("can't wrap untagged union"),
else => @compileError(@typeName(T)),
};
}
test "isomorphism" {
init();
defer deinit();
const Immutable = struct {
nothing: void = {},
boolean: bool = true,
integer: u16 = 42069,
float: f64 = 420.69,
enumeration: enum { this, that } = .that,
array: [3]u64 = .{ 1, 4, 2 },
string: [:0]const u8 = "foobar",
c_string: [*c]const u8 = "baz",
slice: []const i32 = &.{ 8, 1, 4 },
tagged_union: union(enum) {
integer: i32,
float: f32,
} = .{ .integer = 123456789 },
vector: @Vector(3, u4) = .{ 5, 6, 7 },
fn sum(i: @This()) f64 {
return @as(f64, @floatFromInt(i.integer)) + i.float;
}
};
const i = Immutable{};
try expectEqualDeep(i, try unwrap(Immutable, try wrap(i)));
const sum = try unwrap(@TypeOf(&Immutable.sum), try wrap(Immutable.sum));
try expectEqual(i.sum(), sum(i));
var array: [2]bool = undefined;
const buffer: []bool = &array;
buffer[0] = false;
buffer[1] = true;
try expectEqual(buffer, try unwrap(@TypeOf(buffer), try wrap(buffer)));
}
/// 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(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;
}
test eval {
init();
defer deinit();
try expectEqual(try eval(i32, "(+ 3 7)", @src().fn_name), 10);
}
/// Binds val to name.
pub fn def(name: [*:0]const u8, val: anytype,
documentation: [*:0]const u8) !void {
janet.def(root_env, name, try wrap(val), documentation);
}
test def {
const Number = struct {
const Number = @This();
n: i8,
pub fn nextN(self: Number) Number {
return Number{ .n = self.n + 1 };
}
};
init();
defer deinit();
try def("seven", Number{ .n = 7 }, "number 7 in a struct");
const nine = try eval(Number, "(:next-n (:next-n seven))",
@src().fn_name);
try expectEqual(Number{ .n = 9 }, nine);
}
/// 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(root_env, symbol).value);
}
test resolve {
init();
defer deinit();
try def("pi", 3, "pi for engineers");
try expectEqual(try resolve(u8, "pi"), 3);
}
/// Exposes given function in Janet.
pub fn defn(comptime fun: anytype, reg: struct {
prefix: ?[*:0]const u8 = null,
name: [*:0]const u8,
documentation: [*:0]const u8,
source: SourceLocation,
}) !void {
const cfuns = [_]janet.RegExt{
.{
.name = reg.name,
.cfun = try wrapFn(fun),
.documentation = reg.documentation,
.source_file = reg.source.file,
.source_line = @bitCast(reg.source.line),
},
zeroes(janet.RegExt),
};
if (reg.prefix) |prefix|
janet.cfunsExtPrefix(root_env, prefix, &cfuns)
else
janet.cfunsExt(root_env, null, &cfuns);
}
test defn {
init();
defer deinit();
try defn(struct {
fn add(a: i32, b: i32) i32 { return a + b; }
}.add, .{
.name = "add",
.documentation = "(add a b)\n\nReturn a + b.",
.source = @src(),
});
try expectEqual(try eval(i32, "(add 3 7)", @src().fn_name), 10);
try defn(struct {
fn raise() !void { return error.ThisIsFine; }
}.raise, .{
.name = "raise",
.documentation = "(raise)\n\nRaise an error.",
.source = @src(),
});
try expectError(error.JanetError, eval(void, "(raise)", @src().fn_name));
}
|