1 //===-- lib/Semantics/symbol.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/symbol.h"
10 #include "flang/Common/idioms.h"
11 #include "flang/Evaluate/expression.h"
12 #include "flang/Semantics/scope.h"
13 #include "flang/Semantics/semantics.h"
14 #include "flang/Semantics/tools.h"
15 #include "llvm/Support/raw_ostream.h"
16 #include <string>
17 
18 namespace Fortran::semantics {
19 
20 template <typename T>
21 static void DumpOptional(llvm::raw_ostream &os, const char *label, const T &x) {
22   if (x) {
23     os << ' ' << label << ':' << *x;
24   }
25 }
26 template <typename T>
27 static void DumpExpr(llvm::raw_ostream &os, const char *label,
28     const std::optional<evaluate::Expr<T>> &x) {
29   if (x) {
30     x->AsFortran(os << ' ' << label << ':');
31   }
32 }
33 
34 static void DumpBool(llvm::raw_ostream &os, const char *label, bool x) {
35   if (x) {
36     os << ' ' << label;
37   }
38 }
39 
40 static void DumpSymbolVector(llvm::raw_ostream &os, const SymbolVector &list) {
41   char sep{' '};
42   for (const Symbol &elem : list) {
43     os << sep << elem.name();
44     sep = ',';
45   }
46 }
47 
48 static void DumpType(llvm::raw_ostream &os, const Symbol &symbol) {
49   if (const auto *type{symbol.GetType()}) {
50     os << *type << ' ';
51   }
52 }
53 static void DumpType(llvm::raw_ostream &os, const DeclTypeSpec *type) {
54   if (type) {
55     os << ' ' << *type;
56   }
57 }
58 
59 template <typename T>
60 static void DumpList(llvm::raw_ostream &os, const char *label, const T &list) {
61   if (!list.empty()) {
62     os << ' ' << label << ':';
63     char sep{' '};
64     for (const auto &elem : list) {
65       os << sep << elem;
66       sep = ',';
67     }
68   }
69 }
70 
71 const Scope *ModuleDetails::parent() const {
72   return isSubmodule_ && scope_ ? &scope_->parent() : nullptr;
73 }
74 const Scope *ModuleDetails::ancestor() const {
75   return isSubmodule_ && scope_ ? FindModuleContaining(*scope_) : nullptr;
76 }
77 void ModuleDetails::set_scope(const Scope *scope) {
78   CHECK(!scope_);
79   bool scopeIsSubmodule{scope->parent().kind() == Scope::Kind::Module};
80   CHECK(isSubmodule_ == scopeIsSubmodule);
81   scope_ = scope;
82 }
83 
84 llvm::raw_ostream &operator<<(
85     llvm::raw_ostream &os, const SubprogramDetails &x) {
86   DumpBool(os, "isInterface", x.isInterface_);
87   DumpExpr(os, "bindName", x.bindName_);
88   if (x.result_) {
89     DumpType(os << " result:", x.result());
90     os << x.result_->name();
91     if (!x.result_->attrs().empty()) {
92       os << ", " << x.result_->attrs();
93     }
94   }
95   if (x.entryScope_) {
96     os << " entry";
97     if (x.entryScope_->symbol()) {
98       os << " in " << x.entryScope_->symbol()->name();
99     }
100   }
101   char sep{'('};
102   os << ' ';
103   for (const Symbol *arg : x.dummyArgs_) {
104     os << sep;
105     sep = ',';
106     if (arg) {
107       DumpType(os, *arg);
108       os << arg->name();
109     } else {
110       os << '*';
111     }
112   }
113   os << (sep == '(' ? "()" : ")");
114   return os;
115 }
116 
117 void EntityDetails::set_type(const DeclTypeSpec &type) {
118   CHECK(!type_);
119   type_ = &type;
120 }
121 
122 void AssocEntityDetails::set_rank(int rank) { rank_ = rank; }
123 void EntityDetails::ReplaceType(const DeclTypeSpec &type) { type_ = &type; }
124 
125 void ObjectEntityDetails::set_shape(const ArraySpec &shape) {
126   CHECK(shape_.empty());
127   for (const auto &shapeSpec : shape) {
128     shape_.push_back(shapeSpec);
129   }
130 }
131 void ObjectEntityDetails::set_coshape(const ArraySpec &coshape) {
132   CHECK(coshape_.empty());
133   for (const auto &shapeSpec : coshape) {
134     coshape_.push_back(shapeSpec);
135   }
136 }
137 
138 ProcEntityDetails::ProcEntityDetails(EntityDetails &&d) : EntityDetails(d) {
139   if (type()) {
140     interface_.set_type(*type());
141   }
142 }
143 
144 UseErrorDetails::UseErrorDetails(const UseDetails &useDetails) {
145   add_occurrence(useDetails.location(), *GetUsedModule(useDetails).scope());
146 }
147 UseErrorDetails &UseErrorDetails::add_occurrence(
148     const SourceName &location, const Scope &module) {
149   occurrences_.push_back(std::make_pair(location, &module));
150   return *this;
151 }
152 
153 GenericDetails::GenericDetails(const SymbolVector &specificProcs)
154     : specificProcs_{specificProcs} {}
155 
156 void GenericDetails::AddSpecificProc(
157     const Symbol &proc, SourceName bindingName) {
158   specificProcs_.push_back(proc);
159   bindingNames_.push_back(bindingName);
160 }
161 void GenericDetails::set_specific(Symbol &specific) {
162   CHECK(!specific_);
163   CHECK(!derivedType_);
164   specific_ = &specific;
165 }
166 void GenericDetails::set_derivedType(Symbol &derivedType) {
167   CHECK(!specific_);
168   CHECK(!derivedType_);
169   derivedType_ = &derivedType;
170 }
171 
172 const Symbol *GenericDetails::CheckSpecific() const {
173   return const_cast<GenericDetails *>(this)->CheckSpecific();
174 }
175 Symbol *GenericDetails::CheckSpecific() {
176   if (specific_) {
177     for (const Symbol &proc : specificProcs_) {
178       if (&proc == specific_) {
179         return nullptr;
180       }
181     }
182     return specific_;
183   } else {
184     return nullptr;
185   }
186 }
187 
188 void GenericDetails::CopyFrom(const GenericDetails &from) {
189   if (from.specific_) {
190     CHECK(!specific_ || specific_ == from.specific_);
191     specific_ = from.specific_;
192   }
193   if (from.derivedType_) {
194     CHECK(!derivedType_ || derivedType_ == from.derivedType_);
195     derivedType_ = from.derivedType_;
196   }
197   for (const Symbol &symbol : from.specificProcs_) {
198     if (std::find_if(specificProcs_.begin(), specificProcs_.end(),
199             [&](const Symbol &mySymbol) { return &mySymbol == &symbol; }) ==
200         specificProcs_.end()) {
201       specificProcs_.push_back(symbol);
202     }
203   }
204 }
205 
206 // The name of the kind of details for this symbol.
207 // This is primarily for debugging.
208 std::string DetailsToString(const Details &details) {
209   return std::visit(
210       common::visitors{
211           [](const UnknownDetails &) { return "Unknown"; },
212           [](const MainProgramDetails &) { return "MainProgram"; },
213           [](const ModuleDetails &) { return "Module"; },
214           [](const SubprogramDetails &) { return "Subprogram"; },
215           [](const SubprogramNameDetails &) { return "SubprogramName"; },
216           [](const EntityDetails &) { return "Entity"; },
217           [](const ObjectEntityDetails &) { return "ObjectEntity"; },
218           [](const ProcEntityDetails &) { return "ProcEntity"; },
219           [](const DerivedTypeDetails &) { return "DerivedType"; },
220           [](const UseDetails &) { return "Use"; },
221           [](const UseErrorDetails &) { return "UseError"; },
222           [](const HostAssocDetails &) { return "HostAssoc"; },
223           [](const GenericDetails &) { return "Generic"; },
224           [](const ProcBindingDetails &) { return "ProcBinding"; },
225           [](const NamelistDetails &) { return "Namelist"; },
226           [](const CommonBlockDetails &) { return "CommonBlockDetails"; },
227           [](const FinalProcDetails &) { return "FinalProc"; },
228           [](const TypeParamDetails &) { return "TypeParam"; },
229           [](const MiscDetails &) { return "Misc"; },
230           [](const AssocEntityDetails &) { return "AssocEntity"; },
231       },
232       details);
233 }
234 
235 const std::string Symbol::GetDetailsName() const {
236   return DetailsToString(details_);
237 }
238 
239 void Symbol::set_details(Details &&details) {
240   CHECK(CanReplaceDetails(details));
241   details_ = std::move(details);
242 }
243 
244 bool Symbol::CanReplaceDetails(const Details &details) const {
245   if (has<UnknownDetails>()) {
246     return true; // can always replace UnknownDetails
247   } else {
248     return std::visit(
249         common::visitors{
250             [](const UseErrorDetails &) { return true; },
251             [&](const ObjectEntityDetails &) { return has<EntityDetails>(); },
252             [&](const ProcEntityDetails &) { return has<EntityDetails>(); },
253             [&](const SubprogramDetails &) {
254               return has<SubprogramNameDetails>() || has<EntityDetails>();
255             },
256             [&](const DerivedTypeDetails &) {
257               auto *derived{detailsIf<DerivedTypeDetails>()};
258               return derived && derived->isForwardReferenced();
259             },
260             [](const auto &) { return false; },
261         },
262         details);
263   }
264 }
265 
266 // Usually a symbol's name is the first occurrence in the source, but sometimes
267 // we want to replace it with one at a different location (but same characters).
268 void Symbol::ReplaceName(const SourceName &name) {
269   CHECK(name == name_);
270   name_ = name;
271 }
272 
273 void Symbol::SetType(const DeclTypeSpec &type) {
274   std::visit(common::visitors{
275                  [&](EntityDetails &x) { x.set_type(type); },
276                  [&](ObjectEntityDetails &x) { x.set_type(type); },
277                  [&](AssocEntityDetails &x) { x.set_type(type); },
278                  [&](ProcEntityDetails &x) { x.interface().set_type(type); },
279                  [&](TypeParamDetails &x) { x.set_type(type); },
280                  [](auto &) {},
281              },
282       details_);
283 }
284 
285 bool Symbol::IsFuncResult() const {
286   return std::visit(
287       common::visitors{[](const EntityDetails &x) { return x.isFuncResult(); },
288           [](const ObjectEntityDetails &x) { return x.isFuncResult(); },
289           [](const ProcEntityDetails &x) { return x.isFuncResult(); },
290           [](const HostAssocDetails &x) { return x.symbol().IsFuncResult(); },
291           [](const auto &) { return false; }},
292       details_);
293 }
294 
295 bool Symbol::IsObjectArray() const {
296   const auto *details{std::get_if<ObjectEntityDetails>(&details_)};
297   return details && details->IsArray();
298 }
299 
300 bool Symbol::IsSubprogram() const {
301   return std::visit(
302       common::visitors{
303           [](const SubprogramDetails &) { return true; },
304           [](const SubprogramNameDetails &) { return true; },
305           [](const GenericDetails &) { return true; },
306           [](const UseDetails &x) { return x.symbol().IsSubprogram(); },
307           [](const auto &) { return false; },
308       },
309       details_);
310 }
311 
312 bool Symbol::IsFromModFile() const {
313   return test(Flag::ModFile) ||
314       (!owner_->IsGlobal() && owner_->symbol()->IsFromModFile());
315 }
316 
317 ObjectEntityDetails::ObjectEntityDetails(EntityDetails &&d)
318     : EntityDetails(d) {}
319 
320 llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const EntityDetails &x) {
321   DumpBool(os, "dummy", x.isDummy());
322   DumpBool(os, "funcResult", x.isFuncResult());
323   if (x.type()) {
324     os << " type: " << *x.type();
325   }
326   DumpExpr(os, "bindName", x.bindName_);
327   return os;
328 }
329 
330 llvm::raw_ostream &operator<<(
331     llvm::raw_ostream &os, const ObjectEntityDetails &x) {
332   os << *static_cast<const EntityDetails *>(&x);
333   DumpList(os, "shape", x.shape());
334   DumpList(os, "coshape", x.coshape());
335   DumpExpr(os, "init", x.init_);
336   return os;
337 }
338 
339 llvm::raw_ostream &operator<<(
340     llvm::raw_ostream &os, const AssocEntityDetails &x) {
341   os << *static_cast<const EntityDetails *>(&x);
342   if (auto assocRank{x.rank()}) {
343     os << " rank: " << *assocRank;
344   }
345   DumpExpr(os, "expr", x.expr());
346   return os;
347 }
348 
349 llvm::raw_ostream &operator<<(
350     llvm::raw_ostream &os, const ProcEntityDetails &x) {
351   if (auto *symbol{x.interface_.symbol()}) {
352     os << ' ' << symbol->name();
353   } else {
354     DumpType(os, x.interface_.type());
355   }
356   DumpExpr(os, "bindName", x.bindName());
357   DumpOptional(os, "passName", x.passName());
358   if (x.init()) {
359     if (const Symbol * target{*x.init()}) {
360       os << " => " << target->name();
361     } else {
362       os << " => NULL()";
363     }
364   }
365   return os;
366 }
367 
368 llvm::raw_ostream &operator<<(
369     llvm::raw_ostream &os, const DerivedTypeDetails &x) {
370   DumpBool(os, "sequence", x.sequence_);
371   DumpList(os, "components", x.componentNames_);
372   return os;
373 }
374 
375 llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const Details &details) {
376   os << DetailsToString(details);
377   std::visit( //
378       common::visitors{
379           [&](const UnknownDetails &) {},
380           [&](const MainProgramDetails &) {},
381           [&](const ModuleDetails &x) {
382             if (x.isSubmodule()) {
383               os << " (";
384               if (x.ancestor()) {
385                 auto ancestor{x.ancestor()->GetName().value()};
386                 os << ancestor;
387                 if (x.parent()) {
388                   auto parent{x.parent()->GetName().value()};
389                   if (ancestor != parent) {
390                     os << ':' << parent;
391                   }
392                 }
393               }
394               os << ")";
395             }
396           },
397           [&](const SubprogramNameDetails &x) {
398             os << ' ' << EnumToString(x.kind());
399           },
400           [&](const UseDetails &x) {
401             os << " from " << x.symbol().name() << " in "
402                << GetUsedModule(x).name();
403           },
404           [&](const UseErrorDetails &x) {
405             os << " uses:";
406             for (const auto &[location, module] : x.occurrences()) {
407               os << " from " << module->GetName().value() << " at " << location;
408             }
409           },
410           [](const HostAssocDetails &) {},
411           [&](const GenericDetails &x) {
412             os << ' ' << x.kind().ToString();
413             DumpBool(os, "(specific)", x.specific() != nullptr);
414             DumpBool(os, "(derivedType)", x.derivedType() != nullptr);
415             os << " procs:";
416             DumpSymbolVector(os, x.specificProcs());
417           },
418           [&](const ProcBindingDetails &x) {
419             os << " => " << x.symbol().name();
420             DumpOptional(os, "passName", x.passName());
421           },
422           [&](const NamelistDetails &x) {
423             os << ':';
424             DumpSymbolVector(os, x.objects());
425           },
426           [&](const CommonBlockDetails &x) {
427             if (x.alignment()) {
428               os << " alignment=" << x.alignment();
429             }
430             os << ':';
431             for (const auto &object : x.objects()) {
432               os << ' ' << object->name();
433             }
434           },
435           [&](const FinalProcDetails &) {},
436           [&](const TypeParamDetails &x) {
437             DumpOptional(os, "type", x.type());
438             os << ' ' << common::EnumToString(x.attr());
439             DumpExpr(os, "init", x.init());
440           },
441           [&](const MiscDetails &x) {
442             os << ' ' << MiscDetails::EnumToString(x.kind());
443           },
444           [&](const auto &x) { os << x; },
445       },
446       details);
447   return os;
448 }
449 
450 llvm::raw_ostream &operator<<(llvm::raw_ostream &o, Symbol::Flag flag) {
451   return o << Symbol::EnumToString(flag);
452 }
453 
454 llvm::raw_ostream &operator<<(
455     llvm::raw_ostream &o, const Symbol::Flags &flags) {
456   std::size_t n{flags.count()};
457   std::size_t seen{0};
458   for (std::size_t j{0}; seen < n; ++j) {
459     Symbol::Flag flag{static_cast<Symbol::Flag>(j)};
460     if (flags.test(flag)) {
461       if (seen++ > 0) {
462         o << ", ";
463       }
464       o << flag;
465     }
466   }
467   return o;
468 }
469 
470 llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const Symbol &symbol) {
471   os << symbol.name();
472   if (!symbol.attrs().empty()) {
473     os << ", " << symbol.attrs();
474   }
475   if (!symbol.flags().empty()) {
476     os << " (" << symbol.flags() << ')';
477   }
478   if (symbol.size_) {
479     os << " size=" << symbol.size_ << " offset=" << symbol.offset_;
480   }
481   os << ": " << symbol.details_;
482   return os;
483 }
484 
485 // Output a unique name for a scope by qualifying it with the names of
486 // parent scopes. For scopes without corresponding symbols, use the kind
487 // with an index (e.g. Block1, Block2, etc.).
488 static void DumpUniqueName(llvm::raw_ostream &os, const Scope &scope) {
489   if (!scope.IsGlobal()) {
490     DumpUniqueName(os, scope.parent());
491     os << '/';
492     if (auto *scopeSymbol{scope.symbol()};
493         scopeSymbol && !scopeSymbol->name().empty()) {
494       os << scopeSymbol->name();
495     } else {
496       int index{1};
497       for (auto &child : scope.parent().children()) {
498         if (child == scope) {
499           break;
500         }
501         if (child.kind() == scope.kind()) {
502           ++index;
503         }
504       }
505       os << Scope::EnumToString(scope.kind()) << index;
506     }
507   }
508 }
509 
510 // Dump a symbol for UnparseWithSymbols. This will be used for tests so the
511 // format should be reasonably stable.
512 llvm::raw_ostream &DumpForUnparse(
513     llvm::raw_ostream &os, const Symbol &symbol, bool isDef) {
514   DumpUniqueName(os, symbol.owner());
515   os << '/' << symbol.name();
516   if (isDef) {
517     if (!symbol.attrs().empty()) {
518       os << ' ' << symbol.attrs();
519     }
520     if (!symbol.flags().empty()) {
521       os << " (" << symbol.flags() << ')';
522     }
523     os << ' ' << symbol.GetDetailsName();
524     DumpType(os, symbol.GetType());
525   }
526   return os;
527 }
528 
529 const DerivedTypeSpec *Symbol::GetParentTypeSpec(const Scope *scope) const {
530   if (const Symbol * parentComponent{GetParentComponent(scope)}) {
531     const auto &object{parentComponent->get<ObjectEntityDetails>()};
532     return &object.type()->derivedTypeSpec();
533   } else {
534     return nullptr;
535   }
536 }
537 
538 const Symbol *Symbol::GetParentComponent(const Scope *scope) const {
539   if (const auto *dtDetails{detailsIf<DerivedTypeDetails>()}) {
540     if (!scope) {
541       scope = scope_;
542     }
543     return dtDetails->GetParentComponent(DEREF(scope));
544   } else {
545     return nullptr;
546   }
547 }
548 
549 void DerivedTypeDetails::add_component(const Symbol &symbol) {
550   if (symbol.test(Symbol::Flag::ParentComp)) {
551     CHECK(componentNames_.empty());
552   }
553   componentNames_.push_back(symbol.name());
554 }
555 
556 const Symbol *DerivedTypeDetails::GetParentComponent(const Scope &scope) const {
557   if (auto extends{GetParentComponentName()}) {
558     if (auto iter{scope.find(*extends)}; iter != scope.cend()) {
559       if (const Symbol & symbol{*iter->second};
560           symbol.test(Symbol::Flag::ParentComp)) {
561         return &symbol;
562       }
563     }
564   }
565   return nullptr;
566 }
567 
568 void TypeParamDetails::set_type(const DeclTypeSpec &type) {
569   CHECK(!type_);
570   type_ = &type;
571 }
572 
573 bool GenericKind::IsIntrinsicOperator() const {
574   return Is(OtherKind::Concat) || Has<common::LogicalOperator>() ||
575       Has<common::NumericOperator>() || Has<common::RelationalOperator>();
576 }
577 
578 bool GenericKind::IsOperator() const {
579   return IsDefinedOperator() || IsIntrinsicOperator();
580 }
581 
582 std::string GenericKind::ToString() const {
583   return std::visit(
584       common::visitors {
585         [](const OtherKind &x) { return EnumToString(x); },
586             [](const DefinedIo &x) { return EnumToString(x); },
587 #if !__clang__ && __GNUC__ == 7 && __GNUC_MINOR__ == 2
588             [](const common::NumericOperator &x) {
589               return common::EnumToString(x);
590             },
591             [](const common::LogicalOperator &x) {
592               return common::EnumToString(x);
593             },
594             [](const common::RelationalOperator &x) {
595               return common::EnumToString(x);
596             },
597 #else
598             [](const auto &x) { return common::EnumToString(x); },
599 #endif
600       },
601       u);
602 }
603 
604 bool GenericKind::Is(GenericKind::OtherKind x) const {
605   const OtherKind *y{std::get_if<OtherKind>(&u)};
606   return y && *y == x;
607 }
608 
609 } // namespace Fortran::semantics
610