1 //===-- lib/Semantics/scope.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/scope.h"
10 #include "flang/Parser/characters.h"
11 #include "flang/Semantics/symbol.h"
12 #include "flang/Semantics/type.h"
13 #include "llvm/Support/raw_ostream.h"
14 #include <algorithm>
15 #include <memory>
16 
17 namespace Fortran::semantics {
18 
19 Symbols<1024> Scope::allSymbols;
20 
21 bool EquivalenceObject::operator==(const EquivalenceObject &that) const {
22   return symbol == that.symbol && subscripts == that.subscripts &&
23       substringStart == that.substringStart;
24 }
25 
26 bool EquivalenceObject::operator<(const EquivalenceObject &that) const {
27   return &symbol < &that.symbol ||
28       (&symbol == &that.symbol &&
29           (subscripts < that.subscripts ||
30               (subscripts == that.subscripts &&
31                   substringStart < that.substringStart)));
32 }
33 
34 std::string EquivalenceObject::AsFortran() const {
35   std::string buf;
36   llvm::raw_string_ostream ss{buf};
37   ss << symbol.name().ToString();
38   if (!subscripts.empty()) {
39     char sep{'('};
40     for (auto subscript : subscripts) {
41       ss << sep << subscript;
42       sep = ',';
43     }
44     ss << ')';
45   }
46   if (substringStart) {
47     ss << '(' << *substringStart << ":)";
48   }
49   return ss.str();
50 }
51 
52 bool Scope::IsModule() const {
53   return kind_ == Kind::Module && !symbol_->get<ModuleDetails>().isSubmodule();
54 }
55 bool Scope::IsSubmodule() const {
56   return kind_ == Kind::Module && symbol_->get<ModuleDetails>().isSubmodule();
57 }
58 
59 Scope &Scope::MakeScope(Kind kind, Symbol *symbol) {
60   return children_.emplace_back(*this, kind, symbol);
61 }
62 
63 template <typename T>
64 static std::vector<common::Reference<T>> GetSortedSymbols(
65     std::map<SourceName, MutableSymbolRef> symbols) {
66   std::vector<common::Reference<T>> result;
67   result.reserve(symbols.size());
68   for (auto &pair : symbols) {
69     result.push_back(*pair.second);
70   }
71   std::sort(result.begin(), result.end());
72   return result;
73 }
74 
75 MutableSymbolVector Scope::GetSymbols() {
76   return GetSortedSymbols<Symbol>(symbols_);
77 }
78 SymbolVector Scope::GetSymbols() const {
79   return GetSortedSymbols<const Symbol>(symbols_);
80 }
81 
82 Scope::iterator Scope::find(const SourceName &name) {
83   return symbols_.find(name);
84 }
85 Scope::size_type Scope::erase(const SourceName &name) {
86   auto it{symbols_.find(name)};
87   if (it != end()) {
88     symbols_.erase(it);
89     return 1;
90   } else {
91     return 0;
92   }
93 }
94 Symbol *Scope::FindSymbol(const SourceName &name) const {
95   auto it{find(name)};
96   if (it != end()) {
97     return &*it->second;
98   } else if (CanImport(name)) {
99     return parent_.FindSymbol(name);
100   } else {
101     return nullptr;
102   }
103 }
104 
105 Symbol *Scope::FindComponent(SourceName name) const {
106   CHECK(IsDerivedType());
107   auto found{find(name)};
108   if (found != end()) {
109     return &*found->second;
110   } else if (const Scope * parent{GetDerivedTypeParent()}) {
111     return parent->FindComponent(name);
112   } else {
113     return nullptr;
114   }
115 }
116 
117 bool Scope::Contains(const Scope &that) const {
118   for (const Scope *scope{&that};; scope = &scope->parent()) {
119     if (*scope == *this) {
120       return true;
121     }
122     if (scope->IsGlobal()) {
123       return false;
124     }
125   }
126 }
127 
128 Symbol *Scope::CopySymbol(const Symbol &symbol) {
129   auto pair{try_emplace(symbol.name(), symbol.attrs())};
130   if (!pair.second) {
131     return nullptr; // already exists
132   } else {
133     Symbol &result{*pair.first->second};
134     result.flags() = symbol.flags();
135     result.set_details(common::Clone(symbol.details()));
136     return &result;
137   }
138 }
139 
140 void Scope::add_equivalenceSet(EquivalenceSet &&set) {
141   equivalenceSets_.emplace_back(std::move(set));
142 }
143 
144 void Scope::add_crayPointer(const SourceName &name, Symbol &pointer) {
145   CHECK(pointer.test(Symbol::Flag::CrayPointer));
146   crayPointers_.emplace(name, pointer);
147 }
148 
149 Symbol &Scope::MakeCommonBlock(const SourceName &name) {
150   const auto it{commonBlocks_.find(name)};
151   if (it != commonBlocks_.end()) {
152     return *it->second;
153   } else {
154     Symbol &symbol{MakeSymbol(name, Attrs{}, CommonBlockDetails{})};
155     commonBlocks_.emplace(name, symbol);
156     return symbol;
157   }
158 }
159 Symbol *Scope::FindCommonBlock(const SourceName &name) {
160   const auto it{commonBlocks_.find(name)};
161   return it != commonBlocks_.end() ? &*it->second : nullptr;
162 }
163 
164 Scope *Scope::FindSubmodule(const SourceName &name) const {
165   auto it{submodules_.find(name)};
166   if (it == submodules_.end()) {
167     return nullptr;
168   } else {
169     return &*it->second;
170   }
171 }
172 bool Scope::AddSubmodule(const SourceName &name, Scope &submodule) {
173   return submodules_.emplace(name, submodule).second;
174 }
175 
176 const DeclTypeSpec *Scope::FindType(const DeclTypeSpec &type) const {
177   auto it{std::find(declTypeSpecs_.begin(), declTypeSpecs_.end(), type)};
178   return it != declTypeSpecs_.end() ? &*it : nullptr;
179 }
180 
181 const DeclTypeSpec &Scope::MakeNumericType(
182     TypeCategory category, KindExpr &&kind) {
183   return MakeLengthlessType(NumericTypeSpec{category, std::move(kind)});
184 }
185 const DeclTypeSpec &Scope::MakeLogicalType(KindExpr &&kind) {
186   return MakeLengthlessType(LogicalTypeSpec{std::move(kind)});
187 }
188 const DeclTypeSpec &Scope::MakeTypeStarType() {
189   return MakeLengthlessType(DeclTypeSpec{DeclTypeSpec::TypeStar});
190 }
191 const DeclTypeSpec &Scope::MakeClassStarType() {
192   return MakeLengthlessType(DeclTypeSpec{DeclTypeSpec::ClassStar});
193 }
194 // Types that can't have length parameters can be reused without having to
195 // compare length expressions. They are stored in the global scope.
196 const DeclTypeSpec &Scope::MakeLengthlessType(DeclTypeSpec &&type) {
197   const auto *found{FindType(type)};
198   return found ? *found : declTypeSpecs_.emplace_back(std::move(type));
199 }
200 
201 const DeclTypeSpec &Scope::MakeCharacterType(
202     ParamValue &&length, KindExpr &&kind) {
203   return declTypeSpecs_.emplace_back(
204       CharacterTypeSpec{std::move(length), std::move(kind)});
205 }
206 
207 DeclTypeSpec &Scope::MakeDerivedType(
208     DeclTypeSpec::Category category, DerivedTypeSpec &&spec) {
209   return declTypeSpecs_.emplace_back(category, std::move(spec));
210 }
211 
212 Scope::ImportKind Scope::GetImportKind() const {
213   if (importKind_) {
214     return *importKind_;
215   }
216   if (symbol_ && !symbol_->attrs().test(Attr::MODULE)) {
217     if (auto *details{symbol_->detailsIf<SubprogramDetails>()}) {
218       if (details->isInterface()) {
219         return ImportKind::None; // default for non-mod-proc interface body
220       }
221     }
222   }
223   return ImportKind::Default;
224 }
225 
226 std::optional<parser::MessageFixedText> Scope::SetImportKind(ImportKind kind) {
227   if (!importKind_) {
228     importKind_ = kind;
229     return std::nullopt;
230   }
231   bool hasNone{kind == ImportKind::None || *importKind_ == ImportKind::None};
232   bool hasAll{kind == ImportKind::All || *importKind_ == ImportKind::All};
233   // Check C8100 and C898: constraints on multiple IMPORT statements
234   if (hasNone || hasAll) {
235     return hasNone
236         ? "IMPORT,NONE must be the only IMPORT statement in a scope"_err_en_US
237         : "IMPORT,ALL must be the only IMPORT statement in a scope"_err_en_US;
238   } else if (kind != *importKind_ &&
239       (kind != ImportKind::Only || kind != ImportKind::Only)) {
240     return "Every IMPORT must have ONLY specifier if one of them does"_err_en_US;
241   } else {
242     return std::nullopt;
243   }
244 }
245 
246 void Scope::add_importName(const SourceName &name) {
247   importNames_.insert(name);
248 }
249 
250 // true if name can be imported or host-associated from parent scope.
251 bool Scope::CanImport(const SourceName &name) const {
252   if (IsGlobal() || parent_.IsGlobal()) {
253     return false;
254   }
255   switch (GetImportKind()) {
256     SWITCH_COVERS_ALL_CASES
257   case ImportKind::None:
258     return false;
259   case ImportKind::All:
260   case ImportKind::Default:
261     return true;
262   case ImportKind::Only:
263     return importNames_.count(name) > 0;
264   }
265 }
266 
267 const Scope *Scope::FindScope(parser::CharBlock source) const {
268   return const_cast<Scope *>(this)->FindScope(source);
269 }
270 
271 Scope *Scope::FindScope(parser::CharBlock source) {
272   bool isContained{sourceRange_.Contains(source)};
273   if (!isContained && !IsGlobal() && !IsModuleFile()) {
274     return nullptr;
275   }
276   for (auto &child : children_) {
277     if (auto *scope{child.FindScope(source)}) {
278       return scope;
279     }
280   }
281   return isContained ? this : nullptr;
282 }
283 
284 void Scope::AddSourceRange(const parser::CharBlock &source) {
285   for (auto *scope = this; !scope->IsGlobal(); scope = &scope->parent()) {
286     scope->sourceRange_.ExtendToCover(source);
287   }
288 }
289 
290 llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const Scope &scope) {
291   os << Scope::EnumToString(scope.kind()) << " scope: ";
292   if (auto *symbol{scope.symbol()}) {
293     os << *symbol << ' ';
294   }
295   if (scope.derivedTypeSpec_) {
296     os << "instantiation of " << *scope.derivedTypeSpec_ << ' ';
297   }
298   os << scope.children_.size() << " children\n";
299   for (const auto &pair : scope.symbols_) {
300     const Symbol &symbol{*pair.second};
301     os << "  " << symbol << '\n';
302   }
303   if (!scope.equivalenceSets_.empty()) {
304     os << "  Equivalence Sets:\n";
305     for (const auto &set : scope.equivalenceSets_) {
306       os << "   ";
307       for (const auto &object : set) {
308         os << ' ' << object.AsFortran();
309       }
310       os << '\n';
311     }
312   }
313   for (const auto &pair : scope.commonBlocks_) {
314     const Symbol &symbol{*pair.second};
315     os << "  " << symbol << '\n';
316   }
317   return os;
318 }
319 
320 bool Scope::IsStmtFunction() const {
321   return symbol_ && symbol_->test(Symbol::Flag::StmtFunction);
322 }
323 
324 bool Scope::IsParameterizedDerivedType() const {
325   if (!IsDerivedType()) {
326     return false;
327   }
328   if (const Scope * parent{GetDerivedTypeParent()}) {
329     if (parent->IsParameterizedDerivedType()) {
330       return true;
331     }
332   }
333   for (const auto &pair : symbols_) {
334     if (pair.second->has<TypeParamDetails>()) {
335       return true;
336     }
337   }
338   return false;
339 }
340 
341 const DeclTypeSpec *Scope::FindInstantiatedDerivedType(
342     const DerivedTypeSpec &spec, DeclTypeSpec::Category category) const {
343   DeclTypeSpec type{category, spec};
344   if (const auto *result{FindType(type)}) {
345     return result;
346   } else if (IsGlobal()) {
347     return nullptr;
348   } else {
349     return parent().FindInstantiatedDerivedType(spec, category);
350   }
351 }
352 
353 const Scope *Scope::GetDerivedTypeParent() const {
354   if (const Symbol * symbol{GetSymbol()}) {
355     if (const DerivedTypeSpec * parent{symbol->GetParentTypeSpec(this)}) {
356       return parent->scope();
357     }
358   }
359   return nullptr;
360 }
361 
362 const Scope &Scope::GetDerivedTypeBase() const {
363   const Scope *child{this};
364   for (const Scope *parent{GetDerivedTypeParent()}; parent != nullptr;
365        parent = child->GetDerivedTypeParent()) {
366     child = parent;
367   }
368   return *child;
369 }
370 
371 void Scope::InstantiateDerivedTypes(SemanticsContext &context) {
372   for (DeclTypeSpec &type : declTypeSpecs_) {
373     if (type.category() == DeclTypeSpec::TypeDerived ||
374         type.category() == DeclTypeSpec::ClassDerived) {
375       type.derivedTypeSpec().Instantiate(*this, context);
376     }
377   }
378 }
379 } // namespace Fortran::semantics
380