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