Skip to content

Commit

Permalink
feat: Warn about code after return and stop generating
Browse files Browse the repository at this point in the history
closes #52
  • Loading branch information
giann committed Feb 29, 2024
1 parent 7baaa7a commit 6fb8d77
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ var value = from {
}
```
- `recursive_call_limit` build option limit recursive calls (default to 200)
- Compiler will warn about code after a `return` statement

## 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)
Expand Down
19 changes: 19 additions & 0 deletions src/Codegen.zig
Original file line number Diff line number Diff line change
Expand Up @@ -829,8 +829,27 @@ fn generateBinary(self: *Self, node: Ast.Node.Index, breaks: ?*std.ArrayList(usi
}

fn generateBlock(self: *Self, node: Ast.Node.Index, breaks: ?*std.ArrayList(usize)) Error!?*obj.ObjFunction {
const tags = self.ast.nodes.items(.tag);

var seen_return = false;
for (self.ast.nodes.items(.components)[node].Block) |statement| {
if (seen_return) {
self.reporter.warnFmt(
.code_after_return,
self.ast.tokens.get(
self.ast.nodes.items(.location)[statement],
),
"Code after return statement will never be reached",
.{},
);

// No need to generate following statements
break;
}

_ = try self.generateNode(statement, breaks);

seen_return = !seen_return and tags[statement] == .Return;
}

try self.patchOptJumps(node);
Expand Down
2 changes: 1 addition & 1 deletion src/Parser.zig
Original file line number Diff line number Diff line change
Expand Up @@ -3420,7 +3420,7 @@ fn argumentList(self: *Self) ![]Ast.Call.Argument {
}

fn call(self: *Self, _: bool, callee: Ast.Node.Index) Error!Ast.Node.Index {
const start_location = self.current_token.? - 1;
const start_location = self.ast.nodes.items(.location)[callee];
const callee_type_def = self.ast.nodes.items(.type_def)[callee];

const arguments = try self.argumentList();
Expand Down
1 change: 1 addition & 0 deletions src/Reporter.zig
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ pub const Error = enum(u8) {
inferred_type = 90,
empty_import = 91,
import_already_exists = 92,
code_after_return = 93,
};

// Inspired by https://github.com/zesterer/ariadne
Expand Down
10 changes: 10 additions & 0 deletions tests/compile_errors/027-early-return.buzz
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
| Code after return statement will never be reached
import "std";

test "Early return" {
print("I sure hope i'm not interrupted...");

return;

print("Guess I was");
}

0 comments on commit 6fb8d77

Please sign in to comment.