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