1 //===-- lib/Semantics/check-return.cpp ------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "check-return.h"
10 #include "flang/Common/Fortran-features.h"
11 #include "flang/Parser/message.h"
12 #include "flang/Parser/parse-tree.h"
13 #include "flang/Semantics/semantics.h"
14 #include "flang/Semantics/tools.h"
15 
16 namespace Fortran::semantics {
17 
18 static const Scope *FindContainingSubprogram(const Scope &start) {
19   const Scope *scope{FindProgramUnitContaining(start)};
20   return scope &&
21           (scope->kind() == Scope::Kind::MainProgram ||
22               scope->kind() == Scope::Kind::Subprogram)
23       ? scope
24       : nullptr;
25 }
26 
27 void ReturnStmtChecker::Leave(const parser::ReturnStmt &returnStmt) {
28   // R1542 Expression analysis validates the scalar-int-expr
29   // C1574 The return-stmt shall be in the inclusive scope of a function or
30   // subroutine subprogram.
31   // C1575 The scalar-int-expr is allowed only in the inclusive scope of a
32   // subroutine subprogram.
33   const auto &scope{context_.FindScope(context_.location().value())};
34   if (const auto *subprogramScope{FindContainingSubprogram(scope)}) {
35     if (returnStmt.v &&
36         (subprogramScope->kind() == Scope::Kind::MainProgram ||
37             IsFunction(*subprogramScope->GetSymbol()))) {
38       context_.Say(
39           "RETURN with expression is only allowed in SUBROUTINE subprogram"_err_en_US);
40     } else if (context_.ShouldWarn(common::LanguageFeature::ProgramReturn)) {
41       context_.Say("RETURN should not appear in a main program"_en_US);
42     }
43   }
44 }
45 
46 } // namespace Fortran::semantics
47