aboutsummaryrefslogtreecommitdiff
path: root/src/z/Env/root.zig
blob: c2ebade93ec9e50a1b572e151d7455534a716148 (plain)
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
const std = @import("std");

const mod = @import("../root.zig");
const js = @import("js.zig");

const Self = @This();

pub const Call = @import("call.zig").Call;
pub const Future = @import("Future.zig");
pub const Value = @import("value.zig").Value;
pub const Object = extern struct {};

pub const window: *Object = @ptrFromInt(1);

calls: std.ArrayList(Call) = .empty,
values: std.ArrayList(Value) = .empty,
pool: std.heap.MemoryPool(Value) = .empty,
results: std.ArrayList(*Value) = .empty,
gpa: std.mem.Allocator,

pub fn init(gpa: std.mem.Allocator) Self {
    return .{ .gpa = gpa };
}

pub fn getProp(self: *Self, object: *Object, key: []const u8) !Future {
    try self.calls.append(self.gpa, .{
        .kind = .get_prop,
        .num_args = 2,
    });
    try self.values.append(self.gpa, .from(object));
    try self.values.append(self.gpa, .from(key));

    return self.registerFuture();
}

pub fn callMethod(
    self: *Self,
    object: *Object,
    key: []const u8,
    args: anytype,
) !Future {
    try self.calls.append(self.gpa, .{
        .kind = .call_method,
        .num_args = 2 + args.len,
    });

    try self.values.append(self.gpa, .from(object));
    try self.values.append(self.gpa, .from(key));

    inline for (args) |arg| {
        try self.values.append(self.gpa, .from(arg));
    }

    return self.registerFuture();
}

fn registerFuture(self: *Self) !Future {
    const result = try self.pool.create(self.gpa);
    result.kind = .uninit;
    try self.results.append(self.gpa, result);
    return .{ .result = result };
}

pub fn flush(self: *Self) void {
    js.process(
        @ptrCast(self.calls.items),
        @ptrCast(self.values.items),
        @ptrCast(self.results.items),
        self.results.items.len,
    );
    self.calls.clearRetainingCapacity();
    self.values.clearRetainingCapacity();
    self.results.clearRetainingCapacity();
}

pub fn deinit(self: *Self) void {
    self.flush();

    self.calls.deinit(self.gpa);
    self.values.deinit(self.gpa);
    self.pool.deinit(self.gpa);
    self.results.deinit(self.gpa);

    self.* = undefined;
}