diff --git a/gcc/rust/typecheck/rust-hir-type-check-expr.cc b/gcc/rust/typecheck/rust-hir-type-check-expr.cc index af4be5f4e82c..18247c675f68 100644 --- a/gcc/rust/typecheck/rust-hir-type-check-expr.cc +++ b/gcc/rust/typecheck/rust-hir-type-check-expr.cc @@ -150,6 +150,14 @@ TypeCheckExpr::visit (HIR::TupleExpr &expr) void TypeCheckExpr::visit (HIR::ReturnExpr &expr) { + if (!context->have_function_context ()) + { + rust_error_at (expr.get_locus (), + "return statement outside of function body"); + infered = new TyTy::ErrorType (expr.get_mappings ().get_hirid ()); + return; + } + auto fn_return_tyty = context->peek_return_type (); location_t expr_locus = expr.has_return_expr () ? expr.get_expr ()->get_locus () diff --git a/gcc/testsuite/rust/compile/issue-2477.rs b/gcc/testsuite/rust/compile/issue-2477.rs new file mode 100644 index 000000000000..26831a6625d0 --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-2477.rs @@ -0,0 +1,3 @@ +const FOO: u32 = return 0; +// { dg-error "return statement outside of function body" "" { target *-*-* } .-1 } +// { dg-error "expected .u32. got" "" { target *-*-* } .-2 }