DzLox

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

obj::function.zig (1629B)


      1 const std = @import("std");
      2 
      3 const utils = @import("lib::utils.zig");
      4 
      5 const Packed = @import("lib::packed.zig").Packed;
      6 const Obj = @import("obj.zig").Obj;
      7 
      8 pub fn Function(fields: anytype) type {
      9     const Super = Obj(fields);
     10 
     11     return packed struct {
     12         const Self = @This();
     13 
     14         pub const Error = error{ OutOfMemory, InvalidArguments };
     15 
     16         pub const Chunk = *Super.Chunk;
     17         pub const Upvalue = ?*Super.Upvalue;
     18 
     19         pub const Arg = struct {
     20             upvalues: u8 = 0,
     21             chunk: Chunk,
     22             arity: u8 = 0,
     23         };
     24 
     25         obj: Super,
     26         arity: u8,
     27         chunk: Packed(*Super.Chunk),
     28         upvalues: Packed([]Upvalue),
     29 
     30         pub fn init(arg: Arg, allocator: std.mem.Allocator) Error!*Self {
     31             const self: *Self = try allocator.create(Self);
     32             self.* = Self{
     33                 .obj = Super.make(Self),
     34                 .chunk = Packed(Chunk).init(arg.chunk),
     35                 .arity = arg.arity,
     36                 .upvalues = try Packed([]Upvalue).create(allocator, arg.upvalues),
     37             };
     38 
     39             for (self.upvalues.ptr()) |*upvalue| upvalue.* = null;
     40             return self;
     41         }
     42 
     43         pub fn cast(self: anytype) utils.copy_const(@TypeOf(self), *Super) {
     44             return @ptrCast(self);
     45         }
     46 
     47         pub fn format(self: *const Self, writer: *std.Io.Writer) !void {
     48             _ = try writer.print("{d}", .{self.upvalues.len()});
     49         }
     50 
     51         pub fn free(self: *const Self, allocator: std.mem.Allocator) void {
     52             self.upvalues.destroy(allocator);
     53             allocator.destroy(self);
     54         }
     55     };
     56 }