blob: 406396b2f776f5054f4f9b23d96b4702d89d84c7 [file] [log] [blame]
CarolineConcatto64ab3302020-02-25 15:11:521//===-- 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"
peter klausler7a77c202020-03-26 19:25:2915#include "check-case.h"
CarolineConcatto64ab3302020-02-25 15:11:5216#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"
Varun Jayathirtha92c1f6b2020-02-26 02:01:2323#include "check-namelist.h"
CarolineConcatto64ab3302020-02-25 15:11:5224#include "check-nullify.h"
25#include "check-omp-structure.h"
26#include "check-purity.h"
27#include "check-return.h"
28#include "check-stop.h"
29#include "mod-file.h"
30#include "resolve-labels.h"
31#include "resolve-names.h"
32#include "rewrite-parse-tree.h"
33#include "flang/Common/default-kinds.h"
34#include "flang/Parser/parse-tree-visitor.h"
35#include "flang/Parser/tools.h"
36#include "flang/Semantics/expression.h"
37#include "flang/Semantics/scope.h"
38#include "flang/Semantics/symbol.h"
Caroline Concatto8670e492020-02-28 15:11:0339#include "llvm/Support/raw_ostream.h"
CarolineConcatto64ab3302020-02-25 15:11:5240
41namespace Fortran::semantics {
42
43using NameToSymbolMap = std::map<const char *, SymbolRef>;
Caroline Concatto8670e492020-02-28 15:11:0344static void DoDumpSymbols(llvm::raw_ostream &, const Scope &, int indent = 0);
45static void PutIndent(llvm::raw_ostream &, int indent);
CarolineConcatto64ab3302020-02-25 15:11:5246
47static void GetSymbolNames(const Scope &scope, NameToSymbolMap &symbols) {
48 // Finds all symbol names in the scope without collecting duplicates.
49 for (const auto &pair : scope) {
50 symbols.emplace(pair.second->name().begin(), *pair.second);
51 }
52 for (const auto &pair : scope.commonBlocks()) {
53 symbols.emplace(pair.second->name().begin(), *pair.second);
54 }
55 for (const auto &child : scope.children()) {
56 GetSymbolNames(child, symbols);
57 }
58}
59
60// A parse tree visitor that calls Enter/Leave functions from each checker
61// class C supplied as template parameters. Enter is called before the node's
62// children are visited, Leave is called after. No two checkers may have the
63// same Enter or Leave function. Each checker must be constructible from
64// SemanticsContext and have BaseChecker as a virtual base class.
peter klausler7a77c202020-03-26 19:25:2965template <typename... C> class SemanticsVisitor : public virtual C... {
CarolineConcatto64ab3302020-02-25 15:11:5266public:
67 using C::Enter...;
68 using C::Leave...;
69 using BaseChecker::Enter;
70 using BaseChecker::Leave;
71 SemanticsVisitor(SemanticsContext &context)
peter klausler7a77c202020-03-26 19:25:2972 : C{context}..., context_{context} {}
CarolineConcatto64ab3302020-02-25 15:11:5273
peter klausler7a77c202020-03-26 19:25:2974 template <typename N> bool Pre(const N &node) {
CarolineConcatto64ab3302020-02-25 15:11:5275 if constexpr (common::HasMember<const N *, ConstructNode>) {
76 context_.PushConstruct(node);
77 }
78 Enter(node);
79 return true;
80 }
peter klausler7a77c202020-03-26 19:25:2981 template <typename N> void Post(const N &node) {
CarolineConcatto64ab3302020-02-25 15:11:5282 Leave(node);
83 if constexpr (common::HasMember<const N *, ConstructNode>) {
84 context_.PopConstruct();
85 }
86 }
87
peter klausler7a77c202020-03-26 19:25:2988 template <typename T> bool Pre(const parser::Statement<T> &node) {
CarolineConcatto64ab3302020-02-25 15:11:5289 context_.set_location(node.source);
90 Enter(node);
91 return true;
92 }
peter klausler7a77c202020-03-26 19:25:2993 template <typename T> bool Pre(const parser::UnlabeledStatement<T> &node) {
CarolineConcatto64ab3302020-02-25 15:11:5294 context_.set_location(node.source);
95 Enter(node);
96 return true;
97 }
peter klausler7a77c202020-03-26 19:25:2998 template <typename T> void Post(const parser::Statement<T> &node) {
CarolineConcatto64ab3302020-02-25 15:11:5299 Leave(node);
100 context_.set_location(std::nullopt);
101 }
peter klausler7a77c202020-03-26 19:25:29102 template <typename T> void Post(const parser::UnlabeledStatement<T> &node) {
CarolineConcatto64ab3302020-02-25 15:11:52103 Leave(node);
104 context_.set_location(std::nullopt);
105 }
106
107 bool Walk(const parser::Program &program) {
108 parser::Walk(program, *this);
109 return !context_.AnyFatalError();
110 }
111
112private:
113 SemanticsContext &context_;
114};
115
peter klauslerc42f6312020-03-19 23:31:10116class EntryChecker : public virtual BaseChecker {
117public:
118 explicit EntryChecker(SemanticsContext &context) : context_{context} {}
119 void Leave(const parser::EntryStmt &) {
peter klausler7a77c202020-03-26 19:25:29120 if (!context_.constructStack().empty()) { // C1571
peter klauslerc42f6312020-03-19 23:31:10121 context_.Say("ENTRY may not appear in an executable construct"_err_en_US);
122 }
123 }
124
125private:
126 SemanticsContext &context_;
127};
128
CarolineConcatto64ab3302020-02-25 15:11:52129using StatementSemanticsPass1 = ExprChecker;
Varun Jayathirtha92c1f6b2020-02-26 02:01:23130using StatementSemanticsPass2 = SemanticsVisitor<AllocateChecker,
peter klausler7a77c202020-03-26 19:25:29131 ArithmeticIfStmtChecker, AssignmentChecker, CaseChecker, CoarrayChecker,
132 DataChecker, DeallocateChecker, DoForallChecker, EntryChecker,
133 IfStmtChecker, IoChecker, NamelistChecker, NullifyChecker,
134 OmpStructureChecker, PurityChecker, ReturnStmtChecker, StopChecker>;
CarolineConcatto64ab3302020-02-25 15:11:52135
136static bool PerformStatementSemantics(
137 SemanticsContext &context, parser::Program &program) {
138 ResolveNames(context, program);
139 RewriteParseTree(context, program);
140 CheckDeclarations(context);
141 StatementSemanticsPass1{context}.Walk(program);
142 StatementSemanticsPass2{context}.Walk(program);
143 return !context.AnyFatalError();
144}
145
146SemanticsContext::SemanticsContext(
147 const common::IntrinsicTypeDefaultKinds &defaultKinds,
148 const common::LanguageFeatureControl &languageFeatures,
149 parser::AllSources &allSources)
peter klausler7a77c202020-03-26 19:25:29150 : defaultKinds_{defaultKinds}, languageFeatures_{languageFeatures},
151 allSources_{allSources},
152 intrinsics_{evaluate::IntrinsicProcTable::Configure(defaultKinds_)},
153 foldingContext_{
154 parser::ContextualMessages{&messages_}, defaultKinds_, intrinsics_} {}
CarolineConcatto64ab3302020-02-25 15:11:52155
156SemanticsContext::~SemanticsContext() {}
157
158int SemanticsContext::GetDefaultKind(TypeCategory category) const {
159 return defaultKinds_.GetDefaultKind(category);
160}
161
162bool SemanticsContext::IsEnabled(common::LanguageFeature feature) const {
163 return languageFeatures_.IsEnabled(feature);
164}
165
166bool SemanticsContext::ShouldWarn(common::LanguageFeature feature) const {
167 return languageFeatures_.ShouldWarn(feature);
168}
169
170const DeclTypeSpec &SemanticsContext::MakeNumericType(
171 TypeCategory category, int kind) {
172 if (kind == 0) {
173 kind = GetDefaultKind(category);
174 }
175 return globalScope_.MakeNumericType(category, KindExpr{kind});
176}
177const DeclTypeSpec &SemanticsContext::MakeLogicalType(int kind) {
178 if (kind == 0) {
179 kind = GetDefaultKind(TypeCategory::Logical);
180 }
181 return globalScope_.MakeLogicalType(KindExpr{kind});
182}
183
184bool SemanticsContext::AnyFatalError() const {
185 return !messages_.empty() &&
186 (warningsAreErrors_ || messages_.AnyFatalError());
187}
188bool SemanticsContext::HasError(const Symbol &symbol) {
189 return CheckError(symbol.test(Symbol::Flag::Error));
190}
191bool SemanticsContext::HasError(const Symbol *symbol) {
192 return CheckError(!symbol || HasError(*symbol));
193}
194bool SemanticsContext::HasError(const parser::Name &name) {
195 return HasError(name.symbol);
196}
197void SemanticsContext::SetError(Symbol &symbol, bool value) {
198 if (value) {
199 CHECK(AnyFatalError());
200 symbol.set(Symbol::Flag::Error);
201 }
202}
203bool SemanticsContext::CheckError(bool error) {
204 CHECK(!error || AnyFatalError());
205 return error;
206}
207
208const Scope &SemanticsContext::FindScope(parser::CharBlock source) const {
209 return const_cast<SemanticsContext *>(this)->FindScope(source);
210}
211
212Scope &SemanticsContext::FindScope(parser::CharBlock source) {
213 if (auto *scope{globalScope_.FindScope(source)}) {
214 return *scope;
215 } else {
216 common::die("SemanticsContext::FindScope(): invalid source location");
217 }
218}
219
220void SemanticsContext::PopConstruct() {
221 CHECK(!constructStack_.empty());
222 constructStack_.pop_back();
223}
224
225void SemanticsContext::CheckIndexVarRedefine(const parser::CharBlock &location,
226 const Symbol &variable, parser::MessageFixedText &&message) {
227 if (const Symbol * root{GetAssociationRoot(variable)}) {
228 auto it{activeIndexVars_.find(*root)};
229 if (it != activeIndexVars_.end()) {
230 std::string kind{EnumToString(it->second.kind)};
231 Say(location, std::move(message), kind, root->name())
232 .Attach(it->second.location, "Enclosing %s construct"_en_US, kind);
233 }
234 }
235}
236
237void SemanticsContext::WarnIndexVarRedefine(
238 const parser::CharBlock &location, const Symbol &variable) {
239 CheckIndexVarRedefine(
240 location, variable, "Possible redefinition of %s variable '%s'"_en_US);
241}
242
243void SemanticsContext::CheckIndexVarRedefine(
244 const parser::CharBlock &location, const Symbol &variable) {
245 CheckIndexVarRedefine(
246 location, variable, "Cannot redefine %s variable '%s'"_err_en_US);
247}
248
249void SemanticsContext::CheckIndexVarRedefine(const parser::Variable &variable) {
250 if (const Symbol * entity{GetLastName(variable).symbol}) {
251 CheckIndexVarRedefine(variable.GetSource(), *entity);
252 }
253}
254
255void SemanticsContext::CheckIndexVarRedefine(const parser::Name &name) {
256 if (const Symbol * entity{name.symbol}) {
257 CheckIndexVarRedefine(name.source, *entity);
258 }
259}
260
261void SemanticsContext::ActivateIndexVar(
262 const parser::Name &name, IndexVarKind kind) {
263 CheckIndexVarRedefine(name);
264 if (const Symbol * indexVar{name.symbol}) {
265 if (const Symbol * root{GetAssociationRoot(*indexVar)}) {
266 activeIndexVars_.emplace(*root, IndexVarInfo{name.source, kind});
267 }
268 }
269}
270
271void SemanticsContext::DeactivateIndexVar(const parser::Name &name) {
272 if (Symbol * indexVar{name.symbol}) {
273 if (const Symbol * root{GetAssociationRoot(*indexVar)}) {
274 auto it{activeIndexVars_.find(*root)};
275 if (it != activeIndexVars_.end() && it->second.location == name.source) {
276 activeIndexVars_.erase(it);
277 }
278 }
279 }
280}
281
282SymbolVector SemanticsContext::GetIndexVars(IndexVarKind kind) {
283 SymbolVector result;
284 for (const auto &[symbol, info] : activeIndexVars_) {
285 if (info.kind == kind) {
286 result.push_back(symbol);
287 }
288 }
289 return result;
290}
291
292bool Semantics::Perform() {
293 return ValidateLabels(context_, program_) &&
peter klausler7a77c202020-03-26 19:25:29294 parser::CanonicalizeDo(program_) && // force line break
CarolineConcatto64ab3302020-02-25 15:11:52295 CanonicalizeOmp(context_.messages(), program_) &&
296 PerformStatementSemantics(context_, program_) &&
297 ModFileWriter{context_}.WriteAll();
298}
299
Caroline Concatto8670e492020-02-28 15:11:03300void Semantics::EmitMessages(llvm::raw_ostream &os) const {
CarolineConcatto64ab3302020-02-25 15:11:52301 context_.messages().Emit(os, cooked_);
302}
303
Caroline Concatto8670e492020-02-28 15:11:03304void Semantics::DumpSymbols(llvm::raw_ostream &os) {
CarolineConcatto64ab3302020-02-25 15:11:52305 DoDumpSymbols(os, context_.globalScope());
306}
307
Caroline Concatto8670e492020-02-28 15:11:03308void Semantics::DumpSymbolsSources(llvm::raw_ostream &os) const {
CarolineConcatto64ab3302020-02-25 15:11:52309 NameToSymbolMap symbols;
310 GetSymbolNames(context_.globalScope(), symbols);
311 for (const auto &pair : symbols) {
312 const Symbol &symbol{pair.second};
313 if (auto sourceInfo{cooked_.GetSourcePositionRange(symbol.name())}) {
314 os << symbol.name().ToString() << ": " << sourceInfo->first.file.path()
315 << ", " << sourceInfo->first.line << ", " << sourceInfo->first.column
316 << "-" << sourceInfo->second.column << "\n";
317 } else if (symbol.has<semantics::UseDetails>()) {
318 os << symbol.name().ToString() << ": "
319 << symbol.GetUltimate().owner().symbol()->name().ToString() << "\n";
320 }
321 }
322}
323
Caroline Concatto8670e492020-02-28 15:11:03324void DoDumpSymbols(llvm::raw_ostream &os, const Scope &scope, int indent) {
CarolineConcatto64ab3302020-02-25 15:11:52325 PutIndent(os, indent);
326 os << Scope::EnumToString(scope.kind()) << " scope:";
327 if (const auto *symbol{scope.symbol()}) {
328 os << ' ' << symbol->name();
329 }
330 os << '\n';
331 ++indent;
332 for (const auto &pair : scope) {
333 const auto &symbol{*pair.second};
334 PutIndent(os, indent);
335 os << symbol << '\n';
336 if (const auto *details{symbol.detailsIf<GenericDetails>()}) {
337 if (const auto &type{details->derivedType()}) {
338 PutIndent(os, indent);
339 os << *type << '\n';
340 }
341 }
342 }
343 if (!scope.equivalenceSets().empty()) {
344 PutIndent(os, indent);
345 os << "Equivalence Sets:";
346 for (const auto &set : scope.equivalenceSets()) {
347 os << ' ';
348 char sep = '(';
349 for (const auto &object : set) {
350 os << sep << object.AsFortran();
351 sep = ',';
352 }
353 os << ')';
354 }
355 os << '\n';
356 }
357 if (!scope.crayPointers().empty()) {
358 PutIndent(os, indent);
359 os << "Cray Pointers:";
360 for (const auto &[pointee, pointer] : scope.crayPointers()) {
361 os << " (" << pointer->name() << ',' << pointee << ')';
362 }
363 }
364 for (const auto &pair : scope.commonBlocks()) {
365 const auto &symbol{*pair.second};
366 PutIndent(os, indent);
367 os << symbol << '\n';
368 }
369 for (const auto &child : scope.children()) {
370 DoDumpSymbols(os, child, indent);
371 }
372 --indent;
373}
374
Caroline Concatto8670e492020-02-28 15:11:03375static void PutIndent(llvm::raw_ostream &os, int indent) {
CarolineConcatto64ab3302020-02-25 15:11:52376 for (int i = 0; i < indent; ++i) {
377 os << " ";
378 }
379}
peter klausler7a77c202020-03-26 19:25:29380} // namespace Fortran::semantics