1 //===-- include/flang/Semantics/scope.h -------------------------*- C++ -*-===//
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 #ifndef FORTRAN_SEMANTICS_SCOPE_H_
10 #define FORTRAN_SEMANTICS_SCOPE_H_
11 
12 #include "attr.h"
13 #include "symbol.h"
14 #include "flang/Common/Fortran.h"
15 #include "flang/Common/idioms.h"
16 #include "flang/Common/reference.h"
17 #include "flang/Parser/message.h"
18 #include "flang/Parser/provenance.h"
19 #include <list>
20 #include <map>
21 #include <optional>
22 #include <set>
23 #include <string>
24 
25 namespace llvm {
26 class raw_ostream;
27 }
28 
29 namespace Fortran::semantics {
30 
31 using namespace parser::literals;
32 
33 using common::ConstantSubscript;
34 
35 class SemanticsContext;
36 
37 // An equivalence object is represented by a symbol for the variable name,
38 // the indices for an array element, and the lower bound for a substring.
39 struct EquivalenceObject {
EquivalenceObjectEquivalenceObject40   EquivalenceObject(Symbol &symbol, std::vector<ConstantSubscript> subscripts,
41       std::optional<ConstantSubscript> substringStart, parser::CharBlock source)
42       : symbol{symbol}, subscripts{subscripts},
43         substringStart{substringStart}, source{source} {}
EquivalenceObjectEquivalenceObject44   explicit EquivalenceObject(Symbol &symbol)
45       : symbol{symbol}, source{symbol.name()} {}
46 
47   bool operator==(const EquivalenceObject &) const;
48   bool operator<(const EquivalenceObject &) const;
49   std::string AsFortran() const;
50 
51   Symbol &symbol;
52   std::vector<ConstantSubscript> subscripts; // for array elem
53   std::optional<ConstantSubscript> substringStart;
54   parser::CharBlock source;
55 };
56 using EquivalenceSet = std::vector<EquivalenceObject>;
57 
58 class Scope {
59   using mapType = std::map<SourceName, MutableSymbolRef>;
60 
61 public:
62   ENUM_CLASS(Kind, Global, IntrinsicModules, Module, MainProgram, Subprogram,
63       BlockData, DerivedType, BlockConstruct, Forall, OtherConstruct,
64       ImpliedDos)
65   using ImportKind = common::ImportKind;
66 
67   // Create the Global scope -- the root of the scope tree
Scope(SemanticsContext & context)68   explicit Scope(SemanticsContext &context)
69       : Scope{*this, Kind::Global, nullptr, context} {}
Scope(Scope & parent,Kind kind,Symbol * symbol,SemanticsContext & context)70   Scope(Scope &parent, Kind kind, Symbol *symbol, SemanticsContext &context)
71       : parent_{parent}, kind_{kind}, symbol_{symbol}, context_{context} {
72     if (symbol) {
73       symbol->set_scope(this);
74     }
75   }
76   Scope(const Scope &) = delete;
77 
78   bool operator==(const Scope &that) const { return this == &that; }
79   bool operator!=(const Scope &that) const { return this != &that; }
80 
parent()81   Scope &parent() {
82     CHECK(&parent_ != this);
83     return parent_;
84   }
parent()85   const Scope &parent() const {
86     CHECK(&parent_ != this);
87     return parent_;
88   }
kind()89   Kind kind() const { return kind_; }
IsGlobal()90   bool IsGlobal() const { return kind_ == Kind::Global; }
IsIntrinsicModules()91   bool IsIntrinsicModules() const { return kind_ == Kind::IntrinsicModules; }
IsTopLevel()92   bool IsTopLevel() const {
93     return kind_ == Kind::Global || kind_ == Kind::IntrinsicModules;
94   }
IsModule()95   bool IsModule() const {
96     return kind_ == Kind::Module &&
97         !symbol_->get<ModuleDetails>().isSubmodule();
98   }
IsSubmodule()99   bool IsSubmodule() const {
100     return kind_ == Kind::Module && symbol_->get<ModuleDetails>().isSubmodule();
101   }
IsDerivedType()102   bool IsDerivedType() const { return kind_ == Kind::DerivedType; }
103   bool IsStmtFunction() const;
104   bool IsParameterizedDerivedType() const;
IsParameterizedDerivedTypeInstantiation()105   bool IsParameterizedDerivedTypeInstantiation() const {
106     return kind_ == Kind::DerivedType && !symbol_;
107   }
108   /// Does this derived type have at least one kind parameter ?
109   bool IsDerivedTypeWithKindParameter() const;
110   /// Does this derived type have at least one length parameter ?
111   bool IsDerivedTypeWithLengthParameter() const;
symbol()112   Symbol *symbol() { return symbol_; }
symbol()113   const Symbol *symbol() const { return symbol_; }
context()114   SemanticsContext &context() const { return context_; }
115 
116   inline const Symbol *GetSymbol() const;
117   const Scope *GetDerivedTypeParent() const;
118   const Scope &GetDerivedTypeBase() const;
119   inline std::optional<SourceName> GetName() const;
120   bool Contains(const Scope &) const;
121   /// Make a scope nested in this one
122   Scope &MakeScope(Kind kind, Symbol *symbol = nullptr);
GetMutableSemanticsContext()123   SemanticsContext &GetMutableSemanticsContext() const {
124     return const_cast<SemanticsContext &>(context());
125   }
126 
127   using size_type = mapType::size_type;
128   using iterator = mapType::iterator;
129   using const_iterator = mapType::const_iterator;
130 
begin()131   iterator begin() { return symbols_.begin(); }
end()132   iterator end() { return symbols_.end(); }
begin()133   const_iterator begin() const { return symbols_.begin(); }
end()134   const_iterator end() const { return symbols_.end(); }
cbegin()135   const_iterator cbegin() const { return symbols_.cbegin(); }
cend()136   const_iterator cend() const { return symbols_.cend(); }
137 
138   // Return symbols in declaration order (the iterators above are in name order)
139   SymbolVector GetSymbols() const;
140   MutableSymbolVector GetSymbols();
141 
142   iterator find(const SourceName &name);
find(const SourceName & name)143   const_iterator find(const SourceName &name) const {
144     return symbols_.find(name);
145   }
146   size_type erase(const SourceName &);
empty()147   bool empty() const { return symbols_.empty(); }
148 
149   // Look for symbol by name in this scope and host (depending on imports).
150   Symbol *FindSymbol(const SourceName &) const;
151 
152   // Look for component symbol by name in a derived type's scope and
153   // parents'.
154   Symbol *FindComponent(SourceName) const;
155 
156   /// Make a Symbol with unknown details.
157   std::pair<iterator, bool> try_emplace(
158       const SourceName &name, Attrs attrs = Attrs()) {
159     return try_emplace(name, attrs, UnknownDetails());
160   }
161   /// Make a Symbol with provided details.
162   template <typename D>
try_emplace(const SourceName & name,D && details)163   common::IfNoLvalue<std::pair<iterator, bool>, D> try_emplace(
164       const SourceName &name, D &&details) {
165     return try_emplace(name, Attrs(), std::move(details));
166   }
167   /// Make a Symbol with attrs and details
168   template <typename D>
try_emplace(const SourceName & name,Attrs attrs,D && details)169   common::IfNoLvalue<std::pair<iterator, bool>, D> try_emplace(
170       const SourceName &name, Attrs attrs, D &&details) {
171     Symbol &symbol{MakeSymbol(name, attrs, std::move(details))};
172     return symbols_.emplace(name, symbol);
173   }
174   // Make a copy of a symbol in this scope; nullptr if one is already there
175   Symbol *CopySymbol(const Symbol &);
176 
equivalenceSets()177   std::list<EquivalenceSet> &equivalenceSets() { return equivalenceSets_; }
equivalenceSets()178   const std::list<EquivalenceSet> &equivalenceSets() const {
179     return equivalenceSets_;
180   }
181   void add_equivalenceSet(EquivalenceSet &&);
182   // Cray pointers are saved as map of pointee name -> pointer symbol
crayPointers()183   const mapType &crayPointers() const { return crayPointers_; }
184   void add_crayPointer(const SourceName &, Symbol &);
commonBlocks()185   mapType &commonBlocks() { return commonBlocks_; }
commonBlocks()186   const mapType &commonBlocks() const { return commonBlocks_; }
187   Symbol &MakeCommonBlock(const SourceName &);
188   Symbol *FindCommonBlock(const SourceName &) const;
189 
190   /// Make a Symbol but don't add it to the scope.
191   template <typename D>
MakeSymbol(const SourceName & name,Attrs attrs,D && details)192   common::IfNoLvalue<Symbol &, D> MakeSymbol(
193       const SourceName &name, Attrs attrs, D &&details) {
194     return allSymbols.Make(*this, name, attrs, std::move(details));
195   }
196 
children()197   std::list<Scope> &children() { return children_; }
children()198   const std::list<Scope> &children() const { return children_; }
199 
200   // For Module scope, maintain a mapping of all submodule scopes with this
201   // module as its ancestor module. AddSubmodule returns false if already there.
202   Scope *FindSubmodule(const SourceName &) const;
203   bool AddSubmodule(const SourceName &, Scope &);
204 
205   const DeclTypeSpec *FindType(const DeclTypeSpec &) const;
206   const DeclTypeSpec &MakeNumericType(TypeCategory, KindExpr &&kind);
207   const DeclTypeSpec &MakeLogicalType(KindExpr &&kind);
208   const DeclTypeSpec &MakeCharacterType(
209       ParamValue &&length, KindExpr &&kind = KindExpr{0});
210   DeclTypeSpec &MakeDerivedType(DeclTypeSpec::Category, DerivedTypeSpec &&);
211   const DeclTypeSpec &MakeTypeStarType();
212   const DeclTypeSpec &MakeClassStarType();
213   const DeclTypeSpec *GetType(const SomeExpr &);
214 
size()215   std::size_t size() const { return size_; }
set_size(std::size_t size)216   void set_size(std::size_t size) { size_ = size; }
alignment()217   std::optional<std::size_t> alignment() const { return alignment_; }
218 
SetAlignment(std::size_t n)219   void SetAlignment(std::size_t n) {
220     alignment_ = std::max(alignment_.value_or(0), n);
221   }
222 
223   ImportKind GetImportKind() const;
224   // Names appearing in IMPORT statements in this scope
importNames()225   std::set<SourceName> importNames() const { return importNames_; }
226 
227   // Set the kind of imports from host into this scope.
228   // Return an error message for incompatible kinds.
229   std::optional<parser::MessageFixedText> SetImportKind(ImportKind);
230 
231   void add_importName(const SourceName &);
232 
233   // These members pertain to instantiations of parameterized derived types.
derivedTypeSpec()234   const DerivedTypeSpec *derivedTypeSpec() const { return derivedTypeSpec_; }
derivedTypeSpec()235   DerivedTypeSpec *derivedTypeSpec() { return derivedTypeSpec_; }
set_derivedTypeSpec(DerivedTypeSpec & spec)236   void set_derivedTypeSpec(DerivedTypeSpec &spec) { derivedTypeSpec_ = &spec; }
instantiationContext()237   parser::Message::Reference instantiationContext() const {
238     return instantiationContext_;
239   };
set_instantiationContext(parser::Message::Reference && mref)240   void set_instantiationContext(parser::Message::Reference &&mref) {
241     instantiationContext_ = std::move(mref);
242   }
243 
hasSAVE()244   bool hasSAVE() const { return hasSAVE_; }
245   void set_hasSAVE(bool yes = true) { hasSAVE_ = yes; }
246 
247   // The range of the source of this and nested scopes.
sourceRange()248   const parser::CharBlock &sourceRange() const { return sourceRange_; }
249   void AddSourceRange(const parser::CharBlock &);
250   // Find the smallest scope under this one that contains source
251   const Scope *FindScope(parser::CharBlock) const;
252   Scope *FindScope(parser::CharBlock);
253 
254   // Attempts to find a match for a derived type instance
255   const DeclTypeSpec *FindInstantiatedDerivedType(const DerivedTypeSpec &,
256       DeclTypeSpec::Category = DeclTypeSpec::TypeDerived) const;
257 
IsModuleFile()258   bool IsModuleFile() const {
259     return kind_ == Kind::Module && symbol_ &&
260         symbol_->test(Symbol::Flag::ModFile);
261   }
262 
263   void InstantiateDerivedTypes();
264 
runtimeDerivedTypeDescription()265   const Symbol *runtimeDerivedTypeDescription() const {
266     return runtimeDerivedTypeDescription_;
267   }
set_runtimeDerivedTypeDescription(const Symbol & symbol)268   void set_runtimeDerivedTypeDescription(const Symbol &symbol) {
269     runtimeDerivedTypeDescription_ = &symbol;
270   }
271 
272 private:
273   Scope &parent_; // this is enclosing scope, not extended derived type base
274   const Kind kind_;
275   std::size_t size_{0}; // size in bytes
276   std::optional<std::size_t> alignment_; // required alignment in bytes
277   parser::CharBlock sourceRange_;
278   Symbol *const symbol_; // if not null, symbol_->scope() == this
279   std::list<Scope> children_;
280   mapType symbols_;
281   mapType commonBlocks_;
282   std::list<EquivalenceSet> equivalenceSets_;
283   mapType crayPointers_;
284   std::map<SourceName, common::Reference<Scope>> submodules_;
285   std::list<DeclTypeSpec> declTypeSpecs_;
286   std::optional<ImportKind> importKind_;
287   std::set<SourceName> importNames_;
288   DerivedTypeSpec *derivedTypeSpec_{nullptr}; // dTS->scope() == this
289   parser::Message::Reference instantiationContext_;
290   bool hasSAVE_{false}; // scope has a bare SAVE statement
291   const Symbol *runtimeDerivedTypeDescription_{nullptr};
292   SemanticsContext &context_;
293   // When additional data members are added to Scope, remember to
294   // copy them, if appropriate, in FindOrInstantiateDerivedType().
295 
296   // Storage for all Symbols. Every Symbol is in allSymbols and every Symbol*
297   // or Symbol& points to one in there.
298   static Symbols<1024> allSymbols;
299 
300   bool CanImport(const SourceName &) const;
301   const DeclTypeSpec &MakeLengthlessType(DeclTypeSpec &&);
302 
303   friend llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Scope &);
304 };
305 
306 // Inline so that it can be called from Evaluate without a link-time dependency.
307 
GetSymbol()308 inline const Symbol *Scope::GetSymbol() const {
309   return symbol_         ? symbol_
310       : derivedTypeSpec_ ? &derivedTypeSpec_->typeSymbol()
311                          : nullptr;
312 }
313 
GetName()314 inline std::optional<SourceName> Scope::GetName() const {
315   if (const auto *sym{GetSymbol()}) {
316     return sym->name();
317   } else {
318     return std::nullopt;
319   }
320 }
321 
322 } // namespace Fortran::semantics
323 #endif // FORTRAN_SEMANTICS_SCOPE_H_
324