Skip to content

Commit 7b196cb

Browse files
committed
test: add test cases for top-level return restrictions
Add test cases demonstrating that return statements are not allowed at the top-level scope, while being permitted within functions and nested function contexts
1 parent 7b0bab7 commit 7b196cb

File tree

4 files changed

+49
-4
lines changed

4 files changed

+49
-4
lines changed

test_programs/r5/1.lox

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
---
22
expected_error_type: compile
33
---
4-
return "foo";
4+
fun foo() {
5+
return "at function scope is ok";
6+
}
7+
8+
return; // Error: Can't return from top-level code.

test_programs/r5/2.lox

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,19 @@
11
---
2-
expected_error_type: none
2+
expected_error_type: compile
33
---
4+
fun foo() {
5+
if (true) {
6+
// Return inside nested blocks in a function is fine
7+
return "early return";
8+
}
9+
10+
for (var i = 0; i < 10; i = i + 1) {
11+
// Return inside loops in a function is fine too
12+
return "loop return";
13+
}
14+
}
15+
16+
// But this is still an error
17+
if (true) {
18+
return "conditional return"; // Error: Can't return from top-level code.
19+
}

test_programs/r5/3.lox

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,13 @@
11
---
2-
expected_error_type: none
2+
expected_error_type: compile
33
---
4+
{
5+
return "not allowed in a block either"; // Error: Can't return from top-level code.
6+
}
7+
8+
fun allowed() {
9+
if (true) {
10+
return "this is fine"; // This is ok
11+
}
12+
return; // This is also ok
13+
}

test_programs/r5/4.lox

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,18 @@
11
---
2-
expected_error_type: none
2+
expected_error_type: compile
33
---
4+
fun outer() {
5+
fun inner() {
6+
return "ok";
7+
}
8+
9+
return "also ok";
10+
}
11+
12+
if (true) {
13+
fun nested() {
14+
return; // This is fine
15+
}
16+
17+
return "not ok"; // Error: Can't return from top-level code.
18+
}

0 commit comments

Comments
 (0)