robin/maivi

a tiny cute lua web framework

git clone https://git.robinwobin.dev/robin/maivi

robinmaivi: proper io usage6e07b35

push-srxvuswpkqxx
7.3 KiB272 linesraw
1const std = @import("std");
2const Io = std.Io;
3
4const fern = @import("fern");
5const options = @import("options");
6const zlua = @import("zlua");
7pub const Lua = zlua.Lua;
8
9const maivi = @import("../root.zig");
10const helpers = maivi.helpers;
11pub const read_data = @import("./data.zig").read;
12const embed = @import("embed.zig");
13const lua_display = @import("lua_display.zig");
14const lua_md4c = if (options.md4c) @import("lua_md4c.zig");
15const lua_print = @import("lua_print.zig").lua_print;
16const lua_read = @import("lua_read.zig").lua_read;
17const lua_str = @import("lua_str.zig");
18pub const pcall = @import("pcall.zig").pcall;
19
20pub var lua: *Lua = undefined;
21
22pub fn init() !void {
23    fern.trace().ctx("lua.init").log();
24
25    lua = try lua_init();
26}
27
28pub fn thread() *Lua {
29    return lua.newThread();
30}
31
32pub fn lua_init() !*Lua {
33    const l = try Lua.init(maivi.allocator);
34    errdefer l.deinit();
35    l.openBase();
36    l.openOS();
37    l.openDebug();
38    l.openString();
39    l.openTable();
40    l.openMath();
41    l.openBit32();
42
43    // package ================================================================
44
45    l.openPackage();
46
47    _ = l.getGlobal("package");
48
49    {
50        const path = try std.fmt.allocPrint(maivi.allocator, "{s}/?.lua;{s}/?/init.lua", .{ maivi.config.luaroot, maivi.config.luaroot });
51        defer maivi.allocator.free(path);
52        _ = l.pushString(path);
53        l.setField(-2, "path");
54    }
55
56    if (options.runtime) {
57        const path = try std.fmt.allocPrint(maivi.allocator, "{s}/?.lua;{s}/?/init.lua", .{ maivi.config.runtime, maivi.config.runtime });
58        defer maivi.allocator.free(path);
59
60        _ = l.getField(-1, "path");
61        _ = l.pushString(";");
62        _ = l.pushString(path);
63        _ = l.concat(3);
64        l.setField(-2, "path");
65    }
66
67    l.pop(1); // pops "package"
68
69    // global fn ==============================================================
70
71    l.register("print", zlua.wrap(lua_print));
72    l.register("read", zlua.wrap(lua_read));
73
74    // maivi ======================================================================
75
76    if (options.runtime)
77        try do_require(l, "maivi")
78    else
79        try do_buffer(l, embed.maivi_module, "@runtime/maivi.lua");
80    l.setGlobal("maivi");
81
82    _ = l.getGlobal("maivi");
83
84    _ = try lua_str.lua_openstr(l);
85    l.setField(-2, "str");
86
87    _ = try lua_display.lua_opendisplay(l);
88    l.setField(-2, "display");
89
90    try do_buffer(l, embed.inspect_module, "@inspect_lua");
91    l.setField(-2, "inspect");
92
93    _ = try maivi.Router.lua_openrouter(l);
94    l.setField(-2, "router");
95
96    l.pop(1); // pops "maivi"
97
98    // h ==========================================================================
99
100    if (options.runtime)
101        try do_require(l, "h")
102    else
103        try do_buffer(l, embed.h_module, "@runtime/h.lua");
104    l.setGlobal("h");
105
106    // this =======================================================================
107
108    if (options.runtime)
109        try do_require(l, "this")
110    else
111        try do_buffer(l, embed.this_module, "@runtime/this.lua");
112
113    _ = l.pushString(maivi.config.base_url);
114    l.setField(-2, "base_url");
115    _ = l.pushString(maivi.rev orelse "dev");
116    l.setField(-2, "rev");
117    _ = l.pushBoolean(maivi.dev);
118    l.setField(-2, "dev");
119
120    l.setGlobal("this");
121
122    // iter =======================================================================
123
124    if (options.runtime)
125        try do_require(l, "iter")
126    else
127        try do_buffer(l, embed.iter_module, "@runtime/iter.lua");
128    l.setGlobal("Iter");
129
130    // preload ================================================================
131
132    if (options.md4c) {
133        _ = l.getGlobal("package");
134        _ = l.getField(-1, "loaded");
135        defer l.pop(2); // pops loaded, package
136        _ = try lua_md4c.lua_openmd4c(l);
137        l.setField(-2, "md4c");
138    }
139
140    if (l.getTop() != 0) return error.UnexpectedStackSize;
141
142    return l;
143}
144
145pub fn deinit() void {
146    lua.deinit();
147}
148
149/// * Pops from Stack: `0`
150/// * Pushes to Stack: `1`
151fn do_buffer(l: *Lua, buf: [:0]const u8, chunkname: [:0]const u8) !void {
152    try l.loadBuffer(buf, chunkname);
153    try pcall(l, .{ .results = 1 });
154}
155
156/// * Pops from Stack: `0`
157/// * Pushes to Stack: `1`
158fn do_require(l: *Lua, modname: []const u8) !void {
159    _ = l.getGlobal("require");
160    _ = l.pushString(modname);
161    try pcall(l, .{ .args = 1, .results = 1 });
162}
163
164pub fn setup(io: Io) !void {
165    // load plugins
166    const dir = try Io.Dir.openDirAbsolute(io, maivi.config.root, .{});
167    defer dir.close(io);
168    const plugindir = dir.openDir(io, "plugins", .{ .iterate = true }) catch |err| switch (err) {
169        error.FileNotFound => return,
170        else => return err,
171    };
172    defer plugindir.close(io);
173    var it = plugindir.iterate();
174    while (try it.next(io)) |entry| {
175        if (entry.kind != .file) continue;
176        if (!std.mem.endsWith(u8, entry.name, ".lua")) continue;
177        const contents = try helpers.read_file(io, maivi.allocator, plugindir, entry.name);
178        defer maivi.allocator.free(contents);
179        const filename = try maivi.allocator.dupeZ(u8, entry.name);
180        defer maivi.allocator.free(filename);
181        try lua.loadBuffer(contents, filename);
182        try pcall(lua, .{});
183    }
184
185    // explicitly import `init.lua`
186    try do_require(lua, "init");
187    lua.pop(1);
188}
189
190pub fn toRef(l: *Lua, i: ?i32) i32 {
191    if (i) |idx|
192        l.pushValue(idx);
193    return l.ref(zlua.registry_index);
194}
195
196pub fn setMethodTable(l: *Lua, comptime T: type) !void {
197    const type_info = @typeInfo(T);
198    comptime {
199        if (type_info != .@"struct") @compileError("non-struct type passed as method table");
200        const fields = type_info.@"struct".fields;
201        if (fields.len > 0) @compileError("method table cannot contain fields");
202    }
203
204    l.createTable(0, 1);
205
206    {
207        const decls = type_info.@"struct".decls;
208        l.createTable(0, decls.len);
209        inline for (decls) |field| {
210            try l.pushAny(field.name);
211            l.pushFunction(zlua.wrap(@field(T, field.name)));
212            l.setTable(-3);
213        }
214        l.setField(-2, "__index");
215    }
216
217    l.setMetatable(-2);
218}
219
220pub fn pushCtx(l: *Lua, comptime T: type, ctx: *T) !void {
221    {
222        const stack_size_on_entry = l.getTop();
223
224        // ctx
225
226        const useref = @hasField(T, "ref") and @FieldType(T, "ref") == ?i32;
227
228        if (useref and ctx.ref != null) {
229            fern.debug().msg("reusing ctx ref").str("name", @typeName(T)).log();
230            _ = l.getIndexRaw(zlua.registry_index, ctx.ref.?);
231        } else try l.pushAny(ctx.*);
232
233        if (useref and ctx.ref == null) {
234            ctx.ref = maivi.lua.toRef(l, -1);
235        }
236
237        if (l.getTop() != stack_size_on_entry + 1) return error.UnexpectedStackSize;
238    }
239
240    l.pushLightUserdata(@ptrCast(ctx));
241    l.setField(-2, "ptr");
242}
243
244pub const Event = enum {
245    handle,
246    read_data,
247
248    pub fn str(self: @This()) []const u8 {
249        return switch (self) {
250            else => @tagName(self),
251        };
252    }
253};
254
255pub fn trigger(l: *Lua, comptime T: type, ctx: *T, event: Event, props: anytype) !void {
256    // trigger
257
258    _ = l.getGlobal("maivi");
259    defer l.pop(1);
260    _ = l.getField(-1, "trigger");
261    // -1 => f, -2 => maivi
262    errdefer l.pop(2);
263
264    try pushCtx(l, T, ctx);
265    // -1 => ctx, -2 => f, -3 => maivi
266
267    const hook_str = event.str();
268    _ = l.pushString(hook_str);
269    try l.pushAny(props);
270
271    try pcall(l, .{ .args = 3 });
272}