robin/maivi

a tiny cute lua web framework

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

robinlua: avoid early return in init when no plugin dir is found03ca8ad

main
7.5 KiB275 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    fern.info().ctx("lua.setup").msg("loading plugins").log();
166    // load plugins
167    blk: {
168        const dir = try Io.Dir.openDirAbsolute(io, maivi.config.root, .{});
169        defer dir.close(io);
170        const plugindir = dir.openDir(io, "plugins", .{ .iterate = true }) catch |err| switch (err) {
171            error.FileNotFound => break :blk,
172            else => return err,
173        };
174        defer plugindir.close(io);
175        var it = plugindir.iterate();
176        while (try it.next(io)) |entry| {
177            if (entry.kind != .file) continue;
178            if (!std.mem.endsWith(u8, entry.name, ".lua")) continue;
179            const contents = try helpers.read_file(io, maivi.allocator, plugindir, entry.name);
180            defer maivi.allocator.free(contents);
181            const filename = try maivi.allocator.dupeZ(u8, entry.name);
182            defer maivi.allocator.free(filename);
183            try lua.loadBuffer(contents, filename);
184            try pcall(lua, .{});
185        }
186    }
187
188    fern.info().ctx("lua.setup").msg("running lua init module").log();
189    try do_require(lua, "init");
190    lua.pop(1);
191}
192
193pub fn toRef(l: *Lua, i: ?i32) i32 {
194    if (i) |idx|
195        l.pushValue(idx);
196    return l.ref(zlua.registry_index);
197}
198
199pub fn setMethodTable(l: *Lua, comptime T: type) !void {
200    const type_info = @typeInfo(T);
201    comptime {
202        if (type_info != .@"struct") @compileError("non-struct type passed as method table");
203        const fields = type_info.@"struct".fields;
204        if (fields.len > 0) @compileError("method table cannot contain fields");
205    }
206
207    l.createTable(0, 1);
208
209    {
210        const decls = type_info.@"struct".decls;
211        l.createTable(0, decls.len);
212        inline for (decls) |field| {
213            try l.pushAny(field.name);
214            l.pushFunction(zlua.wrap(@field(T, field.name)));
215            l.setTable(-3);
216        }
217        l.setField(-2, "__index");
218    }
219
220    l.setMetatable(-2);
221}
222
223pub fn pushCtx(l: *Lua, comptime T: type, ctx: *T) !void {
224    {
225        const stack_size_on_entry = l.getTop();
226
227        // ctx
228
229        const useref = @hasField(T, "ref") and @FieldType(T, "ref") == ?i32;
230
231        if (useref and ctx.ref != null) {
232            fern.debug().msg("reusing ctx ref").str("name", @typeName(T)).log();
233            _ = l.getIndexRaw(zlua.registry_index, ctx.ref.?);
234        } else try l.pushAny(ctx.*);
235
236        if (useref and ctx.ref == null) {
237            ctx.ref = maivi.lua.toRef(l, -1);
238        }
239
240        if (l.getTop() != stack_size_on_entry + 1) return error.UnexpectedStackSize;
241    }
242
243    l.pushLightUserdata(@ptrCast(ctx));
244    l.setField(-2, "ptr");
245}
246
247pub const Event = enum {
248    handle,
249    read_data,
250
251    pub fn str(self: @This()) []const u8 {
252        return switch (self) {
253            else => @tagName(self),
254        };
255    }
256};
257
258pub fn trigger(l: *Lua, comptime T: type, ctx: *T, event: Event, props: anytype) !void {
259    // trigger
260
261    _ = l.getGlobal("maivi");
262    defer l.pop(1);
263    _ = l.getField(-1, "trigger");
264    // -1 => f, -2 => maivi
265    errdefer l.pop(2);
266
267    try pushCtx(l, T, ctx);
268    // -1 => ctx, -2 => f, -3 => maivi
269
270    const hook_str = event.str();
271    _ = l.pushString(hook_str);
272    try l.pushAny(props);
273
274    try pcall(l, .{ .args = 3 });
275}