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->IsGlobal()) {
35       return nullptr;
36     }
37   }
38 }
39 
40 const Scope &GetTopLevelUnitContaining(const Scope &start) {
41   CHECK(!start.IsGlobal());
42   return DEREF(FindScopeContaining(
43       start, [](const Scope &scope) { return scope.parent().IsGlobal(); }));
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.IsGlobal());
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.IsGlobal()) {
84     return nullptr;
85   } else {
86     const Scope &scope{GetProgramUnitContaining(start)};
87     return IsPureProcedure(scope) ? &scope : nullptr;
88   }
89 }
90 
91 static bool MightHaveCompatibleDerivedtypes(
92     const std::optional<evaluate::DynamicType> &lhsType,
93     const std::optional<evaluate::DynamicType> &rhsType) {
94   const DerivedTypeSpec *lhsDerived{evaluate::GetDerivedTypeSpec(lhsType)};
95   const DerivedTypeSpec *rhsDerived{evaluate::GetDerivedTypeSpec(rhsType)};
96   if (!lhsDerived || !rhsDerived) {
97     return false;
98   }
99   return *lhsDerived == *rhsDerived ||
100       lhsDerived->MightBeAssignmentCompatibleWith(*rhsDerived);
101 }
102 
103 Tristate IsDefinedAssignment(
104     const std::optional<evaluate::DynamicType> &lhsType, int lhsRank,
105     const std::optional<evaluate::DynamicType> &rhsType, int rhsRank) {
106   if (!lhsType || !rhsType) {
107     return Tristate::No; // error or rhs is untyped
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 (MightHaveCompatibleDerivedtypes(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.IsGlobal() &&
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 bool IsExtensibleType(const DerivedTypeSpec *derived) {
511   return derived && !IsIsoCType(derived) &&
512       !derived->typeSymbol().attrs().test(Attr::BIND_C) &&
513       !derived->typeSymbol().get<DerivedTypeDetails>().sequence();
514 }
515 
516 bool IsBuiltinDerivedType(const DerivedTypeSpec *derived, const char *name) {
517   if (!derived) {
518     return false;
519   } else {
520     const auto &symbol{derived->typeSymbol()};
521     return symbol.owner().IsModule() &&
522         (symbol.owner().GetName().value() == "__fortran_builtins" ||
523             symbol.owner().GetName().value() == "__fortran_type_info") &&
524         symbol.name() == "__builtin_"s + name;
525   }
526 }
527 
528 bool IsIsoCType(const DerivedTypeSpec *derived) {
529   return IsBuiltinDerivedType(derived, "c_ptr") ||
530       IsBuiltinDerivedType(derived, "c_funptr");
531 }
532 
533 bool IsTeamType(const DerivedTypeSpec *derived) {
534   return IsBuiltinDerivedType(derived, "team_type");
535 }
536 
537 bool IsEventTypeOrLockType(const DerivedTypeSpec *derivedTypeSpec) {
538   return IsBuiltinDerivedType(derivedTypeSpec, "event_type") ||
539       IsBuiltinDerivedType(derivedTypeSpec, "lock_type");
540 }
541 
542 bool IsOrContainsEventOrLockComponent(const Symbol &original) {
543   const Symbol &symbol{ResolveAssociations(original)};
544   if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) {
545     if (const DeclTypeSpec * type{details->type()}) {
546       if (const DerivedTypeSpec * derived{type->AsDerived()}) {
547         return IsEventTypeOrLockType(derived) ||
548             FindEventOrLockPotentialComponent(*derived);
549       }
550     }
551   }
552   return false;
553 }
554 
555 // Check this symbol suitable as a type-bound procedure - C769
556 bool CanBeTypeBoundProc(const Symbol *symbol) {
557   if (!symbol || IsDummy(*symbol) || IsProcedurePointer(*symbol)) {
558     return false;
559   } else if (symbol->has<SubprogramNameDetails>()) {
560     return symbol->owner().kind() == Scope::Kind::Module;
561   } else if (auto *details{symbol->detailsIf<SubprogramDetails>()}) {
562     return symbol->owner().kind() == Scope::Kind::Module ||
563         details->isInterface();
564   } else if (const auto *proc{symbol->detailsIf<ProcEntityDetails>()}) {
565     return !symbol->attrs().test(Attr::INTRINSIC) &&
566         proc->HasExplicitInterface();
567   } else {
568     return false;
569   }
570 }
571 
572 bool IsStaticallyInitialized(const Symbol &symbol, bool ignoreDATAstatements) {
573   if (!ignoreDATAstatements && symbol.test(Symbol::Flag::InDataStmt)) {
574     return true;
575   } else if (IsNamedConstant(symbol)) {
576     return false;
577   } else if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
578     return object->init().has_value();
579   } else if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}) {
580     return proc->init().has_value();
581   }
582   return false;
583 }
584 
585 bool IsInitialized(const Symbol &symbol, bool ignoreDATAstatements,
586     const Symbol *derivedTypeSymbol) {
587   if (IsStaticallyInitialized(symbol, ignoreDATAstatements) ||
588       IsAllocatable(symbol)) {
589     return true;
590   } else if (IsNamedConstant(symbol) || IsFunctionResult(symbol) ||
591       IsPointer(symbol)) {
592     return false;
593   } else if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
594     if (!object->isDummy() && object->type()) {
595       const auto *derived{object->type()->AsDerived()};
596       // error recovery: avoid infinite recursion on invalid
597       // recursive usage of a derived type
598       return derived && &derived->typeSymbol() != derivedTypeSymbol &&
599           derived->HasDefaultInitialization();
600     }
601   }
602   return false;
603 }
604 
605 bool IsDestructible(const Symbol &symbol, const Symbol *derivedTypeSymbol) {
606   if (IsAllocatable(symbol) || IsAutomatic(symbol)) {
607     return true;
608   } else if (IsNamedConstant(symbol) || IsFunctionResult(symbol) ||
609       IsPointer(symbol)) {
610     return false;
611   } else if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
612     if (!object->isDummy() && object->type()) {
613       if (const auto *derived{object->type()->AsDerived()}) {
614         return &derived->typeSymbol() != derivedTypeSymbol &&
615             derived->HasDestruction();
616       }
617     }
618   }
619   return false;
620 }
621 
622 bool HasIntrinsicTypeName(const Symbol &symbol) {
623   std::string name{symbol.name().ToString()};
624   if (name == "doubleprecision") {
625     return true;
626   } else if (name == "derived") {
627     return false;
628   } else {
629     for (int i{0}; i != common::TypeCategory_enumSize; ++i) {
630       if (name == parser::ToLowerCaseLetters(EnumToString(TypeCategory{i}))) {
631         return true;
632       }
633     }
634     return false;
635   }
636 }
637 
638 bool IsSeparateModuleProcedureInterface(const Symbol *symbol) {
639   if (symbol && symbol->attrs().test(Attr::MODULE)) {
640     if (auto *details{symbol->detailsIf<SubprogramDetails>()}) {
641       return details->isInterface();
642     }
643   }
644   return false;
645 }
646 
647 // 3.11 automatic data object
648 bool IsAutomatic(const Symbol &symbol) {
649   if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
650     if (!object->isDummy() && !IsAllocatable(symbol) && !IsPointer(symbol)) {
651       if (const DeclTypeSpec * type{symbol.GetType()}) {
652         // If a type parameter value is not a constant expression, the
653         // object is automatic.
654         if (type->category() == DeclTypeSpec::Character) {
655           if (const auto &length{
656                   type->characterTypeSpec().length().GetExplicit()}) {
657             if (!evaluate::IsConstantExpr(*length)) {
658               return true;
659             }
660           }
661         } else if (const DerivedTypeSpec * derived{type->AsDerived()}) {
662           for (const auto &pair : derived->parameters()) {
663             if (const auto &value{pair.second.GetExplicit()}) {
664               if (!evaluate::IsConstantExpr(*value)) {
665                 return true;
666               }
667             }
668           }
669         }
670       }
671       // If an array bound is not a constant expression, the object is
672       // automatic.
673       for (const ShapeSpec &dim : object->shape()) {
674         if (const auto &lb{dim.lbound().GetExplicit()}) {
675           if (!evaluate::IsConstantExpr(*lb)) {
676             return true;
677           }
678         }
679         if (const auto &ub{dim.ubound().GetExplicit()}) {
680           if (!evaluate::IsConstantExpr(*ub)) {
681             return true;
682           }
683         }
684       }
685     }
686   }
687   return false;
688 }
689 
690 bool IsFinalizable(
691     const Symbol &symbol, std::set<const DerivedTypeSpec *> *inProgress) {
692   if (IsPointer(symbol)) {
693     return false;
694   }
695   if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
696     if (object->isDummy() && !IsIntentOut(symbol)) {
697       return false;
698     }
699     const DeclTypeSpec *type{object->type()};
700     const DerivedTypeSpec *typeSpec{type ? type->AsDerived() : nullptr};
701     return typeSpec && IsFinalizable(*typeSpec, inProgress);
702   }
703   return false;
704 }
705 
706 bool IsFinalizable(const DerivedTypeSpec &derived,
707     std::set<const DerivedTypeSpec *> *inProgress) {
708   if (!derived.typeSymbol().get<DerivedTypeDetails>().finals().empty()) {
709     return true;
710   }
711   std::set<const DerivedTypeSpec *> basis;
712   if (inProgress) {
713     if (inProgress->find(&derived) != inProgress->end()) {
714       return false; // don't loop on recursive type
715     }
716   } else {
717     inProgress = &basis;
718   }
719   auto iterator{inProgress->insert(&derived).first};
720   PotentialComponentIterator components{derived};
721   bool result{bool{std::find_if(
722       components.begin(), components.end(), [=](const Symbol &component) {
723         return IsFinalizable(component, inProgress);
724       })}};
725   inProgress->erase(iterator);
726   return result;
727 }
728 
729 bool HasImpureFinal(const DerivedTypeSpec &derived) {
730   if (const auto *details{
731           derived.typeSymbol().detailsIf<DerivedTypeDetails>()}) {
732     const auto &finals{details->finals()};
733     return std::any_of(finals.begin(), finals.end(),
734         [](const auto &x) { return !x.second->attrs().test(Attr::PURE); });
735   } else {
736     return false;
737   }
738 }
739 
740 bool IsCoarray(const Symbol &symbol) { return symbol.Corank() > 0; }
741 
742 bool IsAutomaticObject(const Symbol &symbol) {
743   if (IsDummy(symbol) || IsPointer(symbol) || IsAllocatable(symbol)) {
744     return false;
745   }
746   if (const DeclTypeSpec * type{symbol.GetType()}) {
747     if (type->category() == DeclTypeSpec::Character) {
748       ParamValue length{type->characterTypeSpec().length()};
749       if (length.isExplicit()) {
750         if (MaybeIntExpr lengthExpr{length.GetExplicit()}) {
751           if (!ToInt64(lengthExpr)) {
752             return true;
753           }
754         }
755       }
756     }
757   }
758   if (symbol.IsObjectArray()) {
759     for (const ShapeSpec &spec : symbol.get<ObjectEntityDetails>().shape()) {
760       auto &lbound{spec.lbound().GetExplicit()};
761       auto &ubound{spec.ubound().GetExplicit()};
762       if ((lbound && !evaluate::ToInt64(*lbound)) ||
763           (ubound && !evaluate::ToInt64(*ubound))) {
764         return true;
765       }
766     }
767   }
768   return false;
769 }
770 
771 bool IsAssumedLengthCharacter(const Symbol &symbol) {
772   if (const DeclTypeSpec * type{symbol.GetType()}) {
773     return type->category() == DeclTypeSpec::Character &&
774         type->characterTypeSpec().length().isAssumed();
775   } else {
776     return false;
777   }
778 }
779 
780 bool IsInBlankCommon(const Symbol &symbol) {
781   const Symbol *block{FindCommonBlockContaining(symbol)};
782   return block && block->name().empty();
783 }
784 
785 // C722 and C723:  For a function to be assumed length, it must be external and
786 // of CHARACTER type
787 bool IsExternal(const Symbol &symbol) {
788   return ClassifyProcedure(symbol) == ProcedureDefinitionClass::External;
789 }
790 
791 bool IsModuleProcedure(const Symbol &symbol) {
792   return ClassifyProcedure(symbol) == ProcedureDefinitionClass::Module;
793 }
794 const Symbol *IsExternalInPureContext(
795     const Symbol &symbol, const Scope &scope) {
796   if (const auto *pureProc{FindPureProcedureContaining(scope)}) {
797     return FindExternallyVisibleObject(symbol.GetUltimate(), *pureProc);
798   }
799   return nullptr;
800 }
801 
802 PotentialComponentIterator::const_iterator FindPolymorphicPotentialComponent(
803     const DerivedTypeSpec &derived) {
804   PotentialComponentIterator potentials{derived};
805   return std::find_if(
806       potentials.begin(), potentials.end(), [](const Symbol &component) {
807         if (const auto *details{component.detailsIf<ObjectEntityDetails>()}) {
808           const DeclTypeSpec *type{details->type()};
809           return type && type->IsPolymorphic();
810         }
811         return false;
812       });
813 }
814 
815 bool IsOrContainsPolymorphicComponent(const Symbol &original) {
816   const Symbol &symbol{ResolveAssociations(original)};
817   if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) {
818     if (const DeclTypeSpec * type{details->type()}) {
819       if (type->IsPolymorphic()) {
820         return true;
821       }
822       if (const DerivedTypeSpec * derived{type->AsDerived()}) {
823         return (bool)FindPolymorphicPotentialComponent(*derived);
824       }
825     }
826   }
827   return false;
828 }
829 
830 bool InProtectedContext(const Symbol &symbol, const Scope &currentScope) {
831   return IsProtected(symbol) && !IsHostAssociated(symbol, currentScope);
832 }
833 
834 // C1101 and C1158
835 // Modifiability checks on the leftmost symbol ("base object")
836 // of a data-ref
837 std::optional<parser::MessageFixedText> WhyNotModifiableFirst(
838     const Symbol &symbol, const Scope &scope) {
839   if (symbol.has<AssocEntityDetails>()) {
840     return "'%s' is construct associated with an expression"_en_US;
841   } else if (IsExternalInPureContext(symbol, scope)) {
842     return "'%s' is externally visible and referenced in a pure"
843            " procedure"_en_US;
844   } else if (!IsVariableName(symbol)) {
845     return "'%s' is not a variable"_en_US;
846   } else {
847     return std::nullopt;
848   }
849 }
850 
851 // Modifiability checks on the rightmost symbol of a data-ref
852 std::optional<parser::MessageFixedText> WhyNotModifiableLast(
853     const Symbol &symbol, const Scope &scope) {
854   if (IsOrContainsEventOrLockComponent(symbol)) {
855     return "'%s' is an entity with either an EVENT_TYPE or LOCK_TYPE"_en_US;
856   } else {
857     return std::nullopt;
858   }
859 }
860 
861 // Modifiability checks on the leftmost (base) symbol of a data-ref
862 // that apply only when there are no pointer components or a base
863 // that is a pointer.
864 std::optional<parser::MessageFixedText> WhyNotModifiableIfNoPtr(
865     const Symbol &symbol, const Scope &scope) {
866   if (InProtectedContext(symbol, scope)) {
867     return "'%s' is protected in this scope"_en_US;
868   } else if (IsIntentIn(symbol)) {
869     return "'%s' is an INTENT(IN) dummy argument"_en_US;
870   } else {
871     return std::nullopt;
872   }
873 }
874 
875 // Apply all modifiability checks to a single symbol
876 std::optional<parser::MessageFixedText> WhyNotModifiable(
877     const Symbol &original, const Scope &scope) {
878   const Symbol &symbol{GetAssociationRoot(original)};
879   if (auto first{WhyNotModifiableFirst(symbol, scope)}) {
880     return first;
881   } else if (auto last{WhyNotModifiableLast(symbol, scope)}) {
882     return last;
883   } else if (!IsPointer(symbol)) {
884     return WhyNotModifiableIfNoPtr(symbol, scope);
885   } else {
886     return std::nullopt;
887   }
888 }
889 
890 // Modifiability checks for a data-ref
891 std::optional<parser::Message> WhyNotModifiable(parser::CharBlock at,
892     const SomeExpr &expr, const Scope &scope, bool vectorSubscriptIsOk) {
893   if (auto dataRef{evaluate::ExtractDataRef(expr, true)}) {
894     if (!vectorSubscriptIsOk && evaluate::HasVectorSubscript(expr)) {
895       return parser::Message{at, "Variable has a vector subscript"_en_US};
896     }
897     const Symbol &first{GetAssociationRoot(dataRef->GetFirstSymbol())};
898     if (auto maybeWhyFirst{WhyNotModifiableFirst(first, scope)}) {
899       return parser::Message{first.name(),
900           parser::MessageFormattedText{
901               std::move(*maybeWhyFirst), first.name()}};
902     }
903     const Symbol &last{dataRef->GetLastSymbol()};
904     if (auto maybeWhyLast{WhyNotModifiableLast(last, scope)}) {
905       return parser::Message{last.name(),
906           parser::MessageFormattedText{std::move(*maybeWhyLast), last.name()}};
907     }
908     if (!GetLastPointerSymbol(*dataRef)) {
909       if (auto maybeWhyFirst{WhyNotModifiableIfNoPtr(first, scope)}) {
910         return parser::Message{first.name(),
911             parser::MessageFormattedText{
912                 std::move(*maybeWhyFirst), first.name()}};
913       }
914     }
915   } else if (!evaluate::IsVariable(expr)) {
916     return parser::Message{
917         at, "'%s' is not a variable"_en_US, expr.AsFortran()};
918   } else {
919     // reference to function returning POINTER
920   }
921   return std::nullopt;
922 }
923 
924 class ImageControlStmtHelper {
925   using ImageControlStmts = std::variant<parser::ChangeTeamConstruct,
926       parser::CriticalConstruct, parser::EventPostStmt, parser::EventWaitStmt,
927       parser::FormTeamStmt, parser::LockStmt, parser::StopStmt,
928       parser::SyncAllStmt, parser::SyncImagesStmt, parser::SyncMemoryStmt,
929       parser::SyncTeamStmt, parser::UnlockStmt>;
930 
931 public:
932   template <typename T> bool operator()(const T &) {
933     return common::HasMember<T, ImageControlStmts>;
934   }
935   template <typename T> bool operator()(const common::Indirection<T> &x) {
936     return (*this)(x.value());
937   }
938   bool operator()(const parser::AllocateStmt &stmt) {
939     const auto &allocationList{std::get<std::list<parser::Allocation>>(stmt.t)};
940     for (const auto &allocation : allocationList) {
941       const auto &allocateObject{
942           std::get<parser::AllocateObject>(allocation.t)};
943       if (IsCoarrayObject(allocateObject)) {
944         return true;
945       }
946     }
947     return false;
948   }
949   bool operator()(const parser::DeallocateStmt &stmt) {
950     const auto &allocateObjectList{
951         std::get<std::list<parser::AllocateObject>>(stmt.t)};
952     for (const auto &allocateObject : allocateObjectList) {
953       if (IsCoarrayObject(allocateObject)) {
954         return true;
955       }
956     }
957     return false;
958   }
959   bool operator()(const parser::CallStmt &stmt) {
960     const auto &procedureDesignator{
961         std::get<parser::ProcedureDesignator>(stmt.v.t)};
962     if (auto *name{std::get_if<parser::Name>(&procedureDesignator.u)}) {
963       // TODO: also ensure that the procedure is, in fact, an intrinsic
964       if (name->source == "move_alloc") {
965         const auto &args{std::get<std::list<parser::ActualArgSpec>>(stmt.v.t)};
966         if (!args.empty()) {
967           const parser::ActualArg &actualArg{
968               std::get<parser::ActualArg>(args.front().t)};
969           if (const auto *argExpr{
970                   std::get_if<common::Indirection<parser::Expr>>(
971                       &actualArg.u)}) {
972             return HasCoarray(argExpr->value());
973           }
974         }
975       }
976     }
977     return false;
978   }
979   bool operator()(const parser::Statement<parser::ActionStmt> &stmt) {
980     return std::visit(*this, stmt.statement.u);
981   }
982 
983 private:
984   bool IsCoarrayObject(const parser::AllocateObject &allocateObject) {
985     const parser::Name &name{GetLastName(allocateObject)};
986     return name.symbol && IsCoarray(*name.symbol);
987   }
988 };
989 
990 bool IsImageControlStmt(const parser::ExecutableConstruct &construct) {
991   return std::visit(ImageControlStmtHelper{}, construct.u);
992 }
993 
994 std::optional<parser::MessageFixedText> GetImageControlStmtCoarrayMsg(
995     const parser::ExecutableConstruct &construct) {
996   if (const auto *actionStmt{
997           std::get_if<parser::Statement<parser::ActionStmt>>(&construct.u)}) {
998     return std::visit(
999         common::visitors{
1000             [](const common::Indirection<parser::AllocateStmt> &)
1001                 -> std::optional<parser::MessageFixedText> {
1002               return "ALLOCATE of a coarray is an image control"
1003                      " statement"_en_US;
1004             },
1005             [](const common::Indirection<parser::DeallocateStmt> &)
1006                 -> std::optional<parser::MessageFixedText> {
1007               return "DEALLOCATE of a coarray is an image control"
1008                      " statement"_en_US;
1009             },
1010             [](const common::Indirection<parser::CallStmt> &)
1011                 -> std::optional<parser::MessageFixedText> {
1012               return "MOVE_ALLOC of a coarray is an image control"
1013                      " statement "_en_US;
1014             },
1015             [](const auto &) -> std::optional<parser::MessageFixedText> {
1016               return std::nullopt;
1017             },
1018         },
1019         actionStmt->statement.u);
1020   }
1021   return std::nullopt;
1022 }
1023 
1024 parser::CharBlock GetImageControlStmtLocation(
1025     const parser::ExecutableConstruct &executableConstruct) {
1026   return std::visit(
1027       common::visitors{
1028           [](const common::Indirection<parser::ChangeTeamConstruct>
1029                   &construct) {
1030             return std::get<parser::Statement<parser::ChangeTeamStmt>>(
1031                 construct.value().t)
1032                 .source;
1033           },
1034           [](const common::Indirection<parser::CriticalConstruct> &construct) {
1035             return std::get<parser::Statement<parser::CriticalStmt>>(
1036                 construct.value().t)
1037                 .source;
1038           },
1039           [](const parser::Statement<parser::ActionStmt> &actionStmt) {
1040             return actionStmt.source;
1041           },
1042           [](const auto &) { return parser::CharBlock{}; },
1043       },
1044       executableConstruct.u);
1045 }
1046 
1047 bool HasCoarray(const parser::Expr &expression) {
1048   if (const auto *expr{GetExpr(expression)}) {
1049     for (const Symbol &symbol : evaluate::CollectSymbols(*expr)) {
1050       if (IsCoarray(GetAssociationRoot(symbol))) {
1051         return true;
1052       }
1053     }
1054   }
1055   return false;
1056 }
1057 
1058 bool IsPolymorphic(const Symbol &symbol) {
1059   if (const DeclTypeSpec * type{symbol.GetType()}) {
1060     return type->IsPolymorphic();
1061   }
1062   return false;
1063 }
1064 
1065 bool IsPolymorphicAllocatable(const Symbol &symbol) {
1066   return IsAllocatable(symbol) && IsPolymorphic(symbol);
1067 }
1068 
1069 std::optional<parser::MessageFormattedText> CheckAccessibleComponent(
1070     const Scope &scope, const Symbol &symbol) {
1071   CHECK(symbol.owner().IsDerivedType()); // symbol must be a component
1072   if (symbol.attrs().test(Attr::PRIVATE)) {
1073     if (FindModuleFileContaining(scope)) {
1074       // Don't enforce component accessibility checks in module files;
1075       // there may be forward-substituted named constants of derived type
1076       // whose structure constructors reference private components.
1077     } else if (const Scope *
1078         moduleScope{FindModuleContaining(symbol.owner())}) {
1079       if (!moduleScope->Contains(scope)) {
1080         return parser::MessageFormattedText{
1081             "PRIVATE component '%s' is only accessible within module '%s'"_err_en_US,
1082             symbol.name(), moduleScope->GetName().value()};
1083       }
1084     }
1085   }
1086   return std::nullopt;
1087 }
1088 
1089 std::list<SourceName> OrderParameterNames(const Symbol &typeSymbol) {
1090   std::list<SourceName> result;
1091   if (const DerivedTypeSpec * spec{typeSymbol.GetParentTypeSpec()}) {
1092     result = OrderParameterNames(spec->typeSymbol());
1093   }
1094   const auto &paramNames{typeSymbol.get<DerivedTypeDetails>().paramNames()};
1095   result.insert(result.end(), paramNames.begin(), paramNames.end());
1096   return result;
1097 }
1098 
1099 SymbolVector OrderParameterDeclarations(const Symbol &typeSymbol) {
1100   SymbolVector result;
1101   if (const DerivedTypeSpec * spec{typeSymbol.GetParentTypeSpec()}) {
1102     result = OrderParameterDeclarations(spec->typeSymbol());
1103   }
1104   const auto &paramDecls{typeSymbol.get<DerivedTypeDetails>().paramDecls()};
1105   result.insert(result.end(), paramDecls.begin(), paramDecls.end());
1106   return result;
1107 }
1108 
1109 const DeclTypeSpec &FindOrInstantiateDerivedType(
1110     Scope &scope, DerivedTypeSpec &&spec, DeclTypeSpec::Category category) {
1111   spec.EvaluateParameters(scope.context());
1112   if (const DeclTypeSpec *
1113       type{scope.FindInstantiatedDerivedType(spec, category)}) {
1114     return *type;
1115   }
1116   // Create a new instantiation of this parameterized derived type
1117   // for this particular distinct set of actual parameter values.
1118   DeclTypeSpec &type{scope.MakeDerivedType(category, std::move(spec))};
1119   type.derivedTypeSpec().Instantiate(scope);
1120   return type;
1121 }
1122 
1123 const Symbol *FindSeparateModuleSubprogramInterface(const Symbol *proc) {
1124   if (proc) {
1125     if (const Symbol * submodule{proc->owner().symbol()}) {
1126       if (const auto *details{submodule->detailsIf<ModuleDetails>()}) {
1127         if (const Scope * ancestor{details->ancestor()}) {
1128           const Symbol *iface{ancestor->FindSymbol(proc->name())};
1129           if (IsSeparateModuleProcedureInterface(iface)) {
1130             return iface;
1131           }
1132         }
1133       }
1134     }
1135   }
1136   return nullptr;
1137 }
1138 
1139 ProcedureDefinitionClass ClassifyProcedure(const Symbol &symbol) { // 15.2.2
1140   const Symbol &ultimate{symbol.GetUltimate()};
1141   if (ultimate.attrs().test(Attr::INTRINSIC)) {
1142     return ProcedureDefinitionClass::Intrinsic;
1143   } else if (ultimate.attrs().test(Attr::EXTERNAL)) {
1144     return ProcedureDefinitionClass::External;
1145   } else if (const auto *procDetails{ultimate.detailsIf<ProcEntityDetails>()}) {
1146     if (procDetails->isDummy()) {
1147       return ProcedureDefinitionClass::Dummy;
1148     } else if (IsPointer(ultimate)) {
1149       return ProcedureDefinitionClass::Pointer;
1150     }
1151   } else if (const Symbol * subp{FindSubprogram(symbol)}) {
1152     if (const auto *subpDetails{subp->detailsIf<SubprogramDetails>()}) {
1153       if (subpDetails->stmtFunction()) {
1154         return ProcedureDefinitionClass::StatementFunction;
1155       }
1156     }
1157     switch (ultimate.owner().kind()) {
1158     case Scope::Kind::Global:
1159       return ProcedureDefinitionClass::External;
1160     case Scope::Kind::Module:
1161       return ProcedureDefinitionClass::Module;
1162     case Scope::Kind::MainProgram:
1163     case Scope::Kind::Subprogram:
1164       return ProcedureDefinitionClass::Internal;
1165     default:
1166       break;
1167     }
1168   }
1169   return ProcedureDefinitionClass::None;
1170 }
1171 
1172 // ComponentIterator implementation
1173 
1174 template <ComponentKind componentKind>
1175 typename ComponentIterator<componentKind>::const_iterator
1176 ComponentIterator<componentKind>::const_iterator::Create(
1177     const DerivedTypeSpec &derived) {
1178   const_iterator it{};
1179   it.componentPath_.emplace_back(derived);
1180   it.Increment(); // cue up first relevant component, if any
1181   return it;
1182 }
1183 
1184 template <ComponentKind componentKind>
1185 const DerivedTypeSpec *
1186 ComponentIterator<componentKind>::const_iterator::PlanComponentTraversal(
1187     const Symbol &component) const {
1188   if (const auto *details{component.detailsIf<ObjectEntityDetails>()}) {
1189     if (const DeclTypeSpec * type{details->type()}) {
1190       if (const auto *derived{type->AsDerived()}) {
1191         bool traverse{false};
1192         if constexpr (componentKind == ComponentKind::Ordered) {
1193           // Order Component (only visit parents)
1194           traverse = component.test(Symbol::Flag::ParentComp);
1195         } else if constexpr (componentKind == ComponentKind::Direct) {
1196           traverse = !IsAllocatableOrPointer(component);
1197         } else if constexpr (componentKind == ComponentKind::Ultimate) {
1198           traverse = !IsAllocatableOrPointer(component);
1199         } else if constexpr (componentKind == ComponentKind::Potential) {
1200           traverse = !IsPointer(component);
1201         } else if constexpr (componentKind == ComponentKind::Scope) {
1202           traverse = !IsAllocatableOrPointer(component);
1203         }
1204         if (traverse) {
1205           const Symbol &newTypeSymbol{derived->typeSymbol()};
1206           // Avoid infinite loop if the type is already part of the types
1207           // being visited. It is possible to have "loops in type" because
1208           // C744 does not forbid to use not yet declared type for
1209           // ALLOCATABLE or POINTER components.
1210           for (const auto &node : componentPath_) {
1211             if (&newTypeSymbol == &node.GetTypeSymbol()) {
1212               return nullptr;
1213             }
1214           }
1215           return derived;
1216         }
1217       }
1218     } // intrinsic & unlimited polymorphic not traversable
1219   }
1220   return nullptr;
1221 }
1222 
1223 template <ComponentKind componentKind>
1224 static bool StopAtComponentPre(const Symbol &component) {
1225   if constexpr (componentKind == ComponentKind::Ordered) {
1226     // Parent components need to be iterated upon after their
1227     // sub-components in structure constructor analysis.
1228     return !component.test(Symbol::Flag::ParentComp);
1229   } else if constexpr (componentKind == ComponentKind::Direct) {
1230     return true;
1231   } else if constexpr (componentKind == ComponentKind::Ultimate) {
1232     return component.has<ProcEntityDetails>() ||
1233         IsAllocatableOrPointer(component) ||
1234         (component.get<ObjectEntityDetails>().type() &&
1235             component.get<ObjectEntityDetails>().type()->AsIntrinsic());
1236   } else if constexpr (componentKind == ComponentKind::Potential) {
1237     return !IsPointer(component);
1238   }
1239 }
1240 
1241 template <ComponentKind componentKind>
1242 static bool StopAtComponentPost(const Symbol &component) {
1243   return componentKind == ComponentKind::Ordered &&
1244       component.test(Symbol::Flag::ParentComp);
1245 }
1246 
1247 template <ComponentKind componentKind>
1248 void ComponentIterator<componentKind>::const_iterator::Increment() {
1249   while (!componentPath_.empty()) {
1250     ComponentPathNode &deepest{componentPath_.back()};
1251     if (deepest.component()) {
1252       if (!deepest.descended()) {
1253         deepest.set_descended(true);
1254         if (const DerivedTypeSpec *
1255             derived{PlanComponentTraversal(*deepest.component())}) {
1256           componentPath_.emplace_back(*derived);
1257           continue;
1258         }
1259       } else if (!deepest.visited()) {
1260         deepest.set_visited(true);
1261         return; // this is the next component to visit, after descending
1262       }
1263     }
1264     auto &nameIterator{deepest.nameIterator()};
1265     if (nameIterator == deepest.nameEnd()) {
1266       componentPath_.pop_back();
1267     } else if constexpr (componentKind == ComponentKind::Scope) {
1268       deepest.set_component(*nameIterator++->second);
1269       deepest.set_descended(false);
1270       deepest.set_visited(true);
1271       return; // this is the next component to visit, before descending
1272     } else {
1273       const Scope &scope{deepest.GetScope()};
1274       auto scopeIter{scope.find(*nameIterator++)};
1275       if (scopeIter != scope.cend()) {
1276         const Symbol &component{*scopeIter->second};
1277         deepest.set_component(component);
1278         deepest.set_descended(false);
1279         if (StopAtComponentPre<componentKind>(component)) {
1280           deepest.set_visited(true);
1281           return; // this is the next component to visit, before descending
1282         } else {
1283           deepest.set_visited(!StopAtComponentPost<componentKind>(component));
1284         }
1285       }
1286     }
1287   }
1288 }
1289 
1290 template <ComponentKind componentKind>
1291 std::string
1292 ComponentIterator<componentKind>::const_iterator::BuildResultDesignatorName()
1293     const {
1294   std::string designator{""};
1295   for (const auto &node : componentPath_) {
1296     designator += "%" + DEREF(node.component()).name().ToString();
1297   }
1298   return designator;
1299 }
1300 
1301 template class ComponentIterator<ComponentKind::Ordered>;
1302 template class ComponentIterator<ComponentKind::Direct>;
1303 template class ComponentIterator<ComponentKind::Ultimate>;
1304 template class ComponentIterator<ComponentKind::Potential>;
1305 template class ComponentIterator<ComponentKind::Scope>;
1306 
1307 UltimateComponentIterator::const_iterator FindCoarrayUltimateComponent(
1308     const DerivedTypeSpec &derived) {
1309   UltimateComponentIterator ultimates{derived};
1310   return std::find_if(ultimates.begin(), ultimates.end(), IsCoarray);
1311 }
1312 
1313 UltimateComponentIterator::const_iterator FindPointerUltimateComponent(
1314     const DerivedTypeSpec &derived) {
1315   UltimateComponentIterator ultimates{derived};
1316   return std::find_if(ultimates.begin(), ultimates.end(), IsPointer);
1317 }
1318 
1319 PotentialComponentIterator::const_iterator FindEventOrLockPotentialComponent(
1320     const DerivedTypeSpec &derived) {
1321   PotentialComponentIterator potentials{derived};
1322   return std::find_if(
1323       potentials.begin(), potentials.end(), [](const Symbol &component) {
1324         if (const auto *details{component.detailsIf<ObjectEntityDetails>()}) {
1325           const DeclTypeSpec *type{details->type()};
1326           return type && IsEventTypeOrLockType(type->AsDerived());
1327         }
1328         return false;
1329       });
1330 }
1331 
1332 UltimateComponentIterator::const_iterator FindAllocatableUltimateComponent(
1333     const DerivedTypeSpec &derived) {
1334   UltimateComponentIterator ultimates{derived};
1335   return std::find_if(ultimates.begin(), ultimates.end(), IsAllocatable);
1336 }
1337 
1338 UltimateComponentIterator::const_iterator
1339 FindPolymorphicAllocatableUltimateComponent(const DerivedTypeSpec &derived) {
1340   UltimateComponentIterator ultimates{derived};
1341   return std::find_if(
1342       ultimates.begin(), ultimates.end(), IsPolymorphicAllocatable);
1343 }
1344 
1345 UltimateComponentIterator::const_iterator
1346 FindPolymorphicAllocatableNonCoarrayUltimateComponent(
1347     const DerivedTypeSpec &derived) {
1348   UltimateComponentIterator ultimates{derived};
1349   return std::find_if(ultimates.begin(), ultimates.end(), [](const Symbol &x) {
1350     return IsPolymorphicAllocatable(x) && !IsCoarray(x);
1351   });
1352 }
1353 
1354 const Symbol *FindUltimateComponent(const DerivedTypeSpec &derived,
1355     const std::function<bool(const Symbol &)> &predicate) {
1356   UltimateComponentIterator ultimates{derived};
1357   if (auto it{std::find_if(ultimates.begin(), ultimates.end(),
1358           [&predicate](const Symbol &component) -> bool {
1359             return predicate(component);
1360           })}) {
1361     return &*it;
1362   }
1363   return nullptr;
1364 }
1365 
1366 const Symbol *FindUltimateComponent(const Symbol &symbol,
1367     const std::function<bool(const Symbol &)> &predicate) {
1368   if (predicate(symbol)) {
1369     return &symbol;
1370   } else if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
1371     if (const auto *type{object->type()}) {
1372       if (const auto *derived{type->AsDerived()}) {
1373         return FindUltimateComponent(*derived, predicate);
1374       }
1375     }
1376   }
1377   return nullptr;
1378 }
1379 
1380 const Symbol *FindImmediateComponent(const DerivedTypeSpec &type,
1381     const std::function<bool(const Symbol &)> &predicate) {
1382   if (const Scope * scope{type.scope()}) {
1383     const Symbol *parent{nullptr};
1384     for (const auto &pair : *scope) {
1385       const Symbol *symbol{&*pair.second};
1386       if (predicate(*symbol)) {
1387         return symbol;
1388       }
1389       if (symbol->test(Symbol::Flag::ParentComp)) {
1390         parent = symbol;
1391       }
1392     }
1393     if (parent) {
1394       if (const auto *object{parent->detailsIf<ObjectEntityDetails>()}) {
1395         if (const auto *type{object->type()}) {
1396           if (const auto *derived{type->AsDerived()}) {
1397             return FindImmediateComponent(*derived, predicate);
1398           }
1399         }
1400       }
1401     }
1402   }
1403   return nullptr;
1404 }
1405 
1406 bool IsFunctionResultWithSameNameAsFunction(const Symbol &symbol) {
1407   if (IsFunctionResult(symbol)) {
1408     if (const Symbol * function{symbol.owner().symbol()}) {
1409       return symbol.name() == function->name();
1410     }
1411   }
1412   return false;
1413 }
1414 
1415 void LabelEnforce::Post(const parser::GotoStmt &gotoStmt) {
1416   checkLabelUse(gotoStmt.v);
1417 }
1418 void LabelEnforce::Post(const parser::ComputedGotoStmt &computedGotoStmt) {
1419   for (auto &i : std::get<std::list<parser::Label>>(computedGotoStmt.t)) {
1420     checkLabelUse(i);
1421   }
1422 }
1423 
1424 void LabelEnforce::Post(const parser::ArithmeticIfStmt &arithmeticIfStmt) {
1425   checkLabelUse(std::get<1>(arithmeticIfStmt.t));
1426   checkLabelUse(std::get<2>(arithmeticIfStmt.t));
1427   checkLabelUse(std::get<3>(arithmeticIfStmt.t));
1428 }
1429 
1430 void LabelEnforce::Post(const parser::AssignStmt &assignStmt) {
1431   checkLabelUse(std::get<parser::Label>(assignStmt.t));
1432 }
1433 
1434 void LabelEnforce::Post(const parser::AssignedGotoStmt &assignedGotoStmt) {
1435   for (auto &i : std::get<std::list<parser::Label>>(assignedGotoStmt.t)) {
1436     checkLabelUse(i);
1437   }
1438 }
1439 
1440 void LabelEnforce::Post(const parser::AltReturnSpec &altReturnSpec) {
1441   checkLabelUse(altReturnSpec.v);
1442 }
1443 
1444 void LabelEnforce::Post(const parser::ErrLabel &errLabel) {
1445   checkLabelUse(errLabel.v);
1446 }
1447 void LabelEnforce::Post(const parser::EndLabel &endLabel) {
1448   checkLabelUse(endLabel.v);
1449 }
1450 void LabelEnforce::Post(const parser::EorLabel &eorLabel) {
1451   checkLabelUse(eorLabel.v);
1452 }
1453 
1454 void LabelEnforce::checkLabelUse(const parser::Label &labelUsed) {
1455   if (labels_.find(labelUsed) == labels_.end()) {
1456     SayWithConstruct(context_, currentStatementSourcePosition_,
1457         parser::MessageFormattedText{
1458             "Control flow escapes from %s"_err_en_US, construct_},
1459         constructSourcePosition_);
1460   }
1461 }
1462 
1463 parser::MessageFormattedText LabelEnforce::GetEnclosingConstructMsg() {
1464   return {"Enclosing %s statement"_en_US, construct_};
1465 }
1466 
1467 void LabelEnforce::SayWithConstruct(SemanticsContext &context,
1468     parser::CharBlock stmtLocation, parser::MessageFormattedText &&message,
1469     parser::CharBlock constructLocation) {
1470   context.Say(stmtLocation, message)
1471       .Attach(constructLocation, GetEnclosingConstructMsg());
1472 }
1473 
1474 bool HasAlternateReturns(const Symbol &subprogram) {
1475   for (const auto *dummyArg : subprogram.get<SubprogramDetails>().dummyArgs()) {
1476     if (!dummyArg) {
1477       return true;
1478     }
1479   }
1480   return false;
1481 }
1482 
1483 bool InCommonBlock(const Symbol &symbol) {
1484   const auto *details{symbol.detailsIf<ObjectEntityDetails>()};
1485   return details && details->commonBlock();
1486 }
1487 
1488 const std::optional<parser::Name> &MaybeGetNodeName(
1489     const ConstructNode &construct) {
1490   return std::visit(
1491       common::visitors{
1492           [&](const parser::BlockConstruct *blockConstruct)
1493               -> const std::optional<parser::Name> & {
1494             return std::get<0>(blockConstruct->t).statement.v;
1495           },
1496           [&](const auto *a) -> const std::optional<parser::Name> & {
1497             return std::get<0>(std::get<0>(a->t).statement.t);
1498           },
1499       },
1500       construct);
1501 }
1502 
1503 std::optional<ArraySpec> ToArraySpec(
1504     evaluate::FoldingContext &context, const evaluate::Shape &shape) {
1505   if (auto extents{evaluate::AsConstantExtents(context, shape)}) {
1506     ArraySpec result;
1507     for (const auto &extent : *extents) {
1508       result.emplace_back(ShapeSpec::MakeExplicit(Bound{extent}));
1509     }
1510     return {std::move(result)};
1511   } else {
1512     return std::nullopt;
1513   }
1514 }
1515 
1516 std::optional<ArraySpec> ToArraySpec(evaluate::FoldingContext &context,
1517     const std::optional<evaluate::Shape> &shape) {
1518   return shape ? ToArraySpec(context, *shape) : std::nullopt;
1519 }
1520 
1521 } // namespace Fortran::semantics
1522