Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tailcall #262

Merged
merged 3 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ var value = <{
## Changed
- Map type notation has changed from `{K, V}` to `{K: V}`. Similarly map expression with specified typed went from `{<K, V>, ...}` to `{<K: V>, ...}` (https://github.com/buzz-language/buzz/issues/253)
- `File.readLine`, `File.readAll`, `Socket.readLine`, `Socket.readAll` have now an optional `maxSize` argument
- Tail call optimization (https://github.com/buzz-language/buzz/issues/9). The effect should be limited for recursive calls since the JIT should kick in pretty quickly in those use cases.

## Fixed

Expand Down
11 changes: 9 additions & 2 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ const BuzzBuildOptions = struct {
jit: BuzzJITOptions,
target: Build.ResolvedTarget,
cycle_limit: ?u128,
recursive_call_limit: u32,
recursive_call_limit: ?u32,
stack_size: usize = 100_000,

pub fn step(self: @This(), b: *Build) *Build.Module {
var options = b.addOptions();
Expand All @@ -74,6 +75,7 @@ const BuzzBuildOptions = struct {
options.addOption(@TypeOf(self.mimalloc), "mimalloc", self.mimalloc);
options.addOption(@TypeOf(self.cycle_limit), "cycle_limit", self.cycle_limit);
options.addOption(@TypeOf(self.recursive_call_limit), "recursive_call_limit", self.recursive_call_limit);
options.addOption(@TypeOf(self.stack_size), "stack_size", self.stack_size);

self.debug.step(options);
self.gc.step(options);
Expand Down Expand Up @@ -153,7 +155,12 @@ pub fn build(b: *Build) !void {
u32,
"recursive_call_limit",
"Maximum depth for recursive calls",
) orelse 200,
),
.stack_size = b.option(
usize,
"stack_size",
"Stack maximum size",
) orelse 100_000,
.mimalloc = b.option(
bool,
"mimalloc",
Expand Down
1 change: 1 addition & 0 deletions src/Ast.zig
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ pub const Call = struct {
callee_type_def: *obj.ObjTypeDef,
arguments: []Argument,
catch_default: ?Node.Index,
tail_call: bool = false,

pub const Argument = struct {
name: ?TokenIndex,
Expand Down
2 changes: 2 additions & 0 deletions src/Chunk.zig
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ pub const OpCode = enum(u8) {
OP_FIBER_FOREACH,

OP_CALL,
OP_TAIL_CALL,
OP_INSTANCE_INVOKE,
OP_INSTANCE_TAIL_INVOKE,
OP_STRING_INVOKE,
OP_PATTERN_INVOKE,
OP_FIBER_INVOKE,
Expand Down
12 changes: 9 additions & 3 deletions src/Codegen.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1316,15 +1316,21 @@ fn generateCall(self: *Self, node: Ast.Node.Index, breaks: ?*std.ArrayList(usize
try self.emitCodeArg(
locations[node],
switch (type_defs[node_components[components.callee].Dot.callee].?.def_type) {
.ObjectInstance, .ProtocolInstance => .OP_INSTANCE_INVOKE,
.ObjectInstance, .ProtocolInstance => if (components.tail_call)
.OP_INSTANCE_TAIL_INVOKE
else
.OP_INSTANCE_INVOKE,
.String => .OP_STRING_INVOKE,
.Pattern => .OP_PATTERN_INVOKE,
.Fiber => .OP_FIBER_INVOKE,
.List => .OP_LIST_INVOKE,
.Map => .OP_MAP_INVOKE,
else => unexpected: {
std.debug.assert(self.reporter.had_error);
break :unexpected .OP_INSTANCE_INVOKE;
break :unexpected if (components.tail_call)
.OP_INSTANCE_TAIL_INVOKE
else
.OP_INSTANCE_INVOKE;
},
},
try self.identifierConstant(lexemes[node_components[components.callee].Dot.identifier]),
Expand All @@ -1334,7 +1340,7 @@ fn generateCall(self: *Self, node: Ast.Node.Index, breaks: ?*std.ArrayList(usize
if (!invoked) {
try self.emitCodeArgs(
locations[node],
.OP_CALL,
if (components.tail_call) .OP_TAIL_CALL else .OP_CALL,
@intCast(arguments_order_ref.items.len),
if (components.catch_default != null) 1 else 0,
);
Expand Down
12 changes: 9 additions & 3 deletions src/Parser.zig
Original file line number Diff line number Diff line change
Expand Up @@ -7673,14 +7673,20 @@ fn returnStatement(self: *Self) Error!Ast.Node.Index {
self.reportError(.syntax, "Can't use `return` at top-level.");
}

const value =
if (!try self.match(.Semicolon))
const value = if (!try self.match(.Semicolon))
try self.expression(false)
else
null;

if (value != null) {
if (value) |uvalue| {
try self.consume(.Semicolon, "Expected `;` after return value.");

// Tail call (TODO: do it for dot call)
if (self.ast.nodes.items(.tag)[uvalue] == .Call) {
self.ast.nodes.items(.components)[uvalue].Call.tail_call = true;
} else if (self.ast.nodes.items(.tag)[uvalue] == .Dot and self.ast.nodes.items(.components)[uvalue].Dot.member_kind == .Call) {
self.ast.nodes.items(.components)[self.ast.nodes.items(.components)[uvalue].Dot.value_or_call_or_enum.Call].Call.tail_call = true;
}
}

return try self.ast.appendNode(
Expand Down
29 changes: 16 additions & 13 deletions src/buzz_api.zig
Original file line number Diff line number Diff line change
Expand Up @@ -752,6 +752,7 @@ pub export fn bz_invoke(
len,
if (catch_value) |v| v.* else null,
false,
false,
) catch unreachable;

// If not compiled, run it with the VM loop
Expand Down Expand Up @@ -1175,19 +1176,21 @@ export fn bz_context(ctx: *NativeCtx, closure_value: Value, new_ctx: *NativeCtx,
else
null;

// If recursive call, update counter
ctx.vm.current_fiber.recursive_count = if (closure != null and closure.?.function == ctx.vm.current_fiber.current_compiled_function)
ctx.vm.current_fiber.recursive_count + 1
else
0;

if (ctx.vm.current_fiber.recursive_count > BuildOptions.recursive_call_limit) {
ctx.vm.throw(
VM.Error.ReachedMaximumRecursiveCall,
(ctx.vm.gc.copyString("Maximum recursive call reached") catch @panic("Maximum recursive call reached")).toValue(),
null,
null,
) catch @panic("Maximum recursive call reached");
if (BuildOptions.recursive_call_limit) |recursive_call_limit| {
// If recursive call, update counter
ctx.vm.current_fiber.recursive_count = if (closure != null and closure.?.function == ctx.vm.current_fiber.current_compiled_function)
ctx.vm.current_fiber.recursive_count + 1
else
0;

if (ctx.vm.current_fiber.recursive_count > recursive_call_limit) {
ctx.vm.throw(
VM.Error.ReachedMaximumRecursiveCall,
(ctx.vm.gc.copyString("Maximum recursive call reached") catch @panic("Maximum recursive call reached")).toValue(),
null,
null,
) catch @panic("Maximum recursive call reached");
}
}

// If bound method, replace closure on the stack by the receiver
Expand Down
2 changes: 2 additions & 0 deletions src/disassembler.zig
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,7 @@ pub fn disassembleInstruction(chunk: *Chunk, offset: usize) !usize {
.OP_LOOP => jumpInstruction(instruction, chunk, false, offset),

.OP_INSTANCE_INVOKE,
.OP_INSTANCE_TAIL_INVOKE,
.OP_STRING_INVOKE,
.OP_PATTERN_INVOKE,
.OP_FIBER_INVOKE,
Expand All @@ -306,6 +307,7 @@ pub fn disassembleInstruction(chunk: *Chunk, offset: usize) !usize {
=> try invokeInstruction(instruction, chunk, offset),

.OP_CALL,
.OP_TAIL_CALL,
.OP_FIBER,
.OP_INVOKE_FIBER,
=> triInstruction(instruction, chunk, offset),
Expand Down
Loading
Loading