Skip to content

Commit

Permalink
feat: list.reverse
Browse files Browse the repository at this point in the history
  • Loading branch information
giann committed Mar 14, 2024
1 parent 4f32ca9 commit 3c0e31e
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/builtin/list.zig
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,22 @@ pub fn len(ctx: *NativeCtx) c_int {
return 1;
}

pub fn reverse(ctx: *NativeCtx) c_int {
const list: *ObjList = ObjList.cast(ctx.vm.peek(0).obj()).?;

var new_list = ctx.vm.gc.allocateObject(
ObjList,
ObjList.init(ctx.vm.gc.allocator, list.type_def),
) catch @panic("Out of memory");

new_list.items.appendSlice(list.items.items) catch @panic("Out of memory");
std.mem.reverse(Value, new_list.items.items);

ctx.vm.push(new_list.toValue());

return 1;
}

pub fn pop(ctx: *NativeCtx) c_int {
const list: *ObjList = ObjList.cast(ctx.vm.peek(0).obj()).?;

Expand Down
29 changes: 29 additions & 0 deletions src/obj.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1621,6 +1621,7 @@ pub const ObjList = struct {
.{ "pop", buzz_builtin.list.pop },
.{ "reduce", buzz_builtin.list.reduce },
.{ "remove", buzz_builtin.list.remove },
.{ "reverse", buzz_builtin.list.reverse },
.{ "sort", buzz_builtin.list.sort },
.{ "sub", buzz_builtin.list.sub },
},
Expand Down Expand Up @@ -2430,6 +2431,34 @@ pub const ObjList = struct {

try self.methods.put("clone", native_type);

return native_type;
} else if (mem.eql(u8, method, "reverse")) {
// We omit first arg: it'll be OP_SWAPed in and we already parsed it
// It's always the list.

const method_def = ObjFunction.FunctionDef{
.id = ObjFunction.FunctionDef.nextId(),
.script_name = try parser.gc.copyString("builtin"),
.name = try parser.gc.copyString("reverse"),
.parameters = std.AutoArrayHashMap(*ObjString, *ObjTypeDef).init(parser.gc.allocator),
.defaults = std.AutoArrayHashMap(*ObjString, Value).init(parser.gc.allocator),
.return_type = obj_list,
.yield_type = try parser.gc.type_registry.getTypeDef(.{ .def_type = .Void }),
.generic_types = std.AutoArrayHashMap(*ObjString, *ObjTypeDef).init(parser.gc.allocator),
.function_type = .Extern,
};

const resolved_type: ObjTypeDef.TypeUnion = .{ .Function = method_def };

const native_type = try parser.gc.type_registry.getTypeDef(
ObjTypeDef{
.def_type = .Function,
.resolved_type = resolved_type,
},
);

try self.methods.put("reverse", native_type);

return native_type;
}

Expand Down

0 comments on commit 3c0e31e

Please sign in to comment.