DzLox

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

vm::native.zig (2018B)


      1 const std = @import("std");
      2 
      3 const GC = @import("gc.zig").GC;
      4 const Value = @import("value.zig").Value;
      5 
      6 pub const Error = GC.Obj.Native.Error;
      7 
      8 pub const Clock = struct {
      9     var start: std.Io.Timestamp = undefined;
     10 
     11     pub fn set_start(io: std.Io) void {
     12         start = std.Io.Timestamp.now(io, std.Io.Clock.awake);
     13     }
     14 
     15     pub fn clock(gc: *GC, _: []const Value) Error!Value {
     16         return Value.init(@as(f64, @floatFromInt(std.Io.Timestamp.untilNow(start, gc.io, std.Io.Clock.awake).toMilliseconds())));
     17     }
     18 };
     19 
     20 pub fn put(_: *GC, args: []const Value) Error!Value {
     21     std.debug.print("{f}", .{args[0]});
     22     return Value.init({});
     23 }
     24 
     25 pub fn table(gc: *GC, args: []const Value) Error!Value {
     26     var tbl = gc.emplace(.Table, null, {}) catch return Error.Native;
     27     if (args.len % 2 != 0) return Error.Native;
     28     var i: usize = 0;
     29     while (i < args.len) : (i += 2) {
     30         _ = tbl.set(args[i], args[i + 1]) catch return Error.Native;
     31     }
     32     return Value.init(tbl.cast());
     33 }
     34 
     35 pub fn list(gc: *GC, args: []const Value) Error!Value {
     36     var lis = gc.emplace(.List, null, {}) catch return Error.Native;
     37     for (args) |arg| {
     38         lis.list.ptr().push(-1, arg) catch return Error.Native;
     39     }
     40     return Value.init(lis.cast());
     41 }
     42 
     43 pub fn typeof(gc: *GC, args: []const Value) Error!Value {
     44     return Value.init(gc.emplace_cast(.String, null, &.{args[0].typeName()}) catch return Error.Native);
     45 }
     46 
     47 pub fn rungc(gc: *GC, _: []const Value) Error!Value {
     48     gc.collect();
     49     return Value.init({});
     50 }
     51 
     52 pub fn len(_: *GC, val: []const Value) Error!Value {
     53     if (val[0].cast_if(Value.obj)) |obj| {
     54         const ret = switch (obj.type) {
     55             .String => (obj.cast(.String) catch unreachable).len,
     56             .Table => (obj.cast(.Table) catch unreachable).table.ptr().count,
     57             .List => (obj.cast(.List) catch unreachable).list.ptr().len(),
     58             else => return Error.Native,
     59         };
     60         return Value.init(@as(f64, @floatFromInt(ret)));
     61     }
     62     return Error.Native;
     63 }