From 062af5a96556f91586a28d7095b9c532a21f68ae Mon Sep 17 00:00:00 2001 From: Benoit Giannangeli Date: Tue, 7 Oct 2025 16:32:41 +0200 Subject: [PATCH] fix: Use unmanaged ArrayList and HashMaps everywhere --- CRUSH.md | 32 +++ out.txt | 0 src/Ast.zig | 14 +- src/Codegen.zig | 60 +++-- src/FFI.zig | 70 +++-- src/GC.zig | 13 +- src/Jit.zig | 5 +- src/Parser.zig | 439 ++++++++++++++++++------------- src/Reporter.zig | 71 ++--- src/Scanner.zig | 10 +- src/builtin/list.zig | 6 +- src/builtin/str.zig | 10 +- src/buzz_api.zig | 38 ++- src/disassembler.zig | 15 +- src/lib/buzz_buffer.zig | 9 +- src/lib/buzz_crypto.zig | 11 - src/lib/buzz_ffi.zig | 12 +- src/lib/buzz_http.zig | 7 +- src/lib/buzz_os.zig | 18 +- src/main.zig | 6 +- src/obj.zig | 44 ++-- src/repl.zig | 16 +- src/tests/fmt.zig | 2 +- src/value.zig | 10 +- src/vm.zig | 17 +- src/wasm_repl.zig | 10 +- src/writeable_array_list.zig | 13 +- tests/042-anonymous-objects.buzz | 17 +- 28 files changed, 556 insertions(+), 419 deletions(-) create mode 100644 CRUSH.md create mode 100644 out.txt diff --git a/CRUSH.md b/CRUSH.md new file mode 100644 index 00000000..de0f76dc --- /dev/null +++ b/CRUSH.md @@ -0,0 +1,32 @@ +CRUSH.md + +Build, lint, test +- Build: zig build +- Run REPL: zig build run +- Run file: zig build run -- path/to/file.buzz +- Install (user): zig build -Doptimize=ReleaseSafe install -p ~/.local +- Install (system): sudo zig build -Doptimize=ReleaseSafe install -p /usr/local +- Clean: rm -rf .zig-cache zig-out +- Typecheck/lsp: zls (use your editor’s Zig LSP); no separate typecheck script +- Format Zig: zig fmt . +- Web WASM tooling: npm install; node src/wasm.ts (uses esbuild+ts) +- Run single test: zig build run -- tests/068-testing.buzz --name "" (tests are Buzz scripts; prefer targeted script runs) +- Example single test: zig build run -- tests/023-std.buzz + +Project conventions +- Language: Zig 0.15.x; entry in src/main.zig; build via build.zig; vendor deps under vendors/ +- Buzz tests: each .buzz file in tests/ acts as an executable scenario; keep them self-contained +- Imports: Zig uses relative imports (const x = @import("file.zig")); keep import blocks at top, grouped std, vendors, local +- Formatting: run zig fmt before commits; keep line width conventional (~100) and avoid trailing spaces +- Types: prefer explicit types in public APIs; use var/const deliberately; avoid anyopaque unless necessary +- Naming: snake_case for Zig functions/vars, TitleCase for types, SCREAMING_SNAKE for compile-time consts +- Errors: use Zig error sets; return !T and propagate with try/errdefer; avoid panic except unrecoverable +- Memory: use provided allocators; pair alloc/free; errdefer for cleanup; avoid leaks in hot paths +- Concurrency: fibers exist at Buzz level; in Zig keep APIs non-blocking where possible +- Logging/Reporting: use Reporter.zig utilities; avoid printing in libraries +- Performance: prefer slices over arrays; minimize copies; use inline and comptime judiciously + +Notes +- No .cursor or Copilot rules found +- VS Code: install Buzz extension and Zig LSP for best experience +- Security: never commit secrets; do not log keys or tokens diff --git a/out.txt b/out.txt new file mode 100644 index 00000000..e69de29b diff --git a/src/Ast.zig b/src/Ast.zig index 340e9539..cc9cf897 100644 --- a/src/Ast.zig +++ b/src/Ast.zig @@ -625,11 +625,11 @@ pub const Slice = struct { const left_map = if (left.isObj()) obj.ObjMap.cast(left.obj()) else null; if (right_string) |rs| { - var new_string = std.array_list.Managed(u8).init(gc.allocator); - try new_string.appendSlice(left_string.?.string); - try new_string.appendSlice(rs.string); + var new_string = std.ArrayList(u8).empty; + try new_string.appendSlice(gc.allocator, left_string.?.string); + try new_string.appendSlice(gc.allocator, rs.string); - return (try gc.copyString(try new_string.toOwnedSlice())).toValue(); + return (try gc.copyString(try new_string.toOwnedSlice(gc.allocator))).toValue(); } else if (right_float) |rf| { return Value.fromDouble(rf + left_float.?); } else if (right_integer) |ri| { @@ -819,13 +819,13 @@ pub const Slice = struct { .String => string: { const elements = self.nodes.items(.components)[node].String; - var string = std.array_list.Managed(u8).init(gc.allocator); - const writer = &string.writer(); + var string = std.ArrayList(u8).empty; + const writer = &string.writer(gc.allocator); for (elements) |element| { try (try self.toValue(element, gc)).toString(writer); } - break :string (try gc.copyString(try string.toOwnedSlice())).toValue(); + break :string (try gc.copyString(try string.toOwnedSlice(gc.allocator))).toValue(); }, .Subscript => subscript: { const components = self.nodes.items(.components)[node].Subscript; diff --git a/src/Codegen.zig b/src/Codegen.zig index 3c5b26f9..08ba2893 100644 --- a/src/Codegen.zig +++ b/src/Codegen.zig @@ -1142,10 +1142,14 @@ fn generateCall(self: *Self, node: Ast.Node.Index, breaks: ?*Breaks) Error!?*obj const arg_keys = args.keys(); const arg_count = arg_keys.len; - var missing_arguments = std.StringArrayHashMap(usize).init(self.gc.allocator); - defer missing_arguments.deinit(); + var missing_arguments = std.StringArrayHashMapUnmanaged(usize).empty; + defer missing_arguments.deinit(self.gc.allocator); for (arg_keys, 0..) |arg_name, pindex| { - try missing_arguments.put(arg_name.string, pindex); + try missing_arguments.put( + self.gc.allocator, + arg_name.string, + pindex, + ); } if (components.arguments.len > args.count()) { @@ -1211,10 +1215,11 @@ fn generateCall(self: *Self, node: Ast.Node.Index, breaks: ?*Breaks) Error!?*obj } // Argument order reference - var arguments_order_ref = std.array_list.Managed([]const u8).init(self.gc.allocator); - defer arguments_order_ref.deinit(); + var arguments_order_ref = std.ArrayList([]const u8).empty; + defer arguments_order_ref.deinit(self.gc.allocator); for (components.arguments) |arg| { try arguments_order_ref.append( + self.gc.allocator, if (arg.name) |name| lexemes[name] else @@ -1224,8 +1229,8 @@ fn generateCall(self: *Self, node: Ast.Node.Index, breaks: ?*Breaks) Error!?*obj // Push default arguments if (missing_arguments.count() > 0) { - var tmp_missing_arguments = try missing_arguments.clone(); - defer tmp_missing_arguments.deinit(); + var tmp_missing_arguments = try missing_arguments.clone(self.gc.allocator); + defer tmp_missing_arguments.deinit(self.gc.allocator); const missing_keys = tmp_missing_arguments.keys(); for (missing_keys) |missing_key| { if (defaults.get(try self.gc.copyString(missing_key))) |default| { @@ -1233,7 +1238,7 @@ fn generateCall(self: *Self, node: Ast.Node.Index, breaks: ?*Breaks) Error!?*obj try self.emitConstant(locations[node], default); try self.OP_CLONE(locations[node]); - try arguments_order_ref.append(missing_key); + try arguments_order_ref.append(self.gc.allocator, missing_key); _ = missing_arguments.orderedRemove(missing_key); needs_reorder = true; } @@ -1241,8 +1246,8 @@ fn generateCall(self: *Self, node: Ast.Node.Index, breaks: ?*Breaks) Error!?*obj } if (missing_arguments.count() > 0) { - var missing = std.array_list.Managed(u8).init(self.gc.allocator); - const missing_writer = missing.writer(); + var missing = std.ArrayList(u8).empty; + const missing_writer = missing.writer(self.gc.allocator); for (missing_arguments.keys(), 0..) |key, i| { try missing_writer.print( "{s}{s}", @@ -1255,7 +1260,7 @@ fn generateCall(self: *Self, node: Ast.Node.Index, breaks: ?*Breaks) Error!?*obj }, ); } - defer missing.deinit(); + defer missing.deinit(self.gc.allocator); self.reporter.reportErrorFmt( .call_arguments, self.ast.tokens.get(locations[node]), @@ -1342,8 +1347,8 @@ fn generateCall(self: *Self, node: Ast.Node.Index, breaks: ?*Breaks) Error!?*obj } else if (error_types) |errors| { if (self.current.?.enclosing != null and self.current.?.function.?.type_def.resolved_type.?.Function.function_type != .Test) { var handles_any = false; - var not_handled = std.array_list.Managed(*obj.ObjTypeDef).init(self.gc.allocator); - defer not_handled.deinit(); + var not_handled = std.ArrayList(*obj.ObjTypeDef).empty; + defer not_handled.deinit(self.gc.allocator); for (errors) |error_type| { if (error_type.def_type == .Void) { continue; @@ -1373,12 +1378,12 @@ fn generateCall(self: *Self, node: Ast.Node.Index, breaks: ?*Breaks) Error!?*obj locations[components.callee], ); } else { - try not_handled.append(error_type); + try not_handled.append(self.gc.allocator, error_type); } } if (handles_any) { - not_handled.clearAndFree(); + not_handled.clearAndFree(self.gc.allocator); break; } } @@ -3621,10 +3626,11 @@ fn generateObjectInit(self: *Self, node: Ast.Node.Index, breaks: ?*Breaks) Error var fields = if (node_type_def.def_type == .ObjectInstance) inst: { const fields = node_type_def.resolved_type.?.ObjectInstance.of.resolved_type.?.Object.fields; - var fields_type_defs = std.StringArrayHashMap(*obj.ObjTypeDef).init(self.gc.allocator); + var fields_type_defs = std.StringArrayHashMapUnmanaged(*obj.ObjTypeDef).empty; var it = fields.iterator(); while (it.next()) |kv| { try fields_type_defs.put( + self.gc.allocator, kv.value_ptr.*.name, kv.value_ptr.*.type_def, ); @@ -3633,7 +3639,7 @@ fn generateObjectInit(self: *Self, node: Ast.Node.Index, breaks: ?*Breaks) Error } else node_type_def.resolved_type.?.ForeignContainer.buzz_type; defer if (node_type_def.def_type == .ObjectInstance) { - fields.deinit(); + fields.deinit(self.gc.allocator); }; const object_location = if (node_type_def.def_type == .ObjectInstance) @@ -3642,8 +3648,8 @@ fn generateObjectInit(self: *Self, node: Ast.Node.Index, breaks: ?*Breaks) Error node_type_def.resolved_type.?.ForeignContainer.location; // Keep track of what's been initialized or not by this statement - var init_properties = std.StringHashMap(void).init(self.gc.allocator); - defer init_properties.deinit(); + var init_properties = std.StringHashMapUnmanaged(void).empty; + defer init_properties.deinit(self.gc.allocator); for (components.properties) |property| { const property_name = lexemes[property.name]; @@ -3701,7 +3707,7 @@ fn generateObjectInit(self: *Self, node: Ast.Node.Index, breaks: ?*Breaks) Error _ = try self.generateNode(property.value, breaks); - try init_properties.put(property_name, {}); + try init_properties.put(self.gc.allocator, property_name, {}); try self.emitCodeArg( location, @@ -4185,8 +4191,8 @@ fn generateTry(self: *Self, node: Ast.Node.Index, breaks: ?*Breaks) Error!?*obj. // Jump reached if no error was raised const no_error_jump = try self.OP_JUMP(self.ast.nodes.items(.end_location)[components.body]); - var exit_jumps = std.array_list.Managed(usize).init(self.gc.allocator); - defer exit_jumps.deinit(); + var exit_jumps = std.ArrayList(usize).empty; + defer exit_jumps.deinit(self.gc.allocator); self.patchTryOrJit(try_jump); var has_unconditional = components.unconditional_clause != null; @@ -4214,7 +4220,10 @@ fn generateTry(self: *Self, node: Ast.Node.Index, breaks: ?*Breaks) Error!?*obj. self.current.?.try_should_handle = previous; // After handling the error, jump over next clauses - try exit_jumps.append(try self.emitJump(location, .OP_JUMP)); + try exit_jumps.append( + self.gc.allocator, + try self.emitJump(location, .OP_JUMP), + ); self.patchJump(next_clause_jump); // Pop `is` result @@ -4230,7 +4239,10 @@ fn generateTry(self: *Self, node: Ast.Node.Index, breaks: ?*Breaks) Error!?*obj. _ = try self.generateNode(unconditional_clause, breaks); self.current.?.try_should_handle = previous; - try exit_jumps.append(try self.emitJump(location, .OP_JUMP)); + try exit_jumps.append( + self.gc.allocator, + try self.emitJump(location, .OP_JUMP), + ); } // Tell runtime we're not in a try block anymore diff --git a/src/FFI.zig b/src/FFI.zig index 01ae8ffa..bdff3803 100644 --- a/src/FFI.zig +++ b/src/FFI.zig @@ -185,13 +185,13 @@ pub const State = struct { buzz_ast: ?BuzzAst.Slice = null, parser: ?*Parser, type_expr: ?[]const u8 = null, - structs: std.StringHashMap(*Zdef), + structs: std.StringHashMapUnmanaged(*Zdef) = .empty, }; gc: *GC, reporter: Reporter, state: ?State = null, -type_expr_cache: std.StringHashMap(?*Zdef), +type_expr_cache: std.StringHashMapUnmanaged(?*Zdef) = .empty, pub fn init(gc: *GC) Self { return .{ @@ -200,12 +200,11 @@ pub fn init(gc: *GC) Self { .allocator = gc.allocator, .error_prefix = "FFI", }, - .type_expr_cache = .init(gc.allocator), }; } pub fn deinit(self: *Self) void { - self.type_expr_cache.deinit(); + self.type_expr_cache.deinit(self.gc.allocator); } pub fn parseTypeExpr(self: *Self, ztype: []const u8) !?*Zdef { @@ -213,10 +212,10 @@ pub fn parseTypeExpr(self: *Self, ztype: []const u8) !?*Zdef { return zdef; } - var full = std.array_list.Managed(u8).init(self.gc.allocator); - defer full.deinit(); + var full = std.ArrayList(u8).empty; + defer full.deinit(self.gc.allocator); - full.writer().print("const zig_type: {s};", .{ztype}) catch @panic("Out of memory"); + full.writer(self.gc.allocator).print("const zig_type: {s};", .{ztype}) catch @panic("Out of memory"); const zdef = try self.parse( null, @@ -227,6 +226,7 @@ pub fn parseTypeExpr(self: *Self, ztype: []const u8) !?*Zdef { std.debug.assert(zdef == null or zdef.?.len == 1); self.type_expr_cache.put( + self.gc.allocator, ztype, if (zdef) |z| z[0] else null, ) catch @panic("Out of memory"); @@ -259,10 +259,9 @@ pub fn parse(self: *Self, parser: ?*Parser, source: Ast.TokenIndex, type_expr: ? duped, .zig, ) catch @panic("Could not parse zdef"), - .structs = .init(self.gc.allocator), }; defer { - self.state.?.structs.deinit(); + self.state.?.structs.deinit(self.gc.allocator); self.state = null; } @@ -291,15 +290,15 @@ pub fn parse(self: *Self, parser: ?*Parser, source: Ast.TokenIndex, type_expr: ? return null; } - var zdefs = std.array_list.Managed(*Zdef).init(self.gc.allocator); + var zdefs = std.ArrayList(*Zdef).empty; for (root_decls) |decl| { if (try self.getZdef(decl)) |zdef| { - try zdefs.append(zdef); + try zdefs.append(self.gc.allocator, zdef); } } - return try zdefs.toOwnedSlice(); + return try zdefs.toOwnedSlice(self.gc.allocator); } fn getZdef(self: *Self, decl_index: Ast.Node.Index) !?*Zdef { @@ -345,7 +344,11 @@ fn getZdef(self: *Self, decl_index: Ast.Node.Index) !?*Zdef { ast.simpleVarDecl(decl_index).ast.init_node.unwrap().?, ); - try self.state.?.structs.put(name, zdef); + try self.state.?.structs.put( + self.gc.allocator, + name, + zdef, + ); break :var_decl zdef; }, @@ -468,10 +471,10 @@ fn containerDecl(self: *Self, name: []const u8, decl_index: Ast.Node.Index) anye } fn unionContainer(self: *Self, name: []const u8, container: Ast.full.ContainerDecl) anyerror!*Zdef { - var fields = std.array_list.Managed(ZigType.UnionField).init(self.gc.allocator); - var get_set_fields = std.StringArrayHashMap(o.ObjForeignContainer.ContainerDef.Field).init(self.gc.allocator); - var buzz_fields = std.StringArrayHashMap(*o.ObjTypeDef).init(self.gc.allocator); - var decls = std.array_list.Managed(ZigType.Declaration).init(self.gc.allocator); + var fields = std.ArrayList(ZigType.UnionField).empty; + var get_set_fields = std.StringArrayHashMapUnmanaged(o.ObjForeignContainer.ContainerDef.Field).empty; + var buzz_fields = std.StringArrayHashMapUnmanaged(*o.ObjTypeDef).empty; + var decls = std.ArrayList(ZigType.Declaration).empty; var next_field: ?*Zdef = null; for (container.ast.members, 0..) |member, idx| { const member_zdef = next_field orelse try self.getZdef(member); @@ -482,6 +485,7 @@ fn unionContainer(self: *Self, name: []const u8, container: Ast.full.ContainerDe null; try fields.append( + self.gc.allocator, ZigType.UnionField{ .name = member_zdef.?.name, .type = &member_zdef.?.zig_type, @@ -490,17 +494,20 @@ fn unionContainer(self: *Self, name: []const u8, container: Ast.full.ContainerDe ); try decls.append( + self.gc.allocator, ZigType.Declaration{ .name = member_zdef.?.name, }, ); try buzz_fields.put( + self.gc.allocator, member_zdef.?.name, member_zdef.?.type_def, ); try get_set_fields.put( + self.gc.allocator, member_zdef.?.name, .{ // Always 0 since this is an enum @@ -520,10 +527,10 @@ fn unionContainer(self: *Self, name: []const u8, container: Ast.full.ContainerDe }, }; - var qualified_name = std.array_list.Managed(u8).init(self.gc.allocator); - defer qualified_name.deinit(); + var qualified_name = std.ArrayList(u8).empty; + defer qualified_name.deinit(self.gc.allocator); - try qualified_name.writer().print( + try qualified_name.writer(self.gc.allocator).print( "{s}.{s}", .{ self.state.?.script, @@ -557,10 +564,10 @@ fn unionContainer(self: *Self, name: []const u8, container: Ast.full.ContainerDe } fn structContainer(self: *Self, name: []const u8, container: Ast.full.ContainerDecl) anyerror!*Zdef { - var fields = std.array_list.Managed(ZigType.StructField).init(self.gc.allocator); - var get_set_fields = std.StringArrayHashMap(o.ObjForeignContainer.ContainerDef.Field).init(self.gc.allocator); - var buzz_fields = std.StringArrayHashMap(*o.ObjTypeDef).init(self.gc.allocator); - var decls = std.array_list.Managed(ZigType.Declaration).init(self.gc.allocator); + var fields = std.ArrayList(ZigType.StructField).empty; + var get_set_fields = std.StringArrayHashMapUnmanaged(o.ObjForeignContainer.ContainerDef.Field).empty; + var buzz_fields = std.StringArrayHashMapUnmanaged(*o.ObjTypeDef).empty; + var decls = std.ArrayList(ZigType.Declaration).empty; var offset: usize = 0; var next_field: ?*Zdef = null; for (container.ast.members, 0..) |member, idx| { @@ -572,6 +579,7 @@ fn structContainer(self: *Self, name: []const u8, container: Ast.full.ContainerD null; try fields.append( + self.gc.allocator, ZigType.StructField{ .name = member_zdef.?.name, .type = &member_zdef.?.zig_type, @@ -582,17 +590,20 @@ fn structContainer(self: *Self, name: []const u8, container: Ast.full.ContainerD ); try decls.append( + self.gc.allocator, ZigType.Declaration{ .name = member_zdef.?.name, }, ); try buzz_fields.put( + self.gc.allocator, member_zdef.?.name, member_zdef.?.type_def, ); try get_set_fields.put( + self.gc.allocator, member_zdef.?.name, .{ .offset = offset, @@ -836,7 +847,7 @@ fn fnProto(self: *Self, tag: Ast.Node.Tag, decl_index: Ast.Node.Index) anyerror! .function_type = .Extern, }; - var parameters_zig_types = std.array_list.Managed(ZigType.FnType.Param).init(self.gc.allocator); + var parameters_zig_types = std.ArrayList(ZigType.FnType.Param).empty; var zig_fn_type = ZigType.FnType{ .calling_convention = .c, // How could it be something else? @@ -880,6 +891,7 @@ fn fnProto(self: *Self, tag: Ast.Node.Tag, decl_index: Ast.Node.Index) anyerror! ); try parameters_zig_types.append( + self.gc.allocator, .{ .is_generic = false, .is_noalias = false, @@ -888,7 +900,7 @@ fn fnProto(self: *Self, tag: Ast.Node.Tag, decl_index: Ast.Node.Index) anyerror! ); } - zig_fn_type.params = try parameters_zig_types.toOwnedSlice(); + zig_fn_type.params = try parameters_zig_types.toOwnedSlice(self.gc.allocator); const type_def = o.ObjTypeDef{ .def_type = .Function, @@ -906,10 +918,10 @@ fn fnProto(self: *Self, tag: Ast.Node.Tag, decl_index: Ast.Node.Index) anyerror! } fn reportZigError(self: *Self, err: Ast.Error) void { - var message = std.array_list.Managed(u8).init(self.gc.allocator); - defer message.deinit(); + var message = std.ArrayList(u8).empty; + defer message.deinit(self.gc.allocator); - message.writer().print("zdef could not be parsed: {}", .{err.tag}) catch unreachable; + message.writer(self.gc.allocator).print("zdef could not be parsed: {}", .{err.tag}) catch unreachable; const location = self.state.?.buzz_ast.?.tokens.get(self.state.?.source); self.reporter.report( diff --git a/src/GC.zig b/src/GC.zig index 995fb09d..52f64365 100644 --- a/src/GC.zig +++ b/src/GC.zig @@ -941,13 +941,13 @@ pub const Debugger = struct { if (self.tracker.getPtr(ptr)) |tracked| { if (tracked.collected_at) |collected_at| { - var items = std.array_list.Managed(Reporter.ReportItem).init(self.allocator); - defer items.deinit(); + var items = std.ArrayList(Reporter.ReportItem).empty; + defer items.deinit(self.allocator); - var message = std.array_list.Managed(u8).init(self.allocator); - defer message.deinit(); + var message = std.ArrayList(u8).empty; + defer message.deinit(self.allocator); - message.writer().print( + message.writer(self.allocator).print( "Access to already collected {} {*}", .{ tracked.what, @@ -956,6 +956,7 @@ pub const Debugger = struct { ) catch unreachable; items.append( + self.allocator, .{ .location = at.?, .end_location = at.?, @@ -966,6 +967,7 @@ pub const Debugger = struct { if (tracked.allocated_at) |allocated_at| { items.append( + self.allocator, .{ .location = allocated_at, .end_location = allocated_at, @@ -976,6 +978,7 @@ pub const Debugger = struct { } items.append( + self.allocator, .{ .location = collected_at, .end_location = collected_at, diff --git a/src/Jit.zig b/src/Jit.zig index 0afd718b..cbdb0c1e 100644 --- a/src/Jit.zig +++ b/src/Jit.zig @@ -2196,8 +2196,8 @@ fn generateCall(self: *Self, node: Ast.Node.Index) Error!?m.MIR_op_t { const defaults = function_type_def.resolved_type.?.Function.defaults; const arg_keys = args.keys(); - var arguments = std.AutoArrayHashMap(*o.ObjString, m.MIR_op_t).init(self.vm.gc.allocator); - defer arguments.deinit(); + var arguments = std.AutoArrayHashMapUnmanaged(*o.ObjString, m.MIR_op_t).empty; + defer arguments.deinit(self.vm.gc.allocator); // Evaluate arguments for (components.arguments, 0..) |argument, index| { @@ -2207,6 +2207,7 @@ fn generateCall(self: *Self, node: Ast.Node.Index) Error!?m.MIR_op_t { (try self.vm.gc.copyString(lexemes[argument.name.?])); try arguments.put( + self.vm.gc.allocator, actual_arg_key, (try self.generateNode(argument.value)).?, ); diff --git a/src/Parser.zig b/src/Parser.zig index 79b648f4..19b53d79 100644 --- a/src/Parser.zig +++ b/src/Parser.zig @@ -1034,18 +1034,18 @@ pub fn parse(self: *Self, source: []const u8, file_name: ?[]const u8, name: []co } } - var test_slots = std.array_list.Managed(usize).init(self.gc.allocator); - var test_locations = std.array_list.Managed(Ast.TokenIndex).init(self.gc.allocator); + var test_slots = std.ArrayList(usize).empty; + var test_locations = std.ArrayList(Ast.TokenIndex).empty; // Create an entry point wich runs all `test` for (self.globals.items, 0..) |global, index| { if (global.type_def.def_type == .Function and global.type_def.resolved_type.?.Function.function_type == .Test) { - try test_slots.append(index); - try test_locations.append(global.name[0]); + try test_slots.append(self.gc.allocator, index); + try test_locations.append(self.gc.allocator, global.name[0]); } } - entry.test_slots = try test_slots.toOwnedSlice(); - entry.test_locations = try test_locations.toOwnedSlice(); + entry.test_slots = try test_slots.toOwnedSlice(self.gc.allocator); + entry.test_locations = try test_locations.toOwnedSlice(self.gc.allocator); // If we're being imported, put all globals on the stack if (self.imported) { @@ -1244,7 +1244,7 @@ fn beginScope(self: *Self, at: ?Ast.Node.Index) !void { fn endScope(self: *Self) ![]Chunk.OpCode { const current = self.current.?; _ = current.scopes.pop(); - var closing = std.ArrayList(Chunk.OpCode){}; + var closing = std.ArrayList(Chunk.OpCode).empty; current.scope_depth -= 1; while (current.local_count > 0 and current.locals[current.local_count - 1].depth > current.scope_depth) { @@ -1264,20 +1264,20 @@ fn endScope(self: *Self) ![]Chunk.OpCode { fn closeScope(self: *Self, upto_depth: usize) ![]Chunk.OpCode { const current = self.current.?; - var closing = std.array_list.Managed(Chunk.OpCode).init(self.gc.allocator); + var closing = std.ArrayList(Chunk.OpCode).empty; var local_count = current.local_count; while (local_count > 0 and current.locals[local_count - 1].depth > upto_depth - 1) { if (current.locals[local_count - 1].captured) { - try closing.append(.OP_CLOSE_UPVALUE); + try closing.append(self.gc.allocator, .OP_CLOSE_UPVALUE); } else { - try closing.append(.OP_POP); + try closing.append(self.gc.allocator, .OP_POP); } local_count -= 1; } - return try closing.toOwnedSlice(); + return try closing.toOwnedSlice(self.gc.allocator); } inline fn getRule(token: Token.Type) ParseRule { @@ -1378,10 +1378,10 @@ fn parsePrecedence(self: *Self, precedence: Precedence, hanging: bool) Error!Ast fn block(self: *Self, loop_scope: ?LoopScope) Error!Ast.Node.Index { const start_location = self.current_token.? - 1; - var statements = std.array_list.Managed(Ast.Node.Index).init(self.gc.allocator); + var statements = std.ArrayList(Ast.Node.Index).empty; while (!self.check(.RightBrace) and !self.check(.Eof)) { if (try self.declarationOrStatement(loop_scope)) |declOrStmt| { - try statements.append(declOrStmt); + try statements.append(self.gc.allocator, declOrStmt); } } @@ -1394,7 +1394,7 @@ fn block(self: *Self, loop_scope: ?LoopScope) Error!Ast.Node.Index { .end_location = self.current_token.? - 1, .type_def = null, .components = .{ - .Block = try statements.toOwnedSlice(), + .Block = try statements.toOwnedSlice(self.gc.allocator), }, }, ); @@ -1731,16 +1731,16 @@ fn addGlobal( return 0; } - var qualified_name = std.array_list.Managed(Ast.TokenIndex).init(self.gc.allocator); + var qualified_name = std.ArrayList(Ast.TokenIndex).empty; if (self.namespace) |namespace| { - try qualified_name.appendSlice(namespace); + try qualified_name.appendSlice(self.gc.allocator, namespace); } - try qualified_name.append(name); + try qualified_name.append(self.gc.allocator, name); try self.globals.append( self.gc.allocator, .{ - .name = try qualified_name.toOwnedSlice(), + .name = try qualified_name.toOwnedSlice(self.gc.allocator), .node = node, .type_def = global_type, .final = final, @@ -1892,6 +1892,7 @@ fn resolvePlaceholderWithRelation( }, child_placeholder.resolved_generics.?, &self.gc.type_registry, + self.gc.allocator, null, ), true, @@ -3289,9 +3290,9 @@ fn parseFunctionType(self: *Self, parent_generic_types: ?std.AutoArrayHashMapUnm try self.consume(.LeftParen, "Expected `(` after function name."); - var arguments = std.array_list.Managed(Ast.FunctionType.Argument).init(self.gc.allocator); - var parameters = std.AutoArrayHashMapUnmanaged(*obj.ObjString, *obj.ObjTypeDef){}; - var defaults = std.AutoArrayHashMapUnmanaged(*obj.ObjString, Value){}; + var arguments = std.ArrayList(Ast.FunctionType.Argument).empty; + var parameters = std.AutoArrayHashMapUnmanaged(*obj.ObjString, *obj.ObjTypeDef).empty; + var defaults = std.AutoArrayHashMapUnmanaged(*obj.ObjString, Value).empty; var arity: usize = 0; while (!self.check(.RightParen) and !self.check(.Eof)) { arity += 1; @@ -3344,6 +3345,7 @@ fn parseFunctionType(self: *Self, parent_generic_types: ?std.AutoArrayHashMapUnm } try arguments.append( + self.gc.allocator, .{ .name = arg_name_token, .default = default, @@ -3387,16 +3389,16 @@ fn parseFunctionType(self: *Self, parent_generic_types: ?std.AutoArrayHashMapUnm yield_type = try self.parseTypeDef(null, true); } - var error_types_list = std.array_list.Managed(Ast.Node.Index).init(self.gc.allocator); - var error_types = std.array_list.Managed(*obj.ObjTypeDef).init(self.gc.allocator); + var error_types_list = std.ArrayList(Ast.Node.Index).empty; + var error_types = std.ArrayList(*obj.ObjTypeDef).empty; if (try self.match(.BangGreater)) { const expects_multiple_error_types = try self.match(.LeftParen); while (!self.check(.Eof)) { const error_type = try self.parseTypeDef(generic_types, true); const error_type_def = self.ast.nodes.items(.type_def)[error_type].?; - try error_types_list.append(error_type); - try error_types.append(error_type_def); + try error_types_list.append(self.gc.allocator, error_type); + try error_types.append(self.gc.allocator, error_type_def); if (error_type_def.optional) { self.reportErrorAtNode( @@ -3453,8 +3455,8 @@ fn parseFunctionType(self: *Self, parent_generic_types: ?std.AutoArrayHashMapUnm .is_signature = false, .lambda = false, .name = name_token, - .arguments = try arguments.toOwnedSlice(), - .error_types = try error_types_list.toOwnedSlice(), + .arguments = try arguments.toOwnedSlice(self.gc.allocator), + .error_types = try error_types_list.toOwnedSlice(self.gc.allocator), .generic_types = try generic_types_list.toOwnedSlice(self.gc.allocator), .return_type = return_type, .yield_type = yield_type, @@ -3472,9 +3474,9 @@ fn parseObjType(self: *Self, generic_types: ?std.AutoArrayHashMapUnmanaged(*obj. const qualifier = try std.mem.replaceOwned(u8, self.gc.allocator, self.script_name, "/", "."); defer self.gc.allocator.free(qualifier); - var qualified_name = std.array_list.Managed(u8).init(self.gc.allocator); - defer qualified_name.deinit(); - try qualified_name.writer().print("{s}.anonymous", .{qualifier}); + var qualified_name = std.ArrayList(u8).empty; + defer qualified_name.deinit(self.gc.allocator); + try qualified_name.writer(self.gc.allocator).print("{s}.anonymous", .{qualifier}); const object_def = obj.ObjObject.ObjectDef.init( start_location, @@ -3492,9 +3494,9 @@ fn parseObjType(self: *Self, generic_types: ?std.AutoArrayHashMapUnmanaged(*obj. // Anonymous object can only have properties without default values (no methods, no static fields) // They can't self reference since their anonymous - var field_names = std.StringHashMap(void).init(self.gc.allocator); - defer field_names.deinit(); - var fields = std.array_list.Managed(Ast.AnonymousObjectType.Field).init(self.gc.allocator); + var field_names = std.StringHashMapUnmanaged(void).empty; + defer field_names.deinit(self.gc.allocator); + var fields = std.ArrayList(Ast.AnonymousObjectType.Field).empty; var tuple_index: u8 = 0; var obj_is_tuple = false; var obj_is_not_tuple = false; @@ -3587,8 +3589,13 @@ fn parseObjType(self: *Self, generic_types: ?std.AutoArrayHashMapUnmanaged(*obj. .index = property_idx, }, ); - try field_names.put(property_name_lexeme, {}); + try field_names.put( + self.gc.allocator, + property_name_lexeme, + {}, + ); try fields.append( + self.gc.allocator, .{ .name = property_name, .type = property_type, @@ -3610,7 +3617,7 @@ fn parseObjType(self: *Self, generic_types: ?std.AutoArrayHashMapUnmanaged(*obj. .type_def = try self.gc.type_registry.getTypeDef(object_type), .components = .{ .AnonymousObjectType = .{ - .fields = try fields.toOwnedSlice(), + .fields = try fields.toOwnedSlice(self.gc.allocator), }, }, }, @@ -3669,8 +3676,8 @@ fn parseUserType(self: *Self, instance: bool, mutable: bool) Error!Ast.Node.Inde } // Concrete generic types list - var resolved_generics = std.array_list.Managed(*obj.ObjTypeDef).init(self.gc.allocator); - var generic_nodes = std.array_list.Managed(Ast.Node.Index).init(self.gc.allocator); + var resolved_generics = std.ArrayList(*obj.ObjTypeDef).empty; + var generic_nodes = std.ArrayList(Ast.Node.Index).empty; const generic_resolve = if (try self.match(.DoubleColon)) gn: { const generic_start = self.current_token.? - 1; @@ -3679,6 +3686,7 @@ fn parseUserType(self: *Self, instance: bool, mutable: bool) Error!Ast.Node.Inde var i: usize = 0; while (!self.check(.Greater) and !self.check(.Eof)) : (i += 1) { try generic_nodes.append( + self.gc.allocator, try self.parseTypeDef( if (self.current.?.generics) |generics| generics.* @@ -3689,6 +3697,7 @@ fn parseUserType(self: *Self, instance: bool, mutable: bool) Error!Ast.Node.Inde ); try resolved_generics.append( + self.gc.allocator, self.ast.nodes.items(.type_def)[generic_nodes.items[generic_nodes.items.len - 1]].?, ); @@ -3712,8 +3721,9 @@ fn parseUserType(self: *Self, instance: bool, mutable: bool) Error!Ast.Node.Inde var_type = try var_type.?.populateGenerics( self.current_token.? - 1, var_type.?.resolved_type.?.Object.id, - try resolved_generics.toOwnedSlice(), + try resolved_generics.toOwnedSlice(self.gc.allocator), &self.gc.type_registry, + self.gc.allocator, null, ); break :gn try self.ast.appendNode( @@ -3723,7 +3733,7 @@ fn parseUserType(self: *Self, instance: bool, mutable: bool) Error!Ast.Node.Inde .end_location = self.current_token.? - 1, .type_def = var_type, .components = .{ - .GenericResolveType = try generic_nodes.toOwnedSlice(), + .GenericResolveType = try generic_nodes.toOwnedSlice(self.gc.allocator), }, }, ); @@ -3762,8 +3772,8 @@ fn parseGenericResolve(self: *Self, callee_type_def: *obj.ObjTypeDef, expr: ?Ast else self.current_token.? - 1; - var resolved_generics = std.array_list.Managed(Ast.Node.Index).init(self.gc.allocator); - var resolved_generics_types = std.array_list.Managed(*obj.ObjTypeDef).init(self.gc.allocator); + var resolved_generics = std.ArrayList(Ast.Node.Index).empty; + var resolved_generics_types = std.ArrayList(*obj.ObjTypeDef).empty; try self.consume(.Less, "Expected `<` at start of generic types list"); @@ -3779,8 +3789,8 @@ fn parseGenericResolve(self: *Self, callee_type_def: *obj.ObjTypeDef, expr: ?Ast ); } - try resolved_generics.append(resolved_generic); - try resolved_generics_types.append(self.ast.nodes.items(.type_def)[resolved_generic].?); + try resolved_generics.append(self.gc.allocator, resolved_generic); + try resolved_generics_types.append(self.gc.allocator, self.ast.nodes.items(.type_def)[resolved_generic].?); if (!self.check(.Greater)) { try self.consume(.Comma, "Expected `,` between generic types"); @@ -3805,17 +3815,18 @@ fn parseGenericResolve(self: *Self, callee_type_def: *obj.ObjTypeDef, expr: ?Ast callee_type_def.resolved_type.?.Object.id else null, - try resolved_generics_types.toOwnedSlice(), + try resolved_generics_types.toOwnedSlice(self.gc.allocator), &self.gc.type_registry, + self.gc.allocator, null, ), .components = if (expr) |e| .{ .GenericResolve = .{ .expression = e, - .resolved_types = try resolved_generics.toOwnedSlice(), + .resolved_types = try resolved_generics.toOwnedSlice(self.gc.allocator), }, } else .{ - .GenericResolveType = try resolved_generics.toOwnedSlice(), + .GenericResolveType = try resolved_generics.toOwnedSlice(self.gc.allocator), }, }, ); @@ -3952,7 +3963,7 @@ fn expressionStatement(self: *Self, hanging: bool) Error!Ast.Node.Index { fn list(self: *Self, _: bool) Error!Ast.Node.Index { const start_location = self.current_token.? - 1; - var items = std.array_list.Managed(Ast.Node.Index).init(self.gc.allocator); + var items = std.ArrayList(Ast.Node.Index).empty; var explicit_item_type: ?Ast.Node.Index = null; var item_type: ?*obj.ObjTypeDef = null; @@ -3970,7 +3981,7 @@ fn list(self: *Self, _: bool) Error!Ast.Node.Index { while (!(try self.match(.RightBracket)) and !(try self.match(.Eof))) { const actual_item = try self.expression(false); - try items.append(actual_item); + try items.append(self.gc.allocator, actual_item); if (item_type == null) { if (common_type == null) { @@ -4140,7 +4151,7 @@ fn grouping(self: *Self, _: bool) Error!Ast.Node.Index { } fn argumentList(self: *Self) ![]Ast.Call.Argument { - var arguments = std.array_list.Managed(Ast.Call.Argument).init(self.gc.allocator); + var arguments = std.ArrayList(Ast.Call.Argument).empty; const start_location = self.current_token.? - 1; @@ -4173,6 +4184,7 @@ fn argumentList(self: *Self) ![]Ast.Call.Argument { const is_named_expr = arg_count != 0 and arg_name != null and hanging and (self.check(.Comma) or self.check(.RightParen)); try arguments.append( + self.gc.allocator, .{ .name = if ((!hanging and arg_name != null) or is_named_expr) arg_name.? @@ -4190,7 +4202,7 @@ fn argumentList(self: *Self) ![]Ast.Call.Argument { "Can't have more than 255 arguments.", ); - return try arguments.toOwnedSlice(); + return try arguments.toOwnedSlice(self.gc.allocator); } arg_count += 1; @@ -4301,7 +4313,7 @@ fn map(self: *Self, _: bool) Error!Ast.Node.Index { try self.consume(.Greater, "Expected `>` after map type."); } - var entries = std.array_list.Managed(Ast.Map.Entry).init(self.gc.allocator); + var entries = std.ArrayList(Ast.Map.Entry).empty; if (key_type_node == null or try self.match(.Comma)) { var common_key_type: ?*obj.ObjTypeDef = null; var common_value_type: ?*obj.ObjTypeDef = null; @@ -4313,6 +4325,7 @@ fn map(self: *Self, _: bool) Error!Ast.Node.Index { const value = try self.expression(false); try entries.append( + self.gc.allocator, .{ .key = key, .value = value, @@ -4444,7 +4457,7 @@ fn map(self: *Self, _: bool) Error!Ast.Node.Index { .Map = .{ .explicit_key_type = key_type_node, .explicit_value_type = value_type_node, - .entries = try entries.toOwnedSlice(), + .entries = try entries.toOwnedSlice(self.gc.allocator), }, }, }, @@ -4454,9 +4467,9 @@ fn map(self: *Self, _: bool) Error!Ast.Node.Index { fn objectInit(self: *Self, _: bool, object: Ast.Node.Index) Error!Ast.Node.Index { const start_location = self.ast.nodes.items(.location)[object]; const obj_type_def = self.ast.nodes.items(.type_def)[object]; - var properties = std.array_list.Managed(Ast.ObjectInit.Property).init(self.gc.allocator); - var property_names = std.StringHashMap(Ast.Node.Index).init(self.gc.allocator); - defer property_names.deinit(); + var properties = std.ArrayList(Ast.ObjectInit.Property).empty; + var property_names = std.StringHashMapUnmanaged(Ast.Node.Index).empty; + defer property_names.deinit(self.gc.allocator); while (!self.check(.RightBrace) and !self.check(.Eof)) { try self.consume(.Identifier, "Expected property name"); @@ -4477,7 +4490,11 @@ fn objectInit(self: *Self, _: bool, object: Ast.Node.Index) Error!Ast.Node.Index "Defined here", ); } - try property_names.put(property_name_lexeme, property_name); + try property_names.put( + self.gc.allocator, + property_name_lexeme, + property_name, + ); var property_placeholder: ?*obj.ObjTypeDef = null; @@ -4508,6 +4525,7 @@ fn objectInit(self: *Self, _: bool, object: Ast.Node.Index) Error!Ast.Node.Index // Named variable with the same name as property if (self.check(.Comma) or self.check(.RightBrace)) { try properties.append( + self.gc.allocator, .{ .name = property_name, .value = try self.expression(true), @@ -4517,6 +4535,7 @@ fn objectInit(self: *Self, _: bool, object: Ast.Node.Index) Error!Ast.Node.Index try self.consume(.Equal, "Expected `=` after property name."); try properties.append( + self.gc.allocator, .{ .name = property_name, .value = try self.expression(false), @@ -4546,7 +4565,7 @@ fn objectInit(self: *Self, _: bool, object: Ast.Node.Index) Error!Ast.Node.Index .components = .{ .ObjectInit = .{ .object = object, - .properties = try properties.toOwnedSlice(), + .properties = try properties.toOwnedSlice(self.gc.allocator), }, }, }, @@ -4559,9 +4578,9 @@ fn anonymousObjectInit(self: *Self, _: bool) Error!Ast.Node.Index { const qualifier = try std.mem.replaceOwned(u8, self.gc.allocator, self.script_name, "/", "."); defer self.gc.allocator.free(qualifier); - var qualified_name = std.array_list.Managed(u8).init(self.gc.allocator); - defer qualified_name.deinit(); - try qualified_name.writer().print("{s}.anonymous", .{qualifier}); + var qualified_name = std.ArrayList(u8).empty; + defer qualified_name.deinit(self.gc.allocator); + try qualified_name.writer(self.gc.allocator).print("{s}.anonymous", .{qualifier}); const object_def = obj.ObjObject.ObjectDef.init( start_location, @@ -4580,9 +4599,9 @@ fn anonymousObjectInit(self: *Self, _: bool) Error!Ast.Node.Index { // Anonymous object can only have properties without default values (no methods, no static fields) // They can't self reference since their anonymous - var properties = std.array_list.Managed(Ast.ObjectInit.Property).init(self.gc.allocator); - var property_names = std.StringHashMap(Ast.Node.Index).init(self.gc.allocator); - defer property_names.deinit(); + var properties = std.ArrayList(Ast.ObjectInit.Property).empty; + var property_names = std.StringHashMapUnmanaged(Ast.Node.Index).empty; + defer property_names.deinit(self.gc.allocator); var tuple_index: u8 = 0; var obj_is_tuple = false; @@ -4644,11 +4663,13 @@ fn anonymousObjectInit(self: *Self, _: bool) Error!Ast.Node.Index { const property_name_lexeme = self.ast.tokens.items(.lexeme)[property_name]; try property_names.put( + self.gc.allocator, property_name_lexeme, property_name, ); try properties.append( + self.gc.allocator, .{ .name = property_name, .value = expr, @@ -4703,7 +4724,11 @@ fn anonymousObjectInit(self: *Self, _: bool) Error!Ast.Node.Index { "Defined here", ); } - try property_names.put(property_name_lexeme, property_name); + try property_names.put( + self.gc.allocator, + property_name_lexeme, + property_name, + ); // Named variable with the same name as property or tuple notation try self.consume(.Equal, "Expected `=` after property name."); @@ -4711,6 +4736,7 @@ fn anonymousObjectInit(self: *Self, _: bool) Error!Ast.Node.Index { const expr = try self.expression(false); try properties.append( + self.gc.allocator, .{ .name = property_name, .value = expr, @@ -4755,7 +4781,7 @@ fn anonymousObjectInit(self: *Self, _: bool) Error!Ast.Node.Index { .components = .{ .ObjectInit = .{ .object = null, - .properties = try properties.toOwnedSlice(), + .properties = try properties.toOwnedSlice(self.gc.allocator), }, }, }, @@ -5955,16 +5981,16 @@ fn qualifiedName(self: *Self) Error![]const Ast.TokenIndex { // Assumes one identifier has already been consumed std.debug.assert(self.ast.tokens.items(.tag)[self.current_token.? - 1] == .Identifier); - var name = std.array_list.Managed(Ast.TokenIndex).init(self.gc.allocator); + var name = std.ArrayList(Ast.TokenIndex).empty; - try name.append(self.current_token.? - 1); + try name.append(self.gc.allocator, self.current_token.? - 1); while ((try self.match(.AntiSlash)) and !self.check(.Eof)) { try self.consume(.Identifier, "Expected identifier"); - try name.append(self.current_token.? - 1); + try name.append(self.gc.allocator, self.current_token.? - 1); } - return try name.toOwnedSlice(); + return try name.toOwnedSlice(self.gc.allocator); } fn variable(self: *Self, can_assign: bool) Error!Ast.Node.Index { @@ -5984,9 +6010,9 @@ fn function( function_type: obj.ObjFunction.FunctionType, this: ?*obj.ObjTypeDef, ) Error!Ast.Node.Index { - var error_types = std.array_list.Managed(Ast.Node.Index).init(self.gc.allocator); - var arguments = std.array_list.Managed(Ast.FunctionType.Argument).init(self.gc.allocator); - var generic_types = std.array_list.Managed(Ast.TokenIndex).init(self.gc.allocator); + var error_types = std.ArrayList(Ast.Node.Index).empty; + var arguments = std.ArrayList(Ast.FunctionType.Argument).empty; + var generic_types = std.ArrayList(Ast.TokenIndex).empty; const function_signature = try self.ast.appendNode( .{ @@ -6094,7 +6120,7 @@ fn function( ), ); - try generic_types.append(generic_identifier_token); + try generic_types.append(self.gc.allocator, generic_identifier_token); } else { const location = self.ast.tokens.get(self.current_token.? - 1); self.reporter.reportErrorFmt( @@ -6126,7 +6152,7 @@ fn function( try self.consume(.Greater, "Expected `>` after generic types list"); } - self.ast.nodes.items(.components)[function_signature].FunctionType.generic_types = try generic_types.toOwnedSlice(); + self.ast.nodes.items(.components)[function_signature].FunctionType.generic_types = try generic_types.toOwnedSlice(self.gc.allocator); try self.consume(.LeftParen, "Expected `(` after function name."); @@ -6210,6 +6236,7 @@ fn function( }; try arguments.append( + self.gc.allocator, .{ .name = local.name, .type = argument_type_node, @@ -6233,7 +6260,7 @@ fn function( try self.consume(.RightParen, "Expected `)` after function parameters."); } - self.ast.nodes.items(.components)[function_signature].FunctionType.arguments = try arguments.toOwnedSlice(); + self.ast.nodes.items(.components)[function_signature].FunctionType.arguments = try arguments.toOwnedSlice(self.gc.allocator); // Parse return type const return_type_node = if (function_type != .Test and try self.match(.Greater)) @@ -6285,7 +6312,7 @@ fn function( // Error set if (function_type.canHaveErrorSet() and (try self.match(.BangGreater))) { - var error_typedefs = std.array_list.Managed(*obj.ObjTypeDef).init(self.gc.allocator); + var error_typedefs = std.ArrayList(*obj.ObjTypeDef).empty; const end_token: Token.Type = if (function_type.canOmitBody()) .Semicolon else .LeftBrace; @@ -6296,8 +6323,8 @@ fn function( ); const error_type = self.ast.nodes.items(.type_def)[error_type_node].?; - try error_types.append(error_type_node); - try error_typedefs.append(error_type); + try error_types.append(self.gc.allocator, error_type_node); + try error_typedefs.append(self.gc.allocator, error_type); if (error_type.optional) { self.reportErrorAtNode( @@ -6314,11 +6341,13 @@ fn function( } if (error_types.items.len > 0) { - function_typedef.resolved_type.?.Function.error_types = try error_typedefs.toOwnedSlice(); + function_typedef.resolved_type.?.Function.error_types = try error_typedefs.toOwnedSlice( + self.gc.allocator, + ); } } - self.ast.nodes.items(.components)[function_signature].FunctionType.error_types = try error_types.toOwnedSlice(); + self.ast.nodes.items(.components)[function_signature].FunctionType.error_types = try error_types.toOwnedSlice(self.gc.allocator); self.ast.nodes.items(.end_location)[function_signature] = self.current_token.? - 1; // Parse body @@ -6853,12 +6882,12 @@ fn blockExpression(self: *Self, _: bool) Error!Ast.Node.Index { try self.beginScope(null); self.current.?.in_block_expression = self.current.?.scope_depth; - var statements = std.array_list.Managed(Ast.Node.Index).init(self.gc.allocator); + var statements = std.ArrayList(Ast.Node.Index).empty; var out: ?Ast.Node.Index = null; while (!self.check(.RightBrace) and !self.check(.Eof)) { if (try self.declarationOrStatement(null)) |stmt| { - try statements.append(stmt); + try statements.append(self.gc.allocator, stmt); if (self.ast.nodes.items(.tag)[stmt] == .Out) { if (out != null) { @@ -6908,7 +6937,7 @@ fn blockExpression(self: *Self, _: bool) Error!Ast.Node.Index { else self.gc.type_registry.void_type, .components = .{ - .BlockExpression = try statements.toOwnedSlice(), + .BlockExpression = try statements.toOwnedSlice(self.gc.allocator), }, .ends_scope = try self.endScope(), }, @@ -7155,10 +7184,12 @@ fn exportStatement(self: *Self, docblock: ?Ast.TokenIndex) Error!Ast.Node.Index // If we're exporting an imported global, overwrite its namespace const name = global.name[global.name.len - 1]; // self.gc.allocator.free(global.name); - var new_global_name = std.array_list.Managed(Ast.TokenIndex).init(self.gc.allocator); - try new_global_name.appendSlice(self.namespace orelse &[_]Ast.TokenIndex{}); - try new_global_name.append(name); - global.name = try new_global_name.toOwnedSlice(); + var new_global_name = std.ArrayList(Ast.TokenIndex).empty; + try new_global_name.appendSlice(self.gc.allocator, self.namespace orelse &[_]Ast.TokenIndex{}); + try new_global_name.append(self.gc.allocator, name); + global.name = try new_global_name.toOwnedSlice( + self.gc.allocator, + ); try self.consume(.Semicolon, "Expected `;` after statement."); @@ -7253,7 +7284,7 @@ fn objectDeclaration(self: *Self) Error!Ast.Node.Index { // Conforms to protocols? var protocols = std.AutoHashMapUnmanaged(*obj.ObjTypeDef, void){}; - var protocol_nodes = std.array_list.Managed(Ast.Node.Index).init(self.gc.allocator); + var protocol_nodes = std.ArrayList(Ast.Node.Index).empty; var protocol_count: usize = 0; if (try self.match(.Less)) { while (!self.check(.Greater) and !self.check(.Eof)) : (protocol_count += 1) { @@ -7294,7 +7325,7 @@ fn objectDeclaration(self: *Self) Error!Ast.Node.Index { protocol, {}, ); - try protocol_nodes.append(protocol_node); + try protocol_nodes.append(self.gc.allocator, protocol_node); if (!(try self.match(.Comma))) { break; @@ -7312,9 +7343,9 @@ fn objectDeclaration(self: *Self) Error!Ast.Node.Index { // Qualified name to avoid cross script collision const qualifier = try std.mem.replaceOwned(u8, self.gc.allocator, self.script_name, "/", "\\"); defer self.gc.allocator.free(qualifier); - var qualified_object_name = std.array_list.Managed(u8).init(self.gc.allocator); - defer qualified_object_name.deinit(); - try qualified_object_name.writer().print( + var qualified_object_name = std.ArrayList(u8).empty; + defer qualified_object_name.deinit(self.gc.allocator); + try qualified_object_name.writer(self.gc.allocator).print( "{s}.{s}", .{ qualifier, @@ -7353,7 +7384,7 @@ fn objectDeclaration(self: *Self) Error!Ast.Node.Index { self.current_object = object_frame; // Parse generic types - var generics = std.array_list.Managed(Ast.TokenIndex).init(self.gc.allocator); + var generics = std.ArrayList(Ast.TokenIndex).empty; if (try self.match(.DoubleColon)) { try self.consume(.Less, "Expected generic types list after `::`"); var i: usize = 0; @@ -7379,7 +7410,7 @@ fn objectDeclaration(self: *Self) Error!Ast.Node.Index { ), ); - try generics.append(generic_identifier_token); + try generics.append(self.gc.allocator, generic_identifier_token); } else { const location = self.ast.tokens.get(self.current_token.? - 1); self.reporter.reportErrorFmt( @@ -7416,14 +7447,14 @@ fn objectDeclaration(self: *Self) Error!Ast.Node.Index { // Body try self.consume(.LeftBrace, "Expected `{` before object body."); - var members = std.array_list.Managed(Ast.ObjectDeclaration.Member).init(self.gc.allocator); + var members = std.ArrayList(Ast.ObjectDeclaration.Member).empty; // To avoid using the same name twice - var fields = std.StringArrayHashMap(void).init(self.gc.allocator); - defer fields.deinit(); + var fields = std.StringArrayHashMapUnmanaged(void).empty; + defer fields.deinit(self.gc.allocator); // Members types - var properties_type = std.StringHashMap(*obj.ObjTypeDef).init(self.gc.allocator); + var properties_type = std.StringHashMapUnmanaged(*obj.ObjTypeDef).empty; // Docblocks var property_idx: usize = 0; @@ -7535,6 +7566,7 @@ fn objectDeclaration(self: *Self) Error!Ast.Node.Index { static_or_method_property_idx += 1; try members.append( + self.gc.allocator, .{ .name = method_token, .docblock = docblock, @@ -7543,8 +7575,12 @@ fn objectDeclaration(self: *Self) Error!Ast.Node.Index { .property_type = null, }, ); - try fields.put(method_name, {}); - try properties_type.put(method_name, self.ast.nodes.items(.type_def)[method_node].?); + try fields.put(self.gc.allocator, method_name, {}); + try properties_type.put( + self.gc.allocator, + method_name, + self.ast.nodes.items(.type_def)[method_node].?, + ); } else { // Property const final = try self.match(.Final); @@ -7682,6 +7718,7 @@ fn objectDeclaration(self: *Self) Error!Ast.Node.Index { } try members.append( + self.gc.allocator, .{ .name = property_token, .docblock = docblock, @@ -7690,8 +7727,13 @@ fn objectDeclaration(self: *Self) Error!Ast.Node.Index { .property_type = property_type, }, ); - try fields.put(property_lexeme, {}); + try fields.put( + self.gc.allocator, + property_lexeme, + {}, + ); try properties_type.put( + self.gc.allocator, property_lexeme, self.ast.nodes.items(.type_def)[property_type].?, ); @@ -7733,9 +7775,9 @@ fn objectDeclaration(self: *Self) Error!Ast.Node.Index { .ObjectDeclaration = .{ .name = object_name_token, .slot = @intCast(slot), - .protocols = try protocol_nodes.toOwnedSlice(), - .generics = try generics.toOwnedSlice(), - .members = try members.toOwnedSlice(), + .protocols = try protocol_nodes.toOwnedSlice(self.gc.allocator), + .generics = try generics.toOwnedSlice(self.gc.allocator), + .members = try members.toOwnedSlice(self.gc.allocator), }, }, }, @@ -7786,9 +7828,9 @@ fn protocolDeclaration(self: *Self) Error!Ast.Node.Index { // Qualified name to avoid cross script collision const qualifier = try std.mem.replaceOwned(u8, self.gc.allocator, self.script_name, "/", "\\"); defer self.gc.allocator.free(qualifier); - var qualified_protocol_name = std.array_list.Managed(u8).init(self.gc.allocator); - defer qualified_protocol_name.deinit(); - try qualified_protocol_name.writer().print( + var qualified_protocol_name = std.ArrayList(u8).empty; + defer qualified_protocol_name.deinit(self.gc.allocator); + try qualified_protocol_name.writer(self.gc.allocator).print( "{s}.{s}", .{ qualifier, @@ -7817,9 +7859,9 @@ fn protocolDeclaration(self: *Self) Error!Ast.Node.Index { // Body try self.consume(.LeftBrace, "Expected `{` before protocol body."); - var fields = std.StringHashMap(void).init(self.gc.allocator); - defer fields.deinit(); - var methods = std.array_list.Managed(Ast.ProtocolDeclaration.Method).init(self.gc.allocator); + var fields = std.StringHashMapUnmanaged(void).empty; + defer fields.deinit(self.gc.allocator); + var methods = std.ArrayList(Ast.ProtocolDeclaration.Method).empty; while (!self.check(.RightBrace) and !self.check(.Eof)) { const docblock = if (try self.match(.Docblock)) self.current_token.? - 1 @@ -7869,8 +7911,9 @@ fn protocolDeclaration(self: *Self) Error!Ast.Node.Index { method_name_token, ); - try fields.put(method_name, {}); + try fields.put(self.gc.allocator, method_name, {}); try methods.append( + self.gc.allocator, .{ .docblock = docblock, .method = method_node, @@ -7911,7 +7954,7 @@ fn protocolDeclaration(self: *Self) Error!Ast.Node.Index { .ProtocolDeclaration = .{ .name = protocol_name, .slot = @intCast(slot), - .methods = try methods.toOwnedSlice(), + .methods = try methods.toOwnedSlice(self.gc.allocator), }, }, }, @@ -7959,9 +8002,9 @@ fn enumDeclaration(self: *Self) Error!Ast.Node.Index { // Qualified name to avoid cross script collision const qualifier = try std.mem.replaceOwned(u8, self.gc.allocator, self.script_name, "/", "."); defer self.gc.allocator.free(qualifier); - var qualified_name = std.array_list.Managed(u8).init(self.gc.allocator); - defer qualified_name.deinit(); - try qualified_name.writer().print( + var qualified_name = std.ArrayList(u8).empty; + defer qualified_name.deinit(self.gc.allocator); + try qualified_name.writer(self.gc.allocator).print( "{s}.{s}", .{ qualifier, enum_name_lexeme }, ); @@ -7996,9 +8039,9 @@ fn enumDeclaration(self: *Self) Error!Ast.Node.Index { try self.consume(.LeftBrace, "Expected `{` before enum body."); - var cases = std.array_list.Managed(Ast.Enum.Case).init(self.gc.allocator); - var def_cases = std.array_list.Managed([]const u8).init(self.gc.allocator); - var cases_loc = std.array_list.Managed(Ast.TokenIndex).init(self.gc.allocator); + var cases = std.ArrayList(Ast.Enum.Case).empty; + var def_cases = std.ArrayList([]const u8).empty; + var cases_loc = std.ArrayList(Ast.TokenIndex).empty; var values_omitted = true; var case_index: v.Integer = 0; while (!self.check(.RightBrace) and !self.check(.Eof)) : (case_index += 1) { @@ -8025,19 +8068,21 @@ fn enumDeclaration(self: *Self) Error!Ast.Node.Index { try self.consume(.Equal, "Expected `=` after case name."); try cases.append( + self.gc.allocator, .{ .name = case_name_token, .docblock = docblock, .value = try self.expression(false), }, ); - try cases_loc.append(case_name_token); + try cases_loc.append(self.gc.allocator, case_name_token); values_omitted = false; } else { - try cases_loc.append(case_name_token); + try cases_loc.append(self.gc.allocator, case_name_token); if (enum_case_type.def_type == .Integer) { try cases.append( + self.gc.allocator, .{ .name = case_name_token, .docblock = docblock, @@ -8056,6 +8101,7 @@ fn enumDeclaration(self: *Self) Error!Ast.Node.Index { ); } else { try cases.append( + self.gc.allocator, .{ .name = case_name_token, .docblock = docblock, @@ -8078,15 +8124,15 @@ fn enumDeclaration(self: *Self) Error!Ast.Node.Index { } } - try def_cases.append(case_name); + try def_cases.append(self.gc.allocator, case_name); if (!self.check(.RightBrace)) { try self.consume(.Comma, "Expected `,` after case definition."); } } - enum_type.resolved_type.?.Enum.cases = try def_cases.toOwnedSlice(); - enum_type.resolved_type.?.Enum.cases_locations = try cases_loc.toOwnedSlice(); + enum_type.resolved_type.?.Enum.cases = try def_cases.toOwnedSlice(self.gc.allocator); + enum_type.resolved_type.?.Enum.cases_locations = try cases_loc.toOwnedSlice(self.gc.allocator); try self.consume(.RightBrace, "Expected `}` after enum body."); @@ -8099,7 +8145,7 @@ fn enumDeclaration(self: *Self) Error!Ast.Node.Index { ); } - const cases_slice = try cases.toOwnedSlice(); + const cases_slice = try cases.toOwnedSlice(self.gc.allocator); self.ast.nodes.set( node_slot, .{ @@ -8124,7 +8170,7 @@ fn enumDeclaration(self: *Self) Error!Ast.Node.Index { obj.ObjEnum.init(enum_type), ); - var obj_cases = std.array_list.Managed(Value).init(self.gc.allocator); + var obj_cases = std.ArrayList(Value).empty; for (cases_slice, 0..) |case, idx| { if (case.value != null and !(try self.ast.slice().isConstant(self.gc.allocator, case.value.?))) { self.reportErrorAtNode( @@ -8138,6 +8184,7 @@ fn enumDeclaration(self: *Self) Error!Ast.Node.Index { } try obj_cases.append( + self.gc.allocator, if (case.value) |case_value| try self.ast.slice().toValue(case_value, self.gc) else if (enum_type.def_type == .Integer) @@ -8149,7 +8196,7 @@ fn enumDeclaration(self: *Self) Error!Ast.Node.Index { ); } - @"enum".cases = try obj_cases.toOwnedSlice(); + @"enum".cases = try obj_cases.toOwnedSlice(self.gc.allocator); enum_type.resolved_type.?.Enum.value = @"enum"; self.ast.nodes.items(.value)[node_slot] = @"enum".toValue(); @@ -8400,7 +8447,7 @@ fn testStatement(self: *Self) Error!Ast.Node.Index { } fn searchPaths(self: *Self, file_name: []const u8) ![][]const u8 { - var paths = std.array_list.Managed([]const u8).init(self.gc.allocator); + var paths = std.ArrayList([]const u8).empty; for (search_paths) |path| { const filled = try std.mem.replaceOwned( @@ -8435,17 +8482,17 @@ fn searchPaths(self: *Self, file_name: []const u8) ![][]const u8 { "/", "\\", ); - try paths.append(windows); + try paths.append(self.gc.allocator, windows); } else { - try paths.append(prefixed); + try paths.append(self.gc.allocator, prefixed); } } - return try paths.toOwnedSlice(); + return try paths.toOwnedSlice(self.gc.allocator); } fn searchLibPaths(self: *Self, file_name: []const u8) ![][]const u8 { - var paths = std.array_list.Managed([]const u8).init(self.gc.allocator); + var paths = std.ArrayList([]const u8).empty; for (lib_search_paths) |path| { const filled = try std.mem.replaceOwned( @@ -8485,16 +8532,16 @@ fn searchLibPaths(self: *Self, file_name: []const u8) ![][]const u8 { "/", "\\", ); - try paths.append(windows); + try paths.append(self.gc.allocator, windows); } else { - try paths.append(prefixed); + try paths.append(self.gc.allocator, prefixed); } } for (user_library_paths orelse &[_][]const u8{}) |path| { - var filled = std.array_list.Managed(u8).init(self.gc.allocator); + var filled = std.ArrayList(u8).empty; - try filled.writer().print( + try filled.writer(self.gc.allocator).print( "{s}{s}{s}.{s}", .{ path, @@ -8514,11 +8561,11 @@ fn searchLibPaths(self: *Self, file_name: []const u8) ![][]const u8 { }, ); - try paths.append(try filled.toOwnedSlice()); + try paths.append(self.gc.allocator, try filled.toOwnedSlice(self.gc.allocator)); - var prefixed_filled = std.array_list.Managed(u8).init(self.gc.allocator); + var prefixed_filled = std.ArrayList(u8).empty; - try prefixed_filled.writer().print( + try prefixed_filled.writer(self.gc.allocator).print( "{s}{s}lib{s}.{s}", .{ path, @@ -8538,14 +8585,17 @@ fn searchLibPaths(self: *Self, file_name: []const u8) ![][]const u8 { }, ); - try paths.append(try prefixed_filled.toOwnedSlice()); + try paths.append( + self.gc.allocator, + try prefixed_filled.toOwnedSlice(self.gc.allocator), + ); } - return try paths.toOwnedSlice(); + return try paths.toOwnedSlice(self.gc.allocator); } fn searchZdefLibPaths(self: *Self, file_name: []const u8) ![][]const u8 { - var paths = std.array_list.Managed([]const u8).init(self.gc.allocator); + var paths = std.ArrayList([]const u8).empty; for (zdef_search_paths) |path| { const filled = try std.mem.replaceOwned(u8, self.gc.allocator, path, "?", file_name); @@ -8571,16 +8621,16 @@ fn searchZdefLibPaths(self: *Self, file_name: []const u8) ![][]const u8 { "/", "\\", ); - try paths.append(windows); + try paths.append(self.gc.allocator, windows); } else { - try paths.append(suffixed); + try paths.append(self.gc.allocator, suffixed); } } for (Self.user_library_paths orelse &[_][]const u8{}) |path| { - var filled = std.array_list.Managed(u8).init(self.gc.allocator); + var filled = std.ArrayList(u8).empty; - try filled.writer().print( + try filled.writer(self.gc.allocator).print( "{s}{s}{s}.{s}", .{ path, @@ -8600,11 +8650,11 @@ fn searchZdefLibPaths(self: *Self, file_name: []const u8) ![][]const u8 { }, ); - try paths.append(try filled.toOwnedSlice()); + try paths.append(self.gc.allocator, try filled.toOwnedSlice(self.gc.allocator)); - var prefixed_filled = std.array_list.Managed(u8).init(self.gc.allocator); + var prefixed_filled = std.ArrayList(u8).empty; - try prefixed_filled.writer().print( + try prefixed_filled.writer(self.gc.allocator).print( "{s}{s}lib{s}.{s}", .{ path, @@ -8624,10 +8674,13 @@ fn searchZdefLibPaths(self: *Self, file_name: []const u8) ![][]const u8 { }, ); - try paths.append(try prefixed_filled.toOwnedSlice()); + try paths.append( + self.gc.allocator, + try prefixed_filled.toOwnedSlice(self.gc.allocator), + ); } - return try paths.toOwnedSlice(); + return try paths.toOwnedSlice(self.gc.allocator); } fn readStaticScript(self: *Self, file_name: []const u8) ?[2][]const u8 { @@ -8730,9 +8783,9 @@ fn readScript(self: *Self, file_name: []const u8) !?[2][]const u8 { } if (file == null) { - var search_report = std.array_list.Managed(u8).init(self.gc.allocator); - defer search_report.deinit(); - var writer = search_report.writer(); + var search_report = std.ArrayList(u8).empty; + defer search_report.deinit(self.gc.allocator); + var writer = search_report.writer(self.gc.allocator); for (paths) |path| { try writer.print(" no file `{s}`\n", .{path}); @@ -8777,7 +8830,7 @@ fn importScript( path_token: Ast.TokenIndex, file_name: []const u8, prefix: ?[]const Ast.TokenIndex, - imported_symbols: *std.StringHashMap(Ast.Node.Index), + imported_symbols: *std.StringHashMapUnmanaged(Ast.Node.Index), ) Error!?ScriptImport { var import = self.imports.get(file_name); @@ -8852,17 +8905,18 @@ fn importScript( if (global.export_alias) |export_alias| { const previous_name = global.name; - var new_name = std.array_list.Managed(Ast.TokenIndex).init(self.gc.allocator); + var new_name = std.ArrayList(Ast.TokenIndex).empty; try new_name.appendSlice( + self.gc.allocator, if (global.name.len > 1) global.name[0 .. global.name.len - 1] else &[_]Ast.TokenIndex{}, ); - try new_name.append(export_alias); + try new_name.append(self.gc.allocator, export_alias); self.gc.allocator.free(previous_name); // TODO: will this free be an issue? - global.name = try new_name.toOwnedSlice(); + global.name = try new_name.toOwnedSlice(self.gc.allocator); global.export_alias = null; } } else { @@ -8916,17 +8970,18 @@ fn importScript( } // If requalified, overwrite namespace - var imported_name = std.array_list.Managed(Ast.TokenIndex).init(self.gc.allocator); + var imported_name = std.ArrayList(Ast.TokenIndex).empty; try imported_name.appendSlice( + self.gc.allocator, if (prefix != null and prefix.?.len == 1 and std.mem.eql(u8, lexemes[prefix.?[0]], "_")) &[_]Ast.TokenIndex{} // With a `_` override, we erase the namespace else prefix orelse global.name[0 .. global.name.len - 1], // override or take initial namespace ); - try imported_name.append(global.name[global.name.len - 1]); + try imported_name.append(self.gc.allocator, global.name[global.name.len - 1]); // self.gc.allocator.free(global.name); - global.name = try imported_name.toOwnedSlice(); + global.name = try imported_name.toOwnedSlice(self.gc.allocator); } global.imported_from = file_name; @@ -9049,9 +9104,9 @@ fn importLibSymbol( ); } - var search_report = std.array_list.Managed(u8).init(self.gc.allocator); - defer search_report.deinit(); - var writer = search_report.writer(); + var search_report = std.ArrayList(u8).empty; + defer search_report.deinit(self.gc.allocator); + var writer = search_report.writer(self.gc.allocator); for (paths) |path| { try writer.print(" no file `{s}`\n", .{path}); @@ -9078,8 +9133,8 @@ fn importLibSymbol( fn importStatement(self: *Self) Error!Ast.Node.Index { const start_location = self.current_token.? - 1; - var imported_symbols = std.StringHashMap(Ast.TokenIndex).init(self.gc.allocator); - var symbols = std.array_list.Managed(Ast.TokenIndex).init(self.gc.allocator); + var imported_symbols = std.StringHashMapUnmanaged(Ast.TokenIndex).empty; + var symbols = std.ArrayList(Ast.TokenIndex).empty; while ((try self.match(.Identifier)) and !self.check(.Eof)) { const symbol = self.ast.tokens.items(.lexeme)[self.current_token.? - 1]; @@ -9096,8 +9151,12 @@ fn importStatement(self: *Self) Error!Ast.Node.Index { "Imported here", ); } - try imported_symbols.put(self.ast.tokens.items(.lexeme)[self.current_token.? - 1], self.current_token.? - 1); - try symbols.append(self.current_token.? - 1); + try imported_symbols.put( + self.gc.allocator, + self.ast.tokens.items(.lexeme)[self.current_token.? - 1], + self.current_token.? - 1, + ); + try symbols.append(self.gc.allocator, self.current_token.? - 1); if (!self.check(.From) or self.check(.Comma)) { // Allow trailing comma try self.consume(.Comma, "Expected `,` after identifier."); @@ -9171,7 +9230,7 @@ fn importStatement(self: *Self) Error!Ast.Node.Index { .components = .{ .Import = .{ .prefix = prefix, - .imported_symbols = try symbols.toOwnedSlice(), + .imported_symbols = try symbols.toOwnedSlice(self.gc.allocator), .path = path_token, .import = import, }, @@ -9220,7 +9279,7 @@ fn zdefStatement(self: *Self) Error!Ast.Node.Index { else &[_]*FFI.Zdef{}; - var elements = std.array_list.Managed(Ast.Zdef.ZdefElement).init(self.gc.allocator); + var elements = std.ArrayList(Ast.Zdef.ZdefElement).empty; if (!is_wasm) { for (zdefs) |zdef| { var fn_ptr: ?*anyopaque = null; @@ -9288,9 +9347,9 @@ fn zdefStatement(self: *Self) Error!Ast.Node.Index { fn_ptr = opaque_symbol_method; } else { - var search_report = std.array_list.Managed(u8).init(self.gc.allocator); - defer search_report.deinit(); - var writer = search_report.writer(); + var search_report = std.ArrayList(u8).empty; + defer search_report.deinit(self.gc.allocator); + var writer = search_report.writer(self.gc.allocator); for (paths) |path| { try writer.print(" no file `{s}`\n", .{path}); @@ -9315,6 +9374,7 @@ fn zdefStatement(self: *Self) Error!Ast.Node.Index { } try elements.append( + self.gc.allocator, .{ .fn_ptr = fn_ptr, .slot = @intCast(slot), @@ -9335,7 +9395,7 @@ fn zdefStatement(self: *Self) Error!Ast.Node.Index { .Zdef = .{ .lib_name = lib_name, .source = source, - .elements = try elements.toOwnedSlice(), + .elements = try elements.toOwnedSlice(self.gc.allocator), }, }, }, @@ -9417,11 +9477,12 @@ fn userVarDeclaration(self: *Self, identifier: Ast.TokenIndex, final: bool, muta try self.consume(.Less, "Expected generic types list after `::`"); - var resolved_generics = std.array_list.Managed(*obj.ObjTypeDef).init(self.gc.allocator); - var generic_nodes = std.array_list.Managed(Ast.Node.Index).init(self.gc.allocator); + var resolved_generics = std.ArrayList(*obj.ObjTypeDef).empty; + var generic_nodes = std.ArrayList(Ast.Node.Index).empty; var i: usize = 0; while (!self.check(.Greater) and !self.check(.Eof)) : (i += 1) { try generic_nodes.append( + self.gc.allocator, try self.parseTypeDef( if (self.current.?.generics) |generics| generics.* @@ -9432,6 +9493,7 @@ fn userVarDeclaration(self: *Self, identifier: Ast.TokenIndex, final: bool, muta ); try resolved_generics.append( + self.gc.allocator, self.ast.nodes.items(.type_def)[generic_nodes.items[generic_nodes.items.len - 1]].?, ); @@ -9455,8 +9517,9 @@ fn userVarDeclaration(self: *Self, identifier: Ast.TokenIndex, final: bool, muta var_type = try var_type.?.populateGenerics( self.current_token.? - 1, var_type.?.resolved_type.?.Object.id, - try resolved_generics.toOwnedSlice(), + try resolved_generics.toOwnedSlice(self.gc.allocator), &self.gc.type_registry, + self.gc.allocator, null, ); @@ -9467,7 +9530,7 @@ fn userVarDeclaration(self: *Self, identifier: Ast.TokenIndex, final: bool, muta .end_location = self.current_token.? - 1, .type_def = var_type, .components = .{ - .GenericResolveType = try generic_nodes.toOwnedSlice(), + .GenericResolveType = try generic_nodes.toOwnedSlice(self.gc.allocator), }, }, ); @@ -9517,12 +9580,13 @@ fn forStatement(self: *Self) Error!Ast.Node.Index { try self.beginScope(null); // Should be either VarDeclaration or expression - var init_declarations = std.array_list.Managed(Ast.Node.Index).init(self.gc.allocator); + var init_declarations = std.ArrayList(Ast.Node.Index).empty; while (!self.check(.Semicolon) and !self.check(.Eof)) { try self.consume(.Identifier, "Expected identifier"); const identifier = self.current_token.? - 1; try init_declarations.append( + self.gc.allocator, try self.varDeclaration( identifier, if (try self.match(.Colon)) @@ -9550,9 +9614,9 @@ fn forStatement(self: *Self) Error!Ast.Node.Index { try self.consume(.Semicolon, "Expected `;` after for loop condition."); - var post_loop = std.array_list.Managed(Ast.Node.Index).init(self.gc.allocator); + var post_loop = std.ArrayList(Ast.Node.Index).empty; while (!self.check(.RightParen) and !self.check(.Eof)) { - try post_loop.append(try self.expression(false)); + try post_loop.append(self.gc.allocator, try self.expression(false)); if (!self.check(.RightParen)) { try self.consume(.Comma, "Expected `,` after for loop expression"); @@ -9577,9 +9641,9 @@ fn forStatement(self: *Self) Error!Ast.Node.Index { .end_location = undefined, .components = .{ .For = .{ - .init_declarations = try init_declarations.toOwnedSlice(), + .init_declarations = try init_declarations.toOwnedSlice(self.gc.allocator), .condition = condition, - .post_loop = try post_loop.toOwnedSlice(), + .post_loop = try post_loop.toOwnedSlice(self.gc.allocator), .body = undefined, .label = label, }, @@ -10021,18 +10085,18 @@ fn namespaceStatement(self: *Self) Error!Ast.Node.Index { ); } - var namespace = std.array_list.Managed(Ast.TokenIndex).init(self.gc.allocator); + var namespace = std.ArrayList(Ast.TokenIndex).empty; while (!self.check(.Semicolon) and !self.check(.Eof)) { try self.consume(.Identifier, "Expected namespace identifier"); - try namespace.append(self.current_token.? - 1); + try namespace.append(self.gc.allocator, self.current_token.? - 1); if (!try self.match(.AntiSlash)) { break; } } - self.namespace = try namespace.toOwnedSlice(); + self.namespace = try namespace.toOwnedSlice(self.gc.allocator); try self.consume(.Semicolon, "Expected `;` after statement."); @@ -10070,7 +10134,7 @@ fn tryStatement(self: *Self) Error!Ast.Node.Index { const body = try self.block(null); self.ast.nodes.items(.ends_scope)[body] = try self.endScope(); - var clauses = std.array_list.Managed(Ast.Try.Clause).init(self.gc.allocator); + var clauses = std.ArrayList(Ast.Try.Clause).empty; var unconditional_clause: ?Ast.Node.Index = null; // either catch with no type of catch any while (try self.match(.Catch)) { @@ -10110,6 +10174,7 @@ fn tryStatement(self: *Self) Error!Ast.Node.Index { self.ast.nodes.items(.ends_scope)[catch_block] = try self.endScope(); try clauses.append( + self.gc.allocator, .{ .identifier = identifier, .type_def = type_def, @@ -10144,7 +10209,7 @@ fn tryStatement(self: *Self) Error!Ast.Node.Index { .components = .{ .Try = .{ .body = body, - .clauses = try clauses.toOwnedSlice(), + .clauses = try clauses.toOwnedSlice(self.gc.allocator), .unconditional_clause = unconditional_clause, }, }, diff --git a/src/Reporter.zig b/src/Reporter.zig index b8126a53..cbde0dba 100644 --- a/src/Reporter.zig +++ b/src/Reporter.zig @@ -294,24 +294,26 @@ pub const Report = struct { // Print items // Group items by files - var reported_files = std.StringArrayHashMap(std.array_list.Managed(ReportItem)).init(reporter.allocator); + var reported_files = std.StringArrayHashMapUnmanaged(std.ArrayList(ReportItem)).empty; defer { var it = reported_files.iterator(); while (it.next()) |kv| { - kv.value_ptr.*.deinit(); + kv.value_ptr.*.deinit(reporter.allocator); } - reported_files.deinit(); + reported_files.deinit(reporter.allocator); } for (self.items) |item| { if (reported_files.get(item.end_location.script_name) == null) { try reported_files.put( + reporter.allocator, item.end_location.script_name, - std.array_list.Managed(ReportItem).init(reporter.allocator), + std.ArrayList(ReportItem).empty, ); } - try reported_files.getEntry(item.end_location.script_name).?.value_ptr.append(item); + try reported_files.getEntry(item.end_location.script_name).? + .value_ptr.append(reporter.allocator, item); } var file_it = reported_files.iterator(); @@ -332,24 +334,26 @@ pub const Report = struct { ReportItem.lessThan, ); - var reported_lines = std.AutoArrayHashMap(usize, std.array_list.Managed(ReportItem)).init(reporter.allocator); + var reported_lines = std.AutoArrayHashMapUnmanaged(usize, std.ArrayList(ReportItem)).empty; defer { var it = reported_lines.iterator(); while (it.next()) |kv| { - kv.value_ptr.*.deinit(); + kv.value_ptr.*.deinit(reporter.allocator); } - reported_lines.deinit(); + reported_lines.deinit(reporter.allocator); } for (file_entry.value_ptr.items) |item| { if (reported_lines.get(item.end_location.line) == null) { try reported_lines.put( + reporter.allocator, item.end_location.line, - std.array_list.Managed(ReportItem).init(reporter.allocator), + std.ArrayList(ReportItem).empty, ); } - try reported_lines.getEntry(item.end_location.line).?.value_ptr.append(item); + try reported_lines.getEntry(item.end_location.line).? + .value_ptr.append(reporter.allocator, item); } var previous_line: ?usize = null; @@ -639,14 +643,14 @@ pub fn warnAt(self: *Self, error_type: Error, location: Token, end_location: Tok pub fn reportErrorFmt(self: *Self, error_type: Error, location: Token, end_location: Token, comptime fmt: []const u8, args: anytype) void { @branchHint(.cold); - var message = std.array_list.Managed(u8).init(self.allocator); + var message = std.ArrayList(u8).empty; defer { if (!self.collect) { - message.deinit(); + message.deinit(self.allocator); } } - var writer = message.writer(); + var writer = message.writer(self.allocator); writer.print(fmt, args) catch @panic("Unable to report error"); if (self.panic_mode) { @@ -657,25 +661,25 @@ pub fn reportErrorFmt(self: *Self, error_type: Error, location: Token, end_locat error_type, location, end_location, - message.toOwnedSlice() catch @panic("Untable to report error"), + message.toOwnedSlice(self.allocator) catch @panic("Untable to report error"), ); } pub fn warnFmt(self: *Self, error_type: Error, location: Token, end_location: Token, comptime fmt: []const u8, args: anytype) void { - var message = std.array_list.Managed(u8).init(self.allocator); + var message = std.ArrayList(u8).empty; defer { if (!self.collect) { - message.deinit(); + message.deinit(self.allocator); } } - var writer = message.writer(); + var writer = message.writer(self.allocator); writer.print(fmt, args) catch @panic("Unable to report error"); self.warn( error_type, location, end_location, - message.toOwnedSlice() catch @panic("Unable to report error"), + message.toOwnedSlice(self.allocator) catch @panic("Unable to report error"), ); } @@ -692,14 +696,14 @@ pub fn reportWithOrigin( ) void { @branchHint(.cold); - var message = std.array_list.Managed(u8).init(self.allocator); + var message = std.ArrayList(u8).empty; defer { if (!self.collect) { - message.deinit(); + message.deinit(self.allocator); } } - var writer = message.writer(); + var writer = message.writer(self.allocator); writer.print(fmt, args) catch @panic("Unable to report error"); const items = [_]ReportItem{ @@ -753,28 +757,28 @@ pub fn reportTypeCheck( ) void { @branchHint(.cold); - var actual_message = std.array_list.Managed(u8).init(self.allocator); + var actual_message = std.ArrayList(u8).empty; defer { if (!self.collect) { - actual_message.deinit(); + actual_message.deinit(self.allocator); } } - var writer = &actual_message.writer(); + var writer = &actual_message.writer(self.allocator); writer.print("{s}: got type `", .{message}) catch @panic("Unable to report error"); actual_type.toString(writer, false) catch @panic("Unable to report error"); writer.writeAll("`") catch @panic("Unable to report error"); - var expected_message = std.array_list.Managed(u8).init(self.allocator); + var expected_message = std.ArrayList(u8).empty; defer { if (!self.collect) { - expected_message.deinit(); + expected_message.deinit(self.allocator); } } if (expected_location != null) { - writer = &expected_message.writer(); + writer = &expected_message.writer(self.allocator); } writer.writeAll("expected `") catch @panic("Unable to report error"); @@ -782,18 +786,21 @@ pub fn reportTypeCheck( expected_type.toString(writer, false) catch @panic("Unable to report error"); writer.writeAll("`") catch @panic("Unable to report error"); - var full_message = if (expected_location == null) actual_message else std.array_list.Managed(u8).init(self.allocator); + var full_message = if (expected_location == null) + actual_message + else + std.ArrayList(u8).empty; defer { if (!self.collect and expected_location != null) { - full_message.deinit(); + full_message.deinit(self.allocator); } } if (expected_location != null) { - full_message.writer().print( + full_message.writer(self.allocator).print( "{s}, {s}", .{ - actual_message.toOwnedSlice() catch @panic("Unable to report error"), - expected_message.toOwnedSlice() catch @panic("Unable to report error"), + actual_message.toOwnedSlice(self.allocator) catch @panic("Unable to report error"), + expected_message.toOwnedSlice(self.allocator) catch @panic("Unable to report error"), }, ) catch @panic("Unable to report error"); } diff --git a/src/Scanner.zig b/src/Scanner.zig index 2eecbe2b..97656d29 100644 --- a/src/Scanner.zig +++ b/src/Scanner.zig @@ -212,7 +212,7 @@ fn isLetter(char: u8) bool { fn docblock(self: *Self) !Token { _ = self.advance(); // Skip third `/` - var block = std.array_list.Managed(u8).init(self.allocator); + var block = std.ArrayList(u8).empty; while (!self.isEOF()) { while (!self.isEOF()) { @@ -223,10 +223,10 @@ fn docblock(self: *Self) !Token { self.current.column = 0; _ = self.advance(); - try block.append('\n'); + try block.append(self.allocator, '\n'); break; } else { - try block.append(char); + try block.append(self.allocator, char); } _ = self.advance(); @@ -245,7 +245,9 @@ fn docblock(self: *Self) !Token { return self.makeToken( .Docblock, - .{ .String = std.mem.trim(u8, block.items, " ") }, + .{ + .String = std.mem.trim(u8, block.items, " "), + }, ); } diff --git a/src/builtin/list.zig b/src/builtin/list.zig index ccbe6b22..e265c61e 100644 --- a/src/builtin/list.zig +++ b/src/builtin/list.zig @@ -216,9 +216,9 @@ pub fn join(ctx: *o.NativeCtx) callconv(.c) c_int { const self = o.ObjList.cast(ctx.vm.peek(1).obj()).?; const separator = o.ObjString.cast(ctx.vm.peek(0).obj()).?; - var result = std.array_list.Managed(u8).init(ctx.vm.gc.allocator); - var writer = result.writer(); - defer result.deinit(); + var result = std.ArrayList(u8).empty; + var writer = result.writer(ctx.vm.gc.allocator); + defer result.deinit(ctx.vm.gc.allocator); for (self.items.items, 0..) |item, i| { item.toString(&writer) catch { ctx.vm.panic("Out of memory"); diff --git a/src/builtin/str.zig b/src/builtin/str.zig index 96a34f51..fc072c91 100644 --- a/src/builtin/str.zig +++ b/src/builtin/str.zig @@ -106,10 +106,10 @@ pub fn repeat(ctx: *o.NativeCtx) callconv(.c) c_int { const str = o.ObjString.cast(ctx.vm.peek(1).obj()).?; const n = ctx.vm.peek(0).integer(); - var new_string = std.array_list.Managed(u8).init(ctx.vm.gc.allocator); + var new_string = std.ArrayList(u8).empty; var i: usize = 0; while (i < n) : (i += 1) { - new_string.appendSlice(str.string) catch { + new_string.appendSlice(ctx.vm.gc.allocator, str.string) catch { ctx.vm.panic("Out of memory"); unreachable; }; @@ -440,9 +440,9 @@ pub fn hex(ctx: *o.NativeCtx) callconv(.c) c_int { return 1; } - var result = std.array_list.Managed(u8).init(ctx.vm.gc.allocator); - defer result.deinit(); - var writer = result.writer(); + var result = std.ArrayList(u8).empty; + defer result.deinit(ctx.vm.gc.allocator); + var writer = result.writer(ctx.vm.gc.allocator); for (str.string) |char| { writer.print("{x:0>2}", .{char}) catch { diff --git a/src/buzz_api.zig b/src/buzz_api.zig index 87aa9418..df34a234 100644 --- a/src/buzz_api.zig +++ b/src/buzz_api.zig @@ -83,7 +83,7 @@ export fn bz_valueToCString(value: v.Value) callconv(.c) ?[*:0]const u8 { return @ptrCast(o.ObjString.cast(value.obj()).?.string.ptr); } -fn valueDump(value: v.Value, vm: *VM, seen: *std.AutoHashMap(*o.Obj, void), depth: usize) void { +fn valueDump(value: v.Value, vm: *VM, seen: *std.AutoHashMapUnmanaged(*o.Obj, void), depth: usize) void { if (depth > 50) { io.print("...", .{}); return; @@ -97,7 +97,7 @@ fn valueDump(value: v.Value, vm: *VM, seen: *std.AutoHashMap(*o.Obj, void), dept io.print("{s}", .{string}); } else { - seen.put(value.obj(), {}) catch unreachable; + seen.put(vm.gc.allocator, value.obj(), {}) catch unreachable; switch (value.obj().obj_type) { .Type, @@ -331,8 +331,8 @@ fn valueDump(value: v.Value, vm: *VM, seen: *std.AutoHashMap(*o.Obj, void), dept /// Dump value pub export fn bz_valueDump(value: v.Value, vm: *VM) callconv(.c) void { - var seen = std.AutoHashMap(*o.Obj, void).init(vm.gc.allocator); - defer seen.deinit(); + var seen = std.AutoHashMapUnmanaged(*o.Obj, void).empty; + defer seen.deinit(vm.gc.allocator); valueDump(value, vm, &seen, 0); } @@ -624,7 +624,7 @@ export fn bz_run( } var imports = std.StringHashMapUnmanaged(Parser.ScriptImport){}; - var strings = std.StringHashMap(*o.ObjString).init(self.gc.allocator); + var strings = std.StringHashMapUnmanaged(*o.ObjString).empty; var parser = Parser.init( self.gc, &imports, @@ -641,7 +641,7 @@ export fn bz_run( codegen.deinit(); imports.deinit(self.gc.allocator); parser.deinit(); - strings.deinit(); + strings.deinit(self.gc.allocator); } if (parser.parse(source.?[0..source_len], null, file_name.?[0..file_name_len]) catch null) |ast| { @@ -1497,9 +1497,9 @@ export fn bz_zigTypeAlignment(self: *ZigType) callconv(.c) u16 { } export fn bz_zigTypeToCString(self: *ZigType, vm: *VM) callconv(.c) [*:0]const u8 { - var out = std.array_list.Managed(u8).init(vm.gc.allocator); + var out = std.ArrayList(u8).empty; - out.writer().print("{}\x00", .{self.*}) catch { + out.writer(vm.gc.allocator).print("{}\x00", .{self.*}) catch { vm.panic("Out of memory"); unreachable; }; @@ -1508,8 +1508,8 @@ export fn bz_zigTypeToCString(self: *ZigType, vm: *VM) callconv(.c) [*:0]const u } export fn bz_serialize(vm: *VM, value: v.Value, error_value: *v.Value) callconv(.c) v.Value { - var seen = std.AutoHashMap(*o.Obj, void).init(vm.gc.allocator); - defer seen.deinit(); + var seen = std.AutoHashMapUnmanaged(*o.Obj, void).empty; + defer seen.deinit(vm.gc.allocator); return value.serialize(vm, &seen) catch |err| s: { switch (err) { @@ -1564,8 +1564,7 @@ export fn bz_readZigValueFromBuffer( buf: [*]u8, len: usize, ) callconv(.c) v.Value { - var buffer = std.array_list.Managed(u8).fromOwnedSlice( - vm.gc.allocator, + var buffer = std.ArrayList(u8).fromOwnedSlice( buf[0..len], ); buffer.capacity = len; @@ -1720,8 +1719,7 @@ export fn bz_writeZigValueToBuffer( buf: [*]u8, capacity: usize, ) callconv(.c) void { - var buffer = std.array_list.Managed(u8).fromOwnedSlice( - vm.gc.allocator, + var buffer = std.ArrayList(u8).fromOwnedSlice( buf[0..capacity], ); buffer.capacity = capacity; @@ -1735,7 +1733,7 @@ export fn bz_writeZigValueToBuffer( @as(u8, 0)); const bytes = std.mem.asBytes(&unwrapped); - buffer.replaceRange(at, bytes.len, bytes) catch { + buffer.replaceRange(vm.gc.allocator, at, bytes.len, bytes) catch { vm.panic("Out of memory"); unreachable; }; @@ -1747,7 +1745,7 @@ export fn bz_writeZigValueToBuffer( const unwrapped = o.ObjUserData.cast(value.obj()).?.userdata; const bytes = std.mem.asBytes(&unwrapped); - buffer.replaceRange(at, bytes.len, bytes) catch { + buffer.replaceRange(vm.gc.allocator, at, bytes.len, bytes) catch { vm.panic("Out of memory"); unreachable; }; @@ -1756,7 +1754,7 @@ export fn bz_writeZigValueToBuffer( const unwrapped = value.integer(); const bytes = std.mem.asBytes(&unwrapped)[0..(ztype.Int.bits / 8)]; - buffer.replaceRange(at, bytes.len, bytes) catch { + buffer.replaceRange(vm.gc.allocator, at, bytes.len, bytes) catch { vm.panic("Out of memory"); unreachable; }; @@ -1769,7 +1767,7 @@ export fn bz_writeZigValueToBuffer( const unwrapped = @as(f32, @floatCast(value.double())); const bytes = std.mem.asBytes(&unwrapped); - buffer.replaceRange(at, bytes.len, bytes) catch { + buffer.replaceRange(vm.gc.allocator, at, bytes.len, bytes) catch { vm.panic("Out of memory"); unreachable; }; @@ -1778,7 +1776,7 @@ export fn bz_writeZigValueToBuffer( const unwrapped = value.double(); const bytes = std.mem.asBytes(&unwrapped); - buffer.replaceRange(at, bytes.len, bytes) catch { + buffer.replaceRange(vm.gc.allocator, at, bytes.len, bytes) catch { vm.panic("Out of memory"); unreachable; }; @@ -1803,7 +1801,7 @@ export fn bz_writeZigValueToBuffer( const unwrapped = o.ObjUserData.cast(value.obj()).?.userdata; const bytes = std.mem.asBytes(&unwrapped); - buffer.replaceRange(at, bytes.len, bytes) catch { + buffer.replaceRange(vm.gc.allocator, at, bytes.len, bytes) catch { vm.panic("Out of memory"); unreachable; }; diff --git a/src/disassembler.zig b/src/disassembler.zig index 11a091ef..47715b04 100644 --- a/src/disassembler.zig +++ b/src/disassembler.zig @@ -393,19 +393,12 @@ pub const DumpState = struct { const Self = @This(); vm: *VM, - seen: std.AutoHashMap(*obj.Obj, void), + seen: std.AutoHashMapUnmanaged(*obj.Obj, void) = .empty, depth: usize = 0, tab: usize = 0, - pub fn init(vm: *VM) Self { - return Self{ - .vm = vm, - .seen = std.AutoHashMap(*obj.Obj, void).init(vm.gc.allocator), - }; - } - - pub fn deinit(self: *Self) void { - self.seen.deinit(); + pub fn deinit(self: *Self, allocator: std.mem.Allocator) void { + self.seen.deinit(allocator); } pub fn valueDump(state: *DumpState, value: Value, out: anytype, same_line: bool) void { @@ -430,7 +423,7 @@ pub const DumpState = struct { out.print("{s}", .{string}) catch unreachable; } else { - state.seen.put(value.obj(), {}) catch unreachable; + state.seen.put(state.vm.gc.allocator, value.obj(), {}) catch unreachable; switch (value.obj().obj_type) { .Type, diff --git a/src/lib/buzz_buffer.zig b/src/lib/buzz_buffer.zig index f092dfc4..ae2bb03e 100644 --- a/src/lib/buzz_buffer.zig +++ b/src/lib/buzz_buffer.zig @@ -508,10 +508,10 @@ fn checkBuzzType( btype: api.Value, ) bool { if (!value.bz_valueIs(btype).boolean()) { - var err = std.array_list.Managed(u8).init(api.VM.allocator); - defer err.deinit(); + var err = std.ArrayList(u8).empty; + defer err.deinit(api.VM.allocator); - err.writer().print( + err.writer(api.VM.allocator).print( "Expected buzz value of type `{s}` to match FFI type `{s}`", .{ btype.bz_valueCastToString(vm).bz_valueToCString().?, @@ -631,9 +631,6 @@ fn rawWriteStruct( ); if (!value.bz_valueIs(type_def_value).boolean()) { - var msg = std.array_list.Managed(u8).init(api.VM.allocator); - defer msg.deinit(); - vm.bz_pushError( "ffi.FFITypeMismatchError", "ffi.FFITypeMismatchError".len, diff --git a/src/lib/buzz_crypto.zig b/src/lib/buzz_crypto.zig index 3fb7c43e..f4cfd482 100644 --- a/src/lib/buzz_crypto.zig +++ b/src/lib/buzz_crypto.zig @@ -9,17 +9,6 @@ pub const os = if (is_wasm) else std.os; -fn bin2hex(allocator: std.mem.Allocator, input: []const u8) std.ArrayList(u8) { - var result = std.array_list.Managed(u8).init(allocator); - var writer = result.writer(); - - for (input) |byte| { - writer.print("{x:0>2}", .{byte}) catch @panic("Could not convert string to hex"); - } - - return result; -} - pub export fn hash(ctx: *api.NativeCtx) callconv(.c) c_int { const algo_index = ctx.vm.bz_peek(1).bz_getEnumInstanceValue().integer(); var data_len: usize = 0; diff --git a/src/lib/buzz_ffi.zig b/src/lib/buzz_ffi.zig index fa1439ab..92706ff7 100644 --- a/src/lib/buzz_ffi.zig +++ b/src/lib/buzz_ffi.zig @@ -11,10 +11,10 @@ pub export fn alignOf(ctx: *api.NativeCtx) callconv(.c) c_int { if (zig_type) |ztype| { ctx.vm.bz_push(api.Value.fromInteger(@intCast(ztype.bz_zigTypeAlignment()))); } else { - var msg = std.array_list.Managed(u8).init(api.VM.allocator); - defer msg.deinit(); + var msg = std.ArrayList(u8).empty; + defer msg.deinit(api.VM.allocator); - msg.writer().print( + msg.writer(api.VM.allocator).print( "Could not parse zig type `{s}`", .{ zig_type_str[0..len], @@ -42,10 +42,10 @@ pub export fn sizeOf(ctx: *api.NativeCtx) callconv(.c) c_int { if (zig_type) |ztype| { ctx.vm.bz_push(api.Value.fromInteger(@intCast(ztype.bz_zigTypeSize()))); } else { - var msg = std.array_list.Managed(u8).init(api.VM.allocator); - defer msg.deinit(); + var msg = std.ArrayList(u8).empty; + defer msg.deinit(api.VM.allocator); - msg.writer().print( + msg.writer(api.VM.allocator).print( "Could not parse zig type `{s}`", .{ zig_type_str[0..len], diff --git a/src/lib/buzz_http.zig b/src/lib/buzz_http.zig index f2bb22ba..47a8b840 100644 --- a/src/lib/buzz_http.zig +++ b/src/lib/buzz_http.zig @@ -53,7 +53,7 @@ pub export fn HttpClientSend(ctx: *api.NativeCtx) callconv(.c) c_int { } const header_values = ctx.vm.bz_peek(0); - var headers = std.array_list.Managed(http.Header).init(api.VM.allocator); + var headers = std.ArrayList(http.Header).empty; var next_header_key = api.Value.Null; var next_header_value = header_values.bz_mapNext(&next_header_key); while (next_header_key.val != api.Value.Null.val) : (next_header_value = header_values.bz_mapNext(&next_header_key)) { @@ -68,6 +68,7 @@ pub export fn HttpClientSend(ctx: *api.NativeCtx) callconv(.c) c_int { } headers.append( + api.VM.allocator, .{ .name = key.?[0..key_len], .value = value.?[0..value_len], @@ -173,8 +174,8 @@ pub export fn HttpRequestRead(ctx: *api.NativeCtx) callconv(.c) c_int { ), ); - var body_raw = std.array_list.Managed(u8).init(api.VM.allocator); - defer body_raw.deinit(); + var body_raw = std.ArrayList(u8).empty; + defer body_raw.deinit(api.VM.allocator); request.reader().readAllArrayList(&body_raw, std.math.maxInt(usize)) catch |err| { handleResponseError(ctx, err); diff --git a/src/lib/buzz_os.zig b/src/lib/buzz_os.zig index 8392f0f0..3f96b782 100644 --- a/src/lib/buzz_os.zig +++ b/src/lib/buzz_os.zig @@ -88,9 +88,9 @@ pub export fn tmpFilename(ctx: *api.NativeCtx) callconv(.c) c_int { const prefix_slice = if (prefix_len == 0) "" else prefix.?[0..prefix_len]; - var random_part = std.array_list.Managed(u8).init(api.VM.allocator); - defer random_part.deinit(); - random_part.writer().print("{x}", .{std.crypto.random.int(api.Integer)}) catch { + var random_part = std.ArrayList(u8).empty; + defer random_part.deinit(api.VM.allocator); + random_part.writer(api.VM.allocator).print("{x}", .{std.crypto.random.int(api.Integer)}) catch { ctx.vm.bz_panic("Out of memory", "Out of memory".len); unreachable; }; @@ -107,10 +107,10 @@ pub export fn tmpFilename(ctx: *api.NativeCtx) callconv(.c) c_int { _ = std.base64.standard.Encoder.encode(random_part_b64.items, random_part.items); - var final = std.array_list.Managed(u8).init(api.VM.allocator); - defer final.deinit(); + var final = std.ArrayList(u8).empty; + defer final.deinit(api.VM.allocator); - final.writer().print("{s}{s}-{s}", .{ sysTempDir(), prefix_slice, random_part_b64.items }) catch { + final.writer(api.VM.allocator).print("{s}{s}-{s}", .{ sysTempDir(), prefix_slice, random_part_b64.items }) catch { ctx.vm.bz_panic("Out of memory", "Out of memory".len); unreachable; }; @@ -181,8 +181,8 @@ fn handleSpawnError(ctx: *api.NativeCtx, err: anytype) void { } pub export fn execute(ctx: *api.NativeCtx) callconv(.c) c_int { - var command = std.array_list.Managed([]const u8).init(api.VM.allocator); - defer command.deinit(); + var command = std.ArrayList([]const u8).empty; + defer command.deinit(api.VM.allocator); const argv = ctx.vm.bz_peek(0); const len = argv.bz_listLen(); @@ -197,7 +197,7 @@ pub export fn execute(ctx: *api.NativeCtx) callconv(.c) c_int { std.debug.assert(arg_len > 0); - command.append(arg_str.?[0..arg_len]) catch { + command.append(api.VM.allocator, arg_str.?[0..arg_len]) catch { ctx.vm.bz_panic("Out of memory", "Out of memory".len); unreachable; }; diff --git a/src/main.zig b/src/main.zig index d80a62d4..aa2f8f99 100644 --- a/src/main.zig +++ b/src/main.zig @@ -264,13 +264,13 @@ pub fn main() u8 { } if (res.args.library.len > 0) { - var list = std.array_list.Managed([]const u8).init(allocator); + var list = std.ArrayList([]const u8).empty; for (res.args.library) |path| { - list.append(path) catch return 1; + list.append(allocator, path) catch return 1; } - Parser.user_library_paths = list.toOwnedSlice() catch return 1; + Parser.user_library_paths = list.toOwnedSlice(allocator) catch return 1; } const flavor: RunFlavor = if (res.args.check == 1) diff --git a/src/obj.zig b/src/obj.zig index 04a6fe6c..8e1b18fa 100644 --- a/src/obj.zig +++ b/src/obj.zig @@ -82,12 +82,12 @@ pub const Obj = struct { return obj.cast(T, obj_type); } - pub fn serialize(self: *Self, vm: *VM, seen: *std.AutoHashMap(*Self, void)) SerializeError!Value { + pub fn serialize(self: *Self, vm: *VM, seen: *std.AutoHashMapUnmanaged(*Self, void)) SerializeError!Value { if (seen.get(self) != null) { return error.CircularReference; } - try seen.put(self, {}); + try seen.put(vm.gc.allocator, self, {}); switch (self.obj_type) { .String => return Value.fromObj(self), @@ -509,7 +509,7 @@ pub const Obj = struct { } } - pub fn toString(obj: *Obj, writer: *const std.array_list.Managed(u8).Writer) (Allocator.Error || std.fmt.BufPrintError)!void { + pub fn toString(obj: *Obj, writer: *const std.ArrayList(u8).Writer) (Allocator.Error || std.fmt.BufPrintError)!void { return switch (obj.obj_type) { .String => { const str = ObjString.cast(obj).?.string; @@ -980,9 +980,9 @@ pub const ObjString = struct { } pub fn concat(self: *Self, vm: *VM, other: *Self) !*Self { - var new_string = std.array_list.Managed(u8).init(vm.gc.allocator); - try new_string.appendSlice(self.string); - try new_string.appendSlice(other.string); + var new_string = std.ArrayList(u8).empty; + try new_string.appendSlice(vm.gc.allocator, self.string); + try new_string.appendSlice(vm.gc.allocator, other.string); return vm.gc.copyString(new_string.items); } @@ -1560,10 +1560,10 @@ pub const ObjForeignContainer = struct { qualified_name: *ObjString, zig_type: ZigType, - buzz_type: std.StringArrayHashMap(*ObjTypeDef), + buzz_type: std.StringArrayHashMapUnmanaged(*ObjTypeDef), // Filled by codegen - fields: std.StringArrayHashMap(Field), + fields: std.StringArrayHashMapUnmanaged(Field), pub fn mark(def: *ContainerDef, gc: *GC) !void { try gc.markObj(def.name.toObj()); @@ -4370,15 +4370,16 @@ pub const ObjTypeDef = struct { origin: ?usize, generics: []*Self, type_registry: *TypeRegistry, - visited: ?*std.AutoHashMap(*Self, void), + allocator: std.mem.Allocator, + visited: ?*std.AutoHashMapUnmanaged(*Self, void), ) !*Self { var visited_nodes = if (visited == null) - std.AutoHashMap(*Self, void).init(type_registry.gc.allocator) + std.AutoHashMapUnmanaged(*Self, void).empty else null; defer { if (visited == null) { - visited_nodes.?.deinit(); + visited_nodes.?.deinit(allocator); } } @@ -4388,7 +4389,7 @@ pub const ObjTypeDef = struct { return self; } - try visited_ptr.put(self, {}); + try visited_ptr.put(allocator, self, {}); if (generics.len == 0) { return self; @@ -4455,6 +4456,7 @@ pub const ObjTypeDef = struct { origin, generics, type_registry, + allocator, visited_ptr, ), .yield_type = try (try self.resolved_type.?.Fiber.yield_type.populateGenerics( @@ -4462,6 +4464,7 @@ pub const ObjTypeDef = struct { origin, generics, type_registry, + allocator, visited_ptr, )).cloneOptional(type_registry), }; @@ -4481,6 +4484,7 @@ pub const ObjTypeDef = struct { origin, generics, type_registry, + allocator, visited_ptr, )).toInstance( type_registry, @@ -4523,6 +4527,7 @@ pub const ObjTypeDef = struct { origin, generics, type_registry, + allocator, visited_ptr, ), .has_default = kv.value_ptr.*.has_default, @@ -4558,6 +4563,7 @@ pub const ObjTypeDef = struct { origin, generics, type_registry, + allocator, visited_ptr, ), .mutable = kv.value_ptr.*.mutable, @@ -4577,6 +4583,7 @@ pub const ObjTypeDef = struct { origin, generics, type_registry, + allocator, visited_ptr, )).toInstance( type_registry, @@ -4603,6 +4610,7 @@ pub const ObjTypeDef = struct { origin, generics, type_registry, + allocator, visited_ptr, ), .mutable = kv.value_ptr.*.mutable, @@ -4622,6 +4630,7 @@ pub const ObjTypeDef = struct { origin, generics, type_registry, + allocator, visited_ptr, ), .value_type = try old_map_def.value_type.populateGenerics( @@ -4629,6 +4638,7 @@ pub const ObjTypeDef = struct { origin, generics, type_registry, + allocator, visited_ptr, ), .methods = methods, @@ -4651,6 +4661,7 @@ pub const ObjTypeDef = struct { origin, generics, type_registry, + allocator, visited_ptr, ), ); @@ -4669,6 +4680,7 @@ pub const ObjTypeDef = struct { origin, generics, type_registry, + allocator, visited_ptr, )).toInstance( type_registry, @@ -4687,6 +4699,7 @@ pub const ObjTypeDef = struct { origin, generics, type_registry, + allocator, visited_ptr, )) .toInstance( @@ -4698,6 +4711,7 @@ pub const ObjTypeDef = struct { origin, generics, type_registry, + allocator, visited_ptr, )) .toInstance( @@ -4879,11 +4893,11 @@ pub const ObjTypeDef = struct { } pub fn toStringAlloc(self: *const Self, allocator: Allocator, qualified: bool) (Allocator.Error || std.fmt.BufPrintError)![]const u8 { - var str = std.array_list.Managed(u8).init(allocator); + var str = std.ArrayList(u8).empty; - try self.toString(&str.writer(), qualified); + try self.toString(&str.writer(allocator), qualified); - return try str.toOwnedSlice(); + return try str.toOwnedSlice(allocator); } pub fn toString(self: *const Self, writer: anytype, qualified: bool) (Allocator.Error || std.fmt.BufPrintError)!void { diff --git a/src/repl.zig b/src/repl.zig index 3fc44675..3c344371 100644 --- a/src/repl.zig +++ b/src/repl.zig @@ -117,10 +117,10 @@ pub fn repl(allocator: std.mem.Allocator) !void { var stderr = io.stderrWriter; printBanner(stdout, false); - var buzz_history_path = std.array_list.Managed(u8).init(allocator); - defer buzz_history_path.deinit(); + var buzz_history_path = std.ArrayList(u8).empty; + defer buzz_history_path.deinit(allocator); - try buzz_history_path.writer().print( + try buzz_history_path.writer(allocator).print( "{s}/.buzz_history\x00", .{envMap.get("HOME") orelse "."}, ); @@ -251,13 +251,15 @@ pub fn repl(allocator: std.mem.Allocator) !void { const value = expr orelse vm.globals.items[previous_global_top]; - var value_str = std.array_list.Managed(u8).init(vm.gc.allocator); - defer value_str.deinit(); - var state = disassembler.DumpState.init(&vm); + var value_str = std.ArrayList(u8).empty; + defer value_str.deinit(vm.gc.allocator); + var state = disassembler.DumpState{ + .vm = &vm, + }; state.valueDump( value, - value_str.writer(), + value_str.writer(vm.gc.allocator), false, ); diff --git a/src/tests/fmt.zig b/src/tests/fmt.zig index 2d2985e8..3cf60d20 100644 --- a/src/tests/fmt.zig +++ b/src/tests/fmt.zig @@ -14,7 +14,7 @@ const ignore = std.StaticStringMap(void).initComptime( .{ "examples/2048.buzz", {} }, // statements that enforce newline before them don't take comment into account .{ "tests/042-anonymous-objects.buzz", {} }, - // bad identation of inline if-else else branch + // bad indentation of inline if-else else branch .{ "tests/052-inline-if.buzz", {} }, // something wrong with renderCopy signature .{ "examples/sdl-wrapped.buzz", {} }, diff --git a/src/value.zig b/src/value.zig index 1b031262..6a164272 100644 --- a/src/value.zig +++ b/src/value.zig @@ -151,7 +151,7 @@ pub const Value = packed struct { }; } - pub fn serialize(self: Value, vm: *VM, seen: *std.AutoHashMap(*o.Obj, void)) !Value { + pub fn serialize(self: Value, vm: *VM, seen: *std.AutoHashMapUnmanaged(*o.Obj, void)) !Value { if (self.isObj()) { return try self.obj().serialize(vm, seen); } @@ -160,15 +160,15 @@ pub const Value = packed struct { } pub fn toStringAlloc(value: Value, allocator: Allocator) (Allocator.Error || std.fmt.BufPrintError)![]const u8 { - var str = std.array_list.Managed(u8).init(allocator); + var str = std.ArrayList(u8).empty; - try value.toString(&str.writer()); + try value.toString(&str.writer(allocator)); - return try str.toOwnedSlice(); + return try str.toOwnedSlice(allocator); } // FIXME: should be a std.io.Writer once it exists for ArrayLists - pub fn toString(self: Value, writer: *const std.array_list.Managed(u8).Writer) (Allocator.Error || std.fmt.BufPrintError)!void { + pub fn toString(self: Value, writer: *const std.ArrayList(u8).Writer) (Allocator.Error || std.fmt.BufPrintError)!void { if (self.isObj()) { try self.obj().toString(writer); diff --git a/src/vm.zig b/src/vm.zig index 9952a695..fbffe933 100644 --- a/src/vm.zig +++ b/src/vm.zig @@ -2194,7 +2194,7 @@ pub const VM = struct { const exported_count = vm.peek(0).integer(); // Copy them to this vm globals - var import_cache = std.array_list.Managed(Value).init(self.gc.allocator); + var import_cache = std.ArrayList(Value).empty; if (exported_count > 0) { var i = exported_count; @@ -2205,7 +2205,7 @@ pub const VM = struct { unreachable; }; - import_cache.append(global) catch { + import_cache.append(self.gc.allocator, global) catch { self.panic("Out of memory"); unreachable; }; @@ -2215,7 +2215,7 @@ pub const VM = struct { self.import_registry.put( self.gc.allocator, fullpath, - import_cache.toOwnedSlice() catch { + import_cache.toOwnedSlice(self.gc.allocator) catch { self.panic("Out of memory"); unreachable; }, @@ -4606,18 +4606,18 @@ pub const VM = struct { } fn reportRuntimeError(self: *Self, message: []const u8, error_site: ?Ast.TokenIndex, stack: []const CallFrame) void { - var notes = std.array_list.Managed(Reporter.Note).init(self.gc.allocator); + var notes = std.ArrayList(Reporter.Note).empty; defer { for (notes.items) |note| { self.gc.allocator.free(note.message); } - notes.deinit(); + notes.deinit(self.gc.allocator); } for (stack, 0..) |frame, i| { const next = if (i < stack.len - 1) stack[i + 1] else null; - var msg = std.array_list.Managed(u8).init(self.gc.allocator); - var writer = msg.writer(); + var msg = std.ArrayList(u8).empty; + var writer = msg.writer(self.gc.allocator); if (next) |unext| { const function_name = unext.closure.function.type_def.resolved_type.?.Function.name.string; @@ -4671,8 +4671,9 @@ pub const VM = struct { } notes.append( + self.gc.allocator, .{ - .message = msg.toOwnedSlice() catch @panic("Could not report error"), + .message = msg.toOwnedSlice(self.gc.allocator) catch @panic("Could not report error"), .show_prefix = false, }, ) catch @panic("Could not report error"); diff --git a/src/wasm_repl.zig b/src/wasm_repl.zig index 62742c64..179c36f7 100644 --- a/src/wasm_repl.zig +++ b/src/wasm_repl.zig @@ -142,13 +142,15 @@ pub export fn runLine(ctx: *ReplCtx) void { const value = expr orelse ctx.vm.globals.items[previous_global_top]; - var value_str = std.array_list.Managed(u8).init(ctx.vm.gc.allocator); - defer value_str.deinit(); - var state = DumpState.init(ctx.vm); + var value_str = std.ArrayList(u8).empty; + defer value_str.deinit(ctx.vm.gc.allocator); + var state = DumpState{ + .vm = ctx.vm, + }; state.valueDump( value, - value_str.writer(), + value_str.writer(ctx.vm.gc.allocator), false, ); diff --git a/src/writeable_array_list.zig b/src/writeable_array_list.zig index 1a4f1080..296ce802 100644 --- a/src/writeable_array_list.zig +++ b/src/writeable_array_list.zig @@ -6,17 +6,16 @@ pub fn WriteableArrayList(comptime T: type) type { const Self = @This(); list: std.array_list.Managed(T), - writer: std.Io.Writer, + writer: std.Io.Writer = .{ + .buffer = &.{}, + .vtable = &.{ + .drain = drain, + }, + }, pub fn init(allocator: std.mem.Allocator) Self { return .{ .list = .init(allocator), - .writer = .{ - .buffer = &.{}, - .vtable = &.{ - .drain = drain, - }, - }, }; } diff --git a/tests/042-anonymous-objects.buzz b/tests/042-anonymous-objects.buzz index 42ee235d..8ec646ab 100644 --- a/tests/042-anonymous-objects.buzz +++ b/tests/042-anonymous-objects.buzz @@ -12,8 +12,15 @@ test "Anonymous objects" { // Two anonymous type matches _: obj{ name: str, age: int } = info; - std\assert(info.name == "Joe" and info.age == 36, message: "Could declare, instanciate and acces anonymous objects"); - std\assert(info is obj{ name: str, age: int }, message: "Type safety works with anonymous object"); + std\assert( + info.name == "Joe" and info.age == 36, + message: "Could declare, instanciate and acces anonymous objects", + ); + + std\assert( + info is obj{ name: str, age: int }, + message: "Type safety works with anonymous object", + ); } test "Named variable init" { @@ -45,15 +52,15 @@ test "anonymous objects with different fields order" { callMe(.{ y = 13, x = 12 }); } -// placeholders in anonymous object fields works +/// placeholders in anonymous object fields works object A { board: mut [int], fun free() > void { foreach (x, y in this.board) { var board: mut [obj{ x: int }] = mut []; - - board.append(.{ x = x }); + + board.append(.{ x }); } } }