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