DzLox

:)
git clone https://git.sr.ht/~ashymad/DzLox
Log | Files | Refs | Submodules | LICENSE

obj::native.zig (1647B)


      1 const std = @import("std");
      2 
      3 const utils = @import("lib::utils.zig");
      4 
      5 const Packed = @import("lib::packed.zig").Packed;
      6 const GC = @import("gc.zig").GC;
      7 const Value = @import("value.zig").Value;
      8 const Obj = @import("obj.zig").Obj;
      9 
     10 pub fn Native(fields: anytype) type {
     11     const Super = Obj(fields);
     12 
     13     return packed struct {
     14         const Self = @This();
     15         pub const Error = error{ OutOfMemory, Native };
     16 
     17         pub const Fn = *const fn (*GC, []const Value) Error!Value;
     18 
     19         pub const ArityMin = 0;
     20         pub const ArityMax = std.math.maxInt(u8);
     21 
     22         pub const Arg = struct {
     23             fun: Fn,
     24             arity_min: u8 = ArityMin,
     25             arity_max: u8 = ArityMax,
     26         };
     27 
     28         obj: Super,
     29         fun: Packed(Fn),
     30         arity_min: u8,
     31         arity_max: u8,
     32 
     33         pub fn init(arg: Arg, allocator: std.mem.Allocator) Error!*Self {
     34             const self: *Self = try allocator.create(Self);
     35             self.* = Self{
     36                 .obj = Super.make(Self),
     37                 .fun = Packed(Fn).init(arg.fun),
     38                 .arity_min = arg.arity_min,
     39                 .arity_max = arg.arity_max,
     40             };
     41             return self;
     42         }
     43 
     44         pub fn call(self: *const Self, gc: *GC, argCount: u8, args: [*]Value) Error!Value {
     45             const callable = self.fun.ptr();
     46             return callable(gc, args[0..argCount]);
     47         }
     48 
     49         pub fn cast(self: anytype) utils.copy_const(@TypeOf(self), *Super) {
     50             return @ptrCast(self);
     51         }
     52 
     53         pub fn free(self: *const Self, allocator: std.mem.Allocator) void {
     54             allocator.destroy(self);
     55         }
     56     };
     57 }