1 //===-- lib/Semantics/semantics.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 "flang/Semantics/semantics.h"
10 #include "assignment.h"
11 #include "canonicalize-do.h"
12 #include "canonicalize-omp.h"
13 #include "check-allocate.h"
14 #include "check-arithmeticif.h"
15 #include "check-case.h"
16 #include "check-coarray.h"
17 #include "check-data.h"
18 #include "check-deallocate.h"
19 #include "check-declarations.h"
20 #include "check-do-forall.h"
21 #include "check-if-stmt.h"
22 #include "check-io.h"
23 #include "check-namelist.h"
24 #include "check-nullify.h"
25 #include "check-omp-structure.h"
26 #include "check-purity.h"
27 #include "check-return.h"
28 #include "check-select-rank.h"
29 #include "check-select-type.h"
30 #include "check-stop.h"
31 #include "compute-offsets.h"
32 #include "mod-file.h"
33 #include "resolve-labels.h"
34 #include "resolve-names.h"
35 #include "rewrite-parse-tree.h"
36 #include "flang/Common/default-kinds.h"
37 #include "flang/Parser/parse-tree-visitor.h"
38 #include "flang/Parser/tools.h"
39 #include "flang/Semantics/expression.h"
40 #include "flang/Semantics/scope.h"
41 #include "flang/Semantics/symbol.h"
42 #include "llvm/Support/raw_ostream.h"
43 
44 namespace Fortran::semantics {
45 
46 using NameToSymbolMap = std::map<const char *, SymbolRef>;
47 static void DoDumpSymbols(llvm::raw_ostream &, const Scope &, int indent = 0);
48 static void PutIndent(llvm::raw_ostream &, int indent);
49 
50 static void GetSymbolNames(const Scope &scope, NameToSymbolMap &symbols) {
51   // Finds all symbol names in the scope without collecting duplicates.
52   for (const auto &pair : scope) {
53     symbols.emplace(pair.second->name().begin(), *pair.second);
54   }
55   for (const auto &pair : scope.commonBlocks()) {
56     symbols.emplace(pair.second->name().begin(), *pair.second);
57   }
58   for (const auto &child : scope.children()) {
59     GetSymbolNames(child, symbols);
60   }
61 }
62 
63 // A parse tree visitor that calls Enter/Leave functions from each checker
64 // class C supplied as template parameters. Enter is called before the node's
65 // children are visited, Leave is called after. No two checkers may have the
66 // same Enter or Leave function. Each checker must be constructible from
67 // SemanticsContext and have BaseChecker as a virtual base class.
68 template <typename... C> class SemanticsVisitor : public virtual C... {
69 public:
70   using C::Enter...;
71   using C::Leave...;
72   using BaseChecker::Enter;
73   using BaseChecker::Leave;
74   SemanticsVisitor(SemanticsContext &context)
75       : C{context}..., context_{context} {}
76 
77   template <typename N> bool Pre(const N &node) {
78     if constexpr (common::HasMember<const N *, ConstructNode>) {
79       context_.PushConstruct(node);
80     }
81     Enter(node);
82     return true;
83   }
84   template <typename N> void Post(const N &node) {
85     Leave(node);
86     if constexpr (common::HasMember<const N *, ConstructNode>) {
87       context_.PopConstruct();
88     }
89   }
90 
91   template <typename T> bool Pre(const parser::Statement<T> &node) {
92     context_.set_location(node.source);
93     Enter(node);
94     return true;
95   }
96   template <typename T> bool Pre(const parser::UnlabeledStatement<T> &node) {
97     context_.set_location(node.source);
98     Enter(node);
99     return true;
100   }
101   template <typename T> void Post(const parser::Statement<T> &node) {
102     Leave(node);
103     context_.set_location(std::nullopt);
104   }
105   template <typename T> void Post(const parser::UnlabeledStatement<T> &node) {
106     Leave(node);
107     context_.set_location(std::nullopt);
108   }
109 
110   bool Walk(const parser::Program &program) {
111     parser::Walk(program, *this);
112     return !context_.AnyFatalError();
113   }
114 
115 private:
116   SemanticsContext &context_;
117 };
118 
119 class MiscChecker : public virtual BaseChecker {
120 public:
121   explicit MiscChecker(SemanticsContext &context) : context_{context} {}
122   void Leave(const parser::EntryStmt &) {
123     if (!context_.constructStack().empty()) { // C1571
124       context_.Say("ENTRY may not appear in an executable construct"_err_en_US);
125     }
126   }
127   void Leave(const parser::AssignStmt &stmt) {
128     CheckAssignGotoName(std::get<parser::Name>(stmt.t));
129   }
130   void Leave(const parser::AssignedGotoStmt &stmt) {
131     CheckAssignGotoName(std::get<parser::Name>(stmt.t));
132   }
133 
134 private:
135   void CheckAssignGotoName(const parser::Name &name) {
136     if (context_.HasError(name.symbol)) {
137       return;
138     }
139     const Symbol &symbol{DEREF(name.symbol)};
140     auto type{evaluate::DynamicType::From(symbol)};
141     if (!IsVariableName(symbol) || symbol.Rank() != 0 || !type ||
142         type->category() != TypeCategory::Integer ||
143         type->kind() !=
144             context_.defaultKinds().GetDefaultKind(TypeCategory::Integer)) {
145       context_
146           .Say(name.source,
147               "'%s' must be a default integer scalar variable"_err_en_US,
148               name.source)
149           .Attach(symbol.name(), "Declaration of '%s'"_en_US, symbol.name());
150     }
151   }
152 
153   SemanticsContext &context_;
154 };
155 
156 using StatementSemanticsPass1 = ExprChecker;
157 using StatementSemanticsPass2 = SemanticsVisitor<AllocateChecker,
158     ArithmeticIfStmtChecker, AssignmentChecker, CaseChecker, CoarrayChecker,
159     DataChecker, DeallocateChecker, DoForallChecker, IfStmtChecker, IoChecker,
160     MiscChecker, NamelistChecker, NullifyChecker, OmpStructureChecker,
161     PurityChecker, ReturnStmtChecker, SelectRankConstructChecker,
162     SelectTypeChecker, StopChecker>;
163 
164 static bool PerformStatementSemantics(
165     SemanticsContext &context, parser::Program &program) {
166   ResolveNames(context, program);
167   RewriteParseTree(context, program);
168   ComputeOffsets(context);
169   CheckDeclarations(context);
170   StatementSemanticsPass1{context}.Walk(program);
171   StatementSemanticsPass2{context}.Walk(program);
172   return !context.AnyFatalError();
173 }
174 
175 SemanticsContext::SemanticsContext(
176     const common::IntrinsicTypeDefaultKinds &defaultKinds,
177     const common::LanguageFeatureControl &languageFeatures,
178     parser::AllSources &allSources)
179     : defaultKinds_{defaultKinds}, languageFeatures_{languageFeatures},
180       allSources_{allSources},
181       intrinsics_{evaluate::IntrinsicProcTable::Configure(defaultKinds_)},
182       foldingContext_{
183           parser::ContextualMessages{&messages_}, defaultKinds_, intrinsics_} {}
184 
185 SemanticsContext::~SemanticsContext() {}
186 
187 int SemanticsContext::GetDefaultKind(TypeCategory category) const {
188   return defaultKinds_.GetDefaultKind(category);
189 }
190 
191 bool SemanticsContext::IsEnabled(common::LanguageFeature feature) const {
192   return languageFeatures_.IsEnabled(feature);
193 }
194 
195 bool SemanticsContext::ShouldWarn(common::LanguageFeature feature) const {
196   return languageFeatures_.ShouldWarn(feature);
197 }
198 
199 const DeclTypeSpec &SemanticsContext::MakeNumericType(
200     TypeCategory category, int kind) {
201   if (kind == 0) {
202     kind = GetDefaultKind(category);
203   }
204   return globalScope_.MakeNumericType(category, KindExpr{kind});
205 }
206 const DeclTypeSpec &SemanticsContext::MakeLogicalType(int kind) {
207   if (kind == 0) {
208     kind = GetDefaultKind(TypeCategory::Logical);
209   }
210   return globalScope_.MakeLogicalType(KindExpr{kind});
211 }
212 
213 bool SemanticsContext::AnyFatalError() const {
214   return !messages_.empty() &&
215       (warningsAreErrors_ || messages_.AnyFatalError());
216 }
217 bool SemanticsContext::HasError(const Symbol &symbol) {
218   return CheckError(symbol.test(Symbol::Flag::Error));
219 }
220 bool SemanticsContext::HasError(const Symbol *symbol) {
221   return CheckError(!symbol || HasError(*symbol));
222 }
223 bool SemanticsContext::HasError(const parser::Name &name) {
224   return HasError(name.symbol);
225 }
226 void SemanticsContext::SetError(Symbol &symbol, bool value) {
227   if (value) {
228     CHECK(AnyFatalError());
229     symbol.set(Symbol::Flag::Error);
230   }
231 }
232 bool SemanticsContext::CheckError(bool error) {
233   CHECK(!error || AnyFatalError());
234   return error;
235 }
236 
237 const Scope &SemanticsContext::FindScope(parser::CharBlock source) const {
238   return const_cast<SemanticsContext *>(this)->FindScope(source);
239 }
240 
241 Scope &SemanticsContext::FindScope(parser::CharBlock source) {
242   if (auto *scope{globalScope_.FindScope(source)}) {
243     return *scope;
244   } else {
245     common::die("SemanticsContext::FindScope(): invalid source location");
246   }
247 }
248 
249 void SemanticsContext::PopConstruct() {
250   CHECK(!constructStack_.empty());
251   constructStack_.pop_back();
252 }
253 
254 void SemanticsContext::CheckIndexVarRedefine(const parser::CharBlock &location,
255     const Symbol &variable, parser::MessageFixedText &&message) {
256   if (const Symbol * root{GetAssociationRoot(variable)}) {
257     auto it{activeIndexVars_.find(*root)};
258     if (it != activeIndexVars_.end()) {
259       std::string kind{EnumToString(it->second.kind)};
260       Say(location, std::move(message), kind, root->name())
261           .Attach(it->second.location, "Enclosing %s construct"_en_US, kind);
262     }
263   }
264 }
265 
266 void SemanticsContext::WarnIndexVarRedefine(
267     const parser::CharBlock &location, const Symbol &variable) {
268   CheckIndexVarRedefine(
269       location, variable, "Possible redefinition of %s variable '%s'"_en_US);
270 }
271 
272 void SemanticsContext::CheckIndexVarRedefine(
273     const parser::CharBlock &location, const Symbol &variable) {
274   CheckIndexVarRedefine(
275       location, variable, "Cannot redefine %s variable '%s'"_err_en_US);
276 }
277 
278 void SemanticsContext::CheckIndexVarRedefine(const parser::Variable &variable) {
279   if (const Symbol * entity{GetLastName(variable).symbol}) {
280     CheckIndexVarRedefine(variable.GetSource(), *entity);
281   }
282 }
283 
284 void SemanticsContext::CheckIndexVarRedefine(const parser::Name &name) {
285   if (const Symbol * entity{name.symbol}) {
286     CheckIndexVarRedefine(name.source, *entity);
287   }
288 }
289 
290 void SemanticsContext::ActivateIndexVar(
291     const parser::Name &name, IndexVarKind kind) {
292   CheckIndexVarRedefine(name);
293   if (const Symbol * indexVar{name.symbol}) {
294     if (const Symbol * root{GetAssociationRoot(*indexVar)}) {
295       activeIndexVars_.emplace(*root, IndexVarInfo{name.source, kind});
296     }
297   }
298 }
299 
300 void SemanticsContext::DeactivateIndexVar(const parser::Name &name) {
301   if (Symbol * indexVar{name.symbol}) {
302     if (const Symbol * root{GetAssociationRoot(*indexVar)}) {
303       auto it{activeIndexVars_.find(*root)};
304       if (it != activeIndexVars_.end() && it->second.location == name.source) {
305         activeIndexVars_.erase(it);
306       }
307     }
308   }
309 }
310 
311 SymbolVector SemanticsContext::GetIndexVars(IndexVarKind kind) {
312   SymbolVector result;
313   for (const auto &[symbol, info] : activeIndexVars_) {
314     if (info.kind == kind) {
315       result.push_back(symbol);
316     }
317   }
318   return result;
319 }
320 
321 bool Semantics::Perform() {
322   return ValidateLabels(context_, program_) &&
323       parser::CanonicalizeDo(program_) && // force line break
324       CanonicalizeOmp(context_.messages(), program_) &&
325       PerformStatementSemantics(context_, program_) &&
326       ModFileWriter{context_}.WriteAll();
327 }
328 
329 void Semantics::EmitMessages(llvm::raw_ostream &os) const {
330   context_.messages().Emit(os, cooked_);
331 }
332 
333 void Semantics::DumpSymbols(llvm::raw_ostream &os) {
334   DoDumpSymbols(os, context_.globalScope());
335 }
336 
337 void Semantics::DumpSymbolsSources(llvm::raw_ostream &os) const {
338   NameToSymbolMap symbols;
339   GetSymbolNames(context_.globalScope(), symbols);
340   for (const auto &pair : symbols) {
341     const Symbol &symbol{pair.second};
342     if (auto sourceInfo{cooked_.GetSourcePositionRange(symbol.name())}) {
343       os << symbol.name().ToString() << ": " << sourceInfo->first.file.path()
344          << ", " << sourceInfo->first.line << ", " << sourceInfo->first.column
345          << "-" << sourceInfo->second.column << "\n";
346     } else if (symbol.has<semantics::UseDetails>()) {
347       os << symbol.name().ToString() << ": "
348          << symbol.GetUltimate().owner().symbol()->name().ToString() << "\n";
349     }
350   }
351 }
352 
353 void DoDumpSymbols(llvm::raw_ostream &os, const Scope &scope, int indent) {
354   PutIndent(os, indent);
355   os << Scope::EnumToString(scope.kind()) << " scope:";
356   if (const auto *symbol{scope.symbol()}) {
357     os << ' ' << symbol->name();
358   }
359   if (scope.size()) {
360     os << " size=" << scope.size() << " alignment=" << scope.alignment();
361   }
362   if (scope.derivedTypeSpec()) {
363     os << " instantiation of " << *scope.derivedTypeSpec();
364   }
365   os << '\n';
366   ++indent;
367   for (const auto &pair : scope) {
368     const auto &symbol{*pair.second};
369     PutIndent(os, indent);
370     os << symbol << '\n';
371     if (const auto *details{symbol.detailsIf<GenericDetails>()}) {
372       if (const auto &type{details->derivedType()}) {
373         PutIndent(os, indent);
374         os << *type << '\n';
375       }
376     }
377   }
378   if (!scope.equivalenceSets().empty()) {
379     PutIndent(os, indent);
380     os << "Equivalence Sets:";
381     for (const auto &set : scope.equivalenceSets()) {
382       os << ' ';
383       char sep = '(';
384       for (const auto &object : set) {
385         os << sep << object.AsFortran();
386         sep = ',';
387       }
388       os << ')';
389     }
390     os << '\n';
391   }
392   if (!scope.crayPointers().empty()) {
393     PutIndent(os, indent);
394     os << "Cray Pointers:";
395     for (const auto &[pointee, pointer] : scope.crayPointers()) {
396       os << " (" << pointer->name() << ',' << pointee << ')';
397     }
398   }
399   for (const auto &pair : scope.commonBlocks()) {
400     const auto &symbol{*pair.second};
401     PutIndent(os, indent);
402     os << symbol << '\n';
403   }
404   for (const auto &child : scope.children()) {
405     DoDumpSymbols(os, child, indent);
406   }
407   --indent;
408 }
409 
410 static void PutIndent(llvm::raw_ostream &os, int indent) {
411   for (int i = 0; i < indent; ++i) {
412     os << "  ";
413   }
414 }
415 } // namespace Fortran::semantics
416