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 mis-identified statement functions to array element assignments.
25 /// Convert mis-identified format expressions to namelist group names.
26 /// Convert mis-identified character variables in I/O units to integer
27 /// unit number expressions.
28 class RewriteMutator {
29 public:
30   RewriteMutator(SemanticsContext &context)
31       : errorOnUnresolvedName_{!context.AnyFatalError()},
32         messages_{context.messages()} {}
33 
34   // Default action for a parse tree node is to visit children.
35   template <typename T> bool Pre(T &) { return true; }
36   template <typename T> void Post(T &) {}
37 
38   void Post(parser::Name &);
39   void Post(parser::SpecificationPart &);
40   bool Pre(parser::ExecutionPart &);
41   void Post(parser::IoUnit &);
42   void Post(parser::ReadStmt &);
43   void Post(parser::WriteStmt &);
44 
45   // Name resolution yet implemented:
46   bool Pre(parser::EquivalenceStmt &) { return false; }
47   bool Pre(parser::Keyword &) { return false; }
48   bool Pre(parser::EntryStmt &) { return false; }
49   bool Pre(parser::CompilerDirective &) { return false; }
50 
51   // Don't bother resolving names in end statements.
52   bool Pre(parser::EndBlockDataStmt &) { return false; }
53   bool Pre(parser::EndFunctionStmt &) { return false; }
54   bool Pre(parser::EndInterfaceStmt &) { return false; }
55   bool Pre(parser::EndModuleStmt &) { return false; }
56   bool Pre(parser::EndMpSubprogramStmt &) { return false; }
57   bool Pre(parser::EndProgramStmt &) { return false; }
58   bool Pre(parser::EndSubmoduleStmt &) { return false; }
59   bool Pre(parser::EndSubroutineStmt &) { return false; }
60   bool Pre(parser::EndTypeStmt &) { return false; }
61 
62 private:
63   using stmtFuncType =
64       parser::Statement<common::Indirection<parser::StmtFunctionStmt>>;
65   bool errorOnUnresolvedName_{true};
66   parser::Messages &messages_;
67   std::list<stmtFuncType> stmtFuncsToConvert_;
68 };
69 
70 // Check that name has been resolved to a symbol
71 void RewriteMutator::Post(parser::Name &name) {
72   if (!name.symbol && errorOnUnresolvedName_) {
73     messages_.Say(name.source, "Internal: no symbol found for '%s'"_err_en_US,
74         name.source);
75   }
76 }
77 
78 // Find mis-parsed statement functions and move to stmtFuncsToConvert_ list.
79 void RewriteMutator::Post(parser::SpecificationPart &x) {
80   auto &list{std::get<std::list<parser::DeclarationConstruct>>(x.t)};
81   for (auto it{list.begin()}; it != list.end();) {
82     if (auto stmt{std::get_if<stmtFuncType>(&it->u)}) {
83       Symbol *symbol{std::get<parser::Name>(stmt->statement.value().t).symbol};
84       if (symbol && symbol->has<ObjectEntityDetails>()) {
85         // not a stmt func: remove it here and add to ones to convert
86         stmtFuncsToConvert_.push_back(std::move(*stmt));
87         it = list.erase(it);
88         continue;
89       }
90     }
91     ++it;
92   }
93 }
94 
95 // Insert converted assignments at start of ExecutionPart.
96 bool RewriteMutator::Pre(parser::ExecutionPart &x) {
97   auto origFirst{x.v.begin()}; // insert each elem before origFirst
98   for (stmtFuncType &sf : stmtFuncsToConvert_) {
99     auto stmt{sf.statement.value().ConvertToAssignment()};
100     stmt.source = sf.source;
101     x.v.insert(origFirst,
102         parser::ExecutionPartConstruct{
103             parser::ExecutableConstruct{std::move(stmt)}});
104   }
105   stmtFuncsToConvert_.clear();
106   return true;
107 }
108 
109 void RewriteMutator::Post(parser::IoUnit &x) {
110   if (auto *var{std::get_if<parser::Variable>(&x.u)}) {
111     const parser::Name &last{parser::GetLastName(*var)};
112     DeclTypeSpec *type{last.symbol ? last.symbol->GetType() : nullptr};
113     if (!type || type->category() != DeclTypeSpec::Character) {
114       // If the Variable is not known to be character (any kind), transform
115       // the I/O unit in situ to a FileUnitNumber so that automatic expression
116       // constraint checking will be applied.
117       auto expr{std::visit(
118           [](auto &&indirection) {
119             return parser::Expr{std::move(indirection)};
120           },
121           std::move(var->u))};
122       x.u = parser::FileUnitNumber{
123           parser::ScalarIntExpr{parser::IntExpr{std::move(expr)}}};
124     }
125   }
126 }
127 
128 // When a namelist group name appears (without NML=) in a READ or WRITE
129 // statement in such a way that it can be misparsed as a format expression,
130 // rewrite the I/O statement's parse tree node as if the namelist group
131 // name had appeared with NML=.
132 template <typename READ_OR_WRITE>
133 void FixMisparsedUntaggedNamelistName(READ_OR_WRITE &x) {
134   if (x.iounit && x.format &&
135       std::holds_alternative<parser::Expr>(x.format->u)) {
136     if (const parser::Name * name{parser::Unwrap<parser::Name>(x.format)}) {
137       if (name->symbol && name->symbol->GetUltimate().has<NamelistDetails>()) {
138         x.controls.emplace_front(parser::IoControlSpec{std::move(*name)});
139         x.format.reset();
140       }
141     }
142   }
143 }
144 
145 void RewriteMutator::Post(parser::ReadStmt &x) {
146   FixMisparsedUntaggedNamelistName(x);
147 }
148 
149 void RewriteMutator::Post(parser::WriteStmt &x) {
150   FixMisparsedUntaggedNamelistName(x);
151 }
152 
153 bool RewriteParseTree(SemanticsContext &context, parser::Program &program) {
154   RewriteMutator mutator{context};
155   parser::Walk(program, mutator);
156   return !context.AnyFatalError();
157 }
158 
159 } // namespace Fortran::semantics
160