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 /// Convert misidentified format expressions to namelist group names.
26 /// Convert misidentified character variables in I/O units to integer
27 /// unit number expressions.
28 /// Convert misidentified named constants in data statement values to
29 /// initial data targets
30 class RewriteMutator {
31 public:
RewriteMutator(SemanticsContext & context)32   RewriteMutator(SemanticsContext &context)
33       : errorOnUnresolvedName_{!context.AnyFatalError()},
34         messages_{context.messages()} {}
35 
36   // Default action for a parse tree node is to visit children.
Pre(T &)37   template <typename T> bool Pre(T &) { return true; }
Post(T &)38   template <typename T> void Post(T &) {}
39 
40   void Post(parser::Name &);
41   void Post(parser::SpecificationPart &);
42   bool Pre(parser::ExecutionPart &);
43   void Post(parser::IoUnit &);
44   void Post(parser::ReadStmt &);
45   void Post(parser::WriteStmt &);
46   void Post(parser::DataStmtConstant &);
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 
82 // Find mis-parsed statement functions and move to stmtFuncsToConvert_ list.
Post(parser::SpecificationPart & x)83 void RewriteMutator::Post(parser::SpecificationPart &x) {
84   auto &list{std::get<std::list<parser::DeclarationConstruct>>(x.t)};
85   for (auto it{list.begin()}; it != list.end();) {
86     if (auto stmt{std::get_if<stmtFuncType>(&it->u)}) {
87       Symbol *symbol{std::get<parser::Name>(stmt->statement.value().t).symbol};
88       if (symbol && symbol->has<ObjectEntityDetails>()) {
89         // not a stmt func: remove it here and add to ones to convert
90         stmtFuncsToConvert_.push_back(std::move(*stmt));
91         it = list.erase(it);
92         continue;
93       }
94     }
95     ++it;
96   }
97 }
98 
99 // Insert converted assignments at start of ExecutionPart.
Pre(parser::ExecutionPart & x)100 bool RewriteMutator::Pre(parser::ExecutionPart &x) {
101   auto origFirst{x.v.begin()}; // insert each elem before origFirst
102   for (stmtFuncType &sf : stmtFuncsToConvert_) {
103     auto stmt{sf.statement.value().ConvertToAssignment()};
104     stmt.source = sf.source;
105     x.v.insert(origFirst,
106         parser::ExecutionPartConstruct{
107             parser::ExecutableConstruct{std::move(stmt)}});
108   }
109   stmtFuncsToConvert_.clear();
110   return true;
111 }
112 
113 // Convert a syntactically ambiguous io-unit internal-file-variable to a
114 // file-unit-number.
Post(parser::IoUnit & x)115 void RewriteMutator::Post(parser::IoUnit &x) {
116   if (auto *var{std::get_if<parser::Variable>(&x.u)}) {
117     const parser::Name &last{parser::GetLastName(*var)};
118     DeclTypeSpec *type{last.symbol ? last.symbol->GetType() : nullptr};
119     if (!type || type->category() != DeclTypeSpec::Character) {
120       // If the Variable is not known to be character (any kind), transform
121       // the I/O unit in situ to a FileUnitNumber so that automatic expression
122       // constraint checking will be applied.
123       auto source{var->GetSource()};
124       auto expr{std::visit(
125           [](auto &&indirection) {
126             return parser::Expr{std::move(indirection)};
127           },
128           std::move(var->u))};
129       expr.source = source;
130       x.u = parser::FileUnitNumber{
131           parser::ScalarIntExpr{parser::IntExpr{std::move(expr)}}};
132     }
133   }
134 }
135 
136 // When a namelist group name appears (without NML=) in a READ or WRITE
137 // statement in such a way that it can be misparsed as a format expression,
138 // rewrite the I/O statement's parse tree node as if the namelist group
139 // name had appeared with NML=.
140 template <typename READ_OR_WRITE>
FixMisparsedUntaggedNamelistName(READ_OR_WRITE & x)141 void FixMisparsedUntaggedNamelistName(READ_OR_WRITE &x) {
142   if (x.iounit && x.format &&
143       std::holds_alternative<parser::Expr>(x.format->u)) {
144     if (const parser::Name * name{parser::Unwrap<parser::Name>(x.format)}) {
145       if (name->symbol && name->symbol->GetUltimate().has<NamelistDetails>()) {
146         x.controls.emplace_front(parser::IoControlSpec{std::move(*name)});
147         x.format.reset();
148       }
149     }
150   }
151 }
152 
153 // READ(CVAR) [, ...] will be misparsed as UNIT=CVAR; correct
154 // it to READ CVAR [,...] with CVAR as a format rather than as
155 // an internal I/O unit for unformatted I/O, which Fortran does
156 // not support.
Post(parser::ReadStmt & x)157 void RewriteMutator::Post(parser::ReadStmt &x) {
158   if (x.iounit && !x.format && x.controls.empty()) {
159     if (auto *var{std::get_if<parser::Variable>(&x.iounit->u)}) {
160       const parser::Name &last{parser::GetLastName(*var)};
161       DeclTypeSpec *type{last.symbol ? last.symbol->GetType() : nullptr};
162       if (type && type->category() == DeclTypeSpec::Character) {
163         x.format = std::visit(
164             [](auto &&indirection) {
165               return parser::Expr{std::move(indirection)};
166             },
167             std::move(var->u));
168         x.iounit.reset();
169       }
170     }
171   }
172   FixMisparsedUntaggedNamelistName(x);
173 }
174 
Post(parser::WriteStmt & x)175 void RewriteMutator::Post(parser::WriteStmt &x) {
176   FixMisparsedUntaggedNamelistName(x);
177 }
178 
Post(parser::DataStmtConstant & x)179 void RewriteMutator::Post(parser::DataStmtConstant &x) {
180   if (auto *scalar{std::get_if<parser::Scalar<parser::ConstantValue>>(&x.u)}) {
181     if (auto *named{std::get_if<parser::NamedConstant>(&scalar->thing.u)}) {
182       if (const Symbol * symbol{named->v.symbol}) {
183         if (!IsNamedConstant(*symbol) && symbol->attrs().test(Attr::TARGET)) {
184           x.u = parser::InitialDataTarget{
185               parser::Designator{parser::DataRef{parser::Name{named->v}}}};
186         }
187       }
188     }
189   }
190 }
191 
RewriteParseTree(SemanticsContext & context,parser::Program & program)192 bool RewriteParseTree(SemanticsContext &context, parser::Program &program) {
193   RewriteMutator mutator{context};
194   parser::Walk(program, mutator);
195   return !context.AnyFatalError();
196 }
197 
198 } // namespace Fortran::semantics
199