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