From 18770721ac919abd8d4dc6d117a6798a462106be Mon Sep 17 00:00:00 2001 From: Jacob G-W Date: Sat, 10 Jul 2021 18:19:36 -0400 Subject: [PATCH 1/2] stage2 astgen: error for return outside of function scope --- src/AstGen.zig | 4 ++++ test/compile_errors.zig | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/src/AstGen.zig b/src/AstGen.zig index e2cdffc014..0f497526d1 100644 --- a/src/AstGen.zig +++ b/src/AstGen.zig @@ -6167,6 +6167,10 @@ fn ret(gz: *GenZir, scope: *Scope, node: ast.Node.Index) InnerError!Zir.Inst.Ref const node_datas = tree.nodes.items(.data); const node_tags = tree.nodes.items(.tag); + if (astgen.fn_block == null) { + return astgen.failNode(node, "'return' outside function scope", .{}); + } + if (gz.in_defer) return astgen.failNode(node, "cannot return from defer expression", .{}); const defer_outer = &astgen.fn_block.?.base; diff --git a/test/compile_errors.zig b/test/compile_errors.zig index 6ce1774ecf..6075eee33a 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -2,6 +2,10 @@ const std = @import("std"); const TestContext = @import("../src/test.zig").TestContext; pub fn addCases(ctx: *TestContext) !void { + ctx.objErrStage1("issue #9346: return outside of function scope", + \\pub const empty = return 1; + , &.{"tmp.zig:1:19: error: 'return' outside function scope"}); + ctx.exeErrStage1("std.fmt error for unused arguments", \\pub fn main() !void { \\ @import("std").debug.print("{d} {d} {d} {d} {d}", .{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}); From b0b9c3c2dc4e55609db44dc0564795b7e2ed1b34 Mon Sep 17 00:00:00 2001 From: Jacob G-W Date: Sun, 11 Jul 2021 10:03:47 -0400 Subject: [PATCH 2/2] stage2: remove redundancy from error message invalid 'try' outside function scope -> 'try' outside function scope --- src/AstGen.zig | 2 +- test/cases.zig | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/AstGen.zig b/src/AstGen.zig index 0f497526d1..f62a8f18ab 100644 --- a/src/AstGen.zig +++ b/src/AstGen.zig @@ -4604,7 +4604,7 @@ fn tryExpr( const astgen = parent_gz.astgen; const fn_block = astgen.fn_block orelse { - return astgen.failNode(node, "invalid 'try' outside function scope", .{}); + return astgen.failNode(node, "'try' outside function scope", .{}); }; if (parent_gz.in_defer) return astgen.failNode(node, "'try' not allowed inside defer expression", .{}); diff --git a/test/cases.zig b/test/cases.zig index 37683072a2..f6aa80514c 100644 --- a/test/cases.zig +++ b/test/cases.zig @@ -903,7 +903,7 @@ pub fn addCases(ctx: *TestContext) !void { \\ _ = S; \\} , - &.{":4:13: error: invalid 'try' outside function scope"}, + &.{":4:13: error: 'try' outside function scope"}, ); } {