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