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 std::optional<SourceName> Scope::GetName() const {
118   if (const auto *sym{GetSymbol()}) {
119     return sym->name();
120   } else {
121     return std::nullopt;
122   }
123 }
124 
125 bool Scope::Contains(const Scope &that) const {
126   for (const Scope *scope{&that};; scope = &scope->parent()) {
127     if (*scope == *this) {
128       return true;
129     }
130     if (scope->IsGlobal()) {
131       return false;
132     }
133   }
134 }
135 
136 Symbol *Scope::CopySymbol(const Symbol &symbol) {
137   auto pair{try_emplace(symbol.name(), symbol.attrs())};
138   if (!pair.second) {
139     return nullptr; // already exists
140   } else {
141     Symbol &result{*pair.first->second};
142     result.flags() = symbol.flags();
143     result.set_details(common::Clone(symbol.details()));
144     return &result;
145   }
146 }
147 
148 void Scope::add_equivalenceSet(EquivalenceSet &&set) {
149   equivalenceSets_.emplace_back(std::move(set));
150 }
151 
152 void Scope::add_crayPointer(const SourceName &name, Symbol &pointer) {
153   CHECK(pointer.test(Symbol::Flag::CrayPointer));
154   crayPointers_.emplace(name, pointer);
155 }
156 
157 Symbol &Scope::MakeCommonBlock(const SourceName &name) {
158   const auto it{commonBlocks_.find(name)};
159   if (it != commonBlocks_.end()) {
160     return *it->second;
161   } else {
162     Symbol &symbol{MakeSymbol(name, Attrs{}, CommonBlockDetails{})};
163     commonBlocks_.emplace(name, symbol);
164     return symbol;
165   }
166 }
167 Symbol *Scope::FindCommonBlock(const SourceName &name) {
168   const auto it{commonBlocks_.find(name)};
169   return it != commonBlocks_.end() ? &*it->second : nullptr;
170 }
171 
172 Scope *Scope::FindSubmodule(const SourceName &name) const {
173   auto it{submodules_.find(name)};
174   if (it == submodules_.end()) {
175     return nullptr;
176   } else {
177     return &*it->second;
178   }
179 }
180 bool Scope::AddSubmodule(const SourceName &name, Scope &submodule) {
181   return submodules_.emplace(name, submodule).second;
182 }
183 
184 const DeclTypeSpec *Scope::FindType(const DeclTypeSpec &type) const {
185   auto it{std::find(declTypeSpecs_.begin(), declTypeSpecs_.end(), type)};
186   return it != declTypeSpecs_.end() ? &*it : nullptr;
187 }
188 
189 const DeclTypeSpec &Scope::MakeNumericType(
190     TypeCategory category, KindExpr &&kind) {
191   return MakeLengthlessType(NumericTypeSpec{category, std::move(kind)});
192 }
193 const DeclTypeSpec &Scope::MakeLogicalType(KindExpr &&kind) {
194   return MakeLengthlessType(LogicalTypeSpec{std::move(kind)});
195 }
196 const DeclTypeSpec &Scope::MakeTypeStarType() {
197   return MakeLengthlessType(DeclTypeSpec{DeclTypeSpec::TypeStar});
198 }
199 const DeclTypeSpec &Scope::MakeClassStarType() {
200   return MakeLengthlessType(DeclTypeSpec{DeclTypeSpec::ClassStar});
201 }
202 // Types that can't have length parameters can be reused without having to
203 // compare length expressions. They are stored in the global scope.
204 const DeclTypeSpec &Scope::MakeLengthlessType(DeclTypeSpec &&type) {
205   const auto *found{FindType(type)};
206   return found ? *found : declTypeSpecs_.emplace_back(std::move(type));
207 }
208 
209 const DeclTypeSpec &Scope::MakeCharacterType(
210     ParamValue &&length, KindExpr &&kind) {
211   return declTypeSpecs_.emplace_back(
212       CharacterTypeSpec{std::move(length), std::move(kind)});
213 }
214 
215 DeclTypeSpec &Scope::MakeDerivedType(
216     DeclTypeSpec::Category category, DerivedTypeSpec &&spec) {
217   return declTypeSpecs_.emplace_back(category, std::move(spec));
218 }
219 
220 void Scope::set_chars(parser::CookedSource &cooked) {
221   CHECK(kind_ == Kind::Module);
222   CHECK(parent_.IsGlobal() || parent_.IsModuleFile());
223   CHECK(DEREF(symbol_).test(Symbol::Flag::ModFile));
224   // TODO: Preserve the CookedSource rather than acquiring its string.
225   chars_ = cooked.AcquireData();
226 }
227 
228 Scope::ImportKind Scope::GetImportKind() const {
229   if (importKind_) {
230     return *importKind_;
231   }
232   if (symbol_ && !symbol_->attrs().test(Attr::MODULE)) {
233     if (auto *details{symbol_->detailsIf<SubprogramDetails>()}) {
234       if (details->isInterface()) {
235         return ImportKind::None; // default for non-mod-proc interface body
236       }
237     }
238   }
239   return ImportKind::Default;
240 }
241 
242 std::optional<parser::MessageFixedText> Scope::SetImportKind(ImportKind kind) {
243   if (!importKind_) {
244     importKind_ = kind;
245     return std::nullopt;
246   }
247   bool hasNone{kind == ImportKind::None || *importKind_ == ImportKind::None};
248   bool hasAll{kind == ImportKind::All || *importKind_ == ImportKind::All};
249   // Check C8100 and C898: constraints on multiple IMPORT statements
250   if (hasNone || hasAll) {
251     return hasNone
252         ? "IMPORT,NONE must be the only IMPORT statement in a scope"_err_en_US
253         : "IMPORT,ALL must be the only IMPORT statement in a scope"_err_en_US;
254   } else if (kind != *importKind_ &&
255       (kind != ImportKind::Only || kind != ImportKind::Only)) {
256     return "Every IMPORT must have ONLY specifier if one of them does"_err_en_US;
257   } else {
258     return std::nullopt;
259   }
260 }
261 
262 void Scope::add_importName(const SourceName &name) {
263   importNames_.insert(name);
264 }
265 
266 // true if name can be imported or host-associated from parent scope.
267 bool Scope::CanImport(const SourceName &name) const {
268   if (IsGlobal() || parent_.IsGlobal()) {
269     return false;
270   }
271   switch (GetImportKind()) {
272     SWITCH_COVERS_ALL_CASES
273   case ImportKind::None:
274     return false;
275   case ImportKind::All:
276   case ImportKind::Default:
277     return true;
278   case ImportKind::Only:
279     return importNames_.count(name) > 0;
280   }
281 }
282 
283 const Scope *Scope::FindScope(parser::CharBlock source) const {
284   return const_cast<Scope *>(this)->FindScope(source);
285 }
286 
287 Scope *Scope::FindScope(parser::CharBlock source) {
288   bool isContained{sourceRange_.Contains(source)};
289   if (!isContained && !IsGlobal() && !IsModuleFile()) {
290     return nullptr;
291   }
292   for (auto &child : children_) {
293     if (auto *scope{child.FindScope(source)}) {
294       return scope;
295     }
296   }
297   return isContained ? this : nullptr;
298 }
299 
300 void Scope::AddSourceRange(const parser::CharBlock &source) {
301   for (auto *scope = this; !scope->IsGlobal(); scope = &scope->parent()) {
302     scope->sourceRange_.ExtendToCover(source);
303   }
304 }
305 
306 llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const Scope &scope) {
307   os << Scope::EnumToString(scope.kind()) << " scope: ";
308   if (auto *symbol{scope.symbol()}) {
309     os << *symbol << ' ';
310   }
311   if (scope.derivedTypeSpec_) {
312     os << "instantiation of " << *scope.derivedTypeSpec_ << ' ';
313   }
314   os << scope.children_.size() << " children\n";
315   for (const auto &pair : scope.symbols_) {
316     const Symbol &symbol{*pair.second};
317     os << "  " << symbol << '\n';
318   }
319   if (!scope.equivalenceSets_.empty()) {
320     os << "  Equivalence Sets:\n";
321     for (const auto &set : scope.equivalenceSets_) {
322       os << "   ";
323       for (const auto &object : set) {
324         os << ' ' << object.AsFortran();
325       }
326       os << '\n';
327     }
328   }
329   for (const auto &pair : scope.commonBlocks_) {
330     const Symbol &symbol{*pair.second};
331     os << "  " << symbol << '\n';
332   }
333   return os;
334 }
335 
336 bool Scope::IsParameterizedDerivedType() const {
337   if (!IsDerivedType()) {
338     return false;
339   }
340   if (const Scope * parent{GetDerivedTypeParent()}) {
341     if (parent->IsParameterizedDerivedType()) {
342       return true;
343     }
344   }
345   for (const auto &pair : symbols_) {
346     if (pair.second->has<TypeParamDetails>()) {
347       return true;
348     }
349   }
350   return false;
351 }
352 
353 const DeclTypeSpec *Scope::FindInstantiatedDerivedType(
354     const DerivedTypeSpec &spec, DeclTypeSpec::Category category) const {
355   DeclTypeSpec type{category, spec};
356   if (const auto *result{FindType(type)}) {
357     return result;
358   } else if (IsGlobal()) {
359     return nullptr;
360   } else {
361     return parent().FindInstantiatedDerivedType(spec, category);
362   }
363 }
364 
365 const Symbol *Scope::GetSymbol() const {
366   if (symbol_) {
367     return symbol_;
368   }
369   if (derivedTypeSpec_) {
370     return &derivedTypeSpec_->typeSymbol();
371   }
372   return nullptr;
373 }
374 
375 const Scope *Scope::GetDerivedTypeParent() const {
376   if (const Symbol * symbol{GetSymbol()}) {
377     if (const DerivedTypeSpec * parent{symbol->GetParentTypeSpec(this)}) {
378       return parent->scope();
379     }
380   }
381   return nullptr;
382 }
383 
384 const Scope &Scope::GetDerivedTypeBase() const {
385   const Scope *child{this};
386   for (const Scope *parent{GetDerivedTypeParent()}; parent != nullptr;
387        parent = child->GetDerivedTypeParent()) {
388     child = parent;
389   }
390   return *child;
391 }
392 
393 void Scope::InstantiateDerivedTypes(SemanticsContext &context) {
394   for (DeclTypeSpec &type : declTypeSpecs_) {
395     if (type.category() == DeclTypeSpec::TypeDerived ||
396         type.category() == DeclTypeSpec::ClassDerived) {
397       type.derivedTypeSpec().Instantiate(*this, context);
398     }
399   }
400 }
401 } // namespace Fortran::semantics
402