1 //===-- lib/Semantics/tools.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/Parser/tools.h"
10 #include "flang/Common/Fortran.h"
11 #include "flang/Common/indirection.h"
12 #include "flang/Parser/dump-parse-tree.h"
13 #include "flang/Parser/message.h"
14 #include "flang/Parser/parse-tree.h"
15 #include "flang/Semantics/scope.h"
16 #include "flang/Semantics/semantics.h"
17 #include "flang/Semantics/symbol.h"
18 #include "flang/Semantics/tools.h"
19 #include "flang/Semantics/type.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include <algorithm>
22 #include <set>
23 #include <variant>
24 
25 namespace Fortran::semantics {
26 
27 // Find this or containing scope that matches predicate
28 static const Scope *FindScopeContaining(
29     const Scope &start, std::function<bool(const Scope &)> predicate) {
30   for (const Scope *scope{&start};; scope = &scope->parent()) {
31     if (predicate(*scope)) {
32       return scope;
33     }
34     if (scope->IsTopLevel()) {
35       return nullptr;
36     }
37   }
38 }
39 
40 const Scope &GetTopLevelUnitContaining(const Scope &start) {
41   CHECK(!start.IsTopLevel());
42   return DEREF(FindScopeContaining(
43       start, [](const Scope &scope) { return scope.parent().IsTopLevel(); }));
44 }
45 
46 const Scope &GetTopLevelUnitContaining(const Symbol &symbol) {
47   return GetTopLevelUnitContaining(symbol.owner());
48 }
49 
50 const Scope *FindModuleContaining(const Scope &start) {
51   return FindScopeContaining(
52       start, [](const Scope &scope) { return scope.IsModule(); });
53 }
54 
55 const Scope *FindModuleFileContaining(const Scope &start) {
56   return FindScopeContaining(
57       start, [](const Scope &scope) { return scope.IsModuleFile(); });
58 }
59 
60 const Scope &GetProgramUnitContaining(const Scope &start) {
61   CHECK(!start.IsTopLevel());
62   return DEREF(FindScopeContaining(start, [](const Scope &scope) {
63     switch (scope.kind()) {
64     case Scope::Kind::Module:
65     case Scope::Kind::MainProgram:
66     case Scope::Kind::Subprogram:
67     case Scope::Kind::BlockData:
68       return true;
69     default:
70       return false;
71     }
72   }));
73 }
74 
75 const Scope &GetProgramUnitContaining(const Symbol &symbol) {
76   return GetProgramUnitContaining(symbol.owner());
77 }
78 
79 const Scope *FindPureProcedureContaining(const Scope &start) {
80   // N.B. We only need to examine the innermost containing program unit
81   // because an internal subprogram of a pure subprogram must also
82   // be pure (C1592).
83   if (start.IsTopLevel()) {
84     return nullptr;
85   } else {
86     const Scope &scope{GetProgramUnitContaining(start)};
87     return IsPureProcedure(scope) ? &scope : nullptr;
88   }
89 }
90 
91 // 7.5.2.4 "same derived type" test -- rely on IsTkCompatibleWith() and its
92 // infrastructure to detect and handle comparisons on distinct (but "same")
93 // sequence/bind(C) derived types
94 static bool MightBeSameDerivedType(
95     const std::optional<evaluate::DynamicType> &lhsType,
96     const std::optional<evaluate::DynamicType> &rhsType) {
97   return lhsType && rhsType && rhsType->IsTkCompatibleWith(*lhsType);
98 }
99 
100 Tristate IsDefinedAssignment(
101     const std::optional<evaluate::DynamicType> &lhsType, int lhsRank,
102     const std::optional<evaluate::DynamicType> &rhsType, int rhsRank) {
103   if (!lhsType || !rhsType) {
104     return Tristate::No; // error or rhs is untyped
105   }
106   TypeCategory lhsCat{lhsType->category()};
107   TypeCategory rhsCat{rhsType->category()};
108   if (rhsRank > 0 && lhsRank != rhsRank) {
109     return Tristate::Yes;
110   } else if (lhsCat != TypeCategory::Derived) {
111     return ToTristate(lhsCat != rhsCat &&
112         (!IsNumericTypeCategory(lhsCat) || !IsNumericTypeCategory(rhsCat)));
113   } else if (MightBeSameDerivedType(lhsType, rhsType)) {
114     return Tristate::Maybe; // TYPE(t) = TYPE(t) can be defined or intrinsic
115   } else {
116     return Tristate::Yes;
117   }
118 }
119 
120 bool IsIntrinsicRelational(common::RelationalOperator opr,
121     const evaluate::DynamicType &type0, int rank0,
122     const evaluate::DynamicType &type1, int rank1) {
123   if (!evaluate::AreConformable(rank0, rank1)) {
124     return false;
125   } else {
126     auto cat0{type0.category()};
127     auto cat1{type1.category()};
128     if (IsNumericTypeCategory(cat0) && IsNumericTypeCategory(cat1)) {
129       // numeric types: EQ/NE always ok, others ok for non-complex
130       return opr == common::RelationalOperator::EQ ||
131           opr == common::RelationalOperator::NE ||
132           (cat0 != TypeCategory::Complex && cat1 != TypeCategory::Complex);
133     } else {
134       // not both numeric: only Character is ok
135       return cat0 == TypeCategory::Character && cat1 == TypeCategory::Character;
136     }
137   }
138 }
139 
140 bool IsIntrinsicNumeric(const evaluate::DynamicType &type0) {
141   return IsNumericTypeCategory(type0.category());
142 }
143 bool IsIntrinsicNumeric(const evaluate::DynamicType &type0, int rank0,
144     const evaluate::DynamicType &type1, int rank1) {
145   return evaluate::AreConformable(rank0, rank1) &&
146       IsNumericTypeCategory(type0.category()) &&
147       IsNumericTypeCategory(type1.category());
148 }
149 
150 bool IsIntrinsicLogical(const evaluate::DynamicType &type0) {
151   return type0.category() == TypeCategory::Logical;
152 }
153 bool IsIntrinsicLogical(const evaluate::DynamicType &type0, int rank0,
154     const evaluate::DynamicType &type1, int rank1) {
155   return evaluate::AreConformable(rank0, rank1) &&
156       type0.category() == TypeCategory::Logical &&
157       type1.category() == TypeCategory::Logical;
158 }
159 
160 bool IsIntrinsicConcat(const evaluate::DynamicType &type0, int rank0,
161     const evaluate::DynamicType &type1, int rank1) {
162   return evaluate::AreConformable(rank0, rank1) &&
163       type0.category() == TypeCategory::Character &&
164       type1.category() == TypeCategory::Character &&
165       type0.kind() == type1.kind();
166 }
167 
168 bool IsGenericDefinedOp(const Symbol &symbol) {
169   const Symbol &ultimate{symbol.GetUltimate()};
170   if (const auto *generic{ultimate.detailsIf<GenericDetails>()}) {
171     return generic->kind().IsDefinedOperator();
172   } else if (const auto *misc{ultimate.detailsIf<MiscDetails>()}) {
173     return misc->kind() == MiscDetails::Kind::TypeBoundDefinedOp;
174   } else {
175     return false;
176   }
177 }
178 
179 bool IsDefinedOperator(SourceName name) {
180   const char *begin{name.begin()};
181   const char *end{name.end()};
182   return begin != end && begin[0] == '.' && end[-1] == '.';
183 }
184 
185 std::string MakeOpName(SourceName name) {
186   std::string result{name.ToString()};
187   return IsDefinedOperator(name)         ? "OPERATOR(" + result + ")"
188       : result.find("operator(", 0) == 0 ? parser::ToUpperCaseLetters(result)
189                                          : result;
190 }
191 
192 bool IsCommonBlockContaining(const Symbol &block, const Symbol &object) {
193   const auto &objects{block.get<CommonBlockDetails>().objects()};
194   auto found{std::find(objects.begin(), objects.end(), object)};
195   return found != objects.end();
196 }
197 
198 bool IsUseAssociated(const Symbol &symbol, const Scope &scope) {
199   const Scope &owner{GetProgramUnitContaining(symbol.GetUltimate().owner())};
200   return owner.kind() == Scope::Kind::Module &&
201       owner != GetProgramUnitContaining(scope);
202 }
203 
204 bool DoesScopeContain(
205     const Scope *maybeAncestor, const Scope &maybeDescendent) {
206   return maybeAncestor && !maybeDescendent.IsTopLevel() &&
207       FindScopeContaining(maybeDescendent.parent(),
208           [&](const Scope &scope) { return &scope == maybeAncestor; });
209 }
210 
211 bool DoesScopeContain(const Scope *maybeAncestor, const Symbol &symbol) {
212   return DoesScopeContain(maybeAncestor, symbol.owner());
213 }
214 
215 static const Symbol &FollowHostAssoc(const Symbol &symbol) {
216   for (const Symbol *s{&symbol};;) {
217     const auto *details{s->detailsIf<HostAssocDetails>()};
218     if (!details) {
219       return *s;
220     }
221     s = &details->symbol();
222   }
223 }
224 
225 bool IsHostAssociated(const Symbol &symbol, const Scope &scope) {
226   const Scope &subprogram{GetProgramUnitContaining(scope)};
227   return DoesScopeContain(
228       &GetProgramUnitContaining(FollowHostAssoc(symbol)), subprogram);
229 }
230 
231 bool IsInStmtFunction(const Symbol &symbol) {
232   if (const Symbol * function{symbol.owner().symbol()}) {
233     return IsStmtFunction(*function);
234   }
235   return false;
236 }
237 
238 bool IsStmtFunctionDummy(const Symbol &symbol) {
239   return IsDummy(symbol) && IsInStmtFunction(symbol);
240 }
241 
242 bool IsStmtFunctionResult(const Symbol &symbol) {
243   return IsFunctionResult(symbol) && IsInStmtFunction(symbol);
244 }
245 
246 bool IsPointerDummy(const Symbol &symbol) {
247   return IsPointer(symbol) && IsDummy(symbol);
248 }
249 
250 // proc-name
251 bool IsProcName(const Symbol &symbol) {
252   return symbol.GetUltimate().has<ProcEntityDetails>();
253 }
254 
255 bool IsBindCProcedure(const Symbol &symbol) {
256   if (const auto *procDetails{symbol.detailsIf<ProcEntityDetails>()}) {
257     if (const Symbol * procInterface{procDetails->interface().symbol()}) {
258       // procedure component with a BIND(C) interface
259       return IsBindCProcedure(*procInterface);
260     }
261   }
262   return symbol.attrs().test(Attr::BIND_C) && IsProcedure(symbol);
263 }
264 
265 bool IsBindCProcedure(const Scope &scope) {
266   if (const Symbol * symbol{scope.GetSymbol()}) {
267     return IsBindCProcedure(*symbol);
268   } else {
269     return false;
270   }
271 }
272 
273 static const Symbol *FindPointerComponent(
274     const Scope &scope, std::set<const Scope *> &visited) {
275   if (!scope.IsDerivedType()) {
276     return nullptr;
277   }
278   if (!visited.insert(&scope).second) {
279     return nullptr;
280   }
281   // If there's a top-level pointer component, return it for clearer error
282   // messaging.
283   for (const auto &pair : scope) {
284     const Symbol &symbol{*pair.second};
285     if (IsPointer(symbol)) {
286       return &symbol;
287     }
288   }
289   for (const auto &pair : scope) {
290     const Symbol &symbol{*pair.second};
291     if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) {
292       if (const DeclTypeSpec * type{details->type()}) {
293         if (const DerivedTypeSpec * derived{type->AsDerived()}) {
294           if (const Scope * nested{derived->scope()}) {
295             if (const Symbol *
296                 pointer{FindPointerComponent(*nested, visited)}) {
297               return pointer;
298             }
299           }
300         }
301       }
302     }
303   }
304   return nullptr;
305 }
306 
307 const Symbol *FindPointerComponent(const Scope &scope) {
308   std::set<const Scope *> visited;
309   return FindPointerComponent(scope, visited);
310 }
311 
312 const Symbol *FindPointerComponent(const DerivedTypeSpec &derived) {
313   if (const Scope * scope{derived.scope()}) {
314     return FindPointerComponent(*scope);
315   } else {
316     return nullptr;
317   }
318 }
319 
320 const Symbol *FindPointerComponent(const DeclTypeSpec &type) {
321   if (const DerivedTypeSpec * derived{type.AsDerived()}) {
322     return FindPointerComponent(*derived);
323   } else {
324     return nullptr;
325   }
326 }
327 
328 const Symbol *FindPointerComponent(const DeclTypeSpec *type) {
329   return type ? FindPointerComponent(*type) : nullptr;
330 }
331 
332 const Symbol *FindPointerComponent(const Symbol &symbol) {
333   return IsPointer(symbol) ? &symbol : FindPointerComponent(symbol.GetType());
334 }
335 
336 // C1594 specifies several ways by which an object might be globally visible.
337 const Symbol *FindExternallyVisibleObject(
338     const Symbol &object, const Scope &scope) {
339   // TODO: Storage association with any object for which this predicate holds,
340   // once EQUIVALENCE is supported.
341   const Symbol &ultimate{GetAssociationRoot(object)};
342   if (IsDummy(ultimate)) {
343     if (IsIntentIn(ultimate)) {
344       return &ultimate;
345     }
346     if (IsPointer(ultimate) && IsPureProcedure(ultimate.owner()) &&
347         IsFunction(ultimate.owner())) {
348       return &ultimate;
349     }
350   } else if (&GetProgramUnitContaining(ultimate) !=
351       &GetProgramUnitContaining(scope)) {
352     return &object;
353   } else if (const Symbol * block{FindCommonBlockContaining(ultimate)}) {
354     return block;
355   }
356   return nullptr;
357 }
358 
359 const Symbol &BypassGeneric(const Symbol &symbol) {
360   const Symbol &ultimate{symbol.GetUltimate()};
361   if (const auto *generic{ultimate.detailsIf<GenericDetails>()}) {
362     if (const Symbol * specific{generic->specific()}) {
363       return *specific;
364     }
365   }
366   return symbol;
367 }
368 
369 bool ExprHasTypeCategory(
370     const SomeExpr &expr, const common::TypeCategory &type) {
371   auto dynamicType{expr.GetType()};
372   return dynamicType && dynamicType->category() == type;
373 }
374 
375 bool ExprTypeKindIsDefault(
376     const SomeExpr &expr, const SemanticsContext &context) {
377   auto dynamicType{expr.GetType()};
378   return dynamicType &&
379       dynamicType->category() != common::TypeCategory::Derived &&
380       dynamicType->kind() == context.GetDefaultKind(dynamicType->category());
381 }
382 
383 // If an analyzed expr or assignment is missing, dump the node and die.
384 template <typename T>
385 static void CheckMissingAnalysis(bool absent, const T &x) {
386   if (absent) {
387     std::string buf;
388     llvm::raw_string_ostream ss{buf};
389     ss << "node has not been analyzed:\n";
390     parser::DumpTree(ss, x);
391     common::die(ss.str().c_str());
392   }
393 }
394 
395 template <typename T> static const SomeExpr *GetTypedExpr(const T &x) {
396   CheckMissingAnalysis(!x.typedExpr, x);
397   return common::GetPtrFromOptional(x.typedExpr->v);
398 }
399 const SomeExpr *GetExprHelper::Get(const parser::Expr &x) {
400   return GetTypedExpr(x);
401 }
402 const SomeExpr *GetExprHelper::Get(const parser::Variable &x) {
403   return GetTypedExpr(x);
404 }
405 const SomeExpr *GetExprHelper::Get(const parser::DataStmtConstant &x) {
406   return GetTypedExpr(x);
407 }
408 const SomeExpr *GetExprHelper::Get(const parser::AllocateObject &x) {
409   return GetTypedExpr(x);
410 }
411 const SomeExpr *GetExprHelper::Get(const parser::PointerObject &x) {
412   return GetTypedExpr(x);
413 }
414 
415 const evaluate::Assignment *GetAssignment(const parser::AssignmentStmt &x) {
416   CheckMissingAnalysis(!x.typedAssignment, x);
417   return common::GetPtrFromOptional(x.typedAssignment->v);
418 }
419 const evaluate::Assignment *GetAssignment(
420     const parser::PointerAssignmentStmt &x) {
421   CheckMissingAnalysis(!x.typedAssignment, x);
422   return common::GetPtrFromOptional(x.typedAssignment->v);
423 }
424 
425 const Symbol *FindInterface(const Symbol &symbol) {
426   return std::visit(
427       common::visitors{
428           [](const ProcEntityDetails &details) {
429             return details.interface().symbol();
430           },
431           [](const ProcBindingDetails &details) { return &details.symbol(); },
432           [](const auto &) -> const Symbol * { return nullptr; },
433       },
434       symbol.details());
435 }
436 
437 const Symbol *FindSubprogram(const Symbol &symbol) {
438   return std::visit(
439       common::visitors{
440           [&](const ProcEntityDetails &details) -> const Symbol * {
441             if (const Symbol * interface{details.interface().symbol()}) {
442               return FindSubprogram(*interface);
443             } else {
444               return &symbol;
445             }
446           },
447           [](const ProcBindingDetails &details) {
448             return FindSubprogram(details.symbol());
449           },
450           [&](const SubprogramDetails &) { return &symbol; },
451           [](const UseDetails &details) {
452             return FindSubprogram(details.symbol());
453           },
454           [](const HostAssocDetails &details) {
455             return FindSubprogram(details.symbol());
456           },
457           [](const auto &) -> const Symbol * { return nullptr; },
458       },
459       symbol.details());
460 }
461 
462 const Symbol *FindOverriddenBinding(const Symbol &symbol) {
463   if (symbol.has<ProcBindingDetails>()) {
464     if (const DeclTypeSpec * parentType{FindParentTypeSpec(symbol.owner())}) {
465       if (const DerivedTypeSpec * parentDerived{parentType->AsDerived()}) {
466         if (const Scope * parentScope{parentDerived->typeSymbol().scope()}) {
467           return parentScope->FindComponent(symbol.name());
468         }
469       }
470     }
471   }
472   return nullptr;
473 }
474 
475 const DeclTypeSpec *FindParentTypeSpec(const DerivedTypeSpec &derived) {
476   return FindParentTypeSpec(derived.typeSymbol());
477 }
478 
479 const DeclTypeSpec *FindParentTypeSpec(const DeclTypeSpec &decl) {
480   if (const DerivedTypeSpec * derived{decl.AsDerived()}) {
481     return FindParentTypeSpec(*derived);
482   } else {
483     return nullptr;
484   }
485 }
486 
487 const DeclTypeSpec *FindParentTypeSpec(const Scope &scope) {
488   if (scope.kind() == Scope::Kind::DerivedType) {
489     if (const auto *symbol{scope.symbol()}) {
490       return FindParentTypeSpec(*symbol);
491     }
492   }
493   return nullptr;
494 }
495 
496 const DeclTypeSpec *FindParentTypeSpec(const Symbol &symbol) {
497   if (const Scope * scope{symbol.scope()}) {
498     if (const auto *details{symbol.detailsIf<DerivedTypeDetails>()}) {
499       if (const Symbol * parent{details->GetParentComponent(*scope)}) {
500         return parent->GetType();
501       }
502     }
503   }
504   return nullptr;
505 }
506 
507 const EquivalenceSet *FindEquivalenceSet(const Symbol &symbol) {
508   const Symbol &ultimate{symbol.GetUltimate()};
509   for (const EquivalenceSet &set : ultimate.owner().equivalenceSets()) {
510     for (const EquivalenceObject &object : set) {
511       if (object.symbol == ultimate) {
512         return &set;
513       }
514     }
515   }
516   return nullptr;
517 }
518 
519 bool IsOrContainsEventOrLockComponent(const Symbol &original) {
520   const Symbol &symbol{ResolveAssociations(original)};
521   if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) {
522     if (const DeclTypeSpec * type{details->type()}) {
523       if (const DerivedTypeSpec * derived{type->AsDerived()}) {
524         return IsEventTypeOrLockType(derived) ||
525             FindEventOrLockPotentialComponent(*derived);
526       }
527     }
528   }
529   return false;
530 }
531 
532 // Check this symbol suitable as a type-bound procedure - C769
533 bool CanBeTypeBoundProc(const Symbol *symbol) {
534   if (!symbol || IsDummy(*symbol) || IsProcedurePointer(*symbol)) {
535     return false;
536   } else if (symbol->has<SubprogramNameDetails>()) {
537     return symbol->owner().kind() == Scope::Kind::Module;
538   } else if (auto *details{symbol->detailsIf<SubprogramDetails>()}) {
539     return symbol->owner().kind() == Scope::Kind::Module ||
540         details->isInterface();
541   } else if (const auto *proc{symbol->detailsIf<ProcEntityDetails>()}) {
542     return !symbol->attrs().test(Attr::INTRINSIC) &&
543         proc->HasExplicitInterface();
544   } else {
545     return false;
546   }
547 }
548 
549 bool HasDeclarationInitializer(const Symbol &symbol) {
550   if (IsNamedConstant(symbol)) {
551     return false;
552   } else if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
553     return object->init().has_value();
554   } else if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}) {
555     return proc->init().has_value();
556   } else {
557     return false;
558   }
559 }
560 
561 bool IsInitialized(
562     const Symbol &symbol, bool ignoreDataStatements, bool ignoreAllocatable) {
563   if (!ignoreAllocatable && IsAllocatable(symbol)) {
564     return true;
565   } else if (!ignoreDataStatements && symbol.test(Symbol::Flag::InDataStmt)) {
566     return true;
567   } else if (HasDeclarationInitializer(symbol)) {
568     return true;
569   } else if (IsNamedConstant(symbol) || IsFunctionResult(symbol) ||
570       IsPointer(symbol)) {
571     return false;
572   } else if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
573     if (!object->isDummy() && object->type()) {
574       if (const auto *derived{object->type()->AsDerived()}) {
575         return derived->HasDefaultInitialization(ignoreAllocatable);
576       }
577     }
578   }
579   return false;
580 }
581 
582 bool IsDestructible(const Symbol &symbol, const Symbol *derivedTypeSymbol) {
583   if (IsAllocatable(symbol) || IsAutomatic(symbol)) {
584     return true;
585   } else if (IsNamedConstant(symbol) || IsFunctionResult(symbol) ||
586       IsPointer(symbol)) {
587     return false;
588   } else if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
589     if (!object->isDummy() && object->type()) {
590       if (const auto *derived{object->type()->AsDerived()}) {
591         return &derived->typeSymbol() != derivedTypeSymbol &&
592             derived->HasDestruction();
593       }
594     }
595   }
596   return false;
597 }
598 
599 bool HasIntrinsicTypeName(const Symbol &symbol) {
600   std::string name{symbol.name().ToString()};
601   if (name == "doubleprecision") {
602     return true;
603   } else if (name == "derived") {
604     return false;
605   } else {
606     for (int i{0}; i != common::TypeCategory_enumSize; ++i) {
607       if (name == parser::ToLowerCaseLetters(EnumToString(TypeCategory{i}))) {
608         return true;
609       }
610     }
611     return false;
612   }
613 }
614 
615 bool IsSeparateModuleProcedureInterface(const Symbol *symbol) {
616   if (symbol && symbol->attrs().test(Attr::MODULE)) {
617     if (auto *details{symbol->detailsIf<SubprogramDetails>()}) {
618       return details->isInterface();
619     }
620   }
621   return false;
622 }
623 
624 bool IsFinalizable(
625     const Symbol &symbol, std::set<const DerivedTypeSpec *> *inProgress) {
626   if (IsPointer(symbol)) {
627     return false;
628   }
629   if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
630     if (object->isDummy() && !IsIntentOut(symbol)) {
631       return false;
632     }
633     const DeclTypeSpec *type{object->type()};
634     const DerivedTypeSpec *typeSpec{type ? type->AsDerived() : nullptr};
635     return typeSpec && IsFinalizable(*typeSpec, inProgress);
636   }
637   return false;
638 }
639 
640 bool IsFinalizable(const DerivedTypeSpec &derived,
641     std::set<const DerivedTypeSpec *> *inProgress) {
642   if (!derived.typeSymbol().get<DerivedTypeDetails>().finals().empty()) {
643     return true;
644   }
645   std::set<const DerivedTypeSpec *> basis;
646   if (inProgress) {
647     if (inProgress->find(&derived) != inProgress->end()) {
648       return false; // don't loop on recursive type
649     }
650   } else {
651     inProgress = &basis;
652   }
653   auto iterator{inProgress->insert(&derived).first};
654   PotentialComponentIterator components{derived};
655   bool result{bool{std::find_if(
656       components.begin(), components.end(), [=](const Symbol &component) {
657         return IsFinalizable(component, inProgress);
658       })}};
659   inProgress->erase(iterator);
660   return result;
661 }
662 
663 bool HasImpureFinal(const DerivedTypeSpec &derived) {
664   if (const auto *details{
665           derived.typeSymbol().detailsIf<DerivedTypeDetails>()}) {
666     const auto &finals{details->finals()};
667     return std::any_of(finals.begin(), finals.end(),
668         [](const auto &x) { return !x.second->attrs().test(Attr::PURE); });
669   } else {
670     return false;
671   }
672 }
673 
674 bool IsAssumedLengthCharacter(const Symbol &symbol) {
675   if (const DeclTypeSpec * type{symbol.GetType()}) {
676     return type->category() == DeclTypeSpec::Character &&
677         type->characterTypeSpec().length().isAssumed();
678   } else {
679     return false;
680   }
681 }
682 
683 bool IsInBlankCommon(const Symbol &symbol) {
684   const Symbol *block{FindCommonBlockContaining(symbol)};
685   return block && block->name().empty();
686 }
687 
688 // C722 and C723:  For a function to be assumed length, it must be external and
689 // of CHARACTER type
690 bool IsExternal(const Symbol &symbol) {
691   return ClassifyProcedure(symbol) == ProcedureDefinitionClass::External;
692 }
693 
694 // Most scopes have no EQUIVALENCE, and this function is a fast no-op for them.
695 std::list<std::list<SymbolRef>> GetStorageAssociations(const Scope &scope) {
696   UnorderedSymbolSet distinct;
697   for (const EquivalenceSet &set : scope.equivalenceSets()) {
698     for (const EquivalenceObject &object : set) {
699       distinct.emplace(object.symbol);
700     }
701   }
702   // This set is ordered by ascending offsets, with ties broken by greatest
703   // size.  A multiset is used here because multiple symbols may have the
704   // same offset and size; the symbols in the set, however, are distinct.
705   std::multiset<SymbolRef, SymbolOffsetCompare> associated;
706   for (SymbolRef ref : distinct) {
707     associated.emplace(*ref);
708   }
709   std::list<std::list<SymbolRef>> result;
710   std::size_t limit{0};
711   const Symbol *currentCommon{nullptr};
712   for (const Symbol &symbol : associated) {
713     const Symbol *thisCommon{FindCommonBlockContaining(symbol)};
714     if (result.empty() || symbol.offset() >= limit ||
715         thisCommon != currentCommon) {
716       // Start a new group
717       result.emplace_back(std::list<SymbolRef>{});
718       limit = 0;
719       currentCommon = thisCommon;
720     }
721     result.back().emplace_back(symbol);
722     limit = std::max(limit, symbol.offset() + symbol.size());
723   }
724   return result;
725 }
726 
727 bool IsModuleProcedure(const Symbol &symbol) {
728   return ClassifyProcedure(symbol) == ProcedureDefinitionClass::Module;
729 }
730 const Symbol *IsExternalInPureContext(
731     const Symbol &symbol, const Scope &scope) {
732   if (const auto *pureProc{FindPureProcedureContaining(scope)}) {
733     return FindExternallyVisibleObject(symbol.GetUltimate(), *pureProc);
734   }
735   return nullptr;
736 }
737 
738 PotentialComponentIterator::const_iterator FindPolymorphicPotentialComponent(
739     const DerivedTypeSpec &derived) {
740   PotentialComponentIterator potentials{derived};
741   return std::find_if(
742       potentials.begin(), potentials.end(), [](const Symbol &component) {
743         if (const auto *details{component.detailsIf<ObjectEntityDetails>()}) {
744           const DeclTypeSpec *type{details->type()};
745           return type && type->IsPolymorphic();
746         }
747         return false;
748       });
749 }
750 
751 bool IsOrContainsPolymorphicComponent(const Symbol &original) {
752   const Symbol &symbol{ResolveAssociations(original)};
753   if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) {
754     if (const DeclTypeSpec * type{details->type()}) {
755       if (type->IsPolymorphic()) {
756         return true;
757       }
758       if (const DerivedTypeSpec * derived{type->AsDerived()}) {
759         return (bool)FindPolymorphicPotentialComponent(*derived);
760       }
761     }
762   }
763   return false;
764 }
765 
766 bool InProtectedContext(const Symbol &symbol, const Scope &currentScope) {
767   return IsProtected(symbol) && !IsHostAssociated(symbol, currentScope);
768 }
769 
770 // C1101 and C1158
771 // Modifiability checks on the leftmost symbol ("base object")
772 // of a data-ref
773 std::optional<parser::MessageFixedText> WhyNotModifiableFirst(
774     const Symbol &symbol, const Scope &scope) {
775   if (symbol.has<AssocEntityDetails>()) {
776     return "'%s' is construct associated with an expression"_en_US;
777   } else if (IsExternalInPureContext(symbol, scope)) {
778     return "'%s' is externally visible and referenced in a pure"
779            " procedure"_en_US;
780   } else if (!IsVariableName(symbol)) {
781     return "'%s' is not a variable"_en_US;
782   } else {
783     return std::nullopt;
784   }
785 }
786 
787 // Modifiability checks on the rightmost symbol of a data-ref
788 std::optional<parser::MessageFixedText> WhyNotModifiableLast(
789     const Symbol &symbol, const Scope &scope) {
790   if (IsOrContainsEventOrLockComponent(symbol)) {
791     return "'%s' is an entity with either an EVENT_TYPE or LOCK_TYPE"_en_US;
792   } else {
793     return std::nullopt;
794   }
795 }
796 
797 // Modifiability checks on the leftmost (base) symbol of a data-ref
798 // that apply only when there are no pointer components or a base
799 // that is a pointer.
800 std::optional<parser::MessageFixedText> WhyNotModifiableIfNoPtr(
801     const Symbol &symbol, const Scope &scope) {
802   if (InProtectedContext(symbol, scope)) {
803     return "'%s' is protected in this scope"_en_US;
804   } else if (IsIntentIn(symbol)) {
805     return "'%s' is an INTENT(IN) dummy argument"_en_US;
806   } else {
807     return std::nullopt;
808   }
809 }
810 
811 // Apply all modifiability checks to a single symbol
812 std::optional<parser::MessageFixedText> WhyNotModifiable(
813     const Symbol &original, const Scope &scope) {
814   const Symbol &symbol{GetAssociationRoot(original)};
815   if (auto first{WhyNotModifiableFirst(symbol, scope)}) {
816     return first;
817   } else if (auto last{WhyNotModifiableLast(symbol, scope)}) {
818     return last;
819   } else if (!IsPointer(symbol)) {
820     return WhyNotModifiableIfNoPtr(symbol, scope);
821   } else {
822     return std::nullopt;
823   }
824 }
825 
826 // Modifiability checks for a data-ref
827 std::optional<parser::Message> WhyNotModifiable(parser::CharBlock at,
828     const SomeExpr &expr, const Scope &scope, bool vectorSubscriptIsOk) {
829   if (auto dataRef{evaluate::ExtractDataRef(expr, true)}) {
830     if (!vectorSubscriptIsOk && evaluate::HasVectorSubscript(expr)) {
831       return parser::Message{at, "Variable has a vector subscript"_en_US};
832     }
833     const Symbol &first{GetAssociationRoot(dataRef->GetFirstSymbol())};
834     if (auto maybeWhyFirst{WhyNotModifiableFirst(first, scope)}) {
835       return parser::Message{first.name(),
836           parser::MessageFormattedText{
837               std::move(*maybeWhyFirst), first.name()}};
838     }
839     const Symbol &last{dataRef->GetLastSymbol()};
840     if (auto maybeWhyLast{WhyNotModifiableLast(last, scope)}) {
841       return parser::Message{last.name(),
842           parser::MessageFormattedText{std::move(*maybeWhyLast), last.name()}};
843     }
844     if (!GetLastPointerSymbol(*dataRef)) {
845       if (auto maybeWhyFirst{WhyNotModifiableIfNoPtr(first, scope)}) {
846         return parser::Message{first.name(),
847             parser::MessageFormattedText{
848                 std::move(*maybeWhyFirst), first.name()}};
849       }
850     }
851   } else if (!evaluate::IsVariable(expr)) {
852     return parser::Message{
853         at, "'%s' is not a variable"_en_US, expr.AsFortran()};
854   } else {
855     // reference to function returning POINTER
856   }
857   return std::nullopt;
858 }
859 
860 class ImageControlStmtHelper {
861   using ImageControlStmts = std::variant<parser::ChangeTeamConstruct,
862       parser::CriticalConstruct, parser::EventPostStmt, parser::EventWaitStmt,
863       parser::FormTeamStmt, parser::LockStmt, parser::StopStmt,
864       parser::SyncAllStmt, parser::SyncImagesStmt, parser::SyncMemoryStmt,
865       parser::SyncTeamStmt, parser::UnlockStmt>;
866 
867 public:
868   template <typename T> bool operator()(const T &) {
869     return common::HasMember<T, ImageControlStmts>;
870   }
871   template <typename T> bool operator()(const common::Indirection<T> &x) {
872     return (*this)(x.value());
873   }
874   bool operator()(const parser::AllocateStmt &stmt) {
875     const auto &allocationList{std::get<std::list<parser::Allocation>>(stmt.t)};
876     for (const auto &allocation : allocationList) {
877       const auto &allocateObject{
878           std::get<parser::AllocateObject>(allocation.t)};
879       if (IsCoarrayObject(allocateObject)) {
880         return true;
881       }
882     }
883     return false;
884   }
885   bool operator()(const parser::DeallocateStmt &stmt) {
886     const auto &allocateObjectList{
887         std::get<std::list<parser::AllocateObject>>(stmt.t)};
888     for (const auto &allocateObject : allocateObjectList) {
889       if (IsCoarrayObject(allocateObject)) {
890         return true;
891       }
892     }
893     return false;
894   }
895   bool operator()(const parser::CallStmt &stmt) {
896     const auto &procedureDesignator{
897         std::get<parser::ProcedureDesignator>(stmt.v.t)};
898     if (auto *name{std::get_if<parser::Name>(&procedureDesignator.u)}) {
899       // TODO: also ensure that the procedure is, in fact, an intrinsic
900       if (name->source == "move_alloc") {
901         const auto &args{std::get<std::list<parser::ActualArgSpec>>(stmt.v.t)};
902         if (!args.empty()) {
903           const parser::ActualArg &actualArg{
904               std::get<parser::ActualArg>(args.front().t)};
905           if (const auto *argExpr{
906                   std::get_if<common::Indirection<parser::Expr>>(
907                       &actualArg.u)}) {
908             return HasCoarray(argExpr->value());
909           }
910         }
911       }
912     }
913     return false;
914   }
915   bool operator()(const parser::Statement<parser::ActionStmt> &stmt) {
916     return std::visit(*this, stmt.statement.u);
917   }
918 
919 private:
920   bool IsCoarrayObject(const parser::AllocateObject &allocateObject) {
921     const parser::Name &name{GetLastName(allocateObject)};
922     return name.symbol && evaluate::IsCoarray(*name.symbol);
923   }
924 };
925 
926 bool IsImageControlStmt(const parser::ExecutableConstruct &construct) {
927   return std::visit(ImageControlStmtHelper{}, construct.u);
928 }
929 
930 std::optional<parser::MessageFixedText> GetImageControlStmtCoarrayMsg(
931     const parser::ExecutableConstruct &construct) {
932   if (const auto *actionStmt{
933           std::get_if<parser::Statement<parser::ActionStmt>>(&construct.u)}) {
934     return std::visit(
935         common::visitors{
936             [](const common::Indirection<parser::AllocateStmt> &)
937                 -> std::optional<parser::MessageFixedText> {
938               return "ALLOCATE of a coarray is an image control"
939                      " statement"_en_US;
940             },
941             [](const common::Indirection<parser::DeallocateStmt> &)
942                 -> std::optional<parser::MessageFixedText> {
943               return "DEALLOCATE of a coarray is an image control"
944                      " statement"_en_US;
945             },
946             [](const common::Indirection<parser::CallStmt> &)
947                 -> std::optional<parser::MessageFixedText> {
948               return "MOVE_ALLOC of a coarray is an image control"
949                      " statement "_en_US;
950             },
951             [](const auto &) -> std::optional<parser::MessageFixedText> {
952               return std::nullopt;
953             },
954         },
955         actionStmt->statement.u);
956   }
957   return std::nullopt;
958 }
959 
960 parser::CharBlock GetImageControlStmtLocation(
961     const parser::ExecutableConstruct &executableConstruct) {
962   return std::visit(
963       common::visitors{
964           [](const common::Indirection<parser::ChangeTeamConstruct>
965                   &construct) {
966             return std::get<parser::Statement<parser::ChangeTeamStmt>>(
967                 construct.value().t)
968                 .source;
969           },
970           [](const common::Indirection<parser::CriticalConstruct> &construct) {
971             return std::get<parser::Statement<parser::CriticalStmt>>(
972                 construct.value().t)
973                 .source;
974           },
975           [](const parser::Statement<parser::ActionStmt> &actionStmt) {
976             return actionStmt.source;
977           },
978           [](const auto &) { return parser::CharBlock{}; },
979       },
980       executableConstruct.u);
981 }
982 
983 bool HasCoarray(const parser::Expr &expression) {
984   if (const auto *expr{GetExpr(expression)}) {
985     for (const Symbol &symbol : evaluate::CollectSymbols(*expr)) {
986       if (evaluate::IsCoarray(symbol)) {
987         return true;
988       }
989     }
990   }
991   return false;
992 }
993 
994 bool IsPolymorphic(const Symbol &symbol) {
995   if (const DeclTypeSpec * type{symbol.GetType()}) {
996     return type->IsPolymorphic();
997   }
998   return false;
999 }
1000 
1001 bool IsPolymorphicAllocatable(const Symbol &symbol) {
1002   return IsAllocatable(symbol) && IsPolymorphic(symbol);
1003 }
1004 
1005 std::optional<parser::MessageFormattedText> CheckAccessibleComponent(
1006     const Scope &scope, const Symbol &symbol) {
1007   CHECK(symbol.owner().IsDerivedType()); // symbol must be a component
1008   if (symbol.attrs().test(Attr::PRIVATE)) {
1009     if (FindModuleFileContaining(scope)) {
1010       // Don't enforce component accessibility checks in module files;
1011       // there may be forward-substituted named constants of derived type
1012       // whose structure constructors reference private components.
1013     } else if (const Scope *
1014         moduleScope{FindModuleContaining(symbol.owner())}) {
1015       if (!moduleScope->Contains(scope)) {
1016         return parser::MessageFormattedText{
1017             "PRIVATE component '%s' is only accessible within module '%s'"_err_en_US,
1018             symbol.name(), moduleScope->GetName().value()};
1019       }
1020     }
1021   }
1022   return std::nullopt;
1023 }
1024 
1025 std::list<SourceName> OrderParameterNames(const Symbol &typeSymbol) {
1026   std::list<SourceName> result;
1027   if (const DerivedTypeSpec * spec{typeSymbol.GetParentTypeSpec()}) {
1028     result = OrderParameterNames(spec->typeSymbol());
1029   }
1030   const auto &paramNames{typeSymbol.get<DerivedTypeDetails>().paramNames()};
1031   result.insert(result.end(), paramNames.begin(), paramNames.end());
1032   return result;
1033 }
1034 
1035 SymbolVector OrderParameterDeclarations(const Symbol &typeSymbol) {
1036   SymbolVector result;
1037   if (const DerivedTypeSpec * spec{typeSymbol.GetParentTypeSpec()}) {
1038     result = OrderParameterDeclarations(spec->typeSymbol());
1039   }
1040   const auto &paramDecls{typeSymbol.get<DerivedTypeDetails>().paramDecls()};
1041   result.insert(result.end(), paramDecls.begin(), paramDecls.end());
1042   return result;
1043 }
1044 
1045 const DeclTypeSpec &FindOrInstantiateDerivedType(
1046     Scope &scope, DerivedTypeSpec &&spec, DeclTypeSpec::Category category) {
1047   spec.EvaluateParameters(scope.context());
1048   if (const DeclTypeSpec *
1049       type{scope.FindInstantiatedDerivedType(spec, category)}) {
1050     return *type;
1051   }
1052   // Create a new instantiation of this parameterized derived type
1053   // for this particular distinct set of actual parameter values.
1054   DeclTypeSpec &type{scope.MakeDerivedType(category, std::move(spec))};
1055   type.derivedTypeSpec().Instantiate(scope);
1056   return type;
1057 }
1058 
1059 const Symbol *FindSeparateModuleSubprogramInterface(const Symbol *proc) {
1060   if (proc) {
1061     if (const auto *subprogram{proc->detailsIf<SubprogramDetails>()}) {
1062       if (const Symbol * iface{subprogram->moduleInterface()}) {
1063         return iface;
1064       }
1065     }
1066   }
1067   return nullptr;
1068 }
1069 
1070 ProcedureDefinitionClass ClassifyProcedure(const Symbol &symbol) { // 15.2.2
1071   const Symbol &ultimate{symbol.GetUltimate()};
1072   if (ultimate.attrs().test(Attr::INTRINSIC)) {
1073     return ProcedureDefinitionClass::Intrinsic;
1074   } else if (ultimate.attrs().test(Attr::EXTERNAL)) {
1075     return ProcedureDefinitionClass::External;
1076   } else if (const auto *procDetails{ultimate.detailsIf<ProcEntityDetails>()}) {
1077     if (procDetails->isDummy()) {
1078       return ProcedureDefinitionClass::Dummy;
1079     } else if (IsPointer(ultimate)) {
1080       return ProcedureDefinitionClass::Pointer;
1081     }
1082   } else if (const Symbol * subp{FindSubprogram(symbol)}) {
1083     if (const auto *subpDetails{subp->detailsIf<SubprogramDetails>()}) {
1084       if (subpDetails->stmtFunction()) {
1085         return ProcedureDefinitionClass::StatementFunction;
1086       }
1087     }
1088     switch (ultimate.owner().kind()) {
1089     case Scope::Kind::Global:
1090     case Scope::Kind::IntrinsicModules:
1091       return ProcedureDefinitionClass::External;
1092     case Scope::Kind::Module:
1093       return ProcedureDefinitionClass::Module;
1094     case Scope::Kind::MainProgram:
1095     case Scope::Kind::Subprogram:
1096       return ProcedureDefinitionClass::Internal;
1097     default:
1098       break;
1099     }
1100   }
1101   return ProcedureDefinitionClass::None;
1102 }
1103 
1104 // ComponentIterator implementation
1105 
1106 template <ComponentKind componentKind>
1107 typename ComponentIterator<componentKind>::const_iterator
1108 ComponentIterator<componentKind>::const_iterator::Create(
1109     const DerivedTypeSpec &derived) {
1110   const_iterator it{};
1111   it.componentPath_.emplace_back(derived);
1112   it.Increment(); // cue up first relevant component, if any
1113   return it;
1114 }
1115 
1116 template <ComponentKind componentKind>
1117 const DerivedTypeSpec *
1118 ComponentIterator<componentKind>::const_iterator::PlanComponentTraversal(
1119     const Symbol &component) const {
1120   if (const auto *details{component.detailsIf<ObjectEntityDetails>()}) {
1121     if (const DeclTypeSpec * type{details->type()}) {
1122       if (const auto *derived{type->AsDerived()}) {
1123         bool traverse{false};
1124         if constexpr (componentKind == ComponentKind::Ordered) {
1125           // Order Component (only visit parents)
1126           traverse = component.test(Symbol::Flag::ParentComp);
1127         } else if constexpr (componentKind == ComponentKind::Direct) {
1128           traverse = !IsAllocatableOrPointer(component);
1129         } else if constexpr (componentKind == ComponentKind::Ultimate) {
1130           traverse = !IsAllocatableOrPointer(component);
1131         } else if constexpr (componentKind == ComponentKind::Potential) {
1132           traverse = !IsPointer(component);
1133         } else if constexpr (componentKind == ComponentKind::Scope) {
1134           traverse = !IsAllocatableOrPointer(component);
1135         }
1136         if (traverse) {
1137           const Symbol &newTypeSymbol{derived->typeSymbol()};
1138           // Avoid infinite loop if the type is already part of the types
1139           // being visited. It is possible to have "loops in type" because
1140           // C744 does not forbid to use not yet declared type for
1141           // ALLOCATABLE or POINTER components.
1142           for (const auto &node : componentPath_) {
1143             if (&newTypeSymbol == &node.GetTypeSymbol()) {
1144               return nullptr;
1145             }
1146           }
1147           return derived;
1148         }
1149       }
1150     } // intrinsic & unlimited polymorphic not traversable
1151   }
1152   return nullptr;
1153 }
1154 
1155 template <ComponentKind componentKind>
1156 static bool StopAtComponentPre(const Symbol &component) {
1157   if constexpr (componentKind == ComponentKind::Ordered) {
1158     // Parent components need to be iterated upon after their
1159     // sub-components in structure constructor analysis.
1160     return !component.test(Symbol::Flag::ParentComp);
1161   } else if constexpr (componentKind == ComponentKind::Direct) {
1162     return true;
1163   } else if constexpr (componentKind == ComponentKind::Ultimate) {
1164     return component.has<ProcEntityDetails>() ||
1165         IsAllocatableOrPointer(component) ||
1166         (component.get<ObjectEntityDetails>().type() &&
1167             component.get<ObjectEntityDetails>().type()->AsIntrinsic());
1168   } else if constexpr (componentKind == ComponentKind::Potential) {
1169     return !IsPointer(component);
1170   }
1171 }
1172 
1173 template <ComponentKind componentKind>
1174 static bool StopAtComponentPost(const Symbol &component) {
1175   return componentKind == ComponentKind::Ordered &&
1176       component.test(Symbol::Flag::ParentComp);
1177 }
1178 
1179 template <ComponentKind componentKind>
1180 void ComponentIterator<componentKind>::const_iterator::Increment() {
1181   while (!componentPath_.empty()) {
1182     ComponentPathNode &deepest{componentPath_.back()};
1183     if (deepest.component()) {
1184       if (!deepest.descended()) {
1185         deepest.set_descended(true);
1186         if (const DerivedTypeSpec *
1187             derived{PlanComponentTraversal(*deepest.component())}) {
1188           componentPath_.emplace_back(*derived);
1189           continue;
1190         }
1191       } else if (!deepest.visited()) {
1192         deepest.set_visited(true);
1193         return; // this is the next component to visit, after descending
1194       }
1195     }
1196     auto &nameIterator{deepest.nameIterator()};
1197     if (nameIterator == deepest.nameEnd()) {
1198       componentPath_.pop_back();
1199     } else if constexpr (componentKind == ComponentKind::Scope) {
1200       deepest.set_component(*nameIterator++->second);
1201       deepest.set_descended(false);
1202       deepest.set_visited(true);
1203       return; // this is the next component to visit, before descending
1204     } else {
1205       const Scope &scope{deepest.GetScope()};
1206       auto scopeIter{scope.find(*nameIterator++)};
1207       if (scopeIter != scope.cend()) {
1208         const Symbol &component{*scopeIter->second};
1209         deepest.set_component(component);
1210         deepest.set_descended(false);
1211         if (StopAtComponentPre<componentKind>(component)) {
1212           deepest.set_visited(true);
1213           return; // this is the next component to visit, before descending
1214         } else {
1215           deepest.set_visited(!StopAtComponentPost<componentKind>(component));
1216         }
1217       }
1218     }
1219   }
1220 }
1221 
1222 template <ComponentKind componentKind>
1223 std::string
1224 ComponentIterator<componentKind>::const_iterator::BuildResultDesignatorName()
1225     const {
1226   std::string designator{""};
1227   for (const auto &node : componentPath_) {
1228     designator += "%" + DEREF(node.component()).name().ToString();
1229   }
1230   return designator;
1231 }
1232 
1233 template class ComponentIterator<ComponentKind::Ordered>;
1234 template class ComponentIterator<ComponentKind::Direct>;
1235 template class ComponentIterator<ComponentKind::Ultimate>;
1236 template class ComponentIterator<ComponentKind::Potential>;
1237 template class ComponentIterator<ComponentKind::Scope>;
1238 
1239 UltimateComponentIterator::const_iterator FindCoarrayUltimateComponent(
1240     const DerivedTypeSpec &derived) {
1241   UltimateComponentIterator ultimates{derived};
1242   return std::find_if(ultimates.begin(), ultimates.end(),
1243       [](const Symbol &symbol) { return evaluate::IsCoarray(symbol); });
1244 }
1245 
1246 UltimateComponentIterator::const_iterator FindPointerUltimateComponent(
1247     const DerivedTypeSpec &derived) {
1248   UltimateComponentIterator ultimates{derived};
1249   return std::find_if(ultimates.begin(), ultimates.end(), IsPointer);
1250 }
1251 
1252 PotentialComponentIterator::const_iterator FindEventOrLockPotentialComponent(
1253     const DerivedTypeSpec &derived) {
1254   PotentialComponentIterator potentials{derived};
1255   return std::find_if(
1256       potentials.begin(), potentials.end(), [](const Symbol &component) {
1257         if (const auto *details{component.detailsIf<ObjectEntityDetails>()}) {
1258           const DeclTypeSpec *type{details->type()};
1259           return type && IsEventTypeOrLockType(type->AsDerived());
1260         }
1261         return false;
1262       });
1263 }
1264 
1265 UltimateComponentIterator::const_iterator FindAllocatableUltimateComponent(
1266     const DerivedTypeSpec &derived) {
1267   UltimateComponentIterator ultimates{derived};
1268   return std::find_if(ultimates.begin(), ultimates.end(), IsAllocatable);
1269 }
1270 
1271 DirectComponentIterator::const_iterator FindAllocatableOrPointerDirectComponent(
1272     const DerivedTypeSpec &derived) {
1273   DirectComponentIterator directs{derived};
1274   return std::find_if(directs.begin(), directs.end(), IsAllocatableOrPointer);
1275 }
1276 
1277 UltimateComponentIterator::const_iterator
1278 FindPolymorphicAllocatableUltimateComponent(const DerivedTypeSpec &derived) {
1279   UltimateComponentIterator ultimates{derived};
1280   return std::find_if(
1281       ultimates.begin(), ultimates.end(), IsPolymorphicAllocatable);
1282 }
1283 
1284 UltimateComponentIterator::const_iterator
1285 FindPolymorphicAllocatableNonCoarrayUltimateComponent(
1286     const DerivedTypeSpec &derived) {
1287   UltimateComponentIterator ultimates{derived};
1288   return std::find_if(ultimates.begin(), ultimates.end(), [](const Symbol &x) {
1289     return IsPolymorphicAllocatable(x) && !evaluate::IsCoarray(x);
1290   });
1291 }
1292 
1293 const Symbol *FindUltimateComponent(const DerivedTypeSpec &derived,
1294     const std::function<bool(const Symbol &)> &predicate) {
1295   UltimateComponentIterator ultimates{derived};
1296   if (auto it{std::find_if(ultimates.begin(), ultimates.end(),
1297           [&predicate](const Symbol &component) -> bool {
1298             return predicate(component);
1299           })}) {
1300     return &*it;
1301   }
1302   return nullptr;
1303 }
1304 
1305 const Symbol *FindUltimateComponent(const Symbol &symbol,
1306     const std::function<bool(const Symbol &)> &predicate) {
1307   if (predicate(symbol)) {
1308     return &symbol;
1309   } else if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
1310     if (const auto *type{object->type()}) {
1311       if (const auto *derived{type->AsDerived()}) {
1312         return FindUltimateComponent(*derived, predicate);
1313       }
1314     }
1315   }
1316   return nullptr;
1317 }
1318 
1319 const Symbol *FindImmediateComponent(const DerivedTypeSpec &type,
1320     const std::function<bool(const Symbol &)> &predicate) {
1321   if (const Scope * scope{type.scope()}) {
1322     const Symbol *parent{nullptr};
1323     for (const auto &pair : *scope) {
1324       const Symbol *symbol{&*pair.second};
1325       if (predicate(*symbol)) {
1326         return symbol;
1327       }
1328       if (symbol->test(Symbol::Flag::ParentComp)) {
1329         parent = symbol;
1330       }
1331     }
1332     if (parent) {
1333       if (const auto *object{parent->detailsIf<ObjectEntityDetails>()}) {
1334         if (const auto *type{object->type()}) {
1335           if (const auto *derived{type->AsDerived()}) {
1336             return FindImmediateComponent(*derived, predicate);
1337           }
1338         }
1339       }
1340     }
1341   }
1342   return nullptr;
1343 }
1344 
1345 const Symbol *IsFunctionResultWithSameNameAsFunction(const Symbol &symbol) {
1346   if (IsFunctionResult(symbol)) {
1347     if (const Symbol * function{symbol.owner().symbol()}) {
1348       if (symbol.name() == function->name()) {
1349         return function;
1350       }
1351     }
1352   }
1353   return nullptr;
1354 }
1355 
1356 void LabelEnforce::Post(const parser::GotoStmt &gotoStmt) {
1357   checkLabelUse(gotoStmt.v);
1358 }
1359 void LabelEnforce::Post(const parser::ComputedGotoStmt &computedGotoStmt) {
1360   for (auto &i : std::get<std::list<parser::Label>>(computedGotoStmt.t)) {
1361     checkLabelUse(i);
1362   }
1363 }
1364 
1365 void LabelEnforce::Post(const parser::ArithmeticIfStmt &arithmeticIfStmt) {
1366   checkLabelUse(std::get<1>(arithmeticIfStmt.t));
1367   checkLabelUse(std::get<2>(arithmeticIfStmt.t));
1368   checkLabelUse(std::get<3>(arithmeticIfStmt.t));
1369 }
1370 
1371 void LabelEnforce::Post(const parser::AssignStmt &assignStmt) {
1372   checkLabelUse(std::get<parser::Label>(assignStmt.t));
1373 }
1374 
1375 void LabelEnforce::Post(const parser::AssignedGotoStmt &assignedGotoStmt) {
1376   for (auto &i : std::get<std::list<parser::Label>>(assignedGotoStmt.t)) {
1377     checkLabelUse(i);
1378   }
1379 }
1380 
1381 void LabelEnforce::Post(const parser::AltReturnSpec &altReturnSpec) {
1382   checkLabelUse(altReturnSpec.v);
1383 }
1384 
1385 void LabelEnforce::Post(const parser::ErrLabel &errLabel) {
1386   checkLabelUse(errLabel.v);
1387 }
1388 void LabelEnforce::Post(const parser::EndLabel &endLabel) {
1389   checkLabelUse(endLabel.v);
1390 }
1391 void LabelEnforce::Post(const parser::EorLabel &eorLabel) {
1392   checkLabelUse(eorLabel.v);
1393 }
1394 
1395 void LabelEnforce::checkLabelUse(const parser::Label &labelUsed) {
1396   if (labels_.find(labelUsed) == labels_.end()) {
1397     SayWithConstruct(context_, currentStatementSourcePosition_,
1398         parser::MessageFormattedText{
1399             "Control flow escapes from %s"_err_en_US, construct_},
1400         constructSourcePosition_);
1401   }
1402 }
1403 
1404 parser::MessageFormattedText LabelEnforce::GetEnclosingConstructMsg() {
1405   return {"Enclosing %s statement"_en_US, construct_};
1406 }
1407 
1408 void LabelEnforce::SayWithConstruct(SemanticsContext &context,
1409     parser::CharBlock stmtLocation, parser::MessageFormattedText &&message,
1410     parser::CharBlock constructLocation) {
1411   context.Say(stmtLocation, message)
1412       .Attach(constructLocation, GetEnclosingConstructMsg());
1413 }
1414 
1415 bool HasAlternateReturns(const Symbol &subprogram) {
1416   for (const auto *dummyArg : subprogram.get<SubprogramDetails>().dummyArgs()) {
1417     if (!dummyArg) {
1418       return true;
1419     }
1420   }
1421   return false;
1422 }
1423 
1424 bool InCommonBlock(const Symbol &symbol) {
1425   const auto *details{symbol.detailsIf<ObjectEntityDetails>()};
1426   return details && details->commonBlock();
1427 }
1428 
1429 const std::optional<parser::Name> &MaybeGetNodeName(
1430     const ConstructNode &construct) {
1431   return std::visit(
1432       common::visitors{
1433           [&](const parser::BlockConstruct *blockConstruct)
1434               -> const std::optional<parser::Name> & {
1435             return std::get<0>(blockConstruct->t).statement.v;
1436           },
1437           [&](const auto *a) -> const std::optional<parser::Name> & {
1438             return std::get<0>(std::get<0>(a->t).statement.t);
1439           },
1440       },
1441       construct);
1442 }
1443 
1444 std::optional<ArraySpec> ToArraySpec(
1445     evaluate::FoldingContext &context, const evaluate::Shape &shape) {
1446   if (auto extents{evaluate::AsConstantExtents(context, shape)}) {
1447     ArraySpec result;
1448     for (const auto &extent : *extents) {
1449       result.emplace_back(ShapeSpec::MakeExplicit(Bound{extent}));
1450     }
1451     return {std::move(result)};
1452   } else {
1453     return std::nullopt;
1454   }
1455 }
1456 
1457 std::optional<ArraySpec> ToArraySpec(evaluate::FoldingContext &context,
1458     const std::optional<evaluate::Shape> &shape) {
1459   return shape ? ToArraySpec(context, *shape) : std::nullopt;
1460 }
1461 
1462 bool HasDefinedIo(GenericKind::DefinedIo which, const DerivedTypeSpec &derived,
1463     const Scope *scope) {
1464   if (const Scope * dtScope{derived.scope()}) {
1465     for (const auto &pair : *dtScope) {
1466       const Symbol &symbol{*pair.second};
1467       if (const auto *generic{symbol.detailsIf<GenericDetails>()}) {
1468         GenericKind kind{generic->kind()};
1469         if (const auto *io{std::get_if<GenericKind::DefinedIo>(&kind.u)}) {
1470           if (*io == which) {
1471             return true; // type-bound GENERIC exists
1472           }
1473         }
1474       }
1475     }
1476   }
1477   if (scope) {
1478     SourceName name{GenericKind::AsFortran(which)};
1479     evaluate::DynamicType dyDerived{derived};
1480     for (; scope && !scope->IsGlobal(); scope = &scope->parent()) {
1481       auto iter{scope->find(name)};
1482       if (iter != scope->end()) {
1483         const auto &generic{iter->second->GetUltimate().get<GenericDetails>()};
1484         for (auto ref : generic.specificProcs()) {
1485           const Symbol &procSym{ref->GetUltimate()};
1486           if (const auto *subp{procSym.detailsIf<SubprogramDetails>()}) {
1487             if (!subp->dummyArgs().empty()) {
1488               if (const Symbol * first{subp->dummyArgs().at(0)}) {
1489                 if (const DeclTypeSpec * dtSpec{first->GetType()}) {
1490                   if (auto dyDummy{evaluate::DynamicType::From(*dtSpec)}) {
1491                     if (dyDummy->IsTkCompatibleWith(dyDerived)) {
1492                       return true; // GENERIC or INTERFACE not in type
1493                     }
1494                   }
1495                 }
1496               }
1497             }
1498           }
1499         }
1500       }
1501     }
1502   }
1503   return false;
1504 }
1505 
1506 const Symbol *FindUnsafeIoDirectComponent(GenericKind::DefinedIo which,
1507     const DerivedTypeSpec &derived, const Scope *scope) {
1508   if (HasDefinedIo(which, derived, scope)) {
1509     return nullptr;
1510   }
1511   if (const Scope * dtScope{derived.scope()}) {
1512     for (const auto &pair : *dtScope) {
1513       const Symbol &symbol{*pair.second};
1514       if (IsAllocatableOrPointer(symbol)) {
1515         return &symbol;
1516       }
1517       if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) {
1518         if (const DeclTypeSpec * type{details->type()}) {
1519           if (type->category() == DeclTypeSpec::Category::TypeDerived) {
1520             if (const Symbol *
1521                 bad{FindUnsafeIoDirectComponent(
1522                     which, type->derivedTypeSpec(), scope)}) {
1523               return bad;
1524             }
1525           }
1526         }
1527       }
1528     }
1529   }
1530   return nullptr;
1531 }
1532 
1533 } // namespace Fortran::semantics
1534