1 //===-- include/flang/Semantics/tools.h -------------------------*- C++ -*-===//
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 #ifndef FORTRAN_SEMANTICS_TOOLS_H_
10 #define FORTRAN_SEMANTICS_TOOLS_H_
11 
12 // Simple predicates and look-up functions that are best defined
13 // canonically for use in semantic checking.
14 
15 #include "flang/Common/Fortran.h"
16 #include "flang/Common/visit.h"
17 #include "flang/Evaluate/expression.h"
18 #include "flang/Evaluate/shape.h"
19 #include "flang/Evaluate/type.h"
20 #include "flang/Evaluate/variable.h"
21 #include "flang/Parser/message.h"
22 #include "flang/Parser/parse-tree.h"
23 #include "flang/Semantics/attr.h"
24 #include "flang/Semantics/expression.h"
25 #include "flang/Semantics/semantics.h"
26 #include <functional>
27 
28 namespace Fortran::semantics {
29 
30 class DeclTypeSpec;
31 class DerivedTypeSpec;
32 class Scope;
33 class Symbol;
34 
35 // Note: Here ProgramUnit includes internal subprograms while TopLevelUnit
36 // does not. "program-unit" in the Fortran standard matches TopLevelUnit.
37 const Scope &GetTopLevelUnitContaining(const Scope &);
38 const Scope &GetTopLevelUnitContaining(const Symbol &);
39 const Scope &GetProgramUnitContaining(const Scope &);
40 const Scope &GetProgramUnitContaining(const Symbol &);
41 const Scope &GetProgramUnitOrBlockConstructContaining(const Scope &);
42 const Scope &GetProgramUnitOrBlockConstructContaining(const Symbol &);
43 
44 const Scope *FindModuleContaining(const Scope &);
45 const Scope *FindModuleFileContaining(const Scope &);
46 const Scope *FindPureProcedureContaining(const Scope &);
47 const Scope *FindPureProcedureContaining(const Symbol &);
48 const Symbol *FindPointerComponent(const Scope &);
49 const Symbol *FindPointerComponent(const DerivedTypeSpec &);
50 const Symbol *FindPointerComponent(const DeclTypeSpec &);
51 const Symbol *FindPointerComponent(const Symbol &);
52 const Symbol *FindInterface(const Symbol &);
53 const Symbol *FindSubprogram(const Symbol &);
54 const Symbol *FindFunctionResult(const Symbol &);
55 const Symbol *FindOverriddenBinding(const Symbol &);
56 
57 const DeclTypeSpec *FindParentTypeSpec(const DerivedTypeSpec &);
58 const DeclTypeSpec *FindParentTypeSpec(const DeclTypeSpec &);
59 const DeclTypeSpec *FindParentTypeSpec(const Scope &);
60 const DeclTypeSpec *FindParentTypeSpec(const Symbol &);
61 
62 const EquivalenceSet *FindEquivalenceSet(const Symbol &);
63 
64 enum class Tristate { No, Yes, Maybe };
ToTristate(bool x)65 inline Tristate ToTristate(bool x) { return x ? Tristate::Yes : Tristate::No; }
66 
67 // Is this a user-defined assignment? If both sides are the same derived type
68 // (and the ranks are okay) the answer is Maybe.
69 Tristate IsDefinedAssignment(
70     const std::optional<evaluate::DynamicType> &lhsType, int lhsRank,
71     const std::optional<evaluate::DynamicType> &rhsType, int rhsRank);
72 // Test for intrinsic unary and binary operators based on types and ranks
73 bool IsIntrinsicRelational(common::RelationalOperator,
74     const evaluate::DynamicType &, int, const evaluate::DynamicType &, int);
75 bool IsIntrinsicNumeric(const evaluate::DynamicType &);
76 bool IsIntrinsicNumeric(
77     const evaluate::DynamicType &, int, const evaluate::DynamicType &, int);
78 bool IsIntrinsicLogical(const evaluate::DynamicType &);
79 bool IsIntrinsicLogical(
80     const evaluate::DynamicType &, int, const evaluate::DynamicType &, int);
81 bool IsIntrinsicConcat(
82     const evaluate::DynamicType &, int, const evaluate::DynamicType &, int);
83 
84 bool IsGenericDefinedOp(const Symbol &);
85 bool IsDefinedOperator(SourceName);
86 std::string MakeOpName(SourceName);
87 bool DoesScopeContain(const Scope *maybeAncestor, const Scope &maybeDescendent);
88 bool DoesScopeContain(const Scope *, const Symbol &);
89 bool IsUseAssociated(const Symbol &, const Scope &);
90 bool IsHostAssociated(const Symbol &, const Scope &);
IsStmtFunction(const Symbol & symbol)91 inline bool IsStmtFunction(const Symbol &symbol) {
92   const auto *subprogram{symbol.detailsIf<SubprogramDetails>()};
93   return subprogram && subprogram->stmtFunction();
94 }
95 bool IsInStmtFunction(const Symbol &);
96 bool IsStmtFunctionDummy(const Symbol &);
97 bool IsStmtFunctionResult(const Symbol &);
98 bool IsPointerDummy(const Symbol &);
99 bool IsBindCProcedure(const Symbol &);
100 bool IsBindCProcedure(const Scope &);
101 // Returns a pointer to the function's symbol when true, else null
102 const Symbol *IsFunctionResultWithSameNameAsFunction(const Symbol &);
103 bool IsOrContainsEventOrLockComponent(const Symbol &);
104 bool CanBeTypeBoundProc(const Symbol *);
105 // Does a non-PARAMETER symbol have explicit initialization with =value or
106 // =>target in its declaration (but not in a DATA statement)? (Being
107 // ALLOCATABLE or having a derived type with default component initialization
108 // doesn't count; it must be a variable initialization that implies the SAVE
109 // attribute, or a derived type component default value.)
110 bool HasDeclarationInitializer(const Symbol &);
111 // Is the symbol explicitly or implicitly initialized in any way?
112 bool IsInitialized(const Symbol &, bool ignoreDATAstatements = false,
113     bool ignoreAllocatable = false);
114 // Is the symbol a component subject to deallocation or finalization?
115 bool IsDestructible(const Symbol &, const Symbol *derivedType = nullptr);
116 bool HasIntrinsicTypeName(const Symbol &);
117 bool IsSeparateModuleProcedureInterface(const Symbol *);
118 bool HasAlternateReturns(const Symbol &);
119 bool InCommonBlock(const Symbol &);
120 
121 // Return an ultimate component of type that matches predicate, or nullptr.
122 const Symbol *FindUltimateComponent(const DerivedTypeSpec &type,
123     const std::function<bool(const Symbol &)> &predicate);
124 const Symbol *FindUltimateComponent(
125     const Symbol &symbol, const std::function<bool(const Symbol &)> &predicate);
126 
127 // Returns an immediate component of type that matches predicate, or nullptr.
128 // An immediate component of a type is one declared for that type or is an
129 // immediate component of the type that it extends.
130 const Symbol *FindImmediateComponent(
131     const DerivedTypeSpec &, const std::function<bool(const Symbol &)> &);
132 
IsPointer(const Symbol & symbol)133 inline bool IsPointer(const Symbol &symbol) {
134   return symbol.attrs().test(Attr::POINTER);
135 }
IsAllocatable(const Symbol & symbol)136 inline bool IsAllocatable(const Symbol &symbol) {
137   return symbol.attrs().test(Attr::ALLOCATABLE);
138 }
IsAllocatableOrPointer(const Symbol & symbol)139 inline bool IsAllocatableOrPointer(const Symbol &symbol) {
140   return IsPointer(symbol) || IsAllocatable(symbol);
141 }
IsSave(const Symbol & symbol)142 inline bool IsSave(const Symbol &symbol) {
143   return symbol.attrs().test(Attr::SAVE);
144 }
IsNamedConstant(const Symbol & symbol)145 inline bool IsNamedConstant(const Symbol &symbol) {
146   return symbol.attrs().test(Attr::PARAMETER);
147 }
IsOptional(const Symbol & symbol)148 inline bool IsOptional(const Symbol &symbol) {
149   return symbol.attrs().test(Attr::OPTIONAL);
150 }
IsIntentIn(const Symbol & symbol)151 inline bool IsIntentIn(const Symbol &symbol) {
152   return symbol.attrs().test(Attr::INTENT_IN);
153 }
IsIntentInOut(const Symbol & symbol)154 inline bool IsIntentInOut(const Symbol &symbol) {
155   return symbol.attrs().test(Attr::INTENT_INOUT);
156 }
IsIntentOut(const Symbol & symbol)157 inline bool IsIntentOut(const Symbol &symbol) {
158   return symbol.attrs().test(Attr::INTENT_OUT);
159 }
IsProtected(const Symbol & symbol)160 inline bool IsProtected(const Symbol &symbol) {
161   return symbol.attrs().test(Attr::PROTECTED);
162 }
IsImpliedDoIndex(const Symbol & symbol)163 inline bool IsImpliedDoIndex(const Symbol &symbol) {
164   return symbol.owner().kind() == Scope::Kind::ImpliedDos;
165 }
166 bool IsFinalizable(
167     const Symbol &, std::set<const DerivedTypeSpec *> * = nullptr);
168 bool IsFinalizable(
169     const DerivedTypeSpec &, std::set<const DerivedTypeSpec *> * = nullptr);
170 bool HasImpureFinal(const DerivedTypeSpec &);
171 bool IsInBlankCommon(const Symbol &);
IsAssumedSizeArray(const Symbol & symbol)172 inline bool IsAssumedSizeArray(const Symbol &symbol) {
173   const auto *details{symbol.detailsIf<ObjectEntityDetails>()};
174   return details && details->IsAssumedSize();
175 }
176 bool IsAssumedLengthCharacter(const Symbol &);
177 bool IsExternal(const Symbol &);
178 bool IsModuleProcedure(const Symbol &);
179 // Is the symbol modifiable in this scope
180 std::optional<parser::Message> WhyNotModifiable(const Symbol &, const Scope &);
181 std::optional<parser::Message> WhyNotModifiable(SourceName, const SomeExpr &,
182     const Scope &, bool vectorSubscriptIsOk = false);
183 const Symbol *IsExternalInPureContext(const Symbol &, const Scope &);
184 bool HasCoarray(const parser::Expr &);
185 bool IsPolymorphicAllocatable(const Symbol &);
186 // Return an error if component symbol is not accessible from scope (7.5.4.8(2))
187 std::optional<parser::MessageFormattedText> CheckAccessibleComponent(
188     const semantics::Scope &, const Symbol &);
189 
190 // Analysis of image control statements
191 bool IsImageControlStmt(const parser::ExecutableConstruct &);
192 // Get the location of the image control statement in this ExecutableConstruct
193 parser::CharBlock GetImageControlStmtLocation(
194     const parser::ExecutableConstruct &);
195 // Image control statements that reference coarrays need an extra message
196 // to clarify why they're image control statements.  This function returns
197 // std::nullopt for ExecutableConstructs that do not require an extra message.
198 std::optional<parser::MessageFixedText> GetImageControlStmtCoarrayMsg(
199     const parser::ExecutableConstruct &);
200 
201 // Returns the complete list of derived type parameter symbols in
202 // the order in which their declarations appear in the derived type
203 // definitions (parents first).
204 SymbolVector OrderParameterDeclarations(const Symbol &);
205 // Returns the complete list of derived type parameter names in the
206 // order defined by 7.5.3.2.
207 std::list<SourceName> OrderParameterNames(const Symbol &);
208 
209 // Return an existing or new derived type instance
210 const DeclTypeSpec &FindOrInstantiateDerivedType(Scope &, DerivedTypeSpec &&,
211     DeclTypeSpec::Category = DeclTypeSpec::TypeDerived);
212 
213 // When a subprogram defined in a submodule defines a separate module
214 // procedure whose interface is defined in an ancestor (sub)module,
215 // returns a pointer to that interface, else null.
216 const Symbol *FindSeparateModuleSubprogramInterface(const Symbol *);
217 
218 // Determines whether an object might be visible outside a
219 // pure function (C1594); returns a non-null Symbol pointer for
220 // diagnostic purposes if so.
221 const Symbol *FindExternallyVisibleObject(const Symbol &, const Scope &);
222 
223 template <typename A>
FindExternallyVisibleObject(const A &,const Scope &)224 const Symbol *FindExternallyVisibleObject(const A &, const Scope &) {
225   return nullptr; // default base case
226 }
227 
228 template <typename T>
FindExternallyVisibleObject(const evaluate::Designator<T> & designator,const Scope & scope)229 const Symbol *FindExternallyVisibleObject(
230     const evaluate::Designator<T> &designator, const Scope &scope) {
231   if (const Symbol * symbol{designator.GetBaseObject().symbol()}) {
232     return FindExternallyVisibleObject(*symbol, scope);
233   } else if (std::holds_alternative<evaluate::CoarrayRef>(designator.u)) {
234     // Coindexed values are visible even if their image-local objects are not.
235     return designator.GetBaseObject().symbol();
236   } else {
237     return nullptr;
238   }
239 }
240 
241 template <typename T>
FindExternallyVisibleObject(const evaluate::Expr<T> & expr,const Scope & scope)242 const Symbol *FindExternallyVisibleObject(
243     const evaluate::Expr<T> &expr, const Scope &scope) {
244   return common::visit(
245       [&](const auto &x) { return FindExternallyVisibleObject(x, scope); },
246       expr.u);
247 }
248 
249 // Apply GetUltimate(), then if the symbol is a generic procedure shadowing a
250 // specific procedure of the same name, return it instead.
251 const Symbol &BypassGeneric(const Symbol &);
252 
253 using SomeExpr = evaluate::Expr<evaluate::SomeType>;
254 
255 bool ExprHasTypeCategory(
256     const SomeExpr &expr, const common::TypeCategory &type);
257 bool ExprTypeKindIsDefault(
258     const SomeExpr &expr, const SemanticsContext &context);
259 
260 class GetExprHelper {
261 public:
GetExprHelper(SemanticsContext * context)262   explicit GetExprHelper(SemanticsContext *context) : context_{context} {}
GetExprHelper()263   GetExprHelper() : crashIfNoExpr_{true} {}
264 
265   // Specializations for parse tree nodes that have a typedExpr member.
266   const SomeExpr *Get(const parser::Expr &);
267   const SomeExpr *Get(const parser::Variable &);
268   const SomeExpr *Get(const parser::DataStmtConstant &);
269   const SomeExpr *Get(const parser::AllocateObject &);
270   const SomeExpr *Get(const parser::PointerObject &);
271 
Get(const common::Indirection<T> & x)272   template <typename T> const SomeExpr *Get(const common::Indirection<T> &x) {
273     return Get(x.value());
274   }
Get(const std::optional<T> & x)275   template <typename T> const SomeExpr *Get(const std::optional<T> &x) {
276     return x ? Get(*x) : nullptr;
277   }
Get(const T & x)278   template <typename T> const SomeExpr *Get(const T &x) {
279     static_assert(
280         !parser::HasTypedExpr<T>::value, "explicit Get overload must be added");
281     if constexpr (ConstraintTrait<T>) {
282       return Get(x.thing);
283     } else if constexpr (WrapperTrait<T>) {
284       return Get(x.v);
285     } else {
286       return nullptr;
287     }
288   }
289 
290 private:
291   SemanticsContext *context_{nullptr};
292   const bool crashIfNoExpr_{false};
293 };
294 
295 // If a SemanticsContext is passed, even if null, it is possible for a null
296 // pointer to be returned in the event of an expression that had fatal errors.
297 // Use these first two forms in semantics checks for best error recovery.
298 // If a SemanticsContext is not passed, a missing expression will
299 // cause a crash.
300 template <typename T>
GetExpr(SemanticsContext * context,const T & x)301 const SomeExpr *GetExpr(SemanticsContext *context, const T &x) {
302   return GetExprHelper{context}.Get(x);
303 }
304 template <typename T>
GetExpr(SemanticsContext & context,const T & x)305 const SomeExpr *GetExpr(SemanticsContext &context, const T &x) {
306   return GetExprHelper{&context}.Get(x);
307 }
GetExpr(const T & x)308 template <typename T> const SomeExpr *GetExpr(const T &x) {
309   return GetExprHelper{}.Get(x);
310 }
311 
312 const evaluate::Assignment *GetAssignment(const parser::AssignmentStmt &);
313 const evaluate::Assignment *GetAssignment(
314     const parser::PointerAssignmentStmt &);
315 
GetIntValue(const T & x)316 template <typename T> std::optional<std::int64_t> GetIntValue(const T &x) {
317   if (const auto *expr{GetExpr(nullptr, x)}) {
318     return evaluate::ToInt64(*expr);
319   } else {
320     return std::nullopt;
321   }
322 }
323 
IsZero(const T & expr)324 template <typename T> bool IsZero(const T &expr) {
325   auto value{GetIntValue(expr)};
326   return value && *value == 0;
327 }
328 
329 // 15.2.2
330 enum class ProcedureDefinitionClass {
331   None,
332   Intrinsic,
333   External,
334   Internal,
335   Module,
336   Dummy,
337   Pointer,
338   StatementFunction
339 };
340 
341 ProcedureDefinitionClass ClassifyProcedure(const Symbol &);
342 
343 // Returns a list of storage associations due to EQUIVALENCE in a
344 // scope; each storage association is a list of symbol references
345 // in ascending order of scope offset.  Note that the scope may have
346 // more EquivalenceSets than this function's result has storage
347 // associations; these are closures over equivalences.
348 std::list<std::list<SymbolRef>> GetStorageAssociations(const Scope &);
349 
350 // Derived type component iterator that provides a C++ LegacyForwardIterator
351 // iterator over the Ordered, Direct, Ultimate or Potential components of a
352 // DerivedTypeSpec. These iterators can be used with STL algorithms
353 // accepting LegacyForwardIterator.
354 // The kind of component is a template argument of the iterator factory
355 // ComponentIterator.
356 //
357 // - Ordered components are the components from the component order defined
358 // in 7.5.4.7, except that the parent component IS added between the parent
359 // component order and the components in order of declaration.
360 // This "deviation" is important for structure-constructor analysis.
361 // For this kind of iterator, the component tree is recursively visited in the
362 // following order:
363 //  - first, the Ordered components of the parent type (if relevant)
364 //  - then, the parent component (if relevant, different from 7.5.4.7!)
365 //  - then, the components in declaration order (without visiting subcomponents)
366 //
367 // - Ultimate, Direct and Potential components are as defined in 7.5.1.
368 //   - Ultimate components of a derived type are the closure of its components
369 //     of intrinsic type, its ALLOCATABLE or POINTER components, and the
370 //     ultimate components of its non-ALLOCATABLE non-POINTER derived type
371 //     components.  (No ultimate component has a derived type unless it is
372 //     ALLOCATABLE or POINTER.)
373 //   - Direct components of a derived type are all of its components, and all
374 //     of the direct components of its non-ALLOCATABLE non-POINTER derived type
375 //     components.  (Direct components are always present.)
376 //   - Potential subobject components of a derived type are the closure of
377 //     its non-POINTER components and the potential subobject components of
378 //     its non-POINTER derived type components.  (The lifetime of each
379 //     potential subobject component is that of the entire instance.)
380 // Parent and procedure components are considered against these definitions.
381 // For this kind of iterator, the component tree is recursively visited in the
382 // following order:
383 //  - the parent component first (if relevant)
384 //  - then, the components of the parent type (if relevant)
385 //      + visiting the component and then, if it is derived type data component,
386 //        visiting the subcomponents before visiting the next
387 //        component in declaration order.
388 //  - then, components in declaration order, similarly to components of parent
389 //    type.
390 //  Here, the parent component is visited first so that search for a component
391 //  verifying a property will never descend into a component that already
392 //  verifies the property (this helps giving clearer feedback).
393 //
394 // ComponentIterator::const_iterator remain valid during the whole lifetime of
395 // the DerivedTypeSpec passed by reference to the ComponentIterator factory.
396 // Their validity is independent of the ComponentIterator factory lifetime.
397 //
398 // For safety and simplicity, the iterators are read only and can only be
399 // incremented. This could be changed if desired.
400 //
401 // Note that iterators are made in such a way that one can easily test and build
402 // info message in the following way:
403 //    ComponentIterator<ComponentKind::...> comp{derived}
404 //    if (auto it{std::find_if(comp.begin(), comp.end(), predicate)}) {
405 //       msg = it.BuildResultDesignatorName() + " verifies predicates";
406 //       const Symbol *component{*it};
407 //       ....
408 //    }
409 
ENUM_CLASS(ComponentKind,Ordered,Direct,Ultimate,Potential,Scope)410 ENUM_CLASS(ComponentKind, Ordered, Direct, Ultimate, Potential, Scope)
411 
412 template <ComponentKind componentKind> class ComponentIterator {
413 public:
414   ComponentIterator(const DerivedTypeSpec &derived) : derived_{derived} {}
415   class const_iterator {
416   public:
417     using iterator_category = std::forward_iterator_tag;
418     using value_type = SymbolRef;
419     using difference_type = void;
420     using pointer = const Symbol *;
421     using reference = const Symbol &;
422 
423     static const_iterator Create(const DerivedTypeSpec &);
424 
425     const_iterator &operator++() {
426       Increment();
427       return *this;
428     }
429     const_iterator operator++(int) {
430       const_iterator tmp(*this);
431       Increment();
432       return tmp;
433     }
434     reference operator*() const {
435       CHECK(!componentPath_.empty());
436       return DEREF(componentPath_.back().component());
437     }
438     pointer operator->() const { return &**this; }
439 
440     bool operator==(const const_iterator &other) const {
441       return componentPath_ == other.componentPath_;
442     }
443     bool operator!=(const const_iterator &other) const {
444       return !(*this == other);
445     }
446 
447     // bool() operator indicates if the iterator can be dereferenced without
448     // having to check against an end() iterator.
449     explicit operator bool() const { return !componentPath_.empty(); }
450 
451     // Builds a designator name of the referenced component for messages.
452     // The designator helps when the component referred to by the iterator
453     // may be "buried" into other components. This gives the full
454     // path inside the iterated derived type: e.g "%a%b%c%ultimate"
455     // when it->name() only gives "ultimate". Parent components are
456     // part of the path for clarity, even though they could be
457     // skipped.
458     std::string BuildResultDesignatorName() const;
459 
460   private:
461     using name_iterator =
462         std::conditional_t<componentKind == ComponentKind::Scope,
463             typename Scope::const_iterator,
464             typename std::list<SourceName>::const_iterator>;
465 
466     class ComponentPathNode {
467     public:
468       explicit ComponentPathNode(const DerivedTypeSpec &derived)
469           : derived_{derived} {
470         if constexpr (componentKind == ComponentKind::Scope) {
471           const Scope &scope{DEREF(derived.scope())};
472           nameIterator_ = scope.cbegin();
473           nameEnd_ = scope.cend();
474         } else {
475           const std::list<SourceName> &nameList{
476               derived.typeSymbol().get<DerivedTypeDetails>().componentNames()};
477           nameIterator_ = nameList.cbegin();
478           nameEnd_ = nameList.cend();
479         }
480       }
481       const Symbol *component() const { return component_; }
482       void set_component(const Symbol &component) { component_ = &component; }
483       bool visited() const { return visited_; }
484       void set_visited(bool yes) { visited_ = yes; }
485       bool descended() const { return descended_; }
486       void set_descended(bool yes) { descended_ = yes; }
487       name_iterator &nameIterator() { return nameIterator_; }
488       name_iterator nameEnd() { return nameEnd_; }
489       const Symbol &GetTypeSymbol() const { return derived_->typeSymbol(); }
490       const Scope &GetScope() const {
491         return derived_->scope() ? *derived_->scope()
492                                  : DEREF(GetTypeSymbol().scope());
493       }
494       bool operator==(const ComponentPathNode &that) const {
495         return &*derived_ == &*that.derived_ &&
496             nameIterator_ == that.nameIterator_ &&
497             component_ == that.component_;
498       }
499 
500     private:
501       common::Reference<const DerivedTypeSpec> derived_;
502       name_iterator nameEnd_;
503       name_iterator nameIterator_;
504       const Symbol *component_{nullptr}; // until Increment()
505       bool visited_{false};
506       bool descended_{false};
507     };
508 
509     const DerivedTypeSpec *PlanComponentTraversal(
510         const Symbol &component) const;
511     // Advances to the next relevant symbol, if any.  Afterwards, the
512     // iterator will either be at its end or contain no null component().
513     void Increment();
514 
515     std::vector<ComponentPathNode> componentPath_;
516   };
517 
518   const_iterator begin() { return cbegin(); }
519   const_iterator end() { return cend(); }
520   const_iterator cbegin() { return const_iterator::Create(derived_); }
521   const_iterator cend() { return const_iterator{}; }
522 
523 private:
524   const DerivedTypeSpec &derived_;
525 };
526 
527 extern template class ComponentIterator<ComponentKind::Ordered>;
528 extern template class ComponentIterator<ComponentKind::Direct>;
529 extern template class ComponentIterator<ComponentKind::Ultimate>;
530 extern template class ComponentIterator<ComponentKind::Potential>;
531 extern template class ComponentIterator<ComponentKind::Scope>;
532 using OrderedComponentIterator = ComponentIterator<ComponentKind::Ordered>;
533 using DirectComponentIterator = ComponentIterator<ComponentKind::Direct>;
534 using UltimateComponentIterator = ComponentIterator<ComponentKind::Ultimate>;
535 using PotentialComponentIterator = ComponentIterator<ComponentKind::Potential>;
536 using ScopeComponentIterator = ComponentIterator<ComponentKind::Scope>;
537 
538 // Common component searches, the iterator returned is referring to the first
539 // component, according to the order defined for the related ComponentIterator,
540 // that verifies the property from the name.
541 // If no component verifies the property, an end iterator (casting to false)
542 // is returned. Otherwise, the returned iterator casts to true and can be
543 // dereferenced.
544 PotentialComponentIterator::const_iterator FindEventOrLockPotentialComponent(
545     const DerivedTypeSpec &);
546 UltimateComponentIterator::const_iterator FindCoarrayUltimateComponent(
547     const DerivedTypeSpec &);
548 UltimateComponentIterator::const_iterator FindPointerUltimateComponent(
549     const DerivedTypeSpec &);
550 UltimateComponentIterator::const_iterator FindAllocatableUltimateComponent(
551     const DerivedTypeSpec &);
552 DirectComponentIterator::const_iterator FindAllocatableOrPointerDirectComponent(
553     const DerivedTypeSpec &);
554 UltimateComponentIterator::const_iterator
555 FindPolymorphicAllocatableUltimateComponent(const DerivedTypeSpec &);
556 UltimateComponentIterator::const_iterator
557 FindPolymorphicAllocatableNonCoarrayUltimateComponent(const DerivedTypeSpec &);
558 
559 // The LabelEnforce class (given a set of labels) provides an error message if
560 // there is a branch to a label which is not in the given set.
561 class LabelEnforce {
562 public:
LabelEnforce(SemanticsContext & context,std::set<parser::Label> && labels,parser::CharBlock constructSourcePosition,const char * construct)563   LabelEnforce(SemanticsContext &context, std::set<parser::Label> &&labels,
564       parser::CharBlock constructSourcePosition, const char *construct)
565       : context_{context}, labels_{labels},
566         constructSourcePosition_{constructSourcePosition}, construct_{
567                                                                construct} {}
Pre(const T &)568   template <typename T> bool Pre(const T &) { return true; }
Pre(const parser::Statement<T> & statement)569   template <typename T> bool Pre(const parser::Statement<T> &statement) {
570     currentStatementSourcePosition_ = statement.source;
571     return true;
572   }
573 
Post(const T &)574   template <typename T> void Post(const T &) {}
575 
576   void Post(const parser::GotoStmt &gotoStmt);
577   void Post(const parser::ComputedGotoStmt &computedGotoStmt);
578   void Post(const parser::ArithmeticIfStmt &arithmeticIfStmt);
579   void Post(const parser::AssignStmt &assignStmt);
580   void Post(const parser::AssignedGotoStmt &assignedGotoStmt);
581   void Post(const parser::AltReturnSpec &altReturnSpec);
582   void Post(const parser::ErrLabel &errLabel);
583   void Post(const parser::EndLabel &endLabel);
584   void Post(const parser::EorLabel &eorLabel);
585   void checkLabelUse(const parser::Label &labelUsed);
586 
587 private:
588   SemanticsContext &context_;
589   std::set<parser::Label> labels_;
590   parser::CharBlock currentStatementSourcePosition_{nullptr};
591   parser::CharBlock constructSourcePosition_{nullptr};
592   const char *construct_{nullptr};
593 
594   parser::MessageFormattedText GetEnclosingConstructMsg();
595   void SayWithConstruct(SemanticsContext &context,
596       parser::CharBlock stmtLocation, parser::MessageFormattedText &&message,
597       parser::CharBlock constructLocation);
598 };
599 // Return the (possibly null) name of the ConstructNode
600 const std::optional<parser::Name> &MaybeGetNodeName(
601     const ConstructNode &construct);
602 
603 // Convert evaluate::GetShape() result into an ArraySpec
604 std::optional<ArraySpec> ToArraySpec(
605     evaluate::FoldingContext &, const evaluate::Shape &);
606 std::optional<ArraySpec> ToArraySpec(
607     evaluate::FoldingContext &, const std::optional<evaluate::Shape> &);
608 
609 // Searches a derived type and a scope for a particular user defined I/O
610 // procedure.
611 bool HasDefinedIo(
612     GenericKind::DefinedIo, const DerivedTypeSpec &, const Scope * = nullptr);
613 // Seeks out an allocatable or pointer ultimate component that is not
614 // nested in a nonallocatable/nonpointer component with a specific
615 // defined I/O procedure.
616 const Symbol *FindUnsafeIoDirectComponent(
617     GenericKind::DefinedIo, const DerivedTypeSpec &, const Scope * = nullptr);
618 
619 // Some intrinsic operators have more than one name (e.g. `operator(.eq.)` and
620 // `operator(==)`). GetAllNames() returns them all, including symbolName.
621 std::forward_list<std::string> GetAllNames(
622     const SemanticsContext &, const SourceName &);
623 
624 } // namespace Fortran::semantics
625 #endif // FORTRAN_SEMANTICS_TOOLS_H_
626