-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiling.zig
More file actions
44 lines (37 loc) · 1.5 KB
/
Copy pathcompiling.zig
File metadata and controls
44 lines (37 loc) · 1.5 KB
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
//! Compile Luau source to standalone bytecode, then (where supported) JIT it to
//! native code and inspect the disassembly.
const std = @import("std");
const luau = @import("luau");
pub fn main() !void {
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer _ = gpa.deinit();
const alloc = gpa.allocator();
var vm = try luau.Lua.init(alloc);
defer vm.deinit();
vm.openLibs();
// 1) compile to owned bytecode (e.g. to cache or ship precompiled)
const bc = try luau.compile(alloc, "local function f(a, b) return a + b end\nreturn f(20, 22)", .{
.optimization_level = 2,
});
defer alloc.free(bc);
std.debug.print("bytecode: {d} bytes\n", .{bc.len});
try vm.loadBytecode("=chunk", bc, 0);
// 2) native codegen, if the platform supports it
if (luau.codegen.supported()) {
luau.codegen.create(vm);
var stats: luau.codegen.Stats = undefined;
_ = luau.codegen.compileWithStats(vm, -1, 0, &stats);
std.debug.print("jit: {d} functions, {d} bytes of native code\n", .{
stats.functions_compiled, stats.native_code_size,
});
if (luau.codegen.getAssembly(alloc, vm, -1, true, false)) |text| {
defer alloc.free(text);
std.debug.print("disassembly: {d} chars\n", .{text.len});
} else |_| {}
} else {
std.debug.print("native codegen not supported here\n", .{});
}
// 3) run it
try vm.pcall(0, 1, 0);
std.debug.print("result = {d}\n", .{vm.toNumber(-1).?});
}