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