1 //===-- lib/Semantics/rewrite-parse-tree.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 "rewrite-parse-tree.h"
10 #include "flang/Common/indirection.h"
11 #include "flang/Parser/parse-tree-visitor.h"
12 #include "flang/Parser/parse-tree.h"
13 #include "flang/Parser/tools.h"
14 #include "flang/Semantics/scope.h"
15 #include "flang/Semantics/semantics.h"
16 #include "flang/Semantics/symbol.h"
17 #include "flang/Semantics/tools.h"
18 #include <list>
19 
20 namespace Fortran::semantics {
21 
22 using namespace parser::literals;
23 
24 /// Convert misidentified statement functions to array element assignments
25 /// or pointer-valued function result assignments.
26 /// Convert misidentified format expressions to namelist group names.
27 /// Convert misidentified character variables in I/O units to integer
28 /// unit number expressions.
29 /// Convert misidentified named constants in data statement values to
30 /// initial data targets
31 class RewriteMutator {
32 public:
RewriteMutator(SemanticsContext & context)33   RewriteMutator(SemanticsContext &context)
34       : errorOnUnresolvedName_{!context.AnyFatalError()},
35         messages_{context.messages()} {}
36 
37   // Default action for a parse tree node is to visit children.
Pre(T &)38   template <typename T> bool Pre(T &) { return true; }
Post(T &)39   template <typename T> void Post(T &) {}
40 
41   void Post(parser::Name &);
42   void Post(parser::SpecificationPart &);
43   bool Pre(parser::ExecutionPart &);
44   void Post(parser::IoUnit &);
45   void Post(parser::ReadStmt &);
46   void Post(parser::WriteStmt &);
47 
48   // Name resolution yet implemented:
49   // TODO: Can some/all of these now be enabled?
Pre(parser::EquivalenceStmt &)50   bool Pre(parser::EquivalenceStmt &) { return false; }
Pre(parser::Keyword &)51   bool Pre(parser::Keyword &) { return false; }
Pre(parser::EntryStmt &)52   bool Pre(parser::EntryStmt &) { return false; }
Pre(parser::CompilerDirective &)53   bool Pre(parser::CompilerDirective &) { return false; }
54 
55   // Don't bother resolving names in end statements.
Pre(parser::EndBlockDataStmt &)56   bool Pre(parser::EndBlockDataStmt &) { return false; }
Pre(parser::EndFunctionStmt &)57   bool Pre(parser::EndFunctionStmt &) { return false; }
Pre(parser::EndInterfaceStmt &)58   bool Pre(parser::EndInterfaceStmt &) { return false; }
Pre(parser::EndModuleStmt &)59   bool Pre(parser::EndModuleStmt &) { return false; }
Pre(parser::EndMpSubprogramStmt &)60   bool Pre(parser::EndMpSubprogramStmt &) { return false; }
Pre(parser::EndProgramStmt &)61   bool Pre(parser::EndProgramStmt &) { return false; }
Pre(parser::EndSubmoduleStmt &)62   bool Pre(parser::EndSubmoduleStmt &) { return false; }
Pre(parser::EndSubroutineStmt &)63   bool Pre(parser::EndSubroutineStmt &) { return false; }
Pre(parser::EndTypeStmt &)64   bool Pre(parser::EndTypeStmt &) { return false; }
65 
66 private:
67   using stmtFuncType =
68       parser::Statement<common::Indirection<parser::StmtFunctionStmt>>;
69   bool errorOnUnresolvedName_{true};
70   parser::Messages &messages_;
71   std::list<stmtFuncType> stmtFuncsToConvert_;
72 };
73 
74 // Check that name has been resolved to a symbol
Post(parser::Name & name)75 void RewriteMutator::Post(parser::Name &name) {
76   if (!name.symbol && errorOnUnresolvedName_) {
77     messages_.Say(name.source, "Internal: no symbol found for '%s'"_err_en_US,
78         name.source);
79   }
80 }
81 
ReturnsDataPointer(const Symbol & symbol)82 static bool ReturnsDataPointer(const Symbol &symbol) {
83   if (const Symbol * funcRes{FindFunctionResult(symbol)}) {
84     return IsPointer(*funcRes) && !IsProcedure(*funcRes);
85   } else if (const auto *generic{symbol.detailsIf<GenericDetails>()}) {
86     for (auto ref : generic->specificProcs()) {
87       if (ReturnsDataPointer(*ref)) {
88         return true;
89       }
90     }
91   }
92   return false;
93 }
94 
95 // Find mis-parsed statement functions and move to stmtFuncsToConvert_ list.
Post(parser::SpecificationPart & x)96 void RewriteMutator::Post(parser::SpecificationPart &x) {
97   auto &list{std::get<std::list<parser::DeclarationConstruct>>(x.t)};
98   for (auto it{list.begin()}; it != list.end();) {
99     bool isAssignment{false};
100     if (auto *stmt{std::get_if<stmtFuncType>(&it->u)}) {
101       if (const Symbol *
102           symbol{std::get<parser::Name>(stmt->statement.value().t).symbol}) {
103         const Symbol &ultimate{symbol->GetUltimate()};
104         isAssignment =
105             ultimate.has<ObjectEntityDetails>() || ReturnsDataPointer(ultimate);
106         if (isAssignment) {
107           stmtFuncsToConvert_.emplace_back(std::move(*stmt));
108         }
109       }
110     }
111     if (isAssignment) {
112       it = list.erase(it);
113     } else {
114       ++it;
115     }
116   }
117 }
118 
119 // Insert converted assignments at start of ExecutionPart.
Pre(parser::ExecutionPart & x)120 bool RewriteMutator::Pre(parser::ExecutionPart &x) {
121   auto origFirst{x.v.begin()}; // insert each elem before origFirst
122   for (stmtFuncType &sf : stmtFuncsToConvert_) {
123     auto stmt{sf.statement.value().ConvertToAssignment()};
124     stmt.source = sf.source;
125     x.v.insert(origFirst,
126         parser::ExecutionPartConstruct{
127             parser::ExecutableConstruct{std::move(stmt)}});
128   }
129   stmtFuncsToConvert_.clear();
130   return true;
131 }
132 
133 // Convert a syntactically ambiguous io-unit internal-file-variable to a
134 // file-unit-number.
Post(parser::IoUnit & x)135 void RewriteMutator::Post(parser::IoUnit &x) {
136   if (auto *var{std::get_if<parser::Variable>(&x.u)}) {
137     const parser::Name &last{parser::GetLastName(*var)};
138     DeclTypeSpec *type{last.symbol ? last.symbol->GetType() : nullptr};
139     if (!type || type->category() != DeclTypeSpec::Character) {
140       // If the Variable is not known to be character (any kind), transform
141       // the I/O unit in situ to a FileUnitNumber so that automatic expression
142       // constraint checking will be applied.
143       auto source{var->GetSource()};
144       auto expr{common::visit(
145           [](auto &&indirection) {
146             return parser::Expr{std::move(indirection)};
147           },
148           std::move(var->u))};
149       expr.source = source;
150       x.u = parser::FileUnitNumber{
151           parser::ScalarIntExpr{parser::IntExpr{std::move(expr)}}};
152     }
153   }
154 }
155 
156 // When a namelist group name appears (without NML=) in a READ or WRITE
157 // statement in such a way that it can be misparsed as a format expression,
158 // rewrite the I/O statement's parse tree node as if the namelist group
159 // name had appeared with NML=.
160 template <typename READ_OR_WRITE>
FixMisparsedUntaggedNamelistName(READ_OR_WRITE & x)161 void FixMisparsedUntaggedNamelistName(READ_OR_WRITE &x) {
162   if (x.iounit && x.format &&
163       std::holds_alternative<parser::Expr>(x.format->u)) {
164     if (const parser::Name * name{parser::Unwrap<parser::Name>(x.format)}) {
165       if (name->symbol && name->symbol->GetUltimate().has<NamelistDetails>()) {
166         x.controls.emplace_front(parser::IoControlSpec{std::move(*name)});
167         x.format.reset();
168       }
169     }
170   }
171 }
172 
173 // READ(CVAR) [, ...] will be misparsed as UNIT=CVAR; correct
174 // it to READ CVAR [,...] with CVAR as a format rather than as
175 // an internal I/O unit for unformatted I/O, which Fortran does
176 // not support.
Post(parser::ReadStmt & x)177 void RewriteMutator::Post(parser::ReadStmt &x) {
178   if (x.iounit && !x.format && x.controls.empty()) {
179     if (auto *var{std::get_if<parser::Variable>(&x.iounit->u)}) {
180       const parser::Name &last{parser::GetLastName(*var)};
181       DeclTypeSpec *type{last.symbol ? last.symbol->GetType() : nullptr};
182       if (type && type->category() == DeclTypeSpec::Character) {
183         x.format = common::visit(
184             [](auto &&indirection) {
185               return parser::Expr{std::move(indirection)};
186             },
187             std::move(var->u));
188         x.iounit.reset();
189       }
190     }
191   }
192   FixMisparsedUntaggedNamelistName(x);
193 }
194 
Post(parser::WriteStmt & x)195 void RewriteMutator::Post(parser::WriteStmt &x) {
196   FixMisparsedUntaggedNamelistName(x);
197 }
198 
RewriteParseTree(SemanticsContext & context,parser::Program & program)199 bool RewriteParseTree(SemanticsContext &context, parser::Program &program) {
200   RewriteMutator mutator{context};
201   parser::Walk(program, mutator);
202   return !context.AnyFatalError();
203 }
204 
205 } // namespace Fortran::semantics
206