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