From 0ba2c5ffcc5ca89a6565572de34bc1c0cf2492b9 Mon Sep 17 00:00:00 2001 From: Luna Date: Tue, 2 Jun 2020 21:42:26 -0300 Subject: [PATCH 01/43] add basics of searching for lilv --- build.zig | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/build.zig b/build.zig index 622961e..da24ddb 100644 --- a/build.zig +++ b/build.zig @@ -1,5 +1,6 @@ -const builds = @import("std").build; -const Builder = @import("std").build.Builder; +const std = @import("std"); +const builds = std.build; +const Builder = std.build.Builder; fn setupLinks(step: *builds.LibExeObjStep) void { step.linkSystemLibrary("c"); @@ -11,8 +12,26 @@ fn setupLinks(step: *builds.LibExeObjStep) void { step.linkSystemLibrary("GraphicsMagickWand"); step.linkSystemLibrary("GraphicsMagick"); - step.addIncludeDir("/usr/include/lilv-0"); step.addIncludeDir("/usr/include/GraphicsMagick"); + + const possible_lilv_include_dirs = [_][]const u8{ + "/usr/include/lilv-0", + "/usr/include/lilv-0/lilv", + }; + var found_any_lilv = false; + + for (possible_lilv_include_dirs) |possible_lilv_dir| { + var possible_dir = std.fs.cwd().openDir(possible_lilv_dir) catch |err| { + continue; + }; + possible_dir.close(); + found_any_lilv = true; + } + + if (!found_any_lilv) { + std.debug.warn("No LILV library was found :(\n"); + @panic("no lilv found"); + } } pub fn build(b: *Builder) void { From c80a6d0df70c8ef27637cf38be1f5645ab23eaee Mon Sep 17 00:00:00 2001 From: Luna Date: Tue, 2 Jun 2020 21:54:39 -0300 Subject: [PATCH 02/43] fix typos and actually add dirs to step --- build.zig | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/build.zig b/build.zig index da24ddb..8b3484b 100644 --- a/build.zig +++ b/build.zig @@ -13,23 +13,29 @@ fn setupLinks(step: *builds.LibExeObjStep) void { step.linkSystemLibrary("GraphicsMagick"); step.addIncludeDir("/usr/include/GraphicsMagick"); + step.addIncludeDir("/usr/include"); const possible_lilv_include_dirs = [_][]const u8{ - "/usr/include/lilv-0", "/usr/include/lilv-0/lilv", + "/usr/include/lilv-0", }; var found_any_lilv = false; for (possible_lilv_include_dirs) |possible_lilv_dir| { - var possible_dir = std.fs.cwd().openDir(possible_lilv_dir) catch |err| { + var possible_dir = std.fs.cwd().openDir(possible_lilv_dir, .{}) catch |err| { + std.debug.warn("possible lilv {} fail: {}\n", .{ possible_lilv_dir, err }); continue; }; + possible_dir.close(); found_any_lilv = true; + + std.debug.warn("found lilv at '{}'\n", .{possible_lilv_dir}); + step.addIncludeDir(possible_lilv_dir); } if (!found_any_lilv) { - std.debug.warn("No LILV library was found :(\n"); + std.debug.warn("No LILV library was found :(\n", .{}); @panic("no lilv found"); } } From 8d312cd987abd076b40bda6b5c92068aa21985a0 Mon Sep 17 00:00:00 2001 From: Luna Date: Tue, 2 Jun 2020 22:24:43 -0300 Subject: [PATCH 03/43] use lv2.h provided at root of /usr/include fixes ubuntu issues --- .gitignore | 1 + build.zig | 1 + src/lv2_helpers.zig | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index b43912f..44f7213 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ zig-cache/ *.mp3 *.wav +build_runner.zig diff --git a/build.zig b/build.zig index 8b3484b..6858c80 100644 --- a/build.zig +++ b/build.zig @@ -19,6 +19,7 @@ fn setupLinks(step: *builds.LibExeObjStep) void { "/usr/include/lilv-0/lilv", "/usr/include/lilv-0", }; + var found_any_lilv = false; for (possible_lilv_include_dirs) |possible_lilv_dir| { diff --git a/src/lv2_helpers.zig b/src/lv2_helpers.zig index abc9c8f..a72e07d 100644 --- a/src/lv2_helpers.zig +++ b/src/lv2_helpers.zig @@ -4,7 +4,7 @@ const plugin = @import("plugin.zig"); pub const c = @cImport({ @cInclude("sndfile.h"); @cInclude("lilv/lilv.h"); - @cInclude("lv2/core/lv2.h"); + @cInclude("lv2.h"); }); pub fn Lv2Core(comptime ns: []const u8) []const u8 { From fa7e993ec21010dc778a91bd1257d94361c0e5fa Mon Sep 17 00:00:00 2001 From: Luna Date: Thu, 23 Jul 2020 16:31:32 -0300 Subject: [PATCH 04/43] zig fmt pass --- src/custom.zig | 8 ++++---- src/image.zig | 2 +- src/lang.zig | 2 +- src/main.zig | 2 +- src/printer.zig | 6 +++--- src/runner.zig | 4 ++-- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/custom.zig b/src/custom.zig index 0420bd3..e1a9107 100644 --- a/src/custom.zig +++ b/src/custom.zig @@ -16,7 +16,7 @@ pub const RandomNoise = struct { pub fn init( allocator: *std.mem.Allocator, - params: var, + params: anytype, ) ?RandomNoise { var r = std.rand.DefaultPrng.init(params.seed); @@ -64,7 +64,7 @@ pub const WildNoise = struct { pub fn init( allocator: *std.mem.Allocator, - params: var, + params: anytype, ) ?WildNoise { var r = std.rand.DefaultPrng.init(params.seed); @@ -112,7 +112,7 @@ pub const Write = struct { pub fn init( allocator: *std.mem.Allocator, - params: var, + params: anytype, ) Write { return Write{ .data = params.data, @@ -133,7 +133,7 @@ pub const Embed = struct { sndfile: *c.SNDFILE = undefined, buf: []f32 = undefined, - pub fn init(allocator: *std.mem.Allocator, params: var) @This() { + pub fn init(allocator: *std.mem.Allocator, params: anytype) @This() { return Embed{ .allocator = allocator, .filepath = params.path, diff --git a/src/image.zig b/src/image.zig index e0fea67..0501e70 100644 --- a/src/image.zig +++ b/src/image.zig @@ -425,7 +425,7 @@ pub const Image = struct { self: *Image, comptime Plugin: type, position: plugins.Position, - extra: var, + extra: anytype, ) !void { var plugin_opt: ?Plugin = Plugin.init(self.allocator, extra); if (plugin_opt == null) { diff --git a/src/lang.zig b/src/lang.zig index 305eb4a..134307b 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -497,7 +497,7 @@ pub const Lang = struct { self.has_error = false; self.line = 0; } - fn doError(self: *Lang, comptime fmt: []const u8, args: var) void { + fn doError(self: *Lang, comptime fmt: []const u8, args: anytype) void { std.debug.warn("ERROR! at line {}: ", .{self.line}); std.debug.warn(fmt, args); std.debug.warn("\n", .{}); diff --git a/src/main.zig b/src/main.zig index be1b672..a53c1fb 100644 --- a/src/main.zig +++ b/src/main.zig @@ -36,7 +36,7 @@ fn copyCommandToHeap(allocator: *std.mem.Allocator, command: langs.Command, comp return &heap_cmd.base; } -pub fn doRepl(allocator: *std.mem.Allocator, args_it: var) !void { +pub fn doRepl(allocator: *std.mem.Allocator, args_it: anytype) !void { var stdout_file = std.io.getStdOut(); const stdout = &stdout_file.outStream(); const scri_path = try (args_it.next(allocator) orelse @panic("expected scri path")); diff --git a/src/printer.zig b/src/printer.zig index bf32f76..d0b8f2f 100644 --- a/src/printer.zig +++ b/src/printer.zig @@ -1,7 +1,7 @@ const std = @import("std"); const langs = @import("lang.zig"); -fn printCommandWithParams(stream: var, command: var) !void { +fn printCommandWithParams(stream: anytype, command: anytype) !void { const Parameters = @TypeOf(command.parameters); try stream.print(" {} {}", .{ command.split, command.index }); inline for (@typeInfo(Parameters).Struct.fields) |field| { @@ -13,7 +13,7 @@ fn printCommandWithParams(stream: var, command: var) !void { } } -fn printCommand(stream: var, cmd: *langs.Command, comptime tag: langs.Command.Tag) !void { +fn printCommand(stream: anytype, cmd: *langs.Command, comptime tag: langs.Command.Tag) !void { const CommandStruct = langs.Command.tagToType(tag); const casted = cmd.cast(CommandStruct).?; @@ -31,7 +31,7 @@ fn printCommand(stream: var, cmd: *langs.Command, comptime tag: langs.Command.Ta } } -pub fn printList(list: langs.CommandList, stream: var) !void { +pub fn printList(list: langs.CommandList, stream: anytype) !void { for (list.items) |cmd| { const command = @tagName(cmd.tag); try stream.print("{}", .{command}); diff --git a/src/runner.zig b/src/runner.zig index a089a67..acffe2a 100644 --- a/src/runner.zig +++ b/src/runner.zig @@ -209,7 +209,7 @@ pub const Runner = struct { try magick.runRotate(image, rotate_cmd.deg, c_bgfill); } - fn executeLV2Command(self: *@This(), command: var) !void { + fn executeLV2Command(self: *@This(), command: anytype) !void { const pos = plugin.Position{ .split = command.split, .index = command.index, @@ -231,7 +231,7 @@ pub const Runner = struct { try image.runPlugin(typ.lv2_url, pos, params); } - fn executeCustomCommand(self: *@This(), command: var) !void { + fn executeCustomCommand(self: *@This(), command: anytype) !void { const pos = plugin.Position{ .split = command.split, .index = command.index, From 8aa65958d046012c0ceab023e3943c8f94acb380 Mon Sep 17 00:00:00 2001 From: Luna Date: Thu, 23 Jul 2020 16:32:33 -0300 Subject: [PATCH 05/43] cast ptr --- src/plugin.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugin.zig b/src/plugin.zig index b979833..4a5725c 100644 --- a/src/plugin.zig +++ b/src/plugin.zig @@ -142,7 +142,7 @@ pub fn makeContext(allocator: *std.mem.Allocator, plugin_uri: []const u8) !Conte }; defer c.lilv_node_free(uri); - const plugins: *const c.LilvPlugins = c.lilv_world_get_all_plugins(world); + const plugins: *const c.LilvPlugins = c.lilv_world_get_all_plugins(world).?; var plugin: *const c.LilvPlugin = c.lilv_plugins_get_by_uri(plugins, uri) orelse blk: { std.debug.warn("Plugin <{}> not found\n", .{plugin_uri}); From 353d8d69472329666c5df472091da9713231f1db Mon Sep 17 00:00:00 2001 From: Luna Date: Tue, 18 Aug 2020 17:49:23 -0300 Subject: [PATCH 06/43] fix for latest zig --- src/image.zig | 4 ++-- src/lang.zig | 2 -- src/lv2_helpers.zig | 22 +++++++++++----------- src/plugin.zig | 8 ++++---- src/printer.zig | 1 - src/runner.zig | 1 - 6 files changed, 17 insertions(+), 21 deletions(-) diff --git a/src/image.zig b/src/image.zig index 0501e70..2d40b97 100644 --- a/src/image.zig +++ b/src/image.zig @@ -97,7 +97,7 @@ pub fn temporaryName(allocator: *std.mem.Allocator) ![]u8 { var tmp_file: std.fs.File = std.fs.cwd().openFile( nam, .{ .read = true, .write = false }, - ) catch |err| blk: { + ) catch |err| { if (err == error.FileNotFound) return nam else continue; }; @@ -321,7 +321,7 @@ pub const Image = struct { defer self.allocator.free(sym_cstr); var sym = c.lilv_new_string(ctx.world, sym_cstr.ptr); - const port = c.lilv_plugin_get_port_by_symbol(ctx.plugin, sym) orelse blk: { + const port = c.lilv_plugin_get_port_by_symbol(ctx.plugin, sym) orelse { std.debug.warn("assert fail: symbol {} not found on port\n", .{param.sym}); return ImageError.InvalidSymbol; }; diff --git a/src/lang.zig b/src/lang.zig index 134307b..3d33909 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -135,8 +135,6 @@ pub const Command = struct { .embed => Embed, .rotate => Rotate, - - else => @panic("TODO"), }; } diff --git a/src/lv2_helpers.zig b/src/lv2_helpers.zig index a72e07d..1612974 100644 --- a/src/lv2_helpers.zig +++ b/src/lv2_helpers.zig @@ -81,20 +81,20 @@ pub fn setupPorts(ctx: *plugin.Context) ![]Port { defer ctx.allocator.free(values); c.lilv_plugin_get_port_ranges_float(ctx.plugin, null, null, values.ptr); - var lv2_InputPort = c.lilv_new_uri(world, LV2_CORE__InputPort.ptr); - defer std.heap.c_allocator.destroy(lv2_InputPort); + var lv2_InputPort = c.lilv_new_uri(world, LV2_CORE__InputPort.ptr).?; + //defer std.heap.c_allocator.destroy(lv2_InputPort); - var lv2_OutputPort = c.lilv_new_uri(world, LV2_CORE__OutputPort.ptr); - defer std.heap.c_allocator.destroy(lv2_OutputPort); + var lv2_OutputPort = c.lilv_new_uri(world, LV2_CORE__OutputPort.ptr).?; + //defer std.heap.c_allocator.destroy(lv2_OutputPort); - var lv2_AudioPort = c.lilv_new_uri(world, LV2_CORE__AudioPort.ptr); - defer std.heap.c_allocator.destroy(lv2_AudioPort); + var lv2_AudioPort = c.lilv_new_uri(world, LV2_CORE__AudioPort.ptr).?; + //defer std.heap.c_allocator.destroy(lv2_AudioPort); - var lv2_ControlPort = c.lilv_new_uri(world, LV2_CORE__ControlPort.ptr); - defer std.heap.c_allocator.destroy(lv2_ControlPort); + var lv2_ControlPort = c.lilv_new_uri(world, LV2_CORE__ControlPort.ptr).?; + //defer std.heap.c_allocator.destroy(lv2_ControlPort); - var lv2_connectionOptional = c.lilv_new_uri(world, LV2_CORE__connectionOptional.ptr); - defer std.heap.c_allocator.destroy(lv2_connectionOptional); + var lv2_connection_string = c.lilv_new_uri(world, LV2_CORE__connectionOptional.ptr).?; + //defer std.heap.c_allocator.destroy(lv2_connection_string); var i: u32 = 0; while (i < n_ports) : (i += 1) { @@ -111,7 +111,7 @@ pub fn setupPorts(ctx: *plugin.Context) ![]Port { port.value = values[i]; } - port.optional = c.lilv_port_has_property(ctx.plugin, lport, lv2_connectionOptional); + port.optional = c.lilv_port_has_property(ctx.plugin, lport, lv2_connection_string); if (c.lilv_port_is_a(ctx.plugin, lport, lv2_InputPort)) { port.is_input = true; diff --git a/src/plugin.zig b/src/plugin.zig index 4a5725c..78e8a6d 100644 --- a/src/plugin.zig +++ b/src/plugin.zig @@ -104,7 +104,7 @@ pub const RunContext = struct { switch (port.ptype) { .Control => lv2.lilv_instance_connect_port(self.instance, p, &port.value), - .Audio => blk: { + .Audio => { if (port.is_input) { lv2.lilv_instance_connect_port( self.instance, @@ -121,7 +121,7 @@ pub const RunContext = struct { o += 1; } }, - else => lv2.lilv_instance_connect_port(self.instance, p, null), + // else => lv2.lilv_instance_connect_port(self.instance, p, null), } } } @@ -136,7 +136,7 @@ pub fn makeContext(allocator: *std.mem.Allocator, plugin_uri: []const u8) !Conte c.lilv_world_load_all(world); - var uri: *c.LilvNode = c.lilv_new_uri(world, cstr_plugin_uri.ptr) orelse blk: { + var uri: *c.LilvNode = c.lilv_new_uri(world, cstr_plugin_uri.ptr) orelse { std.debug.warn("Invalid plugin URI <{}>\n", .{plugin_uri}); return ImageError.InvalidPlugin; }; @@ -144,7 +144,7 @@ pub fn makeContext(allocator: *std.mem.Allocator, plugin_uri: []const u8) !Conte const plugins: *const c.LilvPlugins = c.lilv_world_get_all_plugins(world).?; - var plugin: *const c.LilvPlugin = c.lilv_plugins_get_by_uri(plugins, uri) orelse blk: { + var plugin: *const c.LilvPlugin = c.lilv_plugins_get_by_uri(plugins, uri) orelse { std.debug.warn("Plugin <{}> not found\n", .{plugin_uri}); return ImageError.UnknownPlugin; }; diff --git a/src/printer.zig b/src/printer.zig index d0b8f2f..69cc4b5 100644 --- a/src/printer.zig +++ b/src/printer.zig @@ -27,7 +27,6 @@ fn printCommand(stream: anytype, cmd: *langs.Command, comptime tag: langs.Comman switch (ctype) { .lv2_command => try printCommandWithParams(stream, casted), .custom_command => try printCommandWithParams(stream, casted), - else => @panic("TODO support command type"), } } diff --git a/src/runner.zig b/src/runner.zig index acffe2a..36c4687 100644 --- a/src/runner.zig +++ b/src/runner.zig @@ -252,7 +252,6 @@ pub const Runner = struct { switch (ctype) { .lv2_command => try self.executeLV2Command(command.*), .custom_command => try self.executeCustomCommand(command.*), - else => @panic("TODO support command type"), } } From 4adf80e51a8ebae30c8cb6f403b68741ca1e5cbb Mon Sep 17 00:00:00 2001 From: Luna Date: Tue, 18 Aug 2020 17:58:04 -0300 Subject: [PATCH 07/43] fix some memory leaks --- src/runner.zig | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/runner.zig b/src/runner.zig index 36c4687..a9ea3e3 100644 --- a/src/runner.zig +++ b/src/runner.zig @@ -40,6 +40,8 @@ pub const Runner = struct { if (self.image) |image| { image.close(); } + + std.process.argsFree(self.allocator, self.args); } pub fn clone(self: *Runner) !Runner { @@ -117,6 +119,7 @@ pub const Runner = struct { } } + /// Caller owns returned memory. fn makeGlitchedPath(self: *Runner) ![]const u8 { // we want to transform basename, if it is "x.bmp" to "x_gN.bmp", where // N is the maximum non-used integer. @@ -180,6 +183,7 @@ pub const Runner = struct { fn quicksaveCmd(self: *Runner) !void { var image = try self.getImage(); const out_path = try self.makeGlitchedPath(); + defer self.allocator.free(out_path); try image.saveTo(out_path); } @@ -187,6 +191,7 @@ pub const Runner = struct { const runqs = cmd.cast(lang.Command.RunQS).?; var image = try self.getImage(); const out_path = try self.makeGlitchedPath(); + defer self.allocator.free(out_path); try image.saveTo(out_path); var proc = try std.ChildProcess.init( From f61e9b013f2b881de15cdae6bf19aa08efc5eef4 Mon Sep 17 00:00:00 2001 From: Luna Date: Tue, 18 Aug 2020 20:40:06 -0300 Subject: [PATCH 08/43] make CommandList free its command pointers --- src/lang.zig | 24 +++++++++++++++++++++++- src/main.zig | 7 +++---- src/printer.zig | 2 +- src/runner.zig | 2 +- 4 files changed, 28 insertions(+), 7 deletions(-) diff --git a/src/lang.zig b/src/lang.zig index 3d33909..80450f3 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -474,7 +474,29 @@ pub const Command = struct { }); }; -pub const CommandList = std.ArrayList(*Command); +const CmdArrayList = std.ArrayList(*Command); + +pub const CommandList = struct { + list: CmdArrayList, + const Self = @This(); + + pub fn init(allocator: *std.mem.Allocator) Self { + return .{ + .list = CmdArrayList.init(allocator), + }; + } + + pub fn deinit(self: *Self) void { + for (self.list.items) |cmd_ptr| { + self.list.allocator.destroy(cmd_ptr); + } + self.list.deinit(); + } + + pub fn append(self: *Self, cmd: *Command) !void { + return try self.list.append(cmd); + } +}; /// A parser. pub const Lang = struct { diff --git a/src/main.zig b/src/main.zig index a53c1fb..119009e 100644 --- a/src/main.zig +++ b/src/main.zig @@ -65,7 +65,7 @@ pub fn doRepl(allocator: *std.mem.Allocator, args_it: anytype) !void { defer existing_cmds.deinit(); // copy the existing command list into the repl's command list - for (existing_cmds.items) |existing_cmd| { + for (existing_cmds.list.items) |existing_cmd| { try cmds.append(existing_cmd); } } else { @@ -210,9 +210,8 @@ pub fn doRepl(allocator: *std.mem.Allocator, args_it: anytype) !void { }; // no command? ignore! - if (cmds_parsed.items.len == 0) continue; - - current = cmds_parsed.items[0].*; + if (cmds_parsed.list.items.len == 0) continue; + current = cmds_parsed.list.items[0].*; // by cloning the parent runner, we can iteratively write // whatever command we want and only commit the good results diff --git a/src/printer.zig b/src/printer.zig index 69cc4b5..5ea5a7b 100644 --- a/src/printer.zig +++ b/src/printer.zig @@ -31,7 +31,7 @@ fn printCommand(stream: anytype, cmd: *langs.Command, comptime tag: langs.Comman } pub fn printList(list: langs.CommandList, stream: anytype) !void { - for (list.items) |cmd| { + for (list.list.items) |cmd| { const command = @tagName(cmd.tag); try stream.print("{}", .{command}); diff --git a/src/runner.zig b/src/runner.zig index a9ea3e3..37fade3 100644 --- a/src/runner.zig +++ b/src/runner.zig @@ -312,7 +312,7 @@ pub const Runner = struct { cmds: lang.CommandList, debug_flag: bool, ) !void { - for (cmds.items) |cmd| { + for (cmds.list.items) |cmd| { cmd.print(); try self.runCommand(cmd.*); } From 708ef45600b244fb8836000249848c3a561b1efb Mon Sep 17 00:00:00 2001 From: Luna Date: Tue, 18 Aug 2020 20:41:57 -0300 Subject: [PATCH 09/43] fix use-after-free on repl --- src/main.zig | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main.zig b/src/main.zig index 119009e..15e1524 100644 --- a/src/main.zig +++ b/src/main.zig @@ -60,9 +60,11 @@ pub fn doRepl(allocator: *std.mem.Allocator, args_it: anytype) !void { var scri_existing = try allocator.alloc(u8, total_bytes); _ = try file_read_opt.?.read(scri_existing); - // we can defer this because we copy the Command structs back to cmds + // we can't defer this directly because we copy the + // Command pointers to the cmds list. running deinit() directly + // would cause those pointers to be freed. var existing_cmds = try lang.parse(scri_existing); - defer existing_cmds.deinit(); + defer existing_cmds.list.deinit(); // copy the existing command list into the repl's command list for (existing_cmds.list.items) |existing_cmd| { From 0cd47be7ac9a398f3c9e4d44fb33132867644c2e Mon Sep 17 00:00:00 2001 From: Luna Date: Tue, 18 Aug 2020 20:53:54 -0300 Subject: [PATCH 10/43] remove need to dupe strings to command structs --- src/lang.zig | 7 +++---- src/main.zig | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/lang.zig b/src/lang.zig index 80450f3..c80af14 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -157,7 +157,7 @@ pub const Command = struct { pub const Load = struct { pub const base_tag = Tag.load; base: Command, - path: []u8, + path: []const u8, }; pub const Quicksave = struct { @@ -568,7 +568,7 @@ pub const Lang = struct { f32 => try std.fmt.parseFloat(f32, arg), u64 => try std.fmt.parseInt(u64, arg, 10), usize => try std.fmt.parseInt(usize, arg, 10), - []const u8 => try self.allocator.dupe(u8, arg), + []const u8 => arg, else => @compileError("parameter struct has unsupported type " ++ @typeName(cmd_field.field_type)), }; @@ -586,8 +586,7 @@ pub const Lang = struct { usize => try std.fmt.parseInt(usize, arg, 10), i32 => try std.fmt.parseInt(i32, arg, 10), f32 => try std.fmt.parseFloat(f32, arg), - []u8 => try self.allocator.dupe(u8, arg), - []const u8 => try self.allocator.dupe(u8, arg), + []const u8 => arg, else => @compileError("Invalid parameter type (" ++ @typeName(cmd_field.field_type) ++ ") left on command struct " ++ @typeName(command_struct) ++ "."), }; diff --git a/src/main.zig b/src/main.zig index 15e1524..4fd6525 100644 --- a/src/main.zig +++ b/src/main.zig @@ -77,7 +77,7 @@ pub fn doRepl(allocator: *std.mem.Allocator, args_it: anytype) !void { // TODO: deliberate memleak here. we only allocate this // command once, for the start of the file, so. var load_cmd = try allocator.create(langs.Command.Load); - std.mem.copy(u8, load_cmd.path, ":0"); + load_cmd.path = ":0"; load_cmd.base.tag = langs.Command.Tag.load; // taking address is fine, because load_cmd lives in the lifetime From 9527426d484d680f4db373c72f98fe1e2c35ef7d Mon Sep 17 00:00:00 2001 From: Luna Date: Tue, 18 Aug 2020 20:54:04 -0300 Subject: [PATCH 11/43] remove memleak when getting args --- src/main.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.zig b/src/main.zig index 4fd6525..962684b 100644 --- a/src/main.zig +++ b/src/main.zig @@ -242,9 +242,9 @@ pub fn main() !void { var args_it = std.process.args(); // TODO print help - - _ = try (args_it.next(allocator) orelse @panic("expected exe name")); + _ = args_it.skip(); const scri_path = try (args_it.next(allocator) orelse @panic("expected scri path or 'repl'")); + defer allocator.free(scri_path); if (std.mem.eql(u8, scri_path, "repl")) { return try doRepl(allocator, &args_it); From 77cceab2886f2b117b4ee4683323067a12ef9fe5 Mon Sep 17 00:00:00 2001 From: Luna Date: Tue, 18 Aug 2020 20:57:33 -0300 Subject: [PATCH 12/43] make Image free its paths --- src/image.zig | 5 +++-- src/runner.zig | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/image.zig b/src/image.zig index 2d40b97..51c1eef 100644 --- a/src/image.zig +++ b/src/image.zig @@ -179,8 +179,9 @@ pub const Image = struct { } pub fn close(self: *Image) void { - //self.allocator.free(self.path); - //self.allocator.free(self.curpath); + self.allocator.free(self.path); + self.allocator.free(self.curpath); + var st: i32 = c.sf_close(self.sndfile); if (st != 0) { diff --git a/src/runner.zig b/src/runner.zig index 37fade3..47f2cab 100644 --- a/src/runner.zig +++ b/src/runner.zig @@ -78,6 +78,7 @@ pub const Runner = struct { } } + // Caller owns returned memory. fn resolveArgPath(self: *Runner, path_or_argidx: []const u8) ![]const u8 { const path = try self.resolveArg(path_or_argidx); const resolved_path = try std.fs.path.resolve( @@ -89,7 +90,7 @@ pub const Runner = struct { } fn loadCmd(self: *Runner, path_or_argidx: []const u8) !void { - var load_path = try self.resolveArgPath(path_or_argidx); + const load_path = try self.resolveArgPath(path_or_argidx); std.debug.warn("\tload path: {}\n", .{load_path}); // we could use ImageMagick to convert from X to BMP From c2834f8254616f5bd2a1a5007ea0b240c6fcefac Mon Sep 17 00:00:00 2001 From: Luna Date: Tue, 18 Aug 2020 21:00:07 -0300 Subject: [PATCH 13/43] properly free Image contents --- src/image.zig | 11 +++++++---- src/runner.zig | 1 + 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/image.zig b/src/image.zig index 51c1eef..46acb24 100644 --- a/src/image.zig +++ b/src/image.zig @@ -179,17 +179,20 @@ pub const Image = struct { } pub fn close(self: *Image) void { - self.allocator.free(self.path); - self.allocator.free(self.curpath); - var st: i32 = c.sf_close(self.sndfile); - if (st != 0) { std.debug.warn("Failed to close {} ({})\n", .{ self.path, c.sf_error_number(st), }); } + + self.allocator.free(self.path); + self.allocator.free(self.curpath); + + var allocator = self.allocator; + self.* = undefined; + allocator.destroy(self); } pub fn read(self: *Image, file_chans: c_int, buf: []f32) bool { diff --git a/src/runner.zig b/src/runner.zig index 47f2cab..442068d 100644 --- a/src/runner.zig +++ b/src/runner.zig @@ -108,6 +108,7 @@ pub const Runner = struct { // we don't copy load_path into a temporary file because we're already // loading it under the SFM_READ mode, which won't cause any destructive // operations on the file. + if (self.image) |image| image.close(); self.image = try Image.open(self.allocator, load_path); } From 7097334201a80fd6cd579ef7991dd7d5437a8575 Mon Sep 17 00:00:00 2001 From: Luna Date: Tue, 18 Aug 2020 21:00:16 -0300 Subject: [PATCH 14/43] turn on gpa --- src/main.zig | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main.zig b/src/main.zig index 962684b..8ea264d 100644 --- a/src/main.zig +++ b/src/main.zig @@ -231,7 +231,12 @@ pub fn doRepl(allocator: *std.mem.Allocator, args_it: anytype) !void { } pub fn main() !void { - const allocator = std.heap.page_allocator; + // const allocator = std.heap.page_allocator; + var allocator_instance = std.heap.GeneralPurposeAllocator(.{}){}; + defer { + _ = allocator_instance.deinit(); + } + const allocator = &allocator_instance.allocator; var lang = langs.Lang.init(allocator); defer lang.deinit(); From 5e8093b26fbeb93ad9ff376ca5f78f8fd16c5afc Mon Sep 17 00:00:00 2001 From: Luna Date: Tue, 18 Aug 2020 21:02:43 -0300 Subject: [PATCH 15/43] free lv2 ports slice --- src/image.zig | 1 + src/lv2_helpers.zig | 2 ++ 2 files changed, 3 insertions(+) diff --git a/src/image.zig b/src/image.zig index 46acb24..32a93ec 100644 --- a/src/image.zig +++ b/src/image.zig @@ -307,6 +307,7 @@ pub const Image = struct { defer ctx.deinit(); var ports = try lv2.setupPorts(&ctx); + defer ctx.allocator.free(ports); if (ctx.n_audio_in > 2) { std.debug.warn("plugin <{}> has more than two inputs.\n", .{plugin_uri}); diff --git a/src/lv2_helpers.zig b/src/lv2_helpers.zig index 1612974..fcfa2c9 100644 --- a/src/lv2_helpers.zig +++ b/src/lv2_helpers.zig @@ -59,6 +59,8 @@ pub const Port = struct { /// Setup ports for a given plugin. Gives an array to pointers of Port structs. /// This setup is required so we link the plugin to the ports later on, and /// also link our buffers, and control values. +/// +/// Caller owns returned memory. pub fn setupPorts(ctx: *plugin.Context) ![]Port { var world = ctx.world; const n_ports: u32 = c.lilv_plugin_get_num_ports(ctx.plugin); From ebf716de179eeca1a1f2fceeea2237927426baa6 Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 8 Nov 2020 18:47:40 -0300 Subject: [PATCH 16/43] fix type for Runner.args --- src/runner.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/runner.zig b/src/runner.zig index 442068d..a10b7a5 100644 --- a/src/runner.zig +++ b/src/runner.zig @@ -26,7 +26,7 @@ pub const Runner = struct { /// If the runner is in REPL mode repl: bool, - args: [][]u8, + args: []const [:0]u8, pub fn init(allocator: *std.mem.Allocator, repl: bool) Runner { return Runner{ From 2acb45fdcace0fa50e108e7a8889358eabd6be43 Mon Sep 17 00:00:00 2001 From: Luna Date: Sat, 3 Apr 2021 21:09:30 -0300 Subject: [PATCH 17/43] build.zig: fix for latest zig --- build.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.zig b/build.zig index 6858c80..467240c 100644 --- a/build.zig +++ b/build.zig @@ -24,14 +24,14 @@ fn setupLinks(step: *builds.LibExeObjStep) void { for (possible_lilv_include_dirs) |possible_lilv_dir| { var possible_dir = std.fs.cwd().openDir(possible_lilv_dir, .{}) catch |err| { - std.debug.warn("possible lilv {} fail: {}\n", .{ possible_lilv_dir, err }); + std.debug.warn("possible lilv {s} fail: {s}\n", .{ possible_lilv_dir, err }); continue; }; possible_dir.close(); found_any_lilv = true; - std.debug.warn("found lilv at '{}'\n", .{possible_lilv_dir}); + std.debug.warn("found lilv at '{s}'\n", .{possible_lilv_dir}); step.addIncludeDir(possible_lilv_dir); } From 667e6cbdac71044e5685351f39bea8fd22ee2bfc Mon Sep 17 00:00:00 2001 From: Luna Date: Sat, 3 Apr 2021 21:09:44 -0300 Subject: [PATCH 18/43] zig fmt pass --- src/lang.zig | 20 +++++--------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/src/lang.zig b/src/lang.zig index c80af14..d5c193a 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -199,33 +199,25 @@ pub const Command = struct { pub const Amp = LV2Command( .amp, "http://lv2plug.in/plugins/eg-amp", - struct { - gain: f32 - }, + struct { gain: f32 }, ); pub const RFlanger = LV2Command( .rflanger, "http://plugin.org.uk/swh-plugins/retroFlange", - struct { - delay_depth_avg: f32, law_freq: f32 - }, + struct { delay_depth_avg: f32, law_freq: f32 }, ); pub const Eq = LV2Command( .rflanger, "http://plugin.org.uk/swh-plugins/dj_eq_mono", - struct { - lo: f32, mid: f32, hi: f32 - }, + struct { lo: f32, mid: f32, hi: f32 }, ); pub const Phaser = LV2Command( .phaser, "http://plugin.org.uk/swh-plugins/lfoPhaser", - struct { - lfo_rate: f32, lfo_depth: f32, fb: f32, spread: f32 - }, + struct { lfo_rate: f32, lfo_depth: f32, fb: f32, spread: f32 }, ); pub const Mbeq = LV2Command( @@ -378,9 +370,7 @@ pub const Command = struct { pub const Foverdrive = LV2Command(.foverdrive, "http://plugin.org.uk/swh-plugins/foverdrive", struct { drive: f32, }); - pub const Thruzero = LV2Command(.thruzero, "http://drobilla.net/plugins/mda/ThruZero", struct { - rate: f32, mix: f32, feedback: f32, depth_mod: f32 - }); + pub const Thruzero = LV2Command(.thruzero, "http://drobilla.net/plugins/mda/ThruZero", struct { rate: f32, mix: f32, feedback: f32, depth_mod: f32 }); pub const Gverb = LV2Command(.gverb, "http://plugin.org.uk/swh-plugins/gverb", struct { roomsize: f32, From 9937365433e06adc4571d5edbf0954542fe26041 Mon Sep 17 00:00:00 2001 From: Luna Date: Sat, 3 Apr 2021 22:16:04 -0300 Subject: [PATCH 19/43] update to latest zig --- src/bmp_valid.zig | 2 +- src/custom.zig | 2 +- src/image.zig | 32 ++++++++++++++++---------------- src/lang.zig | 10 +++++----- src/lv2_helpers.zig | 4 ++-- src/magick.zig | 4 ++-- src/main.zig | 4 ++-- src/plugin.zig | 4 ++-- src/printer.zig | 20 ++++++++------------ src/runner.zig | 15 +++++++-------- 10 files changed, 46 insertions(+), 51 deletions(-) diff --git a/src/bmp_valid.zig b/src/bmp_valid.zig index c4f9438..6468658 100644 --- a/src/bmp_valid.zig +++ b/src/bmp_valid.zig @@ -20,7 +20,7 @@ pub fn magicValid(magic: []const u8) !void { } if (!valid) { - std.debug.warn("\tINVALID HEADER: '{}'\n", .{magic}); + std.debug.warn("\tINVALID HEADER: '{s}'\n", .{magic}); return BMPValidError.InvalidMagic; } } diff --git a/src/custom.zig b/src/custom.zig index e1a9107..03120f0 100644 --- a/src/custom.zig +++ b/src/custom.zig @@ -174,7 +174,7 @@ pub const Embed = struct { if (read_bytes < 0) { const st: i32 = c.sf_error(self.sndfile); - std.debug.warn("Failed to read {} ({})\n", .{ + std.debug.warn("Failed to read {s} ({s})\n", .{ self.filepath, c.sf_error_number(st), }); diff --git a/src/image.zig b/src/image.zig index 32a93ec..b6e13ae 100644 --- a/src/image.zig +++ b/src/image.zig @@ -32,7 +32,7 @@ pub fn sopen( const st: i32 = c.sf_error(file); if (st != 0) { - std.debug.warn("Failed to open {} ({})\n", .{ + std.debug.warn("Failed to open {s} ({s})\n", .{ path, c.sf_error_number(st), }); @@ -181,7 +181,7 @@ pub const Image = struct { pub fn close(self: *Image) void { var st: i32 = c.sf_close(self.sndfile); if (st != 0) { - std.debug.warn("Failed to close {} ({})\n", .{ + std.debug.warn("Failed to close {s} ({s})\n", .{ self.path, c.sf_error_number(st), }); @@ -228,7 +228,7 @@ pub const Image = struct { sseek(out_file, start); while (i <= end) : (i += buf.len) { - std.debug.warn("\t\ti={}, buf.len={}, end={}\n", .{ i, buf.len, end }); + std.debug.warn("\t\ti={d}, buf.len={d}, end={d}\n", .{ i, buf.len, end }); sseek(self.sndfile, i); sseek(out_file, i); @@ -254,7 +254,7 @@ pub const Image = struct { fn getSeekPos(self: *Image, position: plugins.Position) plugins.SeekPos { const file_end = self.frames; var seek_pos = position.seekPos(file_end); - std.debug.warn("\tstart {} end {}\n", .{ seek_pos.start, seek_pos.end }); + std.debug.warn("\tstart {d} end {d}\n", .{ seek_pos.start, seek_pos.end }); return seek_pos; } @@ -267,7 +267,7 @@ pub const Image = struct { self.curpath = path; self.frames = @intCast(usize, in_fmt.frames); - std.debug.warn("\timage: reopened on '{}' (frames={}, fmt.frames={})\n", .{ + std.debug.warn("\timage: reopened on '{s}' (frames={d}, fmt.frames={d})\n", .{ self.curpath, self.frames, in_fmt.frames, @@ -310,12 +310,12 @@ pub const Image = struct { defer ctx.allocator.free(ports); if (ctx.n_audio_in > 2) { - std.debug.warn("plugin <{}> has more than two inputs.\n", .{plugin_uri}); + std.debug.warn("plugin <{s}> has more than two inputs.\n", .{plugin_uri}); return ImageError.InvalidPlugin; } if (ctx.n_audio_out > 2) { - std.debug.warn("plugin <{}> has more than two outputs.\n", .{plugin_uri}); + std.debug.warn("plugin <{s}> has more than two outputs.\n", .{plugin_uri}); return ImageError.InvalidPlugin; } @@ -327,14 +327,14 @@ pub const Image = struct { var sym = c.lilv_new_string(ctx.world, sym_cstr.ptr); const port = c.lilv_plugin_get_port_by_symbol(ctx.plugin, sym) orelse { - std.debug.warn("assert fail: symbol {} not found on port\n", .{param.sym}); + std.debug.warn("assert fail: symbol {s} not found on port\n", .{param.sym}); return ImageError.InvalidSymbol; }; c.lilv_node_free(sym); var idx = c.lilv_port_get_index(ctx.plugin, port); - std.debug.warn("\tset sym={}, idx={} to val={}\n", .{ + std.debug.warn("\tset sym={s}, idx={d} to val={}\n", .{ param.sym, idx, param.value, @@ -345,7 +345,7 @@ pub const Image = struct { // now we need to generate a temporary file and put the output of // running the plugin on that file var tmpnam = try temporaryName(self.allocator); - std.debug.warn("\trunning plugin from '{}' to '{}'\n", .{ self.curpath, tmpnam }); + std.debug.warn("\trunning plugin from '{s}' to '{s}'\n", .{ self.curpath, tmpnam }); var out_fmt = mkSfInfo(); var out_file = try sopen(self.allocator, tmpnam, c.SFM_WRITE, &out_fmt); @@ -378,7 +378,7 @@ pub const Image = struct { sseek(self.sndfile, seek_pos.start); var i: usize = seek_pos.start; - std.debug.warn("\tseek pos start: {} end: {}\n", .{ seek_pos.start, seek_pos.end }); + std.debug.warn("\tseek pos start: {d} end: {d}\n", .{ seek_pos.start, seek_pos.end }); var inbuf = &rctx.buffers.in; var outbuf = &rctx.buffers.out; @@ -389,7 +389,7 @@ pub const Image = struct { const read_bytes = c.sf_readf_float(self.sndfile, inbuf, 1); if (read_bytes == 0) { - std.debug.warn("WARN! reached EOF at idx={}\n", .{i}); + std.debug.warn("WARN! reached EOF at idx={d}\n", .{i}); break; } @@ -422,7 +422,7 @@ pub const Image = struct { } pub fn saveTo(self: *Image, out_path: []const u8) !void { - std.debug.warn("\timg: copy from '{}' to '{}'\n", .{ self.curpath, out_path }); + std.debug.warn("\timg: copy from '{s}' to '{s}'\n", .{ self.curpath, out_path }); try std.fs.copyFileAbsolute(self.curpath, out_path, .{}); } @@ -450,7 +450,7 @@ pub const Image = struct { // the code here is a copypaste of runPlugin() without the specific // lilv things. var tmpnam = try temporaryName(self.allocator); - std.debug.warn("\trunning CUSTOM plugin from '{}' to '{}'\n", .{ self.curpath, tmpnam }); + std.debug.warn("\trunning CUSTOM plugin from '{s}' to '{s}'\n", .{ self.curpath, tmpnam }); var out_fmt = mkSfInfo(); var out_file = try sopen(self.allocator, tmpnam, c.SFM_WRITE, &out_fmt); @@ -477,7 +477,7 @@ pub const Image = struct { sseek(self.sndfile, seek_pos.start); var i: usize = seek_pos.start; - std.debug.warn("\tseek pos start: {} end: {}\n", .{ seek_pos.start, seek_pos.end }); + std.debug.warn("\tseek pos start: {d} end: {d}\n", .{ seek_pos.start, seek_pos.end }); var inbuf = &bufs.in; var outbuf = &bufs.out; @@ -485,7 +485,7 @@ pub const Image = struct { while (i <= seek_pos.end) : (i += 1) { const read_bytes = c.sf_readf_float(self.sndfile, inbuf, 1); if (read_bytes == 0) { - std.debug.warn("WARN! reached EOF at idx={}\n", .{i}); + std.debug.warn("WARN! reached EOF at idx={d}\n", .{i}); break; } diff --git a/src/lang.zig b/src/lang.zig index d5c193a..b299ae0 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -146,7 +146,7 @@ pub const Command = struct { } pub fn print(base: *const @This()) void { - std.debug.warn("tag: {}\n", .{base.tag}); + std.debug.warn("tag: {s}\n", .{base.tag}); } pub const Noop = struct { @@ -549,7 +549,7 @@ pub const Lang = struct { inline for (@typeInfo(@TypeOf(cmd.parameters)).Struct.fields) |cmd_field| { const maybe_arg = tok_it.next(); if (maybe_arg == null) { - self.doError("Expected parameter for {}, got nothing", .{cmd_field.name}); + self.doError("Expected parameter for {s}, got nothing", .{cmd_field.name}); return; } @@ -580,7 +580,7 @@ pub const Lang = struct { else => @compileError("Invalid parameter type (" ++ @typeName(cmd_field.field_type) ++ ") left on command struct " ++ @typeName(command_struct) ++ "."), }; - std.debug.warn("parsing {}, arg of type {} => {}\n", .{ + std.debug.warn("parsing {s}, arg of type {s} => {any}\n", .{ @typeName(command_struct), @typeName(@TypeOf(argument_value)), argument_value, @@ -592,7 +592,7 @@ pub const Lang = struct { cmd.base.tag = command_struct.base_tag; const command = cmd.base.cast(command_struct).?; - std.debug.warn("cmd: {}\n", .{command}); + std.debug.warn("cmd: {s}\n", .{command}); try commands.append(&cmd.base); } @@ -653,7 +653,7 @@ pub const Lang = struct { } if (!found) { - self.doError("Unknown command '{}' ({})", .{ command_string, command_string.len }); + self.doError("Unknown command '{s}' ({d} bytes)", .{ command_string, command_string.len }); continue; } } diff --git a/src/lv2_helpers.zig b/src/lv2_helpers.zig index fcfa2c9..599370c 100644 --- a/src/lv2_helpers.zig +++ b/src/lv2_helpers.zig @@ -118,7 +118,7 @@ pub fn setupPorts(ctx: *plugin.Context) ![]Port { if (c.lilv_port_is_a(ctx.plugin, lport, lv2_InputPort)) { port.is_input = true; } else if (!c.lilv_port_is_a(ctx.plugin, lport, lv2_OutputPort) and !port.optional) { - std.debug.warn("Port {} is neither input or output\n", .{i}); + std.debug.warn("Port {d} is neither input or output\n", .{i}); return error.UnassignedIOPort; } @@ -134,7 +134,7 @@ pub fn setupPorts(ctx: *plugin.Context) ![]Port { ctx.n_audio_out += 1; } } else if (!port.optional) { - std.debug.warn("Port {} has unsupported type\n", .{i}); + std.debug.warn("Port {d} has unsupported type\n", .{i}); return error.UnsupportedPortType; } } diff --git a/src/magick.zig b/src/magick.zig index 33ba882..dd5f295 100644 --- a/src/magick.zig +++ b/src/magick.zig @@ -39,7 +39,7 @@ fn magickLoad(image: *Image) !MagickContext { var curpath = try std.cstr.addNullByte(image.allocator, image.curpath); defer image.allocator.free(curpath); - std.debug.warn("loading '{}'\n", .{curpath}); + std.debug.warn("loading '{s}'\n", .{curpath}); if (mc.MagickReadImage(mctx.wand, curpath.ptr) != 1) return error.MagickReadFail; @@ -54,7 +54,7 @@ fn magickSave(image: *Image, wand: *mc.MagickWand) !void { var c_tmpnam = try std.cstr.addNullByte(allocator, tmpnam); defer allocator.free(c_tmpnam); - std.debug.warn("\tmagick: saving to '{}'..", .{c_tmpnam}); + std.debug.warn("\tmagick: saving to '{s}'..", .{c_tmpnam}); if (mc.MagickWriteImage(wand, c_tmpnam.ptr) != 1) return error.MagickWriteFail; diff --git a/src/main.zig b/src/main.zig index 8ea264d..6ebe124 100644 --- a/src/main.zig +++ b/src/main.zig @@ -38,7 +38,7 @@ fn copyCommandToHeap(allocator: *std.mem.Allocator, command: langs.Command, comp pub fn doRepl(allocator: *std.mem.Allocator, args_it: anytype) !void { var stdout_file = std.io.getStdOut(); - const stdout = &stdout_file.outStream(); + const stdout = &stdout_file.writer(); const scri_path = try (args_it.next(allocator) orelse @panic("expected scri path")); var file_read_opt: ?std.fs.File = std.fs.cwd().openFile(scri_path, .{}) catch |err| blk: { @@ -95,7 +95,7 @@ pub fn doRepl(allocator: *std.mem.Allocator, args_it: anytype) !void { }); defer file.close(); - var out = file.outStream(); + var out = file.writer(); var stream = &out; // since we opened the file for writing, it becomes empty, so, to ensure diff --git a/src/plugin.zig b/src/plugin.zig index 78e8a6d..cb8c64a 100644 --- a/src/plugin.zig +++ b/src/plugin.zig @@ -137,7 +137,7 @@ pub fn makeContext(allocator: *std.mem.Allocator, plugin_uri: []const u8) !Conte c.lilv_world_load_all(world); var uri: *c.LilvNode = c.lilv_new_uri(world, cstr_plugin_uri.ptr) orelse { - std.debug.warn("Invalid plugin URI <{}>\n", .{plugin_uri}); + std.debug.warn("Invalid plugin URI <{s}>\n", .{plugin_uri}); return ImageError.InvalidPlugin; }; defer c.lilv_node_free(uri); @@ -145,7 +145,7 @@ pub fn makeContext(allocator: *std.mem.Allocator, plugin_uri: []const u8) !Conte const plugins: *const c.LilvPlugins = c.lilv_world_get_all_plugins(world).?; var plugin: *const c.LilvPlugin = c.lilv_plugins_get_by_uri(plugins, uri) orelse { - std.debug.warn("Plugin <{}> not found\n", .{plugin_uri}); + std.debug.warn("Plugin <{s}> not found\n", .{plugin_uri}); return ImageError.UnknownPlugin; }; diff --git a/src/printer.zig b/src/printer.zig index 5ea5a7b..c1fab31 100644 --- a/src/printer.zig +++ b/src/printer.zig @@ -3,12 +3,14 @@ const langs = @import("lang.zig"); fn printCommandWithParams(stream: anytype, command: anytype) !void { const Parameters = @TypeOf(command.parameters); - try stream.print(" {} {}", .{ command.split, command.index }); + try stream.print(" {d} {d}", .{ command.split, command.index }); inline for (@typeInfo(Parameters).Struct.fields) |field| { if (field.field_type == f32 or field.field_type == f64) { + try stream.print(" {}", .{@field(command.parameters, field.name)}); + } else if (field.field_type == usize or field.field_type == u64) { try stream.print(" {d}", .{@field(command.parameters, field.name)}); } else { - try stream.print(" {}", .{@field(command.parameters, field.name)}); + try stream.print(" {s}", .{@field(command.parameters, field.name)}); } } } @@ -17,12 +19,6 @@ fn printCommand(stream: anytype, cmd: *langs.Command, comptime tag: langs.Comman const CommandStruct = langs.Command.tagToType(tag); const casted = cmd.cast(CommandStruct).?; - // TODO move this to Tag method? - const is_typed = switch (tag) { - .noop, .load, .quicksave, .runqs, .rotate => false, - else => true, - }; - const ctype = CommandStruct.command_type; switch (ctype) { .lv2_command => try printCommandWithParams(stream, casted), @@ -33,21 +29,21 @@ fn printCommand(stream: anytype, cmd: *langs.Command, comptime tag: langs.Comman pub fn printList(list: langs.CommandList, stream: anytype) !void { for (list.list.items) |cmd| { const command = @tagName(cmd.tag); - try stream.print("{}", .{command}); + try stream.print("{s}", .{command}); switch (cmd.tag) { .load => { const load = cmd.cast(langs.Command.Load).?; - try stream.print(" {}", .{load.path}); + try stream.print(" {s}", .{load.path}); }, .runqs => { const runqs = cmd.cast(langs.Command.RunQS).?; - try stream.print(" {}", .{runqs.program}); + try stream.print(" {s}", .{runqs.program}); }, .noop, .quicksave => {}, .rotate => { const rotate = cmd.cast(langs.Command.Rotate).?; - try stream.print(" {d} {}", .{ rotate.deg, rotate.bgfill }); + try stream.print(" {d} {s}", .{ rotate.deg, rotate.bgfill }); }, .amp => try printCommand(stream, cmd, .amp), diff --git a/src/runner.zig b/src/runner.zig index a10b7a5..1bec75a 100644 --- a/src/runner.zig +++ b/src/runner.zig @@ -67,11 +67,10 @@ pub const Runner = struct { // ':0' should ALWAYS point to the image. if (self.repl) index += 3 else index += 2; - std.debug.warn("ARGS!! {} \n", .{self.args.len}); for (self.args) |arg, idx| { - std.debug.warn("arg{} = {}\n", .{ idx, arg }); + std.debug.warn("arg{d} = {s}\n", .{ idx, arg }); } - std.debug.warn("fetch arg idx={}, val={}\n", .{ index, self.args[index] }); + std.debug.warn("fetch arg idx={d}, val={s}\n", .{ index, self.args[index] }); return self.args[index]; } else { return load_path; @@ -91,7 +90,7 @@ pub const Runner = struct { fn loadCmd(self: *Runner, path_or_argidx: []const u8) !void { const load_path = try self.resolveArgPath(path_or_argidx); - std.debug.warn("\tload path: {}\n", .{load_path}); + std.debug.warn("\tload path: {s}\n", .{load_path}); // we could use ImageMagick to convert from X to BMP // but i can't find an easy way to do things in memory. @@ -101,7 +100,7 @@ pub const Runner = struct { // krita/gimp and make it export a bmp and while in the program you can // apply filters, etc. if (!std.mem.endsWith(u8, load_path, ".bmp") and !std.mem.endsWith(u8, load_path, ".ppm")) { - std.debug.warn("Only BMP files are allowed to be loaded. Got path '{}'\n", .{load_path}); + std.debug.warn("Only BMP files are allowed to be loaded. Got path '{s}'\n", .{load_path}); return RunError.NoBMP; } @@ -138,7 +137,7 @@ pub const Runner = struct { // starts_with would be "x_g", we want to find all files in the directory // that start with that name. - const starts_with = try std.fmt.allocPrint(self.allocator, "{}_g", .{ + const starts_with = try std.fmt.allocPrint(self.allocator, "{s}_g", .{ basename[0..period_idx], }); defer self.allocator.free(starts_with); @@ -172,7 +171,7 @@ pub const Runner = struct { } } - const out_path = try std.fmt.allocPrint(self.allocator, "{}/{}{}{}", .{ + const out_path = try std.fmt.allocPrint(self.allocator, "{s}/{s}{d}{s}", .{ dirname, starts_with, max + 1, @@ -202,7 +201,7 @@ pub const Runner = struct { ); defer proc.deinit(); - std.debug.warn("running '{} {}'\n", .{ runqs.program, out_path }); + std.debug.warn("running '{s} {s}'\n", .{ runqs.program, out_path }); _ = try proc.spawnAndWait(); } From 32b01976d86f49afcbeb63c48f6b6c15a512faf0 Mon Sep 17 00:00:00 2001 From: Luna Date: Sat, 3 Apr 2021 23:05:56 -0300 Subject: [PATCH 20/43] change default scri path to 'run' cli command --- src/main.zig | 43 +++++++++++++++++++++++++------------------ src/runner.zig | 2 +- 2 files changed, 26 insertions(+), 19 deletions(-) diff --git a/src/main.zig b/src/main.zig index 6ebe124..d810652 100644 --- a/src/main.zig +++ b/src/main.zig @@ -248,25 +248,32 @@ pub fn main() !void { // TODO print help _ = args_it.skip(); - const scri_path = try (args_it.next(allocator) orelse @panic("expected scri path or 'repl'")); - defer allocator.free(scri_path); + const cli_command = try (args_it.next(allocator) orelse @panic("expected 'run', 'help', or 'repl'")); + defer allocator.free(cli_command); - if (std.mem.eql(u8, scri_path, "repl")) { + if (std.mem.eql(u8, cli_command, "help")) { + //return try doHelp(); + } else if (std.mem.eql(u8, cli_command, "repl")) { return try doRepl(allocator, &args_it); + } else if (std.mem.eql(u8, cli_command, "run")) { + const scri_path = try (args_it.next(allocator) orelse @panic("run: expected scri path")); + defer allocator.free(scri_path); + + var file = try std.fs.cwd().openFile(scri_path, .{}); + defer file.close(); + + // sadly, we read it all into memory. such is life + const total_bytes = try file.getEndPos(); + + var data = try allocator.alloc(u8, total_bytes); + defer allocator.free(data); + _ = try file.read(data); + + var cmds = try lang.parse(data); + defer cmds.deinit(); + + try runner.runCommands(cmds, true); + } else { + @panic("expected 'run', 'help', or 'repl'"); } - - var file = try std.fs.cwd().openFile(scri_path, .{}); - defer file.close(); - - // sadly, we read it all into memory. such is life - const total_bytes = try file.getEndPos(); - - var data = try allocator.alloc(u8, total_bytes); - defer allocator.free(data); - _ = try file.read(data); - - var cmds = try lang.parse(data); - defer cmds.deinit(); - - try runner.runCommands(cmds, true); } diff --git a/src/runner.zig b/src/runner.zig index 1bec75a..16bbc12 100644 --- a/src/runner.zig +++ b/src/runner.zig @@ -65,7 +65,7 @@ pub const Runner = struct { // 'scritcher repl ./script ./image' // ':0' should ALWAYS point to the image. - if (self.repl) index += 3 else index += 2; + if (self.repl) index += 4 else index += 3; for (self.args) |arg, idx| { std.debug.warn("arg{d} = {s}\n", .{ idx, arg }); From 73c52141468b59d48750ca29c7cc03e859a8eacc Mon Sep 17 00:00:00 2001 From: Luna Date: Sat, 3 Apr 2021 23:20:17 -0300 Subject: [PATCH 21/43] add 'help' command --- src/main.zig | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/main.zig b/src/main.zig index d810652..865ce42 100644 --- a/src/main.zig +++ b/src/main.zig @@ -230,6 +230,13 @@ pub fn doRepl(allocator: *std.mem.Allocator, args_it: anytype) !void { } } +fn doHelp() void { + std.debug.warn("scritcher!\n", .{}); + std.debug.warn("usage: scritcher [run|help|repl]\n", .{}); + std.debug.warn("\tscritcher run path_to_script.scri path_to_input_file.bmp\n", .{}); + std.debug.warn("\tscritcher repl path_to_script.scri path_to_input_file.bmp\n", .{}); +} + pub fn main() !void { // const allocator = std.heap.page_allocator; var allocator_instance = std.heap.GeneralPurposeAllocator(.{}){}; @@ -248,11 +255,16 @@ pub fn main() !void { // TODO print help _ = args_it.skip(); - const cli_command = try (args_it.next(allocator) orelse @panic("expected 'run', 'help', or 'repl'")); + const cli_command_opt = args_it.next(allocator); + if (cli_command_opt == null) { + return doHelp(); + } + + const cli_command = try cli_command_opt.?; defer allocator.free(cli_command); if (std.mem.eql(u8, cli_command, "help")) { - //return try doHelp(); + return doHelp(); } else if (std.mem.eql(u8, cli_command, "repl")) { return try doRepl(allocator, &args_it); } else if (std.mem.eql(u8, cli_command, "run")) { @@ -274,6 +286,7 @@ pub fn main() !void { try runner.runCommands(cmds, true); } else { - @panic("expected 'run', 'help', or 'repl'"); + std.debug.warn("unknown command: '{s}'\n", .{cli_command}); + return error.UnknownCommand; } } From 79d7e137d2e9dd972a800a744499e6483f8047cd Mon Sep 17 00:00:00 2001 From: Luna Date: Sat, 3 Apr 2021 23:21:50 -0300 Subject: [PATCH 22/43] refactor into 'doRun' function --- src/main.zig | 50 +++++++++++++++++++++++++++----------------------- 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/src/main.zig b/src/main.zig index 865ce42..8e68ab3 100644 --- a/src/main.zig +++ b/src/main.zig @@ -237,6 +237,32 @@ fn doHelp() void { std.debug.warn("\tscritcher repl path_to_script.scri path_to_input_file.bmp\n", .{}); } +fn doRun(allocator: *std.mem.Allocator, args_it: anytype) !void { + var lang = langs.Lang.init(allocator); + defer lang.deinit(); + + var runner = runners.Runner.init(allocator, false); + defer runner.deinit(); + + const scri_path = try (args_it.next(allocator) orelse @panic("run: expected scri path")); + defer allocator.free(scri_path); + + var file = try std.fs.cwd().openFile(scri_path, .{}); + defer file.close(); + + // sadly, we read it all into memory. such is life + const total_bytes = try file.getEndPos(); + + var data = try allocator.alloc(u8, total_bytes); + defer allocator.free(data); + _ = try file.read(data); + + var cmds = try lang.parse(data); + defer cmds.deinit(); + + try runner.runCommands(cmds, true); +} + pub fn main() !void { // const allocator = std.heap.page_allocator; var allocator_instance = std.heap.GeneralPurposeAllocator(.{}){}; @@ -245,12 +271,6 @@ pub fn main() !void { } const allocator = &allocator_instance.allocator; - var lang = langs.Lang.init(allocator); - defer lang.deinit(); - - var runner = runners.Runner.init(allocator, false); - defer runner.deinit(); - var args_it = std.process.args(); // TODO print help @@ -268,23 +288,7 @@ pub fn main() !void { } else if (std.mem.eql(u8, cli_command, "repl")) { return try doRepl(allocator, &args_it); } else if (std.mem.eql(u8, cli_command, "run")) { - const scri_path = try (args_it.next(allocator) orelse @panic("run: expected scri path")); - defer allocator.free(scri_path); - - var file = try std.fs.cwd().openFile(scri_path, .{}); - defer file.close(); - - // sadly, we read it all into memory. such is life - const total_bytes = try file.getEndPos(); - - var data = try allocator.alloc(u8, total_bytes); - defer allocator.free(data); - _ = try file.read(data); - - var cmds = try lang.parse(data); - defer cmds.deinit(); - - try runner.runCommands(cmds, true); + return try doRun(allocator, &args_it); } else { std.debug.warn("unknown command: '{s}'\n", .{cli_command}); return error.UnknownCommand; From a9e4c5823a063ee7dcade1211b59f505d13a5b69 Mon Sep 17 00:00:00 2001 From: Luna Date: Sat, 3 Apr 2021 23:22:22 -0300 Subject: [PATCH 23/43] remove implemented TODO --- src/main.zig | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main.zig b/src/main.zig index 8e68ab3..f1cb3c8 100644 --- a/src/main.zig +++ b/src/main.zig @@ -264,7 +264,6 @@ fn doRun(allocator: *std.mem.Allocator, args_it: anytype) !void { } pub fn main() !void { - // const allocator = std.heap.page_allocator; var allocator_instance = std.heap.GeneralPurposeAllocator(.{}){}; defer { _ = allocator_instance.deinit(); @@ -273,7 +272,6 @@ pub fn main() !void { var args_it = std.process.args(); - // TODO print help _ = args_it.skip(); const cli_command_opt = args_it.next(allocator); if (cli_command_opt == null) { From 78cc7fab4b4a232473acc82d7153fa06ae77fff7 Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 4 Apr 2021 17:08:53 -0300 Subject: [PATCH 24/43] fix tests --- src/lang.zig | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/lang.zig b/src/lang.zig index b299ae0..127ff04 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -665,18 +665,18 @@ pub const Lang = struct { }; test "noop" { - var lang = Lang.init(std.heap.direct_allocator); + var lang = Lang.init(std.testing.allocator); defer lang.deinit(); var cmds = try lang.parse("noop;"); defer cmds.deinit(); - std.testing.expectEqual(cmds.len, 1); - std.testing.expectEqual(cmds.items[0].command, .Noop); + std.testing.expectEqual(cmds.list.items.len, 1); + std.testing.expectEqual(cmds.list.items[0].tag, .noop); } test "load, phaser, quicksave" { - var lang = Lang.init(std.heap.direct_allocator); + var lang = Lang.init(std.testing.allocator); defer lang.deinit(); const prog = @@ -688,8 +688,8 @@ test "load, phaser, quicksave" { var cmds = try lang.parse(prog); defer cmds.deinit(); - std.testing.expectEqual(cmds.len, 3); - std.testing.expectEqual(cmds.items[0].command, .Load); - std.testing.expectEqual(cmds.items[1].command, .Phaser); - std.testing.expectEqual(cmds.items[2].command, .Quicksave); + std.testing.expectEqual(cmds.list.items.len, 3); + std.testing.expectEqual(cmds.list.items[0].tag, .load); + std.testing.expectEqual(cmds.list.items[1].tag, .phaser); + std.testing.expectEqual(cmds.list.items[2].tag, .quicksave); } From 2a801a129b29f15bd225c7ee8ba41dc7a315c2af Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 4 Apr 2021 17:45:14 -0300 Subject: [PATCH 25/43] add note about comptime hash map --- src/lang.zig | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/lang.zig b/src/lang.zig index 127ff04..3747941 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -643,7 +643,10 @@ pub const Lang = struct { // in a variable because then that variable must be comptime. // the drawback of this approach is that our emitted code is basically linear - // because we don't use the hashmap anymore. maybe #5359 can help. + // because we don't use the hashmap anymore. + // + // Attempting to use ComptimeHashMap hits compiler bugs and I'm + // not sure if we can map strings to *types* in it. if (std.mem.eql(u8, &lowered_command_name, command_string)) { found = true; From b28f208e659b5ef50258b0ea579f27529c81eff3 Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 4 Apr 2021 17:56:59 -0300 Subject: [PATCH 26/43] add error for non-lv2 args not getting enough args --- src/lang.zig | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/lang.zig b/src/lang.zig index 3747941..e70b553 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -527,9 +527,6 @@ pub const Lang = struct { else => true, }; - // TODO: crash when no arguments are left but we still need - // arguments... - if (is_lv2_command) { const split = tok_it.next(); if (split == null) { @@ -571,7 +568,14 @@ pub const Lang = struct { continue; } } - const arg = tok_it.next().?; + + const arg_opt = tok_it.next(); + if (arg_opt == null) { + self.doError("Expected parameter for {s}, got nothing", .{cmd_field.name}); + return; + } + const arg = arg_opt.?; + const argument_value = switch (cmd_field.field_type) { usize => try std.fmt.parseInt(usize, arg, 10), i32 => try std.fmt.parseInt(i32, arg, 10), From ea3850b99d851f58498581d5b12ce236ae5b787d Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 4 Apr 2021 18:15:42 -0300 Subject: [PATCH 27/43] add test for parse errors --- src/lang.zig | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/lang.zig b/src/lang.zig index e70b553..2f2b4ac 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -507,6 +507,7 @@ pub const Lang = struct { self.has_error = false; self.line = 0; } + fn doError(self: *Lang, comptime fmt: []const u8, args: anytype) void { std.debug.warn("ERROR! at line {}: ", .{self.line}); std.debug.warn(fmt, args); @@ -700,3 +701,20 @@ test "load, phaser, quicksave" { std.testing.expectEqual(cmds.list.items[1].tag, .phaser); std.testing.expectEqual(cmds.list.items[2].tag, .quicksave); } + +test "load, phaser with errors, quicksave" { + var lang = Lang.init(std.testing.allocator); + defer lang.deinit(); + + const prog = + \\load :0; + \\phaser 3 1 25; + \\quicksave; + ; + + var cmds = lang.parse(prog) catch |err| { + return; + }; + + unreachable; +} From b195577dee63a0683f8a7ac8c441e51d359e0132 Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 4 Apr 2021 20:47:18 -0300 Subject: [PATCH 28/43] prevent memleaks on parse errors --- src/lang.zig | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/lang.zig b/src/lang.zig index 2f2b4ac..3ad0c41 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -523,6 +523,11 @@ pub const Lang = struct { ) !void { // Based on the command struct fields, we can parse the arguments. var cmd = try self.allocator.create(command_struct); + + // we already add the command to the list to prevent memory leaks + // by commands that error out + try commands.append(&cmd.base); + const is_lv2_command = switch (command_struct.base_tag) { .noop, .load, .quicksave, .runqs, .rotate => false, else => true, @@ -598,13 +603,12 @@ pub const Lang = struct { cmd.base.tag = command_struct.base_tag; const command = cmd.base.cast(command_struct).?; std.debug.warn("cmd: {s}\n", .{command}); - - try commands.append(&cmd.base); } pub fn parse(self: *Lang, data: []const u8) !CommandList { var splitted_it = std.mem.split(data, ";"); var cmds = CommandList.init(self.allocator); + errdefer cmds.deinit(); while (splitted_it.next()) |stmt_orig| { self.line += 1; From d7d43852422f1abec1fba6b9ba38ca50ebadcacc Mon Sep 17 00:00:00 2001 From: Luna Date: Wed, 27 Apr 2022 20:01:00 -0300 Subject: [PATCH 29/43] fix memory leak on string arguments --- src/lang.zig | 19 +++++++++++++++++-- src/main.zig | 6 +++--- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/lang.zig b/src/lang.zig index 3ad0c41..f465895 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -479,6 +479,21 @@ pub const CommandList = struct { pub fn deinit(self: *Self) void { for (self.list.items) |cmd_ptr| { self.list.allocator.destroy(cmd_ptr); + inline for (@typeInfo(Command.Tag).Enum.fields) |field| { + if (cmd_ptr.tag == @field(Command.Tag, field.name)) { + const actual_tag = + @field(Command.Tag, field.name); + // if we find a match on the tag, we can get the type + const typ = Command.tagToType(actual_tag); + + inline for (@typeInfo(typ).Struct.fields) |cmd_field| { + switch (cmd_field.field_type) { + []u8, []const u8 => self.list.allocator.destroy(@field(typ, cmd_field.name)), + else => {}, + } + } + } + } } self.list.deinit(); } @@ -561,7 +576,7 @@ pub const Lang = struct { f32 => try std.fmt.parseFloat(f32, arg), u64 => try std.fmt.parseInt(u64, arg, 10), usize => try std.fmt.parseInt(usize, arg, 10), - []const u8 => arg, + []const u8 => @as([]const u8, try self.allocator.dupe(u8, arg)), else => @compileError("parameter struct has unsupported type " ++ @typeName(cmd_field.field_type)), }; @@ -586,7 +601,7 @@ pub const Lang = struct { usize => try std.fmt.parseInt(usize, arg, 10), i32 => try std.fmt.parseInt(i32, arg, 10), f32 => try std.fmt.parseFloat(f32, arg), - []const u8 => arg, + []const u8 => @as([]const u8, try self.allocator.dupe(u8, arg)), else => @compileError("Invalid parameter type (" ++ @typeName(cmd_field.field_type) ++ ") left on command struct " ++ @typeName(command_struct) ++ "."), }; diff --git a/src/main.zig b/src/main.zig index f1cb3c8..a096f4f 100644 --- a/src/main.zig +++ b/src/main.zig @@ -40,6 +40,8 @@ pub fn doRepl(allocator: *std.mem.Allocator, args_it: anytype) !void { var stdout_file = std.io.getStdOut(); const stdout = &stdout_file.writer(); const scri_path = try (args_it.next(allocator) orelse @panic("expected scri path")); + errdefer allocator.free(scri_path); + defer allocator.free(scri_path); var file_read_opt: ?std.fs.File = std.fs.cwd().openFile(scri_path, .{}) catch |err| blk: { if (err == error.FileNotFound) break :blk null; @@ -54,11 +56,9 @@ pub fn doRepl(allocator: *std.mem.Allocator, args_it: anytype) !void { defer lang.deinit(); if (total_bytes > 0) { - // this MUST BE long lived (a reference to it is kept inside - // existing_cmds, and then passed along to cmds), - // we can't defer them here var scri_existing = try allocator.alloc(u8, total_bytes); _ = try file_read_opt.?.read(scri_existing); + defer allocator.free(scri_existing); // we can't defer this directly because we copy the // Command pointers to the cmds list. running deinit() directly From 268be1074cf44eb4e0d60a519cd3a3258574710b Mon Sep 17 00:00:00 2001 From: Luna Date: Wed, 27 Apr 2022 20:01:06 -0300 Subject: [PATCH 30/43] port to latest zig fs api --- src/main.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.zig b/src/main.zig index a096f4f..005100b 100644 --- a/src/main.zig +++ b/src/main.zig @@ -89,9 +89,9 @@ pub fn doRepl(allocator: *std.mem.Allocator, args_it: anytype) !void { file_read.close(); } - var file = try std.fs.cwd().openFile(scri_path, .{ - .write = true, + var file = try std.fs.cwd().createFile(scri_path, .{ .read = false, + .truncate = true, }); defer file.close(); From c817170a0423fa65ef28aa15e512db9284edeaa9 Mon Sep 17 00:00:00 2001 From: Luna Date: Wed, 27 Apr 2022 20:01:09 -0300 Subject: [PATCH 31/43] port to latest zig: use std.log --- build.zig | 6 +++--- src/bmp_valid.zig | 5 ++--- src/custom.zig | 3 ++- src/image.zig | 41 +++++++++++++++++++++-------------------- src/lang.zig | 13 +++++++------ src/lv2_helpers.zig | 8 +++++--- src/magick.zig | 7 ++++--- src/main.zig | 18 ++++++++++-------- src/plugin.zig | 5 +++-- src/printer.zig | 2 ++ src/runner.zig | 16 +++++++++------- 11 files changed, 68 insertions(+), 56 deletions(-) diff --git a/build.zig b/build.zig index 467240c..f7b08f9 100644 --- a/build.zig +++ b/build.zig @@ -24,19 +24,19 @@ fn setupLinks(step: *builds.LibExeObjStep) void { for (possible_lilv_include_dirs) |possible_lilv_dir| { var possible_dir = std.fs.cwd().openDir(possible_lilv_dir, .{}) catch |err| { - std.debug.warn("possible lilv {s} fail: {s}\n", .{ possible_lilv_dir, err }); + std.debug.print("possible lilv {s} fail: {s}\n", .{ possible_lilv_dir, err }); continue; }; possible_dir.close(); found_any_lilv = true; - std.debug.warn("found lilv at '{s}'\n", .{possible_lilv_dir}); + std.debug.print("found lilv at '{s}'\n", .{possible_lilv_dir}); step.addIncludeDir(possible_lilv_dir); } if (!found_any_lilv) { - std.debug.warn("No LILV library was found :(\n", .{}); + std.debug.print("No LILV library was found :(\n", .{}); @panic("no lilv found"); } } diff --git a/src/bmp_valid.zig b/src/bmp_valid.zig index 6468658..55970b8 100644 --- a/src/bmp_valid.zig +++ b/src/bmp_valid.zig @@ -1,11 +1,10 @@ const std = @import("std"); - +const log = std.log.scoped(.scritcher_bmp); pub const BMPValidError = error{InvalidMagic}; const VALID_MAGICS = [_][]const u8{ "BM", "BA", - "CI", "CP", "IC", @@ -20,7 +19,7 @@ pub fn magicValid(magic: []const u8) !void { } if (!valid) { - std.debug.warn("\tINVALID HEADER: '{s}'\n", .{magic}); + log.debug("\tINVALID HEADER: '{s}'\n", .{magic}); return BMPValidError.InvalidMagic; } } diff --git a/src/custom.zig b/src/custom.zig index 03120f0..401b39f 100644 --- a/src/custom.zig +++ b/src/custom.zig @@ -4,6 +4,7 @@ const lv2 = @import("lv2_helpers.zig"); const plugins = @import("plugin.zig"); const image = @import("image.zig"); +const log = std.log.scoped(.scritcher_custom); const c = lv2.c; const RunBuffers = plugins.RunBuffers; @@ -174,7 +175,7 @@ pub const Embed = struct { if (read_bytes < 0) { const st: i32 = c.sf_error(self.sndfile); - std.debug.warn("Failed to read {s} ({s})\n", .{ + log.debug("Failed to read {s} ({s})\n", .{ self.filepath, c.sf_error_number(st), }); diff --git a/src/image.zig b/src/image.zig index b6e13ae..4a01845 100644 --- a/src/image.zig +++ b/src/image.zig @@ -3,6 +3,7 @@ const lv2 = @import("lv2_helpers.zig"); const c = lv2.c; const bmp = @import("bmp_valid.zig"); +const log = std.log.scoped(.scritcher_image); const plugins = @import("plugin.zig"); /// Buffer size for main image copying. @@ -32,7 +33,7 @@ pub fn sopen( const st: i32 = c.sf_error(file); if (st != 0) { - std.debug.warn("Failed to open {s} ({s})\n", .{ + log.debug("Failed to open {s} ({s})\n", .{ path, c.sf_error_number(st), }); @@ -47,7 +48,7 @@ pub fn sopen( const frames_on_end_by_end = c.sf_seek(file, frames_on_end, c.SEEK_SET); std.testing.expectEqual(frames_on_end, frames_on_end_by_end); - std.debug.warn("frames on end: {}, frame on end (2): {}\n", .{ frames_on_end, frames_on_end_by_end }); + log.debug("frames on end: {}, frame on end (2): {}\n", .{ frames_on_end, frames_on_end_by_end }); return file.?; } @@ -56,7 +57,7 @@ pub fn swrite(file: *c.SNDFILE, buf: [*]f32, frames: i64) !void { const count = c.sf_writef_float(file, buf, frames); if (count != frames) { - std.debug.warn("Wanted to write {}, got {}\n", .{ frames, count }); + log.debug("Wanted to write {}, got {}\n", .{ frames, count }); return ImageError.WriteFail; } } @@ -68,7 +69,7 @@ pub fn sseek(file: *c.SNDFILE, offset: usize) void { std.testing.expectEqual(frames, frames_current); if (frames != offset_i64) { - std.debug.warn("failed to seek to {} (seeked {} frames, offset_i64={})\n", .{ offset, frames, offset_i64 }); + log.debug("failed to seek to {} (seeked {} frames, offset_i64={})\n", .{ offset, frames, offset_i64 }); } } @@ -181,7 +182,7 @@ pub const Image = struct { pub fn close(self: *Image) void { var st: i32 = c.sf_close(self.sndfile); if (st != 0) { - std.debug.warn("Failed to close {s} ({s})\n", .{ + log.debug("Failed to close {s} ({s})\n", .{ self.path, c.sf_error_number(st), }); @@ -228,7 +229,7 @@ pub const Image = struct { sseek(out_file, start); while (i <= end) : (i += buf.len) { - std.debug.warn("\t\ti={d}, buf.len={d}, end={d}\n", .{ i, buf.len, end }); + log.debug("\t\ti={d}, buf.len={d}, end={d}\n", .{ i, buf.len, end }); sseek(self.sndfile, i); sseek(out_file, i); @@ -254,7 +255,7 @@ pub const Image = struct { fn getSeekPos(self: *Image, position: plugins.Position) plugins.SeekPos { const file_end = self.frames; var seek_pos = position.seekPos(file_end); - std.debug.warn("\tstart {d} end {d}\n", .{ seek_pos.start, seek_pos.end }); + log.debug("\tstart {d} end {d}\n", .{ seek_pos.start, seek_pos.end }); return seek_pos; } @@ -267,7 +268,7 @@ pub const Image = struct { self.curpath = path; self.frames = @intCast(usize, in_fmt.frames); - std.debug.warn("\timage: reopened on '{s}' (frames={d}, fmt.frames={d})\n", .{ + log.debug("\timage: reopened on '{s}' (frames={d}, fmt.frames={d})\n", .{ self.curpath, self.frames, in_fmt.frames, @@ -310,12 +311,12 @@ pub const Image = struct { defer ctx.allocator.free(ports); if (ctx.n_audio_in > 2) { - std.debug.warn("plugin <{s}> has more than two inputs.\n", .{plugin_uri}); + log.debug("plugin <{s}> has more than two inputs.\n", .{plugin_uri}); return ImageError.InvalidPlugin; } if (ctx.n_audio_out > 2) { - std.debug.warn("plugin <{s}> has more than two outputs.\n", .{plugin_uri}); + log.debug("plugin <{s}> has more than two outputs.\n", .{plugin_uri}); return ImageError.InvalidPlugin; } @@ -327,14 +328,14 @@ pub const Image = struct { var sym = c.lilv_new_string(ctx.world, sym_cstr.ptr); const port = c.lilv_plugin_get_port_by_symbol(ctx.plugin, sym) orelse { - std.debug.warn("assert fail: symbol {s} not found on port\n", .{param.sym}); + log.debug("assert fail: symbol {s} not found on port\n", .{param.sym}); return ImageError.InvalidSymbol; }; c.lilv_node_free(sym); var idx = c.lilv_port_get_index(ctx.plugin, port); - std.debug.warn("\tset sym={s}, idx={d} to val={}\n", .{ + log.debug("\tset sym={s}, idx={d} to val={}\n", .{ param.sym, idx, param.value, @@ -345,7 +346,7 @@ pub const Image = struct { // now we need to generate a temporary file and put the output of // running the plugin on that file var tmpnam = try temporaryName(self.allocator); - std.debug.warn("\trunning plugin from '{s}' to '{s}'\n", .{ self.curpath, tmpnam }); + log.debug("\trunning plugin from '{s}' to '{s}'\n", .{ self.curpath, tmpnam }); var out_fmt = mkSfInfo(); var out_file = try sopen(self.allocator, tmpnam, c.SFM_WRITE, &out_fmt); @@ -378,7 +379,7 @@ pub const Image = struct { sseek(self.sndfile, seek_pos.start); var i: usize = seek_pos.start; - std.debug.warn("\tseek pos start: {d} end: {d}\n", .{ seek_pos.start, seek_pos.end }); + log.debug("\tseek pos start: {d} end: {d}\n", .{ seek_pos.start, seek_pos.end }); var inbuf = &rctx.buffers.in; var outbuf = &rctx.buffers.out; @@ -389,7 +390,7 @@ pub const Image = struct { const read_bytes = c.sf_readf_float(self.sndfile, inbuf, 1); if (read_bytes == 0) { - std.debug.warn("WARN! reached EOF at idx={d}\n", .{i}); + log.debug("WARN! reached EOF at idx={d}\n", .{i}); break; } @@ -418,11 +419,11 @@ pub const Image = struct { try self.checkValid(); var time_taken = timer.read(); - std.debug.warn("\ttook {d:.2}ms running plugin\n", .{time_taken / std.time.us_per_ms}); + log.debug("\ttook {d:.2}ms running plugin\n", .{time_taken / std.time.us_per_ms}); } pub fn saveTo(self: *Image, out_path: []const u8) !void { - std.debug.warn("\timg: copy from '{s}' to '{s}'\n", .{ self.curpath, out_path }); + log.debug("\timg: copy from '{s}' to '{s}'\n", .{ self.curpath, out_path }); try std.fs.copyFileAbsolute(self.curpath, out_path, .{}); } @@ -450,7 +451,7 @@ pub const Image = struct { // the code here is a copypaste of runPlugin() without the specific // lilv things. var tmpnam = try temporaryName(self.allocator); - std.debug.warn("\trunning CUSTOM plugin from '{s}' to '{s}'\n", .{ self.curpath, tmpnam }); + log.debug("\trunning CUSTOM plugin from '{s}' to '{s}'\n", .{ self.curpath, tmpnam }); var out_fmt = mkSfInfo(); var out_file = try sopen(self.allocator, tmpnam, c.SFM_WRITE, &out_fmt); @@ -477,7 +478,7 @@ pub const Image = struct { sseek(self.sndfile, seek_pos.start); var i: usize = seek_pos.start; - std.debug.warn("\tseek pos start: {d} end: {d}\n", .{ seek_pos.start, seek_pos.end }); + log.debug("\tseek pos start: {d} end: {d}\n", .{ seek_pos.start, seek_pos.end }); var inbuf = &bufs.in; var outbuf = &bufs.out; @@ -485,7 +486,7 @@ pub const Image = struct { while (i <= seek_pos.end) : (i += 1) { const read_bytes = c.sf_readf_float(self.sndfile, inbuf, 1); if (read_bytes == 0) { - std.debug.warn("WARN! reached EOF at idx={d}\n", .{i}); + log.debug("WARN! reached EOF at idx={d}\n", .{i}); break; } diff --git a/src/lang.zig b/src/lang.zig index f465895..4c4f8f5 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -3,6 +3,7 @@ const std = @import("std"); const plugin = @import("plugin.zig"); const custom = @import("custom.zig"); +const log = std.log.scoped(.scritcher_lang); pub const ParseError = error{ParseFail}; pub const CommandType = enum { @@ -146,7 +147,7 @@ pub const Command = struct { } pub fn print(base: *const @This()) void { - std.debug.warn("tag: {s}\n", .{base.tag}); + log.debug("tag: {s}\n", .{base.tag}); } pub const Noop = struct { @@ -524,9 +525,9 @@ pub const Lang = struct { } fn doError(self: *Lang, comptime fmt: []const u8, args: anytype) void { - std.debug.warn("ERROR! at line {}: ", .{self.line}); - std.debug.warn(fmt, args); - std.debug.warn("\n", .{}); + log.debug("ERROR! at line {}: ", .{self.line}); + log.debug(fmt, args); + log.debug("\n", .{}); self.has_error = true; } @@ -605,7 +606,7 @@ pub const Lang = struct { else => @compileError("Invalid parameter type (" ++ @typeName(cmd_field.field_type) ++ ") left on command struct " ++ @typeName(command_struct) ++ "."), }; - std.debug.warn("parsing {s}, arg of type {s} => {any}\n", .{ + log.debug("parsing {s}, arg of type {s} => {any}\n", .{ @typeName(command_struct), @typeName(@TypeOf(argument_value)), argument_value, @@ -617,7 +618,7 @@ pub const Lang = struct { cmd.base.tag = command_struct.base_tag; const command = cmd.base.cast(command_struct).?; - std.debug.warn("cmd: {s}\n", .{command}); + log.debug("cmd: {s}\n", .{command}); } pub fn parse(self: *Lang, data: []const u8) !CommandList { diff --git a/src/lv2_helpers.zig b/src/lv2_helpers.zig index 599370c..62570df 100644 --- a/src/lv2_helpers.zig +++ b/src/lv2_helpers.zig @@ -1,6 +1,8 @@ const std = @import("std"); const plugin = @import("plugin.zig"); +const log = std.log.scoped(.scritcher_lv2); + pub const c = @cImport({ @cInclude("sndfile.h"); @cInclude("lilv/lilv.h"); @@ -21,7 +23,7 @@ const LV2_CORE__connectionOptional = Lv2Core("#connectionOptional"); pub fn lilv_instance_connect_port( instance: [*c]c.LilvInstance, port_index: u32, - data_location: ?*c_void, + data_location: ?*anyopaque, ) void { instance.?.*.lv2_descriptor.?.*.connect_port.?(instance.?.*.lv2_handle, port_index, data_location); } @@ -118,7 +120,7 @@ pub fn setupPorts(ctx: *plugin.Context) ![]Port { if (c.lilv_port_is_a(ctx.plugin, lport, lv2_InputPort)) { port.is_input = true; } else if (!c.lilv_port_is_a(ctx.plugin, lport, lv2_OutputPort) and !port.optional) { - std.debug.warn("Port {d} is neither input or output\n", .{i}); + log.debug("Port {d} is neither input or output\n", .{i}); return error.UnassignedIOPort; } @@ -134,7 +136,7 @@ pub fn setupPorts(ctx: *plugin.Context) ![]Port { ctx.n_audio_out += 1; } } else if (!port.optional) { - std.debug.warn("Port {d} has unsupported type\n", .{i}); + log.debug("Port {d} has unsupported type\n", .{i}); return error.UnsupportedPortType; } } diff --git a/src/magick.zig b/src/magick.zig index dd5f295..21f6d2d 100644 --- a/src/magick.zig +++ b/src/magick.zig @@ -2,6 +2,7 @@ const std = @import("std"); const images = @import("image.zig"); +const log = std.log.scoped(.scritcher_magick); const Image = images.Image; const mc = @cImport({ @@ -39,7 +40,7 @@ fn magickLoad(image: *Image) !MagickContext { var curpath = try std.cstr.addNullByte(image.allocator, image.curpath); defer image.allocator.free(curpath); - std.debug.warn("loading '{s}'\n", .{curpath}); + log.debug("loading '{s}'\n", .{curpath}); if (mc.MagickReadImage(mctx.wand, curpath.ptr) != 1) return error.MagickReadFail; @@ -54,12 +55,12 @@ fn magickSave(image: *Image, wand: *mc.MagickWand) !void { var c_tmpnam = try std.cstr.addNullByte(allocator, tmpnam); defer allocator.free(c_tmpnam); - std.debug.warn("\tmagick: saving to '{s}'..", .{c_tmpnam}); + log.debug("\tmagick: saving to '{s}'..", .{c_tmpnam}); if (mc.MagickWriteImage(wand, c_tmpnam.ptr) != 1) return error.MagickWriteFail; - std.debug.warn("OK\n", .{}); + log.debug("OK\n", .{}); try image.reopen(tmpnam); } diff --git a/src/main.zig b/src/main.zig index 005100b..c41d2e4 100644 --- a/src/main.zig +++ b/src/main.zig @@ -3,6 +3,8 @@ const langs = @import("lang.zig"); const runners = @import("runner.zig"); const printer = @import("printer.zig"); +const log = std.log.scoped(.scritcher); + test "scritcher" { _ = @import("lang.zig"); _ = @import("runner.zig"); @@ -132,7 +134,7 @@ pub fn doRepl(allocator: *std.mem.Allocator, args_it: anytype) !void { var rd_line = readline.readline("> "); if (rd_line == null) { - std.debug.warn("leaving from eof\n", .{}); + log.debug("leaving from eof\n", .{}); break; } readline.add_history(rd_line); @@ -200,14 +202,14 @@ pub fn doRepl(allocator: *std.mem.Allocator, args_it: anytype) !void { try printer.printList(cmds, stream); continue; } else if (std.mem.eql(u8, line, "quit") or std.mem.eql(u8, line, "q")) { - std.debug.warn("leaving\n", .{}); + log.debug("leaving\n", .{}); break; } else if (std.mem.startsWith(u8, line, "#")) { continue; } var cmds_parsed = lang.parse(line) catch |err| { - std.debug.warn("repl: error while parsing: {}\n", .{err}); + log.debug("repl: error while parsing: {}\n", .{err}); continue; }; @@ -231,10 +233,10 @@ pub fn doRepl(allocator: *std.mem.Allocator, args_it: anytype) !void { } fn doHelp() void { - std.debug.warn("scritcher!\n", .{}); - std.debug.warn("usage: scritcher [run|help|repl]\n", .{}); - std.debug.warn("\tscritcher run path_to_script.scri path_to_input_file.bmp\n", .{}); - std.debug.warn("\tscritcher repl path_to_script.scri path_to_input_file.bmp\n", .{}); + log.debug("scritcher!\n", .{}); + log.debug("usage: scritcher [run|help|repl]\n", .{}); + log.debug("\tscritcher run path_to_script.scri path_to_input_file.bmp\n", .{}); + log.debug("\tscritcher repl path_to_script.scri path_to_input_file.bmp\n", .{}); } fn doRun(allocator: *std.mem.Allocator, args_it: anytype) !void { @@ -288,7 +290,7 @@ pub fn main() !void { } else if (std.mem.eql(u8, cli_command, "run")) { return try doRun(allocator, &args_it); } else { - std.debug.warn("unknown command: '{s}'\n", .{cli_command}); + log.debug("unknown command: '{s}'\n", .{cli_command}); return error.UnknownCommand; } } diff --git a/src/plugin.zig b/src/plugin.zig index cb8c64a..d046edb 100644 --- a/src/plugin.zig +++ b/src/plugin.zig @@ -3,6 +3,7 @@ const std = @import("std"); const lv2 = @import("lv2_helpers.zig"); const c = lv2.c; +const log = std.log.scoped(.scritcher_plugin); const ImageError = @import("image.zig").ImageError; /// Control port @@ -137,7 +138,7 @@ pub fn makeContext(allocator: *std.mem.Allocator, plugin_uri: []const u8) !Conte c.lilv_world_load_all(world); var uri: *c.LilvNode = c.lilv_new_uri(world, cstr_plugin_uri.ptr) orelse { - std.debug.warn("Invalid plugin URI <{s}>\n", .{plugin_uri}); + log.debug("Invalid plugin URI <{s}>\n", .{plugin_uri}); return ImageError.InvalidPlugin; }; defer c.lilv_node_free(uri); @@ -145,7 +146,7 @@ pub fn makeContext(allocator: *std.mem.Allocator, plugin_uri: []const u8) !Conte const plugins: *const c.LilvPlugins = c.lilv_world_get_all_plugins(world).?; var plugin: *const c.LilvPlugin = c.lilv_plugins_get_by_uri(plugins, uri) orelse { - std.debug.warn("Plugin <{s}> not found\n", .{plugin_uri}); + log.debug("Plugin <{s}> not found\n", .{plugin_uri}); return ImageError.UnknownPlugin; }; diff --git a/src/printer.zig b/src/printer.zig index c1fab31..a851602 100644 --- a/src/printer.zig +++ b/src/printer.zig @@ -1,6 +1,8 @@ const std = @import("std"); const langs = @import("lang.zig"); +const log = std.log.scoped(.scritcher_printer); + fn printCommandWithParams(stream: anytype, command: anytype) !void { const Parameters = @TypeOf(command.parameters); try stream.print(" {d} {d}", .{ command.split, command.index }); diff --git a/src/runner.zig b/src/runner.zig index 16bbc12..40684a3 100644 --- a/src/runner.zig +++ b/src/runner.zig @@ -5,6 +5,8 @@ const plugin = @import("plugin.zig"); const custom = @import("custom.zig"); const magick = @import("magick.zig"); +const log = std.log.scoped(.scritcher_runner); + const Position = plugin.Position; const ParamList = plugin.ParamList; const ParamMap = plugin.ParamMap; @@ -65,12 +67,12 @@ pub const Runner = struct { // 'scritcher repl ./script ./image' // ':0' should ALWAYS point to the image. - if (self.repl) index += 4 else index += 3; + if (self.repl) index += 3 else index += 3; for (self.args) |arg, idx| { - std.debug.warn("arg{d} = {s}\n", .{ idx, arg }); + log.debug("arg{d} = {s}\n", .{ idx, arg }); } - std.debug.warn("fetch arg idx={d}, val={s}\n", .{ index, self.args[index] }); + log.debug("fetch arg idx={d}, val={s}\n", .{ index, self.args[index] }); return self.args[index]; } else { return load_path; @@ -90,7 +92,7 @@ pub const Runner = struct { fn loadCmd(self: *Runner, path_or_argidx: []const u8) !void { const load_path = try self.resolveArgPath(path_or_argidx); - std.debug.warn("\tload path: {s}\n", .{load_path}); + log.debug("\tload path: {s}\n", .{load_path}); // we could use ImageMagick to convert from X to BMP // but i can't find an easy way to do things in memory. @@ -100,7 +102,7 @@ pub const Runner = struct { // krita/gimp and make it export a bmp and while in the program you can // apply filters, etc. if (!std.mem.endsWith(u8, load_path, ".bmp") and !std.mem.endsWith(u8, load_path, ".ppm")) { - std.debug.warn("Only BMP files are allowed to be loaded. Got path '{s}'\n", .{load_path}); + log.debug("Only BMP files are allowed to be loaded. Got path '{s}'\n", .{load_path}); return RunError.NoBMP; } @@ -115,7 +117,7 @@ pub const Runner = struct { if (self.image) |image| { return image; } else { - std.debug.warn("image is required!\n", .{}); + log.debug("image is required!\n", .{}); return RunError.ImageRequired; } } @@ -201,7 +203,7 @@ pub const Runner = struct { ); defer proc.deinit(); - std.debug.warn("running '{s} {s}'\n", .{ runqs.program, out_path }); + log.debug("running '{s} {s}'\n", .{ runqs.program, out_path }); _ = try proc.spawnAndWait(); } From 5d1bcf33ee17a39a27bf91b141d54e9bf1cfa360 Mon Sep 17 00:00:00 2001 From: Luna Date: Wed, 27 Apr 2022 20:01:12 -0300 Subject: [PATCH 32/43] fixes for latest zig: a lot of stuff --- src/custom.zig | 31 ++++++++++++++----------- src/image.zig | 24 +++++++++----------- src/lang.zig | 61 +++++++++++++++++++++++++------------------------- src/magick.zig | 1 + src/main.zig | 8 +++---- src/plugin.zig | 8 ++++--- src/runner.zig | 22 +++++++++--------- 7 files changed, 80 insertions(+), 75 deletions(-) diff --git a/src/custom.zig b/src/custom.zig index 401b39f..4e48d6a 100644 --- a/src/custom.zig +++ b/src/custom.zig @@ -12,11 +12,11 @@ const RunBuffers = plugins.RunBuffers; pub const RandomNoise = struct { r: std.rand.DefaultPrng, rand_buf: ?[]f32 = null, - allocator: ?*std.mem.Allocator = null, + allocator: ?std.mem.Allocator = null, cnt: usize = 0, pub fn init( - allocator: *std.mem.Allocator, + allocator: std.mem.Allocator, params: anytype, ) ?RandomNoise { var r = std.rand.DefaultPrng.init(params.seed); @@ -25,7 +25,7 @@ pub const RandomNoise = struct { var rand_buf = allocator.alloc(f32, params.fill_bytes) catch return null; for (rand_buf) |_, idx| { - rand_buf[idx] = r.random.float(f32); + rand_buf[idx] = r.random().float(f32); } return RandomNoise{ @@ -52,7 +52,7 @@ pub const RandomNoise = struct { bufs.out[0] = rand_buf[self.cnt]; self.cnt += 1; } else { - bufs.out[0] = self.r.random.float(f32); + bufs.out[0] = self.r.random().float(f32); } } }; @@ -60,11 +60,11 @@ pub const RandomNoise = struct { pub const WildNoise = struct { r: std.rand.DefaultPrng, rand_buf: ?[]f32 = null, - allocator: ?*std.mem.Allocator = null, + allocator: ?std.mem.Allocator = null, cnt: usize = 0, pub fn init( - allocator: *std.mem.Allocator, + allocator: std.mem.Allocator, params: anytype, ) ?WildNoise { var r = std.rand.DefaultPrng.init(params.seed); @@ -73,7 +73,7 @@ pub const WildNoise = struct { var rand_buf = allocator.alloc(f32, params.fill_bytes) catch return null; for (rand_buf) |_, idx| { - rand_buf[idx] = @intToFloat(f32, r.random.int(u1)); + rand_buf[idx] = @intToFloat(f32, r.random().int(u1)); } return WildNoise{ @@ -99,7 +99,7 @@ pub const WildNoise = struct { bufs.out[0] = rand_buf[self.cnt]; self.cnt += 1; } else { - bufs.out[0] = @intToFloat(f32, self.r.random.int(u1)); + bufs.out[0] = @intToFloat(f32, self.r.random().int(u1)); } } }; @@ -112,15 +112,18 @@ pub const Write = struct { data: f32, pub fn init( - allocator: *std.mem.Allocator, + allocator: std.mem.Allocator, params: anytype, ) Write { + _ = allocator; return Write{ .data = params.data, }; } - pub fn deinit(self: *Write) void {} + pub fn deinit(self: *Write) void { + _ = self; + } pub fn run(self: *Write, bufs: *RunBuffers) void { bufs.out[0] = self.data; @@ -128,13 +131,13 @@ pub const Write = struct { }; pub const Embed = struct { - allocator: *std.mem.Allocator, + allocator: std.mem.Allocator, filepath: []const u8, sndfile: *c.SNDFILE = undefined, buf: []f32 = undefined, - pub fn init(allocator: *std.mem.Allocator, params: anytype) @This() { + pub fn init(allocator: std.mem.Allocator, params: anytype) @This() { return Embed{ .allocator = allocator, .filepath = params.path, @@ -163,7 +166,9 @@ pub const Embed = struct { self.buf = try self.allocator.alloc(f32, @intCast(usize, in_fmt.channels)); } - pub fn deinit(self: *@This()) void {} + pub fn deinit(self: *@This()) void { + _ = self; + } pub fn run(self: *@This(), bufs: *RunBuffers) void { const read_bytes = c.sf_readf_float(self.sndfile, self.buf.ptr, 1); diff --git a/src/image.zig b/src/image.zig index 4a01845..073ffc4 100644 --- a/src/image.zig +++ b/src/image.zig @@ -21,7 +21,7 @@ pub const ImageError = error{ /// Low level integration function with libsndfile. pub fn sopen( - allocator: *std.mem.Allocator, + allocator: std.mem.Allocator, path: []const u8, mode: i32, fmt: *c.SF_INFO, @@ -43,10 +43,10 @@ pub fn sopen( const frames_on_end = c.sf_seek(file, 0, c.SEEK_END); _ = c.sf_seek(file, 0, c.SEEK_SET); - std.testing.expectEqual(fmt.frames, frames_on_end); + try std.testing.expectEqual(fmt.frames, frames_on_end); const frames_on_end_by_end = c.sf_seek(file, frames_on_end, c.SEEK_SET); - std.testing.expectEqual(frames_on_end, frames_on_end_by_end); + try std.testing.expectEqual(frames_on_end, frames_on_end_by_end); log.debug("frames on end: {}, frame on end (2): {}\n", .{ frames_on_end, frames_on_end_by_end }); @@ -66,7 +66,7 @@ pub fn sseek(file: *c.SNDFILE, offset: usize) void { const offset_i64 = @intCast(i64, offset); const frames = c.sf_seek(file, offset_i64, c.SEEK_SET); const frames_current = c.sf_seek(file, 0, c.SEEK_CUR); - std.testing.expectEqual(frames, frames_current); + std.debug.assert(frames == frames_current); if (frames != offset_i64) { log.debug("failed to seek to {} (seeked {} frames, offset_i64={})\n", .{ offset, frames, offset_i64 }); @@ -74,7 +74,7 @@ pub fn sseek(file: *c.SNDFILE, offset: usize) void { } /// Caller owns the returned memory. -pub fn temporaryName(allocator: *std.mem.Allocator) ![]u8 { +pub fn temporaryName(allocator: std.mem.Allocator) ![]u8 { const template_start = "/temp/temp_"; const template = "/tmp/temp_XXXXXXXXXXXXXXXXXXXXX"; var nam = try allocator.alloc(u8, template.len); @@ -89,7 +89,7 @@ pub fn temporaryName(allocator: *std.mem.Allocator) ![]u8 { while (i < 100) : (i += 1) { // generate a random uppercase letter, that is, 65 + random number. for (fill) |_, f_idx| { - var idx = @intCast(u8, r.random.uintLessThan(u5, 24)); + var idx = @intCast(u8, r.random().uintLessThan(u5, 24)); var letter = @as(u8, 65) + idx; fill[f_idx] = letter; } @@ -97,7 +97,7 @@ pub fn temporaryName(allocator: *std.mem.Allocator) ![]u8 { // if we fail to access it, we assume it doesn't exist and return it. var tmp_file: std.fs.File = std.fs.cwd().openFile( nam, - .{ .read = true, .write = false }, + .{ .mode = .read_only }, ) catch |err| { if (err == error.FileNotFound) return nam else continue; }; @@ -122,7 +122,7 @@ pub fn mkSfInfo() c.SF_INFO { } pub const Image = struct { - allocator: *std.mem.Allocator, + allocator: std.mem.Allocator, /// Pointer to the underlying libsndfile's SNDFILE struct. sndfile: *c.SNDFILE, @@ -137,7 +137,7 @@ pub const Image = struct { curpath: []const u8, /// Open a BMP image for later. - pub fn open(allocator: *std.mem.Allocator, path: []const u8) !*Image { + pub fn open(allocator: std.mem.Allocator, path: []const u8) !*Image { var in_fmt = mkSfInfo(); var sndfile = try sopen(allocator, path, c.SFM_READ, &in_fmt); @@ -197,9 +197,7 @@ pub const Image = struct { } pub fn read(self: *Image, file_chans: c_int, buf: []f32) bool { - var file = file_opt.?; - - const n_read: c.sf_count_t = c.sf_readf_float(file, buf.ptr, 1); + const n_read: c.sf_count_t = c.sf_readf_float(self.sndfile, buf.ptr, 1); const buf_chans = @intCast(c_int, buf.len); var i = file_chans - 1; @@ -276,7 +274,7 @@ pub const Image = struct { } pub fn checkValid(self: *Image) !void { - var file = try std.fs.cwd().openFile(self.path, .{ .read = true }); + var file = try std.fs.cwd().openFile(self.path, .{ .mode = .read_only }); defer file.close(); // main bmp header: diff --git a/src/lang.zig b/src/lang.zig index 4c4f8f5..4c5973e 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -471,7 +471,7 @@ pub const CommandList = struct { list: CmdArrayList, const Self = @This(); - pub fn init(allocator: *std.mem.Allocator) Self { + pub fn init(allocator: std.mem.Allocator) Self { return .{ .list = CmdArrayList.init(allocator), }; @@ -486,13 +486,16 @@ pub const CommandList = struct { @field(Command.Tag, field.name); // if we find a match on the tag, we can get the type const typ = Command.tagToType(actual_tag); + _ = typ; - inline for (@typeInfo(typ).Struct.fields) |cmd_field| { - switch (cmd_field.field_type) { - []u8, []const u8 => self.list.allocator.destroy(@field(typ, cmd_field.name)), - else => {}, - } - } + // TODO fix + + //inline for (@typeInfo(typ).Struct.fields) |cmd_field| { + // switch (cmd_field.field_type) { + // []u8, []const u8 => self.list.allocator.destroy(@field(typ, cmd_field.name)), + // else => {}, + // } + //} } } } @@ -506,18 +509,20 @@ pub const CommandList = struct { /// A parser. pub const Lang = struct { - allocator: *std.mem.Allocator, + allocator: std.mem.Allocator, has_error: bool = false, line: usize = 0, - pub fn init(allocator: *std.mem.Allocator) Lang { + pub fn init(allocator: std.mem.Allocator) Lang { return Lang{ .allocator = allocator, }; } - pub fn deinit(self: *Lang) void {} + pub fn deinit(self: *Lang) void { + _ = self; + } pub fn reset(self: *Lang) void { self.has_error = false; @@ -534,7 +539,7 @@ pub const Lang = struct { fn parseCommandArguments( self: *@This(), comptime command_struct: type, - tok_it: *std.mem.TokenIterator, + tok_it: *std.mem.SplitIterator(u8), commands: *CommandList, ) !void { // Based on the command struct fields, we can parse the arguments. @@ -622,7 +627,7 @@ pub const Lang = struct { } pub fn parse(self: *Lang, data: []const u8) !CommandList { - var splitted_it = std.mem.split(data, ";"); + var splitted_it = std.mem.split(u8, data, ";"); var cmds = CommandList.init(self.allocator); errdefer cmds.deinit(); @@ -635,7 +640,7 @@ pub const Lang = struct { if (std.mem.startsWith(u8, stmt, "#")) continue; // TODO better tokenizer instead of just tokenize(" ")...maybe???? - var tok_it = std.mem.tokenize(stmt, " "); + var tok_it = std.mem.split(u8, stmt, " "); var cmd_opt = tok_it.next(); if (cmd_opt == null) { @@ -647,15 +652,14 @@ pub const Lang = struct { var found: bool = false; inline for (@typeInfo(Command).Struct.decls) |cmd_struct_decl| { - switch (cmd_struct_decl.data) { - .Type => |typ| switch (@typeInfo(typ)) { - .Struct => {}, - else => continue, - }, + const struct_name = cmd_struct_decl.name; + const cmd_struct_type = @field(Command, struct_name); + + switch (@typeInfo(@TypeOf(cmd_struct_type))) { + .Struct => {}, else => continue, } - const struct_name = cmd_struct_decl.name; comptime var lowered_command_name = [_]u8{0} ** struct_name.len; comptime { for (struct_name) |c, i| { @@ -675,7 +679,6 @@ pub const Lang = struct { if (std.mem.eql(u8, &lowered_command_name, command_string)) { found = true; - const cmd_struct_type = cmd_struct_decl.data.Type; try self.parseCommandArguments(cmd_struct_type, &tok_it, &cmds); } } @@ -699,8 +702,8 @@ test "noop" { var cmds = try lang.parse("noop;"); defer cmds.deinit(); - std.testing.expectEqual(cmds.list.items.len, 1); - std.testing.expectEqual(cmds.list.items[0].tag, .noop); + try std.testing.expectEqual(cmds.list.items.len, 1); + try std.testing.expectEqual(cmds.list.items[0].tag, .noop); } test "load, phaser, quicksave" { @@ -716,10 +719,10 @@ test "load, phaser, quicksave" { var cmds = try lang.parse(prog); defer cmds.deinit(); - std.testing.expectEqual(cmds.list.items.len, 3); - std.testing.expectEqual(cmds.list.items[0].tag, .load); - std.testing.expectEqual(cmds.list.items[1].tag, .phaser); - std.testing.expectEqual(cmds.list.items[2].tag, .quicksave); + try std.testing.expectEqual(cmds.list.items.len, 3); + try std.testing.expectEqual(cmds.list.items[0].tag, .load); + try std.testing.expectEqual(cmds.list.items[1].tag, .phaser); + try std.testing.expectEqual(cmds.list.items[2].tag, .quicksave); } test "load, phaser with errors, quicksave" { @@ -732,9 +735,5 @@ test "load, phaser with errors, quicksave" { \\quicksave; ; - var cmds = lang.parse(prog) catch |err| { - return; - }; - - unreachable; + try std.testing.expectError(error.ParseFail, lang.parse(prog)); } diff --git a/src/magick.zig b/src/magick.zig index 21f6d2d..c88ceba 100644 --- a/src/magick.zig +++ b/src/magick.zig @@ -29,6 +29,7 @@ pub const MagickContext = struct { } pub fn doErr(self: *MagickContext) !void { + _ = self; return error.WandError; } }; diff --git a/src/main.zig b/src/main.zig index c41d2e4..9045304 100644 --- a/src/main.zig +++ b/src/main.zig @@ -18,13 +18,13 @@ const readline = @cImport({ @cInclude("readline/history.h"); }); -fn wrapInCmdList(allocator: *std.mem.Allocator, cmd: *langs.Command) !langs.CommandList { +fn wrapInCmdList(allocator: std.mem.Allocator, cmd: *langs.Command) !langs.CommandList { var cmds = langs.CommandList.init(allocator); try cmds.append(cmd); return cmds; } -fn copyCommandToHeap(allocator: *std.mem.Allocator, command: langs.Command, comptime tag: langs.Command.Tag) !*langs.Command { +fn copyCommandToHeap(allocator: std.mem.Allocator, command: langs.Command, comptime tag: langs.Command.Tag) !*langs.Command { const CommandStruct = langs.Command.tagToType(tag); const casted = command.cast(CommandStruct).?; var heap_cmd = try allocator.create(CommandStruct); @@ -38,7 +38,7 @@ fn copyCommandToHeap(allocator: *std.mem.Allocator, command: langs.Command, comp return &heap_cmd.base; } -pub fn doRepl(allocator: *std.mem.Allocator, args_it: anytype) !void { +pub fn doRepl(allocator: std.mem.Allocator, args_it: anytype) !void { var stdout_file = std.io.getStdOut(); const stdout = &stdout_file.writer(); const scri_path = try (args_it.next(allocator) orelse @panic("expected scri path")); @@ -239,7 +239,7 @@ fn doHelp() void { log.debug("\tscritcher repl path_to_script.scri path_to_input_file.bmp\n", .{}); } -fn doRun(allocator: *std.mem.Allocator, args_it: anytype) !void { +fn doRun(allocator: std.mem.Allocator, args_it: anytype) !void { var lang = langs.Lang.init(allocator); defer lang.deinit(); diff --git a/src/plugin.zig b/src/plugin.zig index d046edb..8e88283 100644 --- a/src/plugin.zig +++ b/src/plugin.zig @@ -47,7 +47,7 @@ pub const Position = struct { /// Represents the starting context for a single plugin run. pub const Context = struct { - allocator: *std.mem.Allocator, + allocator: std.mem.Allocator, world: *c.LilvWorld, plugin: *const c.LilvPlugin, @@ -75,9 +75,11 @@ pub const RunContext = struct { instance: *c.LilvInstance, pub fn init( - allocator: *std.mem.Allocator, + allocator: std.mem.Allocator, plugin: *const c.LilvPlugin, ) !RunContext { + _ = allocator; // TODO batch RunBuffers? + var instance = c.lilv_plugin_instantiate(plugin, @as(f64, 44100), null); errdefer c.lilv_instance_free(instance); @@ -128,7 +130,7 @@ pub const RunContext = struct { } }; -pub fn makeContext(allocator: *std.mem.Allocator, plugin_uri: []const u8) !Context { +pub fn makeContext(allocator: std.mem.Allocator, plugin_uri: []const u8) !Context { const cstr_plugin_uri = try std.cstr.addNullByte(allocator, plugin_uri); defer allocator.free(cstr_plugin_uri); diff --git a/src/runner.zig b/src/runner.zig index 40684a3..eb41231 100644 --- a/src/runner.zig +++ b/src/runner.zig @@ -20,7 +20,7 @@ pub const RunError = error{ }; pub const Runner = struct { - allocator: *std.mem.Allocator, + allocator: std.mem.Allocator, /// The currently opened image in the runner image: ?*Image = null, @@ -30,7 +30,7 @@ pub const Runner = struct { args: []const [:0]u8, - pub fn init(allocator: *std.mem.Allocator, repl: bool) Runner { + pub fn init(allocator: std.mem.Allocator, repl: bool) Runner { return Runner{ .allocator = allocator, .repl = repl, @@ -164,6 +164,8 @@ pub const Runner = struct { // if N isn't a number, we just ignore that file const idx_str = entry.name[entry_gidx + 2 .. entry_pidx]; const idx = std.fmt.parseInt(usize, idx_str, 10) catch |err| { + log.debug("ignoring file {s}", .{@errorName(err)}); + break :blk {}; }; @@ -254,7 +256,7 @@ pub const Runner = struct { cmd: lang.Command, comptime tag: lang.Command.Tag, ) !void { - comptime const typ = lang.Command.tagToType(tag); + const typ = lang.Command.tagToType(tag); const command = cmd.cast(typ).?; const ctype = typ.command_type; switch (ctype) { @@ -315,6 +317,7 @@ pub const Runner = struct { cmds: lang.CommandList, debug_flag: bool, ) !void { + _ = debug_flag; for (cmds.list.items) |cmd| { cmd.print(); try self.runCommand(cmd.*); @@ -323,18 +326,15 @@ pub const Runner = struct { }; test "running noop" { - const allocator = std.heap.direct_allocator; + const allocator = std.testing.allocator; var cmds = lang.CommandList.init(allocator); defer cmds.deinit(); - var cmd_ptr = try allocator.create(lang.Command); - cmd_ptr.* = lang.Command{ - .command = .Noop, - .args = lang.ArgList.init(allocator), - }; - try cmds.append(cmd_ptr); + var command = lang.Command{ .tag = .noop }; + var noop = lang.Command.Noop{ .base = command }; + try cmds.append(&noop.base); - var runner = Runner.init(allocator); + var runner = Runner.init(allocator, false); defer runner.deinit(); try runner.runCommands(cmds, false); From 1987c4d497d479fe81367fa7bef9c7768518a40d Mon Sep 17 00:00:00 2001 From: Luna Date: Wed, 27 Apr 2022 20:01:14 -0300 Subject: [PATCH 33/43] fix command parsing --- src/lang.zig | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/lang.zig b/src/lang.zig index 4c5973e..98b1e77 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -479,7 +479,7 @@ pub const CommandList = struct { pub fn deinit(self: *Self) void { for (self.list.items) |cmd_ptr| { - self.list.allocator.destroy(cmd_ptr); + //self.list.allocator.destroy(cmd_ptr); inline for (@typeInfo(Command.Tag).Enum.fields) |field| { if (cmd_ptr.tag == @field(Command.Tag, field.name)) { const actual_tag = @@ -530,9 +530,9 @@ pub const Lang = struct { } fn doError(self: *Lang, comptime fmt: []const u8, args: anytype) void { - log.debug("ERROR! at line {}: ", .{self.line}); - log.debug(fmt, args); - log.debug("\n", .{}); + log.err("ERROR! at line {}: ", .{self.line}); + log.err(fmt, args); + log.err("\n", .{}); self.has_error = true; } @@ -655,7 +655,16 @@ pub const Lang = struct { const struct_name = cmd_struct_decl.name; const cmd_struct_type = @field(Command, struct_name); - switch (@typeInfo(@TypeOf(cmd_struct_type))) { + const info_of_info = @typeInfo(@TypeOf(cmd_struct_type)); + + switch (info_of_info) { + .Type => {}, + else => continue, + } + + const info = @typeInfo(cmd_struct_type); + + switch (info) { .Struct => {}, else => continue, } @@ -677,7 +686,7 @@ pub const Lang = struct { // Attempting to use ComptimeHashMap hits compiler bugs and I'm // not sure if we can map strings to *types* in it. - if (std.mem.eql(u8, &lowered_command_name, command_string)) { + if ((!found) and std.mem.eql(u8, &lowered_command_name, command_string)) { found = true; try self.parseCommandArguments(cmd_struct_type, &tok_it, &cmds); } From 2796b654e54e96db6f51824616eaaef22d0edeba Mon Sep 17 00:00:00 2001 From: Luna Date: Thu, 28 Apr 2022 00:08:52 -0300 Subject: [PATCH 34/43] port main() code path to latest zig --- .gitignore | 1 + src/image.zig | 2 +- src/main.zig | 15 +++++++-------- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.gitignore b/.gitignore index 44f7213..346c11d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ zig-cache/ +zig-out/ *.mp3 *.wav build_runner.zig diff --git a/src/image.zig b/src/image.zig index 073ffc4..45aa6da 100644 --- a/src/image.zig +++ b/src/image.zig @@ -161,7 +161,7 @@ pub const Image = struct { var in_fmt = mkSfInfo(); // clone sndfile var sndfile = try sopen(self.allocator, self.curpath, c.SFM_READ, &in_fmt); - std.testing.expectEqual(self.frames, @intCast(usize, in_fmt.frames)); + std.debug.assert(self.frames == @intCast(usize, in_fmt.frames)); var image = try self.allocator.create(Image); diff --git a/src/main.zig b/src/main.zig index 9045304..ee269c1 100644 --- a/src/main.zig +++ b/src/main.zig @@ -41,7 +41,7 @@ fn copyCommandToHeap(allocator: std.mem.Allocator, command: langs.Command, compt pub fn doRepl(allocator: std.mem.Allocator, args_it: anytype) !void { var stdout_file = std.io.getStdOut(); const stdout = &stdout_file.writer(); - const scri_path = try (args_it.next(allocator) orelse @panic("expected scri path")); + const scri_path = (args_it.next() orelse @panic("expected scri path")); errdefer allocator.free(scri_path); defer allocator.free(scri_path); @@ -246,8 +246,7 @@ fn doRun(allocator: std.mem.Allocator, args_it: anytype) !void { var runner = runners.Runner.init(allocator, false); defer runner.deinit(); - const scri_path = try (args_it.next(allocator) orelse @panic("run: expected scri path")); - defer allocator.free(scri_path); + const scri_path = (args_it.next() orelse @panic("run: expected scri path")); var file = try std.fs.cwd().openFile(scri_path, .{}); defer file.close(); @@ -270,18 +269,18 @@ pub fn main() !void { defer { _ = allocator_instance.deinit(); } - const allocator = &allocator_instance.allocator; + const allocator = allocator_instance.allocator(); - var args_it = std.process.args(); + var args_it = try std.process.argsWithAllocator(allocator); + defer args_it.deinit(); _ = args_it.skip(); - const cli_command_opt = args_it.next(allocator); + const cli_command_opt = args_it.next(); if (cli_command_opt == null) { return doHelp(); } - const cli_command = try cli_command_opt.?; - defer allocator.free(cli_command); + const cli_command = cli_command_opt.?; if (std.mem.eql(u8, cli_command, "help")) { return doHelp(); From 6b2ce7e4250719ac4b15158ec289bd3fcf645fb5 Mon Sep 17 00:00:00 2001 From: Luna Date: Thu, 28 Apr 2022 00:28:07 -0300 Subject: [PATCH 35/43] properly fix memleaks --- src/lang.zig | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/src/lang.zig b/src/lang.zig index 98b1e77..5ded695 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -479,25 +479,24 @@ pub const CommandList = struct { pub fn deinit(self: *Self) void { for (self.list.items) |cmd_ptr| { - //self.list.allocator.destroy(cmd_ptr); inline for (@typeInfo(Command.Tag).Enum.fields) |field| { if (cmd_ptr.tag == @field(Command.Tag, field.name)) { const actual_tag = @field(Command.Tag, field.name); // if we find a match on the tag, we can get the type const typ = Command.tagToType(actual_tag); - _ = typ; - // TODO fix - - //inline for (@typeInfo(typ).Struct.fields) |cmd_field| { - // switch (cmd_field.field_type) { - // []u8, []const u8 => self.list.allocator.destroy(@field(typ, cmd_field.name)), - // else => {}, - // } - //} + const inner_command = cmd_ptr.cast(typ).?; + inline for (@typeInfo(typ).Struct.fields) |cmd_field| { + switch (cmd_field.field_type) { + []u8, []const u8 => self.list.allocator.free(@field(inner_command, cmd_field.name)), + else => {}, + } + } } } + + self.list.allocator.destroy(cmd_ptr); } self.list.deinit(); } From ef6c68705dcdaa724d97519390e41b8102e1eb4d Mon Sep 17 00:00:00 2001 From: Luna Date: Sat, 8 Oct 2022 15:05:15 -0300 Subject: [PATCH 36/43] port to latest zig --- build.zig | 8 ++++---- src/lang.zig | 12 ++++++------ src/runner.zig | 11 +++++++---- 3 files changed, 17 insertions(+), 14 deletions(-) diff --git a/build.zig b/build.zig index f7b08f9..ad6f87d 100644 --- a/build.zig +++ b/build.zig @@ -12,8 +12,8 @@ fn setupLinks(step: *builds.LibExeObjStep) void { step.linkSystemLibrary("GraphicsMagickWand"); step.linkSystemLibrary("GraphicsMagick"); - step.addIncludeDir("/usr/include/GraphicsMagick"); - step.addIncludeDir("/usr/include"); + step.addIncludePath("/usr/include/GraphicsMagick"); + step.addIncludePath("/usr/include"); const possible_lilv_include_dirs = [_][]const u8{ "/usr/include/lilv-0/lilv", @@ -24,7 +24,7 @@ fn setupLinks(step: *builds.LibExeObjStep) void { for (possible_lilv_include_dirs) |possible_lilv_dir| { var possible_dir = std.fs.cwd().openDir(possible_lilv_dir, .{}) catch |err| { - std.debug.print("possible lilv {s} fail: {s}\n", .{ possible_lilv_dir, err }); + std.debug.print("possible lilv {s} fail: {s}\n", .{ possible_lilv_dir, @errorName(err) }); continue; }; @@ -32,7 +32,7 @@ fn setupLinks(step: *builds.LibExeObjStep) void { found_any_lilv = true; std.debug.print("found lilv at '{s}'\n", .{possible_lilv_dir}); - step.addIncludeDir(possible_lilv_dir); + step.addIncludePath(possible_lilv_dir); } if (!found_any_lilv) { diff --git a/src/lang.zig b/src/lang.zig index 5ded695..e4a742d 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -94,7 +94,7 @@ pub const Command = struct { rotate, }; - pub fn tagToType(tag: Tag) type { + pub fn tagToType(comptime tag: Tag) type { return switch (tag) { .noop => Noop, .load => Load, @@ -147,7 +147,7 @@ pub const Command = struct { } pub fn print(base: *const @This()) void { - log.debug("tag: {s}\n", .{base.tag}); + log.debug("tag: {}\n", .{base.tag}); } pub const Noop = struct { @@ -529,9 +529,9 @@ pub const Lang = struct { } fn doError(self: *Lang, comptime fmt: []const u8, args: anytype) void { - log.err("ERROR! at line {}: ", .{self.line}); - log.err(fmt, args); - log.err("\n", .{}); + log.warn("ERROR! at line {}: ", .{self.line}); + log.warn(fmt, args); + log.warn("\n", .{}); self.has_error = true; } @@ -622,7 +622,7 @@ pub const Lang = struct { cmd.base.tag = command_struct.base_tag; const command = cmd.base.cast(command_struct).?; - log.debug("cmd: {s}\n", .{command}); + log.debug("cmd: {}\n", .{command}); } pub fn parse(self: *Lang, data: []const u8) !CommandList { diff --git a/src/runner.zig b/src/runner.zig index eb41231..969c469 100644 --- a/src/runner.zig +++ b/src/runner.zig @@ -57,6 +57,7 @@ pub const Runner = struct { } fn resolveArg(self: *Runner, load_path: []const u8) ![]const u8 { + std.debug.assert(load_path.len > 0); if (load_path[0] == ':') { // parse the index from 1 to end var index = try std.fmt.parseInt(usize, load_path[1..], 10); @@ -131,7 +132,7 @@ pub const Runner = struct { const basename = std.fs.path.basename(image.path); const dirname = std.fs.path.dirname(image.path).?; - var dir = try std.fs.cwd().openDir(dirname, .{ .iterate = true }); + var dir = try std.fs.cwd().openIterableDir(dirname, .{}); defer dir.close(); const period_idx = std.mem.lastIndexOf(u8, basename, ".").?; @@ -199,11 +200,11 @@ pub const Runner = struct { defer self.allocator.free(out_path); try image.saveTo(out_path); - var proc = try std.ChildProcess.init( + var proc = std.ChildProcess.init( &[_][]const u8{ runqs.program, out_path }, self.allocator, ); - defer proc.deinit(); + //defer proc.deinit(); log.debug("running '{s} {s}'\n", .{ runqs.program, out_path }); _ = try proc.spawnAndWait(); @@ -331,7 +332,9 @@ test "running noop" { defer cmds.deinit(); var command = lang.Command{ .tag = .noop }; - var noop = lang.Command.Noop{ .base = command }; + + var noop = try allocator.create(lang.Command.Noop); + noop.* = lang.Command.Noop{ .base = command }; try cmds.append(&noop.base); var runner = Runner.init(allocator, false); From 43dad638f20280184dd14eb6b968a0177f0a6b27 Mon Sep 17 00:00:00 2001 From: Luna Date: Sat, 8 Oct 2022 15:06:14 -0300 Subject: [PATCH 37/43] use stage1 --- build.zig | 1 + 1 file changed, 1 insertion(+) diff --git a/build.zig b/build.zig index ad6f87d..520aeb9 100644 --- a/build.zig +++ b/build.zig @@ -45,6 +45,7 @@ pub fn build(b: *Builder) void { const mode = b.standardReleaseOptions(); const exe = b.addExecutable("scritcher", "src/main.zig"); exe.setBuildMode(mode); + exe.use_stage1 = true; exe.install(); setupLinks(exe); From 0f6ac055a484f2e499be79b1e266211c93fc7659 Mon Sep 17 00:00:00 2001 From: Luna Date: Sat, 8 Oct 2022 15:14:56 -0300 Subject: [PATCH 38/43] remove extra newlines from log calls --- src/bmp_valid.zig | 2 +- src/custom.zig | 2 +- src/image.zig | 40 ++++++++++++++++++++-------------------- src/lang.zig | 7 +++---- src/lv2_helpers.zig | 4 ++-- src/magick.zig | 4 ++-- src/main.zig | 16 ++++++++-------- src/plugin.zig | 4 ++-- src/runner.zig | 13 +++++++------ 9 files changed, 46 insertions(+), 46 deletions(-) diff --git a/src/bmp_valid.zig b/src/bmp_valid.zig index 55970b8..6e256e8 100644 --- a/src/bmp_valid.zig +++ b/src/bmp_valid.zig @@ -19,7 +19,7 @@ pub fn magicValid(magic: []const u8) !void { } if (!valid) { - log.debug("\tINVALID HEADER: '{s}'\n", .{magic}); + log.debug("\tINVALID HEADER: '{s}'", .{magic}); return BMPValidError.InvalidMagic; } } diff --git a/src/custom.zig b/src/custom.zig index 4e48d6a..ffb129c 100644 --- a/src/custom.zig +++ b/src/custom.zig @@ -180,7 +180,7 @@ pub const Embed = struct { if (read_bytes < 0) { const st: i32 = c.sf_error(self.sndfile); - log.debug("Failed to read {s} ({s})\n", .{ + log.debug("Failed to read {s} ({s})", .{ self.filepath, c.sf_error_number(st), }); diff --git a/src/image.zig b/src/image.zig index 45aa6da..6a7481c 100644 --- a/src/image.zig +++ b/src/image.zig @@ -33,7 +33,7 @@ pub fn sopen( const st: i32 = c.sf_error(file); if (st != 0) { - log.debug("Failed to open {s} ({s})\n", .{ + log.debug("Failed to open {s} ({s})", .{ path, c.sf_error_number(st), }); @@ -48,7 +48,7 @@ pub fn sopen( const frames_on_end_by_end = c.sf_seek(file, frames_on_end, c.SEEK_SET); try std.testing.expectEqual(frames_on_end, frames_on_end_by_end); - log.debug("frames on end: {}, frame on end (2): {}\n", .{ frames_on_end, frames_on_end_by_end }); + log.debug("frames on end: {}, frame on end (2): {}", .{ frames_on_end, frames_on_end_by_end }); return file.?; } @@ -57,7 +57,7 @@ pub fn swrite(file: *c.SNDFILE, buf: [*]f32, frames: i64) !void { const count = c.sf_writef_float(file, buf, frames); if (count != frames) { - log.debug("Wanted to write {}, got {}\n", .{ frames, count }); + log.debug("Wanted to write {}, got {}", .{ frames, count }); return ImageError.WriteFail; } } @@ -69,7 +69,7 @@ pub fn sseek(file: *c.SNDFILE, offset: usize) void { std.debug.assert(frames == frames_current); if (frames != offset_i64) { - log.debug("failed to seek to {} (seeked {} frames, offset_i64={})\n", .{ offset, frames, offset_i64 }); + log.debug("failed to seek to {} (seeked {} frames, offset_i64={})", .{ offset, frames, offset_i64 }); } } @@ -182,7 +182,7 @@ pub const Image = struct { pub fn close(self: *Image) void { var st: i32 = c.sf_close(self.sndfile); if (st != 0) { - log.debug("Failed to close {s} ({s})\n", .{ + log.debug("Failed to close {s} ({s})", .{ self.path, c.sf_error_number(st), }); @@ -227,7 +227,7 @@ pub const Image = struct { sseek(out_file, start); while (i <= end) : (i += buf.len) { - log.debug("\t\ti={d}, buf.len={d}, end={d}\n", .{ i, buf.len, end }); + log.debug("\t\ti={d}, buf.len={d}, end={d}", .{ i, buf.len, end }); sseek(self.sndfile, i); sseek(out_file, i); @@ -253,7 +253,7 @@ pub const Image = struct { fn getSeekPos(self: *Image, position: plugins.Position) plugins.SeekPos { const file_end = self.frames; var seek_pos = position.seekPos(file_end); - log.debug("\tstart {d} end {d}\n", .{ seek_pos.start, seek_pos.end }); + log.debug("\tstart {d} end {d}", .{ seek_pos.start, seek_pos.end }); return seek_pos; } @@ -266,7 +266,7 @@ pub const Image = struct { self.curpath = path; self.frames = @intCast(usize, in_fmt.frames); - log.debug("\timage: reopened on '{s}' (frames={d}, fmt.frames={d})\n", .{ + log.debug("\timage: reopened on '{s}' (frames={d}, fmt.frames={d})", .{ self.curpath, self.frames, in_fmt.frames, @@ -309,12 +309,12 @@ pub const Image = struct { defer ctx.allocator.free(ports); if (ctx.n_audio_in > 2) { - log.debug("plugin <{s}> has more than two inputs.\n", .{plugin_uri}); + log.debug("plugin <{s}> has more than two inputs.", .{plugin_uri}); return ImageError.InvalidPlugin; } if (ctx.n_audio_out > 2) { - log.debug("plugin <{s}> has more than two outputs.\n", .{plugin_uri}); + log.debug("plugin <{s}> has more than two outputs.", .{plugin_uri}); return ImageError.InvalidPlugin; } @@ -326,14 +326,14 @@ pub const Image = struct { var sym = c.lilv_new_string(ctx.world, sym_cstr.ptr); const port = c.lilv_plugin_get_port_by_symbol(ctx.plugin, sym) orelse { - log.debug("assert fail: symbol {s} not found on port\n", .{param.sym}); + log.debug("assert fail: symbol {s} not found on port", .{param.sym}); return ImageError.InvalidSymbol; }; c.lilv_node_free(sym); var idx = c.lilv_port_get_index(ctx.plugin, port); - log.debug("\tset sym={s}, idx={d} to val={}\n", .{ + log.debug("\tset sym={s}, idx={d} to val={}", .{ param.sym, idx, param.value, @@ -344,7 +344,7 @@ pub const Image = struct { // now we need to generate a temporary file and put the output of // running the plugin on that file var tmpnam = try temporaryName(self.allocator); - log.debug("\trunning plugin from '{s}' to '{s}'\n", .{ self.curpath, tmpnam }); + log.debug("\trunning plugin from '{s}' to '{s}'", .{ self.curpath, tmpnam }); var out_fmt = mkSfInfo(); var out_file = try sopen(self.allocator, tmpnam, c.SFM_WRITE, &out_fmt); @@ -377,7 +377,7 @@ pub const Image = struct { sseek(self.sndfile, seek_pos.start); var i: usize = seek_pos.start; - log.debug("\tseek pos start: {d} end: {d}\n", .{ seek_pos.start, seek_pos.end }); + log.debug("\tseek pos start: {d} end: {d}", .{ seek_pos.start, seek_pos.end }); var inbuf = &rctx.buffers.in; var outbuf = &rctx.buffers.out; @@ -388,7 +388,7 @@ pub const Image = struct { const read_bytes = c.sf_readf_float(self.sndfile, inbuf, 1); if (read_bytes == 0) { - log.debug("WARN! reached EOF at idx={d}\n", .{i}); + log.debug("WARN! reached EOF at idx={d}", .{i}); break; } @@ -417,11 +417,11 @@ pub const Image = struct { try self.checkValid(); var time_taken = timer.read(); - log.debug("\ttook {d:.2}ms running plugin\n", .{time_taken / std.time.us_per_ms}); + log.debug("\ttook {d:.2}ms running plugin", .{time_taken / std.time.us_per_ms}); } pub fn saveTo(self: *Image, out_path: []const u8) !void { - log.debug("\timg: copy from '{s}' to '{s}'\n", .{ self.curpath, out_path }); + log.debug("\timg: copy from '{s}' to '{s}'", .{ self.curpath, out_path }); try std.fs.copyFileAbsolute(self.curpath, out_path, .{}); } @@ -449,7 +449,7 @@ pub const Image = struct { // the code here is a copypaste of runPlugin() without the specific // lilv things. var tmpnam = try temporaryName(self.allocator); - log.debug("\trunning CUSTOM plugin from '{s}' to '{s}'\n", .{ self.curpath, tmpnam }); + log.debug("\trunning CUSTOM plugin from '{s}' to '{s}'", .{ self.curpath, tmpnam }); var out_fmt = mkSfInfo(); var out_file = try sopen(self.allocator, tmpnam, c.SFM_WRITE, &out_fmt); @@ -476,7 +476,7 @@ pub const Image = struct { sseek(self.sndfile, seek_pos.start); var i: usize = seek_pos.start; - log.debug("\tseek pos start: {d} end: {d}\n", .{ seek_pos.start, seek_pos.end }); + log.debug("\tseek pos start: {d} end: {d}", .{ seek_pos.start, seek_pos.end }); var inbuf = &bufs.in; var outbuf = &bufs.out; @@ -484,7 +484,7 @@ pub const Image = struct { while (i <= seek_pos.end) : (i += 1) { const read_bytes = c.sf_readf_float(self.sndfile, inbuf, 1); if (read_bytes == 0) { - log.debug("WARN! reached EOF at idx={d}\n", .{i}); + log.debug("WARN! reached EOF at idx={d}", .{i}); break; } diff --git a/src/lang.zig b/src/lang.zig index e4a742d..08346ff 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -147,7 +147,7 @@ pub const Command = struct { } pub fn print(base: *const @This()) void { - log.debug("tag: {}\n", .{base.tag}); + log.debug("tag: {}", .{base.tag}); } pub const Noop = struct { @@ -531,7 +531,6 @@ pub const Lang = struct { fn doError(self: *Lang, comptime fmt: []const u8, args: anytype) void { log.warn("ERROR! at line {}: ", .{self.line}); log.warn(fmt, args); - log.warn("\n", .{}); self.has_error = true; } @@ -610,7 +609,7 @@ pub const Lang = struct { else => @compileError("Invalid parameter type (" ++ @typeName(cmd_field.field_type) ++ ") left on command struct " ++ @typeName(command_struct) ++ "."), }; - log.debug("parsing {s}, arg of type {s} => {any}\n", .{ + log.debug("parsing {s}, arg of type {s} => {any}", .{ @typeName(command_struct), @typeName(@TypeOf(argument_value)), argument_value, @@ -622,7 +621,7 @@ pub const Lang = struct { cmd.base.tag = command_struct.base_tag; const command = cmd.base.cast(command_struct).?; - log.debug("cmd: {}\n", .{command}); + log.debug("cmd: {}", .{command}); } pub fn parse(self: *Lang, data: []const u8) !CommandList { diff --git a/src/lv2_helpers.zig b/src/lv2_helpers.zig index 62570df..82c961d 100644 --- a/src/lv2_helpers.zig +++ b/src/lv2_helpers.zig @@ -120,7 +120,7 @@ pub fn setupPorts(ctx: *plugin.Context) ![]Port { if (c.lilv_port_is_a(ctx.plugin, lport, lv2_InputPort)) { port.is_input = true; } else if (!c.lilv_port_is_a(ctx.plugin, lport, lv2_OutputPort) and !port.optional) { - log.debug("Port {d} is neither input or output\n", .{i}); + log.debug("Port {d} is neither input or output", .{i}); return error.UnassignedIOPort; } @@ -136,7 +136,7 @@ pub fn setupPorts(ctx: *plugin.Context) ![]Port { ctx.n_audio_out += 1; } } else if (!port.optional) { - log.debug("Port {d} has unsupported type\n", .{i}); + log.debug("Port {d} has unsupported type", .{i}); return error.UnsupportedPortType; } } diff --git a/src/magick.zig b/src/magick.zig index c88ceba..c6adf3c 100644 --- a/src/magick.zig +++ b/src/magick.zig @@ -41,7 +41,7 @@ fn magickLoad(image: *Image) !MagickContext { var curpath = try std.cstr.addNullByte(image.allocator, image.curpath); defer image.allocator.free(curpath); - log.debug("loading '{s}'\n", .{curpath}); + log.debug("loading '{s}'", .{curpath}); if (mc.MagickReadImage(mctx.wand, curpath.ptr) != 1) return error.MagickReadFail; @@ -61,7 +61,7 @@ fn magickSave(image: *Image, wand: *mc.MagickWand) !void { if (mc.MagickWriteImage(wand, c_tmpnam.ptr) != 1) return error.MagickWriteFail; - log.debug("OK\n", .{}); + log.debug("OK", .{}); try image.reopen(tmpnam); } diff --git a/src/main.zig b/src/main.zig index ee269c1..083b204 100644 --- a/src/main.zig +++ b/src/main.zig @@ -134,7 +134,7 @@ pub fn doRepl(allocator: std.mem.Allocator, args_it: anytype) !void { var rd_line = readline.readline("> "); if (rd_line == null) { - log.debug("leaving from eof\n", .{}); + log.debug("leaving from eof", .{}); break; } readline.add_history(rd_line); @@ -202,14 +202,14 @@ pub fn doRepl(allocator: std.mem.Allocator, args_it: anytype) !void { try printer.printList(cmds, stream); continue; } else if (std.mem.eql(u8, line, "quit") or std.mem.eql(u8, line, "q")) { - log.debug("leaving\n", .{}); + log.debug("leaving", .{}); break; } else if (std.mem.startsWith(u8, line, "#")) { continue; } var cmds_parsed = lang.parse(line) catch |err| { - log.debug("repl: error while parsing: {}\n", .{err}); + log.debug("repl: error while parsing: {}", .{err}); continue; }; @@ -233,10 +233,10 @@ pub fn doRepl(allocator: std.mem.Allocator, args_it: anytype) !void { } fn doHelp() void { - log.debug("scritcher!\n", .{}); - log.debug("usage: scritcher [run|help|repl]\n", .{}); - log.debug("\tscritcher run path_to_script.scri path_to_input_file.bmp\n", .{}); - log.debug("\tscritcher repl path_to_script.scri path_to_input_file.bmp\n", .{}); + log.debug("scritcher!", .{}); + log.debug("usage: scritcher [run|help|repl]", .{}); + log.debug("\tscritcher run path_to_script.scri path_to_input_file.bmp", .{}); + log.debug("\tscritcher repl path_to_script.scri path_to_input_file.bmp", .{}); } fn doRun(allocator: std.mem.Allocator, args_it: anytype) !void { @@ -289,7 +289,7 @@ pub fn main() !void { } else if (std.mem.eql(u8, cli_command, "run")) { return try doRun(allocator, &args_it); } else { - log.debug("unknown command: '{s}'\n", .{cli_command}); + log.debug("unknown command: '{s}'", .{cli_command}); return error.UnknownCommand; } } diff --git a/src/plugin.zig b/src/plugin.zig index 8e88283..b0fb504 100644 --- a/src/plugin.zig +++ b/src/plugin.zig @@ -140,7 +140,7 @@ pub fn makeContext(allocator: std.mem.Allocator, plugin_uri: []const u8) !Contex c.lilv_world_load_all(world); var uri: *c.LilvNode = c.lilv_new_uri(world, cstr_plugin_uri.ptr) orelse { - log.debug("Invalid plugin URI <{s}>\n", .{plugin_uri}); + log.debug("Invalid plugin URI <{s}>", .{plugin_uri}); return ImageError.InvalidPlugin; }; defer c.lilv_node_free(uri); @@ -148,7 +148,7 @@ pub fn makeContext(allocator: std.mem.Allocator, plugin_uri: []const u8) !Contex const plugins: *const c.LilvPlugins = c.lilv_world_get_all_plugins(world).?; var plugin: *const c.LilvPlugin = c.lilv_plugins_get_by_uri(plugins, uri) orelse { - log.debug("Plugin <{s}> not found\n", .{plugin_uri}); + log.debug("Plugin <{s}> not found", .{plugin_uri}); return ImageError.UnknownPlugin; }; diff --git a/src/runner.zig b/src/runner.zig index 969c469..76f54a0 100644 --- a/src/runner.zig +++ b/src/runner.zig @@ -71,9 +71,10 @@ pub const Runner = struct { if (self.repl) index += 3 else index += 3; for (self.args) |arg, idx| { - log.debug("arg{d} = {s}\n", .{ idx, arg }); + log.debug("arg{d} = {s}", .{ idx, arg }); } - log.debug("fetch arg idx={d}, val={s}\n", .{ index, self.args[index] }); + log.debug("fetch arg idx={d}", .{index}); + log.debug("fetch arg val={s}", .{self.args[index]}); return self.args[index]; } else { return load_path; @@ -93,7 +94,7 @@ pub const Runner = struct { fn loadCmd(self: *Runner, path_or_argidx: []const u8) !void { const load_path = try self.resolveArgPath(path_or_argidx); - log.debug("\tload path: {s}\n", .{load_path}); + log.debug("\tload path: {s}", .{load_path}); // we could use ImageMagick to convert from X to BMP // but i can't find an easy way to do things in memory. @@ -103,7 +104,7 @@ pub const Runner = struct { // krita/gimp and make it export a bmp and while in the program you can // apply filters, etc. if (!std.mem.endsWith(u8, load_path, ".bmp") and !std.mem.endsWith(u8, load_path, ".ppm")) { - log.debug("Only BMP files are allowed to be loaded. Got path '{s}'\n", .{load_path}); + log.debug("Only BMP files are allowed to be loaded. Got path '{s}'", .{load_path}); return RunError.NoBMP; } @@ -118,7 +119,7 @@ pub const Runner = struct { if (self.image) |image| { return image; } else { - log.debug("image is required!\n", .{}); + log.debug("image is required!", .{}); return RunError.ImageRequired; } } @@ -206,7 +207,7 @@ pub const Runner = struct { ); //defer proc.deinit(); - log.debug("running '{s} {s}'\n", .{ runqs.program, out_path }); + log.debug("running '{s} {s}'", .{ runqs.program, out_path }); _ = try proc.spawnAndWait(); } From ed67a52b151d8531bbe81e783d383864ffc914c5 Mon Sep 17 00:00:00 2001 From: Luna Date: Fri, 4 Aug 2023 21:34:17 -0300 Subject: [PATCH 39/43] fixes for some version of zig --- build.zig | 1 - src/lang.zig | 6 +++--- src/printer.zig | 4 ++-- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/build.zig b/build.zig index 520aeb9..ad6f87d 100644 --- a/build.zig +++ b/build.zig @@ -45,7 +45,6 @@ pub fn build(b: *Builder) void { const mode = b.standardReleaseOptions(); const exe = b.addExecutable("scritcher", "src/main.zig"); exe.setBuildMode(mode); - exe.use_stage1 = true; exe.install(); setupLinks(exe); diff --git a/src/lang.zig b/src/lang.zig index 08346ff..ca5fbec 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -488,7 +488,7 @@ pub const CommandList = struct { const inner_command = cmd_ptr.cast(typ).?; inline for (@typeInfo(typ).Struct.fields) |cmd_field| { - switch (cmd_field.field_type) { + switch (cmd_field.type) { []u8, []const u8 => self.list.allocator.free(@field(inner_command, cmd_field.name)), else => {}, } @@ -576,7 +576,7 @@ pub const Lang = struct { } const arg = maybe_arg.?; - const arg_value = switch (cmd_field.field_type) { + const arg_value = switch (cmd_field.type) { f32 => try std.fmt.parseFloat(f32, arg), u64 => try std.fmt.parseInt(u64, arg, 10), usize => try std.fmt.parseInt(usize, arg, 10), @@ -601,7 +601,7 @@ pub const Lang = struct { } const arg = arg_opt.?; - const argument_value = switch (cmd_field.field_type) { + const argument_value = switch (cmd_field.type) { usize => try std.fmt.parseInt(usize, arg, 10), i32 => try std.fmt.parseInt(i32, arg, 10), f32 => try std.fmt.parseFloat(f32, arg), diff --git a/src/printer.zig b/src/printer.zig index a851602..b3da89b 100644 --- a/src/printer.zig +++ b/src/printer.zig @@ -7,9 +7,9 @@ fn printCommandWithParams(stream: anytype, command: anytype) !void { const Parameters = @TypeOf(command.parameters); try stream.print(" {d} {d}", .{ command.split, command.index }); inline for (@typeInfo(Parameters).Struct.fields) |field| { - if (field.field_type == f32 or field.field_type == f64) { + if (field.type == f32 or field.type == f64) { try stream.print(" {}", .{@field(command.parameters, field.name)}); - } else if (field.field_type == usize or field.field_type == u64) { + } else if (field.type == usize or field.type == u64) { try stream.print(" {d}", .{@field(command.parameters, field.name)}); } else { try stream.print(" {s}", .{@field(command.parameters, field.name)}); From 7cc93c2976208ce6070b6d12843b6e2268061fc0 Mon Sep 17 00:00:00 2001 From: Luna Date: Fri, 4 Aug 2023 21:34:51 -0300 Subject: [PATCH 40/43] zig fmt --- src/custom.zig | 10 +++++----- src/image.zig | 26 +++++++++++++------------- src/lang.zig | 2 +- src/lv2_helpers.zig | 2 +- src/main.zig | 4 ++-- src/plugin.zig | 4 ++-- src/runner.zig | 2 +- 7 files changed, 25 insertions(+), 25 deletions(-) diff --git a/src/custom.zig b/src/custom.zig index ffb129c..d942a3b 100644 --- a/src/custom.zig +++ b/src/custom.zig @@ -24,7 +24,7 @@ pub const RandomNoise = struct { if (params.fill_bytes > 0) { var rand_buf = allocator.alloc(f32, params.fill_bytes) catch return null; - for (rand_buf) |_, idx| { + for (rand_buf, 0..) |_, idx| { rand_buf[idx] = r.random().float(f32); } @@ -72,8 +72,8 @@ pub const WildNoise = struct { if (params.fill_bytes > 0) { var rand_buf = allocator.alloc(f32, params.fill_bytes) catch return null; - for (rand_buf) |_, idx| { - rand_buf[idx] = @intToFloat(f32, r.random().int(u1)); + for (rand_buf, 0..) |_, idx| { + rand_buf[idx] = @as(f32, @floatFromInt(r.random().int(u1))); } return WildNoise{ @@ -99,7 +99,7 @@ pub const WildNoise = struct { bufs.out[0] = rand_buf[self.cnt]; self.cnt += 1; } else { - bufs.out[0] = @intToFloat(f32, self.r.random().int(u1)); + bufs.out[0] = @as(f32, @floatFromInt(self.r.random().int(u1))); } } }; @@ -163,7 +163,7 @@ pub const Embed = struct { image.sseek(self.sndfile, 0); - self.buf = try self.allocator.alloc(f32, @intCast(usize, in_fmt.channels)); + self.buf = try self.allocator.alloc(f32, @as(usize, @intCast(in_fmt.channels))); } pub fn deinit(self: *@This()) void { diff --git a/src/image.zig b/src/image.zig index 6a7481c..47be1cd 100644 --- a/src/image.zig +++ b/src/image.zig @@ -63,7 +63,7 @@ pub fn swrite(file: *c.SNDFILE, buf: [*]f32, frames: i64) !void { } pub fn sseek(file: *c.SNDFILE, offset: usize) void { - const offset_i64 = @intCast(i64, offset); + const offset_i64 = @as(i64, @intCast(offset)); const frames = c.sf_seek(file, offset_i64, c.SEEK_SET); const frames_current = c.sf_seek(file, 0, c.SEEK_CUR); std.debug.assert(frames == frames_current); @@ -80,7 +80,7 @@ pub fn temporaryName(allocator: std.mem.Allocator) ![]u8 { var nam = try allocator.alloc(u8, template.len); std.mem.copy(u8, nam, template); - const seed = @truncate(u64, @bitCast(u128, std.time.nanoTimestamp())); + const seed = @as(u64, @truncate(@as(u128, @bitCast(std.time.nanoTimestamp())))); var r = std.rand.DefaultPrng.init(seed); var fill = nam[template_start.len..nam.len]; @@ -88,8 +88,8 @@ pub fn temporaryName(allocator: std.mem.Allocator) ![]u8 { var i: usize = 0; while (i < 100) : (i += 1) { // generate a random uppercase letter, that is, 65 + random number. - for (fill) |_, f_idx| { - var idx = @intCast(u8, r.random().uintLessThan(u5, 24)); + for (fill, 0..) |_, f_idx| { + var idx = @as(u8, @intCast(r.random().uintLessThan(u5, 24))); var letter = @as(u8, 65) + idx; fill[f_idx] = letter; } @@ -151,7 +151,7 @@ pub const Image = struct { .sndfile = sndfile, .path = path, .curpath = path, - .frames = @intCast(usize, in_fmt.frames), + .frames = @as(usize, @intCast(in_fmt.frames)), }; return image; @@ -161,7 +161,7 @@ pub const Image = struct { var in_fmt = mkSfInfo(); // clone sndfile var sndfile = try sopen(self.allocator, self.curpath, c.SFM_READ, &in_fmt); - std.debug.assert(self.frames == @intCast(usize, in_fmt.frames)); + std.debug.assert(self.frames == @as(usize, @intCast(in_fmt.frames))); var image = try self.allocator.create(Image); @@ -173,7 +173,7 @@ pub const Image = struct { .sndfile = sndfile, .path = self.path, .curpath = self.curpath, - .frames = @intCast(usize, in_fmt.frames), + .frames = @as(usize, @intCast(in_fmt.frames)), }; return image; @@ -198,12 +198,12 @@ pub const Image = struct { pub fn read(self: *Image, file_chans: c_int, buf: []f32) bool { const n_read: c.sf_count_t = c.sf_readf_float(self.sndfile, buf.ptr, 1); - const buf_chans = @intCast(c_int, buf.len); + const buf_chans = @as(c_int, @intCast(buf.len)); var i = file_chans - 1; while (i < buf_chans) : (i += 1) { //buf[@intCast(usize, i)] = buf[i % file_chans]; - buf[@intCast(usize, i)] = buf[@intCast(usize, @mod(i, file_chans))]; + buf[@as(usize, @intCast(i))] = buf[@as(usize, @intCast(@mod(i, file_chans)))]; } return n_read == 1; @@ -237,13 +237,13 @@ pub const Image = struct { var view: []f32 = buf[0..buf.len]; if (bytes_until_end < buf.len) { - read_bytes = c.sf_readf_float(self.sndfile, buf.ptr, @intCast(i64, bytes_until_end)); + read_bytes = c.sf_readf_float(self.sndfile, buf.ptr, @as(i64, @intCast(bytes_until_end))); view = buf[0..bytes_until_end]; } else { - read_bytes = c.sf_readf_float(self.sndfile, buf.ptr, @intCast(i64, buf.len)); + read_bytes = c.sf_readf_float(self.sndfile, buf.ptr, @as(i64, @intCast(buf.len))); } - try swrite(out_file, view.ptr, @intCast(i64, view.len)); + try swrite(out_file, view.ptr, @as(i64, @intCast(view.len))); } sseek(self.sndfile, end); @@ -264,7 +264,7 @@ pub const Image = struct { // std.testing.expectEqual(self.frames, @intCast(usize, in_fmt.frames)); self.curpath = path; - self.frames = @intCast(usize, in_fmt.frames); + self.frames = @as(usize, @intCast(in_fmt.frames)); log.debug("\timage: reopened on '{s}' (frames={d}, fmt.frames={d})", .{ self.curpath, diff --git a/src/lang.zig b/src/lang.zig index ca5fbec..9f85d0f 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -669,7 +669,7 @@ pub const Lang = struct { comptime var lowered_command_name = [_]u8{0} ** struct_name.len; comptime { - for (struct_name) |c, i| { + for (struct_name, 0..) |c, i| { lowered_command_name[i] = std.ascii.toLower(c); } } diff --git a/src/lv2_helpers.zig b/src/lv2_helpers.zig index 82c961d..1d3df64 100644 --- a/src/lv2_helpers.zig +++ b/src/lv2_helpers.zig @@ -69,7 +69,7 @@ pub fn setupPorts(ctx: *plugin.Context) ![]Port { var ports = try ctx.allocator.alloc(Port, n_ports); - for (ports) |_, idx| { + for (ports, 0..) |_, idx| { var port: *Port = &ports[idx]; port.* = Port{ .lilv_port = null, diff --git a/src/main.zig b/src/main.zig index 083b204..7b7b66b 100644 --- a/src/main.zig +++ b/src/main.zig @@ -30,8 +30,8 @@ fn copyCommandToHeap(allocator: std.mem.Allocator, command: langs.Command, compt var heap_cmd = try allocator.create(CommandStruct); @memcpy( - @ptrCast([*]u8, &heap_cmd), - @ptrCast([*]const u8, &casted), + @as([*]u8, @ptrCast(&heap_cmd)), + @as([*]const u8, @ptrCast(&casted)), @sizeOf(CommandStruct), ); diff --git a/src/plugin.zig b/src/plugin.zig index b0fb504..57f8059 100644 --- a/src/plugin.zig +++ b/src/plugin.zig @@ -101,8 +101,8 @@ pub const RunContext = struct { var i: usize = 0; var o: usize = 0; - for (ports) |_, p_idx| { - var p = @intCast(u32, p_idx); + for (ports, 0..) |_, p_idx| { + var p = @as(u32, @intCast(p_idx)); var port: *lv2.Port = &ports[p_idx]; switch (port.ptype) { diff --git a/src/runner.zig b/src/runner.zig index 76f54a0..739a95f 100644 --- a/src/runner.zig +++ b/src/runner.zig @@ -70,7 +70,7 @@ pub const Runner = struct { // ':0' should ALWAYS point to the image. if (self.repl) index += 3 else index += 3; - for (self.args) |arg, idx| { + for (self.args, 0..) |arg, idx| { log.debug("arg{d} = {s}", .{ idx, arg }); } log.debug("fetch arg idx={d}", .{index}); From c73b98a3565a4e39de836ddfb6bb5194f742af3e Mon Sep 17 00:00:00 2001 From: Luna Date: Fri, 4 Aug 2023 21:50:59 -0300 Subject: [PATCH 41/43] fix for zig 0.11 --- build.zig | 38 +++++++++++++++++++++++++------------- src/image.zig | 4 ++-- src/lang.zig | 7 ++++--- src/magick.zig | 4 ++-- src/main.zig | 6 +----- src/plugin.zig | 2 +- src/runner.zig | 4 ++-- 7 files changed, 37 insertions(+), 28 deletions(-) diff --git a/build.zig b/build.zig index ad6f87d..e969b99 100644 --- a/build.zig +++ b/build.zig @@ -12,8 +12,8 @@ fn setupLinks(step: *builds.LibExeObjStep) void { step.linkSystemLibrary("GraphicsMagickWand"); step.linkSystemLibrary("GraphicsMagick"); - step.addIncludePath("/usr/include/GraphicsMagick"); - step.addIncludePath("/usr/include"); + step.addIncludePath(.{ .path = "/usr/include/GraphicsMagick" }); + step.addIncludePath(.{ .path = "/usr/include" }); const possible_lilv_include_dirs = [_][]const u8{ "/usr/include/lilv-0/lilv", @@ -32,7 +32,7 @@ fn setupLinks(step: *builds.LibExeObjStep) void { found_any_lilv = true; std.debug.print("found lilv at '{s}'\n", .{possible_lilv_dir}); - step.addIncludePath(possible_lilv_dir); + step.addIncludePath(.{ .path = possible_lilv_dir }); } if (!found_any_lilv) { @@ -42,22 +42,34 @@ fn setupLinks(step: *builds.LibExeObjStep) void { } pub fn build(b: *Builder) void { - const mode = b.standardReleaseOptions(); - const exe = b.addExecutable("scritcher", "src/main.zig"); - exe.setBuildMode(mode); - exe.install(); + const target = b.standardTargetOptions(.{}); + const optimize = b.standardOptimizeOption(.{}); + const exe = b.addExecutable(.{ + .name = "scritcher", + .root_source_file = .{ .path = "src/main.zig" }, + .target = target, + .optimize = optimize, + }); setupLinks(exe); + b.installArtifact(exe); - const test_obj_step = b.addTest("src/main.zig"); - setupLinks(test_obj_step); + const run_cmd = b.addRunArtifact(exe); - const run_cmd = exe.run(); - run_cmd.step.dependOn(b.getInstallStep()); + if (b.args) |args| { + run_cmd.addArgs(args); + } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); - const test_step = b.step("test", "Run tests"); - test_step.dependOn(&test_obj_step.step); + const test_step = b.addTest(.{ + .root_source_file = .{ .path = "src/main.zig" }, + .target = target, + .optimize = optimize, + }); + setupLinks(test_step); + const run_unit_tests = b.addRunArtifact(test_step); + const test_cmd = b.step("test", "run unit tests"); + test_cmd.dependOn(&run_unit_tests.step); } diff --git a/src/image.zig b/src/image.zig index 47be1cd..3905ea5 100644 --- a/src/image.zig +++ b/src/image.zig @@ -26,7 +26,7 @@ pub fn sopen( mode: i32, fmt: *c.SF_INFO, ) !*c.SNDFILE { - var cstr_path = try std.cstr.addNullByte(allocator, path); + var cstr_path = try allocator.dupeZ(u8, path); defer allocator.free(cstr_path); var file = c.sf_open(cstr_path.ptr, mode, fmt); @@ -321,7 +321,7 @@ pub const Image = struct { // now, for each param for the plugin, we find its port, and set // the value for the port there. for (params.items) |param| { - var sym_cstr = try std.cstr.addNullByte(self.allocator, param.sym); + var sym_cstr = try self.allocator.dupeZ(u8, param.sym); defer self.allocator.free(sym_cstr); var sym = c.lilv_new_string(ctx.world, sym_cstr.ptr); diff --git a/src/lang.zig b/src/lang.zig index 9f85d0f..b18b0fb 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -496,7 +496,8 @@ pub const CommandList = struct { } } - self.list.allocator.destroy(cmd_ptr); + //TODO this is ian invalid free + //self.list.allocator.destroy(cmd_ptr); } self.list.deinit(); } @@ -537,7 +538,7 @@ pub const Lang = struct { fn parseCommandArguments( self: *@This(), comptime command_struct: type, - tok_it: *std.mem.SplitIterator(u8), + tok_it: *std.mem.SplitIterator(u8, .sequence), commands: *CommandList, ) !void { // Based on the command struct fields, we can parse the arguments. @@ -638,7 +639,7 @@ pub const Lang = struct { if (std.mem.startsWith(u8, stmt, "#")) continue; // TODO better tokenizer instead of just tokenize(" ")...maybe???? - var tok_it = std.mem.split(u8, stmt, " "); + var tok_it = std.mem.splitSequence(u8, stmt, " "); var cmd_opt = tok_it.next(); if (cmd_opt == null) { diff --git a/src/magick.zig b/src/magick.zig index c6adf3c..e79f513 100644 --- a/src/magick.zig +++ b/src/magick.zig @@ -38,7 +38,7 @@ fn magickLoad(image: *Image) !MagickContext { var mctx = try MagickContext.init(); errdefer mctx.deinit(); - var curpath = try std.cstr.addNullByte(image.allocator, image.curpath); + var curpath = try image.allocator.dupeZ(u8, image.curpath); defer image.allocator.free(curpath); log.debug("loading '{s}'", .{curpath}); @@ -53,7 +53,7 @@ fn magickSave(image: *Image, wand: *mc.MagickWand) !void { const allocator = image.allocator; var tmpnam = try images.temporaryName(allocator); - var c_tmpnam = try std.cstr.addNullByte(allocator, tmpnam); + var c_tmpnam = try allocator.dupeZ(u8, tmpnam); defer allocator.free(c_tmpnam); log.debug("\tmagick: saving to '{s}'..", .{c_tmpnam}); diff --git a/src/main.zig b/src/main.zig index 7b7b66b..7563392 100644 --- a/src/main.zig +++ b/src/main.zig @@ -29,11 +29,7 @@ fn copyCommandToHeap(allocator: std.mem.Allocator, command: langs.Command, compt const casted = command.cast(CommandStruct).?; var heap_cmd = try allocator.create(CommandStruct); - @memcpy( - @as([*]u8, @ptrCast(&heap_cmd)), - @as([*]const u8, @ptrCast(&casted)), - @sizeOf(CommandStruct), - ); + heap_cmd.* = casted.*; return &heap_cmd.base; } diff --git a/src/plugin.zig b/src/plugin.zig index 57f8059..f5f6517 100644 --- a/src/plugin.zig +++ b/src/plugin.zig @@ -131,7 +131,7 @@ pub const RunContext = struct { }; pub fn makeContext(allocator: std.mem.Allocator, plugin_uri: []const u8) !Context { - const cstr_plugin_uri = try std.cstr.addNullByte(allocator, plugin_uri); + const cstr_plugin_uri = try allocator.dupeZ(u8, plugin_uri); defer allocator.free(cstr_plugin_uri); var world: *c.LilvWorld = c.lilv_world_new().?; diff --git a/src/runner.zig b/src/runner.zig index 739a95f..0eea50b 100644 --- a/src/runner.zig +++ b/src/runner.zig @@ -152,7 +152,7 @@ pub const Runner = struct { while (try it.next()) |entry| { switch (entry.kind) { - .File => blk: { + .file => blk: { if (!std.mem.startsWith(u8, entry.name, starts_with)) break :blk {}; // we want to get the N in x_gN.ext @@ -215,7 +215,7 @@ pub const Runner = struct { const rotate_cmd = cmd.cast(lang.Command.Rotate).?; var image = try self.getImage(); - var c_bgfill = try std.cstr.addNullByte(self.allocator, rotate_cmd.bgfill); + var c_bgfill = try self.allocator.dupeZ(u8, rotate_cmd.bgfill); defer self.allocator.free(c_bgfill); try magick.runRotate(image, rotate_cmd.deg, c_bgfill); From c0da5e68b7d3144ca729b25cb9aea91b3bd853ae Mon Sep 17 00:00:00 2001 From: Luna Date: Sat, 1 Jun 2024 15:46:37 -0300 Subject: [PATCH 42/43] base port to zig 0.12 --- build.zig | 10 ++++------ src/image.zig | 46 ++++++++++++++++++++++----------------------- src/lang.zig | 10 +++++++--- src/lv2_helpers.zig | 16 ++++++++-------- src/magick.zig | 10 +++++----- src/main.zig | 12 +++++++----- src/plugin.zig | 12 ++++++------ src/runner.zig | 12 ++++++------ 8 files changed, 66 insertions(+), 62 deletions(-) diff --git a/build.zig b/build.zig index e969b99..5f2ff5e 100644 --- a/build.zig +++ b/build.zig @@ -1,8 +1,6 @@ const std = @import("std"); -const builds = std.build; -const Builder = std.build.Builder; -fn setupLinks(step: *builds.LibExeObjStep) void { +fn setupLinks(step: *std.Build.Step.Compile) void { step.linkSystemLibrary("c"); step.linkSystemLibrary("lilv-0"); @@ -41,13 +39,13 @@ fn setupLinks(step: *builds.LibExeObjStep) void { } } -pub fn build(b: *Builder) void { +pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "scritcher", - .root_source_file = .{ .path = "src/main.zig" }, + .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); @@ -64,7 +62,7 @@ pub fn build(b: *Builder) void { run_step.dependOn(&run_cmd.step); const test_step = b.addTest(.{ - .root_source_file = .{ .path = "src/main.zig" }, + .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); diff --git a/src/image.zig b/src/image.zig index 3905ea5..e20cfe7 100644 --- a/src/image.zig +++ b/src/image.zig @@ -26,10 +26,10 @@ pub fn sopen( mode: i32, fmt: *c.SF_INFO, ) !*c.SNDFILE { - var cstr_path = try allocator.dupeZ(u8, path); + const cstr_path = try allocator.dupeZ(u8, path); defer allocator.free(cstr_path); - var file = c.sf_open(cstr_path.ptr, mode, fmt); + const file = c.sf_open(cstr_path.ptr, mode, fmt); const st: i32 = c.sf_error(file); if (st != 0) { @@ -78,7 +78,7 @@ pub fn temporaryName(allocator: std.mem.Allocator) ![]u8 { const template_start = "/temp/temp_"; const template = "/tmp/temp_XXXXXXXXXXXXXXXXXXXXX"; var nam = try allocator.alloc(u8, template.len); - std.mem.copy(u8, nam, template); + std.mem.copyForwards(u8, nam, template); const seed = @as(u64, @truncate(@as(u128, @bitCast(std.time.nanoTimestamp())))); var r = std.rand.DefaultPrng.init(seed); @@ -89,8 +89,8 @@ pub fn temporaryName(allocator: std.mem.Allocator) ![]u8 { while (i < 100) : (i += 1) { // generate a random uppercase letter, that is, 65 + random number. for (fill, 0..) |_, f_idx| { - var idx = @as(u8, @intCast(r.random().uintLessThan(u5, 24))); - var letter = @as(u8, 65) + idx; + const idx = @as(u8, @intCast(r.random().uintLessThan(u5, 24))); + const letter = @as(u8, 65) + idx; fill[f_idx] = letter; } @@ -139,9 +139,9 @@ pub const Image = struct { /// Open a BMP image for later. pub fn open(allocator: std.mem.Allocator, path: []const u8) !*Image { var in_fmt = mkSfInfo(); - var sndfile = try sopen(allocator, path, c.SFM_READ, &in_fmt); + const sndfile = try sopen(allocator, path, c.SFM_READ, &in_fmt); - var image = try allocator.create(Image); + const image = try allocator.create(Image); std.debug.assert(in_fmt.frames > @as(i64, 0)); std.debug.assert(in_fmt.seekable == @as(i32, 1)); @@ -160,10 +160,10 @@ pub const Image = struct { pub fn clone(self: *Image) !*Image { var in_fmt = mkSfInfo(); // clone sndfile - var sndfile = try sopen(self.allocator, self.curpath, c.SFM_READ, &in_fmt); + const sndfile = try sopen(self.allocator, self.curpath, c.SFM_READ, &in_fmt); std.debug.assert(self.frames == @as(usize, @intCast(in_fmt.frames))); - var image = try self.allocator.create(Image); + const image = try self.allocator.create(Image); std.debug.assert(in_fmt.frames > @as(i64, 0)); std.debug.assert(in_fmt.seekable == @as(i32, 1)); @@ -180,7 +180,7 @@ pub const Image = struct { } pub fn close(self: *Image) void { - var st: i32 = c.sf_close(self.sndfile); + const st: i32 = c.sf_close(self.sndfile); if (st != 0) { log.debug("Failed to close {s} ({s})", .{ self.path, @@ -252,7 +252,7 @@ pub const Image = struct { fn getSeekPos(self: *Image, position: plugins.Position) plugins.SeekPos { const file_end = self.frames; - var seek_pos = position.seekPos(file_end); + const seek_pos = position.seekPos(file_end); log.debug("\tstart {d} end {d}", .{ seek_pos.start, seek_pos.end }); return seek_pos; } @@ -321,10 +321,10 @@ pub const Image = struct { // now, for each param for the plugin, we find its port, and set // the value for the port there. for (params.items) |param| { - var sym_cstr = try self.allocator.dupeZ(u8, param.sym); + const sym_cstr = try self.allocator.dupeZ(u8, param.sym); defer self.allocator.free(sym_cstr); - var sym = c.lilv_new_string(ctx.world, sym_cstr.ptr); + const sym = c.lilv_new_string(ctx.world, sym_cstr.ptr); const port = c.lilv_plugin_get_port_by_symbol(ctx.plugin, sym) orelse { log.debug("assert fail: symbol {s} not found on port", .{param.sym}); return ImageError.InvalidSymbol; @@ -332,7 +332,7 @@ pub const Image = struct { c.lilv_node_free(sym); - var idx = c.lilv_port_get_index(ctx.plugin, port); + const idx = c.lilv_port_get_index(ctx.plugin, port); log.debug("\tset sym={s}, idx={d} to val={}", .{ param.sym, idx, @@ -343,11 +343,11 @@ pub const Image = struct { // now we need to generate a temporary file and put the output of // running the plugin on that file - var tmpnam = try temporaryName(self.allocator); + const tmpnam = try temporaryName(self.allocator); log.debug("\trunning plugin from '{s}' to '{s}'", .{ self.curpath, tmpnam }); var out_fmt = mkSfInfo(); - var out_file = try sopen(self.allocator, tmpnam, c.SFM_WRITE, &out_fmt); + const out_file = try sopen(self.allocator, tmpnam, c.SFM_WRITE, &out_fmt); var rctx = try plugins.RunContext.init(self.allocator, ctx.plugin); defer rctx.deinit(); @@ -380,7 +380,7 @@ pub const Image = struct { log.debug("\tseek pos start: {d} end: {d}", .{ seek_pos.start, seek_pos.end }); var inbuf = &rctx.buffers.in; - var outbuf = &rctx.buffers.out; + const outbuf = &rctx.buffers.out; while (i <= seek_pos.end) : (i += 1) { inbuf[0] = 0; @@ -416,7 +416,7 @@ pub const Image = struct { try self.reopen(tmpnam); try self.checkValid(); - var time_taken = timer.read(); + const time_taken = timer.read(); log.debug("\ttook {d:.2}ms running plugin", .{time_taken / std.time.us_per_ms}); } @@ -431,7 +431,7 @@ pub const Image = struct { position: plugins.Position, extra: anytype, ) !void { - var plugin_opt: ?Plugin = Plugin.init(self.allocator, extra); + const plugin_opt: ?Plugin = Plugin.init(self.allocator, extra); if (plugin_opt == null) { return ImageError.PluginLoadFail; } @@ -448,11 +448,11 @@ pub const Image = struct { // the code here is a copypaste of runPlugin() without the specific // lilv things. - var tmpnam = try temporaryName(self.allocator); + const tmpnam = try temporaryName(self.allocator); log.debug("\trunning CUSTOM plugin from '{s}' to '{s}'", .{ self.curpath, tmpnam }); var out_fmt = mkSfInfo(); - var out_file = try sopen(self.allocator, tmpnam, c.SFM_WRITE, &out_fmt); + const out_file = try sopen(self.allocator, tmpnam, c.SFM_WRITE, &out_fmt); var bufs = plugins.RunBuffers{}; const seek_pos = self.getSeekPos(position); @@ -478,8 +478,8 @@ pub const Image = struct { var i: usize = seek_pos.start; log.debug("\tseek pos start: {d} end: {d}", .{ seek_pos.start, seek_pos.end }); - var inbuf = &bufs.in; - var outbuf = &bufs.out; + const inbuf = &bufs.in; + const outbuf = &bufs.out; while (i <= seek_pos.end) : (i += 1) { const read_bytes = c.sf_readf_float(self.sndfile, inbuf, 1); diff --git a/src/lang.zig b/src/lang.zig index b18b0fb..72b9e2c 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -143,7 +143,8 @@ pub const Command = struct { if (base.tag != T.base_tag) return null; - return @fieldParentPtr(T, "base", base); + const ptr: *const T = @alignCast(@fieldParentPtr("base", base)); + return ptr; } pub fn print(base: *const @This()) void { @@ -641,7 +642,7 @@ pub const Lang = struct { // TODO better tokenizer instead of just tokenize(" ")...maybe???? var tok_it = std.mem.splitSequence(u8, stmt, " "); - var cmd_opt = tok_it.next(); + const cmd_opt = tok_it.next(); if (cmd_opt == null) { self.doError("No command given", .{}); continue; @@ -669,11 +670,14 @@ pub const Lang = struct { } comptime var lowered_command_name = [_]u8{0} ** struct_name.len; + var runtime_lowered_command_name = [_]u8{0} ** struct_name.len; comptime { for (struct_name, 0..) |c, i| { lowered_command_name[i] = std.ascii.toLower(c); } } + const c_l = lowered_command_name; + std.mem.copyForwards(u8, &runtime_lowered_command_name, &c_l); // if we have a match, we know the proper struct type // to use. this actually works compared to storing command_struct @@ -685,7 +689,7 @@ pub const Lang = struct { // Attempting to use ComptimeHashMap hits compiler bugs and I'm // not sure if we can map strings to *types* in it. - if ((!found) and std.mem.eql(u8, &lowered_command_name, command_string)) { + if ((!found) and std.mem.eql(u8, &runtime_lowered_command_name, command_string)) { found = true; try self.parseCommandArguments(cmd_struct_type, &tok_it, &cmds); } diff --git a/src/lv2_helpers.zig b/src/lv2_helpers.zig index 1d3df64..a59babd 100644 --- a/src/lv2_helpers.zig +++ b/src/lv2_helpers.zig @@ -64,13 +64,13 @@ pub const Port = struct { /// /// Caller owns returned memory. pub fn setupPorts(ctx: *plugin.Context) ![]Port { - var world = ctx.world; + const world = ctx.world; const n_ports: u32 = c.lilv_plugin_get_num_ports(ctx.plugin); var ports = try ctx.allocator.alloc(Port, n_ports); for (ports, 0..) |_, idx| { - var port: *Port = &ports[idx]; + const port: *Port = &ports[idx]; port.* = Port{ .lilv_port = null, .ptype = .Control, @@ -81,23 +81,23 @@ pub fn setupPorts(ctx: *plugin.Context) ![]Port { }; } - var values: []f32 = try ctx.allocator.alloc(f32, n_ports); + const values: []f32 = try ctx.allocator.alloc(f32, n_ports); defer ctx.allocator.free(values); c.lilv_plugin_get_port_ranges_float(ctx.plugin, null, null, values.ptr); - var lv2_InputPort = c.lilv_new_uri(world, LV2_CORE__InputPort.ptr).?; + const lv2_InputPort = c.lilv_new_uri(world, LV2_CORE__InputPort.ptr).?; //defer std.heap.c_allocator.destroy(lv2_InputPort); - var lv2_OutputPort = c.lilv_new_uri(world, LV2_CORE__OutputPort.ptr).?; + const lv2_OutputPort = c.lilv_new_uri(world, LV2_CORE__OutputPort.ptr).?; //defer std.heap.c_allocator.destroy(lv2_OutputPort); - var lv2_AudioPort = c.lilv_new_uri(world, LV2_CORE__AudioPort.ptr).?; + const lv2_AudioPort = c.lilv_new_uri(world, LV2_CORE__AudioPort.ptr).?; //defer std.heap.c_allocator.destroy(lv2_AudioPort); - var lv2_ControlPort = c.lilv_new_uri(world, LV2_CORE__ControlPort.ptr).?; + const lv2_ControlPort = c.lilv_new_uri(world, LV2_CORE__ControlPort.ptr).?; //defer std.heap.c_allocator.destroy(lv2_ControlPort); - var lv2_connection_string = c.lilv_new_uri(world, LV2_CORE__connectionOptional.ptr).?; + const lv2_connection_string = c.lilv_new_uri(world, LV2_CORE__connectionOptional.ptr).?; //defer std.heap.c_allocator.destroy(lv2_connection_string); var i: u32 = 0; diff --git a/src/magick.zig b/src/magick.zig index e79f513..ab59f0a 100644 --- a/src/magick.zig +++ b/src/magick.zig @@ -15,7 +15,7 @@ pub const MagickContext = struct { pub fn init() !MagickContext { mc.InitializeMagick(null); - var wand = mc.NewMagickWand(); + const wand = mc.NewMagickWand(); if (wand == null) return error.WandCreateFail; return MagickContext{ @@ -38,7 +38,7 @@ fn magickLoad(image: *Image) !MagickContext { var mctx = try MagickContext.init(); errdefer mctx.deinit(); - var curpath = try image.allocator.dupeZ(u8, image.curpath); + const curpath = try image.allocator.dupeZ(u8, image.curpath); defer image.allocator.free(curpath); log.debug("loading '{s}'", .{curpath}); @@ -52,8 +52,8 @@ fn magickLoad(image: *Image) !MagickContext { fn magickSave(image: *Image, wand: *mc.MagickWand) !void { const allocator = image.allocator; - var tmpnam = try images.temporaryName(allocator); - var c_tmpnam = try allocator.dupeZ(u8, tmpnam); + const tmpnam = try images.temporaryName(allocator); + const c_tmpnam = try allocator.dupeZ(u8, tmpnam); defer allocator.free(c_tmpnam); log.debug("\tmagick: saving to '{s}'..", .{c_tmpnam}); @@ -72,7 +72,7 @@ pub fn runRotate(image: *Image, deg: f32, bgfill: []const u8) !void { var mctx = try magickLoad(image); defer mctx.deinit(); - var bg = mc.NewPixelWand(); + const bg = mc.NewPixelWand(); defer mc.DestroyPixelWand(bg); if (mc.PixelSetColor(bg, bgfill.ptr) != 1) diff --git a/src/main.zig b/src/main.zig index 7563392..f21087e 100644 --- a/src/main.zig +++ b/src/main.zig @@ -30,6 +30,8 @@ fn copyCommandToHeap(allocator: std.mem.Allocator, command: langs.Command, compt var heap_cmd = try allocator.create(CommandStruct); heap_cmd.* = casted.*; + log.debug("casted: {}", .{casted}); + log.debug("heap_cmd: {}", .{heap_cmd}); return &heap_cmd.base; } @@ -54,7 +56,7 @@ pub fn doRepl(allocator: std.mem.Allocator, args_it: anytype) !void { defer lang.deinit(); if (total_bytes > 0) { - var scri_existing = try allocator.alloc(u8, total_bytes); + const scri_existing = try allocator.alloc(u8, total_bytes); _ = try file_read_opt.?.read(scri_existing); defer allocator.free(scri_existing); @@ -94,7 +96,7 @@ pub fn doRepl(allocator: std.mem.Allocator, args_it: anytype) !void { defer file.close(); var out = file.writer(); - var stream = &out; + const stream = &out; // since we opened the file for writing, it becomes empty, so, to ensure // we don't fuck up later on, we print cmds before starting the repl @@ -118,7 +120,7 @@ pub fn doRepl(allocator: std.mem.Allocator, args_it: anytype) !void { // run the load command try runner.runCommands(cmds, true); - const wanted_runner: []const u8 = std.os.getenv("SCRITCHER_RUNNER") orelse "ristretto"; + const wanted_runner: []const u8 = std.posix.getenv("SCRITCHER_RUNNER") orelse "ristretto"; var runqs_cmd = langs.Command.RunQS{ .base = langs.Command{ .tag = langs.Command.Tag.runqs }, @@ -136,7 +138,7 @@ pub fn doRepl(allocator: std.mem.Allocator, args_it: anytype) !void { readline.add_history(rd_line); //defer std.heap.c_allocator.destroy(rd_line); - var line = rd_line[0..std.mem.len(rd_line)]; + const line = rd_line[0..std.mem.len(rd_line)]; if (std.mem.eql(u8, line, "push")) { const heap_cmd = switch (current.tag) { @@ -250,7 +252,7 @@ fn doRun(allocator: std.mem.Allocator, args_it: anytype) !void { // sadly, we read it all into memory. such is life const total_bytes = try file.getEndPos(); - var data = try allocator.alloc(u8, total_bytes); + const data = try allocator.alloc(u8, total_bytes); defer allocator.free(data); _ = try file.read(data); diff --git a/src/plugin.zig b/src/plugin.zig index f5f6517..29ec224 100644 --- a/src/plugin.zig +++ b/src/plugin.zig @@ -36,7 +36,7 @@ pub const Position = struct { pub fn seekPos(self: Position, total_size: usize) SeekPos { std.debug.assert(self.index <= self.split); - var tot = total_size / self.split; + const tot = total_size / self.split; return SeekPos{ .start = self.index * tot, @@ -80,7 +80,7 @@ pub const RunContext = struct { ) !RunContext { _ = allocator; // TODO batch RunBuffers? - var instance = c.lilv_plugin_instantiate(plugin, @as(f64, 44100), null); + const instance = c.lilv_plugin_instantiate(plugin, @as(f64, 44100), null); errdefer c.lilv_instance_free(instance); if (instance == null) { @@ -102,7 +102,7 @@ pub const RunContext = struct { var o: usize = 0; for (ports, 0..) |_, p_idx| { - var p = @as(u32, @intCast(p_idx)); + const p = @as(u32, @intCast(p_idx)); var port: *lv2.Port = &ports[p_idx]; switch (port.ptype) { @@ -134,12 +134,12 @@ pub fn makeContext(allocator: std.mem.Allocator, plugin_uri: []const u8) !Contex const cstr_plugin_uri = try allocator.dupeZ(u8, plugin_uri); defer allocator.free(cstr_plugin_uri); - var world: *c.LilvWorld = c.lilv_world_new().?; + const world: *c.LilvWorld = c.lilv_world_new().?; errdefer c.lilv_world_free(world); c.lilv_world_load_all(world); - var uri: *c.LilvNode = c.lilv_new_uri(world, cstr_plugin_uri.ptr) orelse { + const uri: *c.LilvNode = c.lilv_new_uri(world, cstr_plugin_uri.ptr) orelse { log.debug("Invalid plugin URI <{s}>", .{plugin_uri}); return ImageError.InvalidPlugin; }; @@ -147,7 +147,7 @@ pub fn makeContext(allocator: std.mem.Allocator, plugin_uri: []const u8) !Contex const plugins: *const c.LilvPlugins = c.lilv_world_get_all_plugins(world).?; - var plugin: *const c.LilvPlugin = c.lilv_plugins_get_by_uri(plugins, uri) orelse { + const plugin: *const c.LilvPlugin = c.lilv_plugins_get_by_uri(plugins, uri) orelse { log.debug("Plugin <{s}> not found", .{plugin_uri}); return ImageError.UnknownPlugin; }; diff --git a/src/runner.zig b/src/runner.zig index 0eea50b..8cc578c 100644 --- a/src/runner.zig +++ b/src/runner.zig @@ -47,7 +47,7 @@ pub const Runner = struct { } pub fn clone(self: *Runner) !Runner { - var cloned_image = if (self.image) |image| try image.clone() else null; + const cloned_image = if (self.image) |image| try image.clone() else null; return Runner{ .allocator = self.allocator, .image = cloned_image, @@ -128,12 +128,12 @@ pub const Runner = struct { fn makeGlitchedPath(self: *Runner) ![]const u8 { // we want to transform basename, if it is "x.bmp" to "x_gN.bmp", where // N is the maximum non-used integer. - var image = try self.getImage(); + const image = try self.getImage(); const basename = std.fs.path.basename(image.path); const dirname = std.fs.path.dirname(image.path).?; - var dir = try std.fs.cwd().openIterableDir(dirname, .{}); + var dir = try std.fs.cwd().openDir(dirname, .{ .iterate = true }); defer dir.close(); const period_idx = std.mem.lastIndexOf(u8, basename, ".").?; @@ -214,8 +214,8 @@ pub const Runner = struct { fn rotateCmd(self: *Runner, cmd: lang.Command) !void { const rotate_cmd = cmd.cast(lang.Command.Rotate).?; - var image = try self.getImage(); - var c_bgfill = try self.allocator.dupeZ(u8, rotate_cmd.bgfill); + const image = try self.getImage(); + const c_bgfill = try self.allocator.dupeZ(u8, rotate_cmd.bgfill); defer self.allocator.free(c_bgfill); try magick.runRotate(image, rotate_cmd.deg, c_bgfill); @@ -332,7 +332,7 @@ test "running noop" { var cmds = lang.CommandList.init(allocator); defer cmds.deinit(); - var command = lang.Command{ .tag = .noop }; + const command = lang.Command{ .tag = .noop }; var noop = try allocator.create(lang.Command.Noop); noop.* = lang.Command.Noop{ .base = command }; From 3af4dc575a1cd9cbdcc98b19ee5fbf269b068880 Mon Sep 17 00:00:00 2001 From: Luna Date: Sat, 1 Jun 2024 16:53:01 -0300 Subject: [PATCH 43/43] fix command ptr alignment --- src/lang.zig | 13 ++++++++++++- src/runner.zig | 10 +++++----- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/lang.zig b/src/lang.zig index 72b9e2c..31e5a73 100644 --- a/src/lang.zig +++ b/src/lang.zig @@ -143,7 +143,18 @@ pub const Command = struct { if (base.tag != T.base_tag) return null; - const ptr: *const T = @alignCast(@fieldParentPtr("base", base)); + //const baseInt = @intFromPtr(base); + + //log.debug("casting from {d}", .{baseInt}); + //log.debug("aligns from 8? {d}", .{baseInt % 8}); + //log.debug("align T: {d} {s}", .{ @alignOf(*T), @typeName(T) }); + //log.debug("align base: {d} {s}", .{ @alignOf(*const @This()), @typeName(@This()) }); + const base_aligned: *const @This() = @alignCast(base); + + const parented = @as(*const T, @alignCast(@fieldParentPtr("base", base_aligned))); + + const ptr: *const T = @alignCast(parented); + //log.debug("align: {d}\n", .{@alignOf(@TypeOf(ptr))}); return ptr; } diff --git a/src/runner.zig b/src/runner.zig index 8cc578c..85b8d79 100644 --- a/src/runner.zig +++ b/src/runner.zig @@ -194,7 +194,7 @@ pub const Runner = struct { try image.saveTo(out_path); } - fn runQSCmd(self: *Runner, cmd: lang.Command) !void { + fn runQSCmd(self: *Runner, cmd: *lang.Command) !void { const runqs = cmd.cast(lang.Command.RunQS).?; var image = try self.getImage(); const out_path = try self.makeGlitchedPath(); @@ -211,7 +211,7 @@ pub const Runner = struct { _ = try proc.spawnAndWait(); } - fn rotateCmd(self: *Runner, cmd: lang.Command) !void { + fn rotateCmd(self: *Runner, cmd: *lang.Command) !void { const rotate_cmd = cmd.cast(lang.Command.Rotate).?; const image = try self.getImage(); @@ -255,7 +255,7 @@ pub const Runner = struct { fn runSingleCommand( self: *@This(), - cmd: lang.Command, + cmd: *lang.Command, comptime tag: lang.Command.Tag, ) !void { const typ = lang.Command.tagToType(tag); @@ -267,7 +267,7 @@ pub const Runner = struct { } } - fn runCommand(self: *@This(), cmd: lang.Command) !void { + fn runCommand(self: *@This(), cmd: *lang.Command) !void { switch (cmd.tag) { .noop => {}, .load => { @@ -322,7 +322,7 @@ pub const Runner = struct { _ = debug_flag; for (cmds.list.items) |cmd| { cmd.print(); - try self.runCommand(cmd.*); + try self.runCommand(cmd); } } };