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 
FindContainingSubprogram(const Scope & start)18 static const Scope *FindContainingSubprogram(const Scope &start) {
19   const Scope &scope{GetProgramUnitContaining(start)};
20   return scope.kind() == Scope::Kind::MainProgram ||
21           scope.kind() == Scope::Kind::Subprogram
22       ? &scope
23       : nullptr;
24 }
25 
Leave(const parser::ReturnStmt & returnStmt)26 void ReturnStmtChecker::Leave(const parser::ReturnStmt &returnStmt) {
27   // R1542 Expression analysis validates the scalar-int-expr
28   // C1574 The return-stmt shall be in the inclusive scope of a function or
29   // subroutine subprogram.
30   // C1575 The scalar-int-expr is allowed only in the inclusive scope of a
31   // subroutine subprogram.
32   const auto &scope{context_.FindScope(context_.location().value())};
33   if (const auto *subprogramScope{FindContainingSubprogram(scope)}) {
34     if (returnStmt.v &&
35         (subprogramScope->kind() == Scope::Kind::MainProgram ||
36             IsFunction(*subprogramScope->GetSymbol()))) {
37       context_.Say(
38           "RETURN with expression is only allowed in SUBROUTINE subprogram"_err_en_US);
39     } else if (context_.ShouldWarn(common::LanguageFeature::ProgramReturn)) {
40       context_.Say("RETURN should not appear in a main program"_en_US);
41     }
42   }
43 }
44 
45 } // namespace Fortran::semantics
46