FLANG
tools.h
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/visit.h"
16#include "flang/Evaluate/expression.h"
17#include "flang/Evaluate/shape.h"
18#include "flang/Evaluate/type.h"
19#include "flang/Evaluate/variable.h"
20#include "flang/Parser/message.h"
21#include "flang/Parser/parse-tree.h"
22#include "flang/Semantics/attr.h"
23#include "flang/Semantics/expression.h"
24#include "flang/Semantics/semantics.h"
25#include "flang/Support/Fortran.h"
26#include "llvm/ADT/ArrayRef.h"
27#include <functional>
28
29namespace Fortran::evaluate::characteristics {
30struct DummyDataObject;
31}
32
33namespace Fortran::semantics {
34
35class DeclTypeSpec;
36class DerivedTypeSpec;
37class Scope;
38class Symbol;
39
40// Note: Here ProgramUnit includes internal subprograms while TopLevelUnit
41// does not. "program-unit" in the Fortran standard matches TopLevelUnit.
42const Scope &GetTopLevelUnitContaining(const Scope &);
43const Scope &GetTopLevelUnitContaining(const Symbol &);
44const Scope &GetProgramUnitContaining(const Scope &);
45const Scope &GetProgramUnitContaining(const Symbol &);
46const Scope &GetProgramUnitOrBlockConstructContaining(const Scope &);
47const Scope &GetProgramUnitOrBlockConstructContaining(const Symbol &);
48
49const Scope *FindModuleContaining(const Scope &);
50const Scope *FindModuleOrSubmoduleContaining(const Scope &);
51const Scope *FindModuleFileContaining(const Scope &);
52const Scope *FindPureProcedureContaining(const Scope &);
53const Scope *FindOpenACCConstructContaining(const Scope *);
54bool HasOpenACCRoutineDirective(const Scope *);
55
56const Symbol *FindInterface(const Symbol &);
57const Symbol *FindSubprogram(const Symbol &);
58const Symbol *FindOverriddenBinding(
59 const Symbol &, bool &isInaccessibleDeferred);
60const Symbol *FindGlobal(const Symbol &);
61
62const DeclTypeSpec *FindParentTypeSpec(const DerivedTypeSpec &);
63const DeclTypeSpec *FindParentTypeSpec(const DeclTypeSpec &);
64const DeclTypeSpec *FindParentTypeSpec(const Scope &);
65const DeclTypeSpec *FindParentTypeSpec(const Symbol &);
66
67const EquivalenceSet *FindEquivalenceSet(const Symbol &);
68
69enum class Tristate { No, Yes, Maybe };
70inline Tristate ToTristate(bool x) { return x ? Tristate::Yes : Tristate::No; }
71
72// Is this a user-defined assignment? If both sides are the same derived type
73// (and the ranks are okay) the answer is Maybe.
74Tristate IsDefinedAssignment(
75 const std::optional<evaluate::DynamicType> &lhsType, int lhsRank,
76 const std::optional<evaluate::DynamicType> &rhsType, int rhsRank);
77// Test for intrinsic unary and binary operators based on types and ranks
78bool IsIntrinsicRelational(common::RelationalOperator,
79 const evaluate::DynamicType &, int, const evaluate::DynamicType &, int);
80bool IsIntrinsicNumeric(const evaluate::DynamicType &);
81bool IsIntrinsicNumeric(
82 const evaluate::DynamicType &, int, const evaluate::DynamicType &, int);
83bool IsIntrinsicLogical(const evaluate::DynamicType &);
84bool IsIntrinsicLogical(
85 const evaluate::DynamicType &, int, const evaluate::DynamicType &, int);
86bool IsIntrinsicConcat(
87 const evaluate::DynamicType &, int, const evaluate::DynamicType &, int);
88
89bool IsGenericDefinedOp(const Symbol &);
90bool IsDefinedOperator(SourceName);
91std::string MakeOpName(SourceName);
92bool IsCommonBlockContaining(const Symbol &, const Symbol &);
93
94// Returns true if maybeAncestor exists and is a proper ancestor of a
95// descendent scope (or symbol owner). Will be false, unlike Scope::Contains(),
96// if maybeAncestor *is* the descendent.
97bool DoesScopeContain(const Scope *maybeAncestor, const Scope &maybeDescendent);
98bool DoesScopeContain(const Scope *, const Symbol &);
99
100bool IsUseAssociated(const Symbol &, const Scope &);
101bool IsHostAssociated(const Symbol &, const Scope &);
102bool IsHostAssociatedIntoSubprogram(const Symbol &, const Scope &);
103inline bool IsStmtFunction(const Symbol &symbol) {
104 const auto *subprogram{symbol.detailsIf<SubprogramDetails>()};
105 return subprogram && subprogram->stmtFunction();
106}
107bool IsInStmtFunction(const Symbol &);
108bool IsStmtFunctionDummy(const Symbol &);
109bool IsStmtFunctionResult(const Symbol &);
110bool IsPointerDummy(const Symbol &);
111bool IsBindCProcedure(const Symbol &);
112bool IsBindCProcedure(const Scope &);
113// Returns a pointer to the function's symbol when true, else null
114const Symbol *IsFunctionResultWithSameNameAsFunction(const Symbol &);
115bool IsOrContainsEventOrLockComponent(const Symbol &);
116bool IsOrContainsNotifyComponent(const Symbol &);
117bool CanBeTypeBoundProc(const Symbol &);
118// Does a non-PARAMETER symbol have explicit initialization with =value or
119// =>target in its declaration (but not in a DATA statement)? (Being
120// ALLOCATABLE or having a derived type with default component initialization
121// doesn't count; it must be a variable initialization that implies the SAVE
122// attribute, or a derived type component default value.)
123bool HasDeclarationInitializer(const Symbol &);
124// Is the symbol explicitly or implicitly initialized in any way?
125bool IsInitialized(const Symbol &, bool ignoreDATAstatements = false,
126 bool ignoreAllocatable = false, bool ignorePointer = true);
127// Is the symbol a component subject to deallocation or finalization?
128bool IsDestructible(const Symbol &, const Symbol *derivedType = nullptr);
129bool HasIntrinsicTypeName(const Symbol &);
130bool IsSeparateModuleProcedureInterface(const Symbol *);
131bool HasAlternateReturns(const Symbol &);
132bool IsAutomaticallyDestroyed(const Symbol &);
133
134// Follow association until the first symbol without HostAssocDetails.
135const Symbol &FollowHostAssoc(const Symbol &);
136
137// Return an ultimate component of type that matches predicate, or nullptr.
138const Symbol *FindUltimateComponent(const DerivedTypeSpec &type,
139 const std::function<bool(const Symbol &)> &predicate);
140const Symbol *FindUltimateComponent(
141 const Symbol &symbol, const std::function<bool(const Symbol &)> &predicate);
142
143// Returns an immediate component of type that matches predicate, or nullptr.
144// An immediate component of a type is one declared for that type or is an
145// immediate component of the type that it extends.
146const Symbol *FindImmediateComponent(
147 const DerivedTypeSpec &, const std::function<bool(const Symbol &)> &);
148
149inline bool IsPointer(const Symbol &symbol) {
150 return symbol.attrs().test(Attr::POINTER);
151}
152inline bool IsAllocatable(const Symbol &symbol) {
153 return symbol.attrs().test(Attr::ALLOCATABLE);
154}
155inline bool IsValue(const Symbol &symbol) {
156 return symbol.attrs().test(Attr::VALUE);
157}
158// IsAllocatableOrObjectPointer() may be the better choice
159inline bool IsAllocatableOrPointer(const Symbol &symbol) {
160 return IsPointer(symbol) || IsAllocatable(symbol);
161}
162inline bool IsNamedConstant(const Symbol &symbol) {
163 return symbol.attrs().test(Attr::PARAMETER);
164}
165inline bool IsOptional(const Symbol &symbol) {
166 return symbol.attrs().test(Attr::OPTIONAL);
167}
168inline bool IsIntentIn(const Symbol &symbol) {
169 return symbol.attrs().test(Attr::INTENT_IN);
170}
171inline bool IsIntentInOut(const Symbol &symbol) {
172 return symbol.attrs().test(Attr::INTENT_INOUT);
173}
174inline bool IsIntentOut(const Symbol &symbol) {
175 return symbol.attrs().test(Attr::INTENT_OUT);
176}
177inline bool IsProtected(const Symbol &symbol) {
178 return symbol.attrs().test(Attr::PROTECTED);
179}
180inline bool IsImpliedDoIndex(const Symbol &symbol) {
181 return symbol.owner().kind() == Scope::Kind::ImpliedDos;
182}
183SymbolVector FinalsForDerivedTypeInstantiation(const DerivedTypeSpec &);
184// Returns a non-null pointer to a FINAL procedure, if any.
185const Symbol *IsFinalizable(const Symbol &,
186 std::set<const DerivedTypeSpec *> * = nullptr,
187 bool withImpureFinalizer = false);
188const Symbol *IsFinalizable(const DerivedTypeSpec &,
189 std::set<const DerivedTypeSpec *> * = nullptr,
190 bool withImpureFinalizer = false, std::optional<int> rank = std::nullopt);
191const Symbol *HasImpureFinal(
192 const Symbol &, std::optional<int> rank = std::nullopt);
193// Is this type finalizable or does it contain any polymorphic allocatable
194// ultimate components?
195bool MayRequireFinalization(const DerivedTypeSpec &);
196// Does this type have an allocatable direct component?
197bool HasAllocatableDirectComponent(const DerivedTypeSpec &);
198// Does this type have any defined assignment at any level (or any polymorphic
199// allocatable)?
200bool MayHaveDefinedAssignment(const DerivedTypeSpec &);
201
202bool IsInBlankCommon(const Symbol &);
203bool IsAssumedLengthCharacter(const Symbol &);
204bool IsExternal(const Symbol &);
205bool IsModuleProcedure(const Symbol &);
206bool HasCoarray(const parser::Expr &);
207bool IsAssumedType(const Symbol &);
208bool IsEnumerationType(const Symbol &);
209bool IsEnumerationType(const DerivedTypeSpec &);
210bool IsPolymorphic(const Symbol &);
211bool IsUnlimitedPolymorphic(const Symbol &);
212bool IsPolymorphicAllocatable(const Symbol &);
213
214bool IsDeviceAllocatable(const Symbol &symbol);
215
216inline bool IsCUDADeviceContext(const Scope *scope) {
217 if (scope) {
218 if (const Symbol * symbol{scope->symbol()}) {
219 if (const auto *subp{symbol->detailsIf<SubprogramDetails>()}) {
220 if (auto attrs{subp->cudaSubprogramAttrs()}) {
221 return *attrs != common::CUDASubprogramAttrs::Host;
222 }
223 }
224 }
225 }
226 return false;
227}
228
229inline bool HasCUDAAttr(const Symbol &sym) {
230 if (const auto *details{sym.GetUltimate().detailsIf<ObjectEntityDetails>()}) {
231 if (details->cudaDataAttr()) {
232 return true;
233 }
234 }
235 return false;
236}
237
238bool HasCUDAComponent(const Symbol &sym);
239bool IsCUDAAddressSpaceAgnostic(
240 const evaluate::characteristics::DummyDataObject &);
241
242inline bool IsCUDADevice(const Symbol &sym) {
243 if (const auto *details{sym.GetUltimate().detailsIf<ObjectEntityDetails>()}) {
244 return details->cudaDataAttr() &&
245 *details->cudaDataAttr() == common::CUDADataAttr::Device;
246 }
247 return false;
248}
249
250inline bool IsCUDAShared(const Symbol &sym) {
251 if (const auto *details{sym.GetUltimate().detailsIf<ObjectEntityDetails>()}) {
252 return details->cudaDataAttr() &&
253 *details->cudaDataAttr() == common::CUDADataAttr::Shared;
254 }
255 return false;
256}
257
258inline bool NeedCUDAAlloc(const Symbol &sym) {
259 if (IsDummy(sym)) {
260 return false;
261 }
262 if (const auto *details{sym.GetUltimate().detailsIf<ObjectEntityDetails>()}) {
263 if (details->cudaDataAttr() &&
264 (*details->cudaDataAttr() == common::CUDADataAttr::Device ||
265 *details->cudaDataAttr() == common::CUDADataAttr::Managed ||
266 *details->cudaDataAttr() == common::CUDADataAttr::Unified ||
267 *details->cudaDataAttr() == common::CUDADataAttr::Shared ||
268 *details->cudaDataAttr() == common::CUDADataAttr::Pinned)) {
269 return true;
270 }
271 }
272 return false;
273}
274
275bool CanCUDASymbolBeGlobal(const Symbol &sym);
276
277const Scope *FindCUDADeviceContext(const Scope *);
278std::optional<common::CUDADataAttr> GetCUDADataAttr(const Symbol *);
279
280bool IsAccessible(const Symbol &, const Scope &);
281
282// Return an error if a symbol is not accessible from a scope
283std::optional<parser::MessageFormattedText> CheckAccessibleSymbol(
284 const Scope &, const Symbol &, bool inStructureConstructor = false);
285
286// Analysis of image control statements
287bool IsImageControlStmt(const parser::ExecutableConstruct &);
288// Get the location of the image control statement in this ExecutableConstruct
289parser::CharBlock GetImageControlStmtLocation(
290 const parser::ExecutableConstruct &);
291// Image control statements that reference coarrays need an extra message
292// to clarify why they're image control statements. This function returns
293// std::nullopt for ExecutableConstructs that do not require an extra message.
294std::optional<parser::MessageFixedText> GetImageControlStmtCoarrayMsg(
295 const parser::ExecutableConstruct &);
296
297// Returns the complete list of derived type parameter symbols in
298// the order in which their declarations appear in the derived type
299// definitions (parents first).
300SymbolVector OrderParameterDeclarations(const Symbol &);
301// Returns the complete list of derived type parameter names in the
302// order defined by 7.5.3.2.
303SymbolVector OrderParameterNames(const Symbol &);
304
305// Return an existing or new derived type instance
306const DeclTypeSpec &FindOrInstantiateDerivedType(Scope &, DerivedTypeSpec &&,
307 DeclTypeSpec::Category = DeclTypeSpec::TypeDerived);
308
309// Clone a derived type's component scope for OpenACC use_device with CUDA
310// Fortran: each component named in `path` (e.g. a%b%c -> {b,c}) gets a
311// distinct component symbol with cudaDataAttr Device in a new DerivedTypeSpec.
312// Returns nullptr if `path` is empty or `origType` is not derived.
313const DeclTypeSpec *CloneDerivedTypeForUseDevice(Scope &containingScope,
314 SemanticsContext &, const DeclTypeSpec &origType,
315 llvm::ArrayRef<SourceName> path);
316
317// When a subprogram defined in a submodule defines a separate module
318// procedure whose interface is defined in an ancestor (sub)module,
319// returns a pointer to that interface, else null.
320const Symbol *FindSeparateModuleSubprogramInterface(const Symbol *);
321
322// Determines whether an object might be visible outside a
323// pure function (C1594); returns a non-null Symbol pointer for
324// diagnostic purposes if so.
325const Symbol *FindExternallyVisibleObject(
326 const Symbol &, const Scope &, bool isPointerDefinition);
327
328template <typename A>
329const Symbol *FindExternallyVisibleObject(const A &, const Scope &) {
330 return nullptr; // default base case
331}
332
333template <typename T>
334const Symbol *FindExternallyVisibleObject(
335 const evaluate::Designator<T> &designator, const Scope &scope) {
336 if (const Symbol * symbol{designator.GetBaseObject().symbol()}) {
337 return FindExternallyVisibleObject(*symbol, scope, false);
338 } else if (std::holds_alternative<evaluate::CoarrayRef>(designator.u)) {
339 // Coindexed values are visible even if their image-local objects are not.
340 return designator.GetBaseObject().symbol();
341 } else {
342 return nullptr;
343 }
344}
345
346template <typename T>
347const Symbol *FindExternallyVisibleObject(
348 const evaluate::Expr<T> &expr, const Scope &scope) {
349 return common::visit(
350 [&](const auto &x) { return FindExternallyVisibleObject(x, scope); },
351 expr.u);
352}
353
354// Applies GetUltimate(), then if the symbol is a generic procedure shadowing a
355// specific procedure of the same name, return it instead.
356const Symbol &BypassGeneric(const Symbol &);
357
358using SomeExpr = evaluate::Expr<evaluate::SomeType>;
359
360bool ExprHasTypeCategory(
361 const SomeExpr &expr, const common::TypeCategory &type);
362bool ExprTypeKindIsDefault(
363 const SomeExpr &expr, const SemanticsContext &context);
364
365class GetExprHelper {
366public:
367 explicit GetExprHelper(SemanticsContext *context) : context_{context} {}
368 GetExprHelper() : crashIfNoExpr_{true} {}
369
370 // Specializations for parse tree nodes that have a typedExpr member.
371 const SomeExpr *Get(const parser::Expr &);
372 const SomeExpr *Get(const parser::Variable &);
373 const SomeExpr *Get(const parser::DataStmtConstant &);
374 const SomeExpr *Get(const parser::AllocateObject &);
375 const SomeExpr *Get(const parser::PointerObject &);
376
377 template <typename T> const SomeExpr *Get(const common::Indirection<T> &x) {
378 return Get(x.value());
379 }
380 template <typename T> const SomeExpr *Get(const std::optional<T> &x) {
381 return x ? Get(*x) : nullptr;
382 }
383 template <typename T> const SomeExpr *Get(const T &x) {
384 static_assert(
385 !parser::HasTypedExpr<T>::value, "explicit Get overload must be added");
386 if constexpr (ConstraintTrait<T>) {
387 return Get(x.thing);
388 } else if constexpr (WrapperTrait<T>) {
389 return Get(x.v);
390 } else {
391 return nullptr;
392 }
393 }
394
395private:
396 SemanticsContext *context_{nullptr};
397 const bool crashIfNoExpr_{false};
398};
399
400// If a SemanticsContext is passed, even if null, it is possible for a null
401// pointer to be returned in the event of an expression that had fatal errors.
402// Use these first two forms in semantics checks for best error recovery.
403// If a SemanticsContext is not passed, a missing expression will
404// cause a crash.
405template <typename T>
406const SomeExpr *GetExpr(SemanticsContext *context, const T &x) {
407 return GetExprHelper{context}.Get(x);
408}
409template <typename T>
410const SomeExpr *GetExpr(SemanticsContext &context, const T &x) {
411 return GetExprHelper{&context}.Get(x);
412}
413template <typename T> const SomeExpr *GetExpr(const T &x) {
414 return GetExprHelper{}.Get(x);
415}
416
417const evaluate::Assignment *GetAssignment(const parser::AssignmentStmt &);
418const evaluate::Assignment *GetAssignment(
419 const parser::PointerAssignmentStmt &);
420
421template <typename T> std::optional<std::int64_t> GetIntValue(const T &x) {
422 if (const auto *expr{GetExpr(nullptr, x)}) {
423 return evaluate::ToInt64(*expr);
424 } else {
425 return std::nullopt;
426 }
427}
428
429template <typename T> bool IsZero(const T &expr) {
430 auto value{GetIntValue(expr)};
431 return value && *value == 0;
432}
433
434// 15.2.2
435enum class ProcedureDefinitionClass {
436 None,
437 Intrinsic,
438 External,
439 Internal,
440 Module,
441 Dummy,
442 Pointer,
443 StatementFunction
444};
445
446ProcedureDefinitionClass ClassifyProcedure(const Symbol &);
447
448// Returns a list of storage associations due to EQUIVALENCE in a
449// scope; each storage association is a list of symbol references
450// in ascending order of scope offset. Note that the scope may have
451// more EquivalenceSets than this function's result has storage
452// associations; these are closures over equivalences.
453std::list<std::list<SymbolRef>> GetStorageAssociations(const Scope &);
454
455// Derived type component iterator that provides a C++ LegacyForwardIterator
456// iterator over the Ordered, Direct, Ultimate or Potential components of a
457// DerivedTypeSpec. These iterators can be used with STL algorithms
458// accepting LegacyForwardIterator.
459// The kind of component is a template argument of the iterator factory
460// ComponentIterator.
461//
462// - Ordered components are the components from the component order defined
463// in 7.5.4.7, except that the parent component IS added between the parent
464// component order and the components in order of declaration.
465// This "deviation" is important for structure-constructor analysis.
466// For this kind of iterator, the component tree is recursively visited in the
467// following order:
468// - first, the Ordered components of the parent type (if relevant)
469// - then, the parent component (if relevant, different from 7.5.4.7!)
470// - then, the components in declaration order (without visiting subcomponents)
471//
472// - Ultimate, Direct and Potential components are as defined in 7.5.1.
473// - Ultimate components of a derived type are the closure of its components
474// of intrinsic type, its ALLOCATABLE or POINTER components, and the
475// ultimate components of its non-ALLOCATABLE non-POINTER derived type
476// components. (No ultimate component has a derived type unless it is
477// ALLOCATABLE or POINTER.)
478// - Direct components of a derived type are all of its components, and all
479// of the direct components of its non-ALLOCATABLE non-POINTER derived type
480// components. (Direct components are always present.)
481// - Potential subobject components of a derived type are the closure of
482// its non-POINTER components and the potential subobject components of
483// its non-POINTER derived type components. (The lifetime of each
484// potential subobject component is that of the entire instance.)
485// - PotentialAndPointer subobject components of a derived type are the
486// closure of its components (including POINTERs) and the
487// PotentialAndPointer subobject components of its non-POINTER derived type
488// components.
489//
490// type t1 ultimate components: x, a, p
491// real x direct components: x, a, p
492// real, allocatable :: a potential components: x, a
493// real, pointer :: p potential & pointers: x, a, p
494// end type
495// type t2 ultimate components: y, c%x, c%a, c%p, b
496// real y direct components: y, c, c%x, c%a, c%p, b
497// type(t1) :: c potential components: y, c, c%x, c%a, b, b%x, b%a
498// type(t1), allocatable :: b potential & pointers: potentials + c%p + b%p
499// end type
500//
501// Parent and procedure components are considered against these definitions.
502// For this kind of iterator, the component tree is recursively visited in the
503// following order:
504// - the parent component first (if relevant)
505// - then, the components of the parent type (if relevant)
506// + visiting the component and then, if it is derived type data component,
507// visiting the subcomponents before visiting the next
508// component in declaration order.
509// - then, components in declaration order, similarly to components of parent
510// type.
511// Here, the parent component is visited first so that search for a component
512// verifying a property will never descend into a component that already
513// verifies the property (this helps giving clearer feedback).
514//
515// ComponentIterator::const_iterator remain valid during the whole lifetime of
516// the DerivedTypeSpec passed by reference to the ComponentIterator factory.
517// Their validity is independent of the ComponentIterator factory lifetime.
518//
519// For safety and simplicity, the iterators are read only and can only be
520// incremented. This could be changed if desired.
521//
522// Note that iterators are made in such a way that one can easily test and build
523// info message in the following way:
524// ComponentIterator<ComponentKind::...> comp{derived}
525// if (auto it{std::find_if(comp.begin(), comp.end(), predicate)}) {
526// msg = it.BuildResultDesignatorName() + " verifies predicates";
527// const Symbol *component{*it};
528// ....
529// }
530
531ENUM_CLASS(ComponentKind, Ordered, Direct, Ultimate, Potential, Scope,
532 PotentialAndPointer)
533
534template <ComponentKind componentKind> class ComponentIterator {
535public:
536 ComponentIterator(const DerivedTypeSpec &derived) : derived_{derived} {}
537 class const_iterator {
538 public:
539 using iterator_category = std::forward_iterator_tag;
540 using value_type = SymbolRef;
541 using difference_type = void;
542 using pointer = const Symbol *;
543 using reference = const Symbol &;
544
545 static const_iterator Create(const DerivedTypeSpec &);
546
547 const_iterator &operator++() {
548 Increment();
549 return *this;
550 }
551 const_iterator operator++(int) {
552 const_iterator tmp(*this);
553 Increment();
554 return tmp;
555 }
556 reference operator*() const {
557 CHECK(!componentPath_.empty());
558 return DEREF(componentPath_.back().component());
559 }
560 pointer operator->() const { return &**this; }
561
562 bool operator==(const const_iterator &other) const {
563 return componentPath_ == other.componentPath_;
564 }
565 bool operator!=(const const_iterator &other) const {
566 return !(*this == other);
567 }
568
569 // bool() operator indicates if the iterator can be dereferenced without
570 // having to check against an end() iterator.
571 explicit operator bool() const { return !componentPath_.empty(); }
572
573 // Returns the current sequence of components, including parent components.
574 SymbolVector GetComponentPath() const;
575
576 // Builds a designator name of the referenced component for messages.
577 // The designator helps when the component referred to by the iterator
578 // may be "buried" into other components. This gives the full
579 // path inside the iterated derived type: e.g "%a%b%c%ultimate"
580 // when it->name() only gives "ultimate". Parent components are
581 // part of the path for clarity, even though they could be
582 // skipped.
583 std::string BuildResultDesignatorName() const;
584
585 private:
586 using name_iterator =
587 std::conditional_t<componentKind == ComponentKind::Scope,
588 typename Scope::const_iterator,
589 typename std::list<SourceName>::const_iterator>;
590
591 class ComponentPathNode {
592 public:
593 explicit ComponentPathNode(const DerivedTypeSpec &derived)
594 : derived_{derived} {
595 if constexpr (componentKind == ComponentKind::Scope) {
596 const Scope &scope{DEREF(derived.GetScope())};
597 nameIterator_ = scope.cbegin();
598 nameEnd_ = scope.cend();
599 } else {
600 const std::list<SourceName> &nameList{
601 derived.typeSymbol().get<DerivedTypeDetails>().componentNames()};
602 nameIterator_ = nameList.cbegin();
603 nameEnd_ = nameList.cend();
604 }
605 }
606 const Symbol *component() const { return component_; }
607 void set_component(const Symbol &component) { component_ = &component; }
608 bool visited() const { return visited_; }
609 void set_visited(bool yes) { visited_ = yes; }
610 bool descended() const { return descended_; }
611 void set_descended(bool yes) { descended_ = yes; }
612 name_iterator &nameIterator() { return nameIterator_; }
613 name_iterator nameEnd() { return nameEnd_; }
614 const Symbol &GetTypeSymbol() const { return derived_->typeSymbol(); }
615 const Scope &GetScope() const {
616 return derived_->scope() ? *derived_->scope()
617 : DEREF(GetTypeSymbol().scope());
618 }
619 bool operator==(const ComponentPathNode &that) const {
620 return &*derived_ == &*that.derived_ &&
621 nameIterator_ == that.nameIterator_ &&
622 component_ == that.component_;
623 }
624
625 private:
626 common::Reference<const DerivedTypeSpec> derived_;
627 name_iterator nameEnd_;
628 name_iterator nameIterator_;
629 const Symbol *component_{nullptr}; // until Increment()
630 bool visited_{false};
631 bool descended_{false};
632 };
633
634 const DerivedTypeSpec *PlanComponentTraversal(
635 const Symbol &component) const;
636 // Advances to the next relevant symbol, if any. Afterwards, the
637 // iterator will either be at its end or contain no null component().
638 void Increment();
639
640 std::vector<ComponentPathNode> componentPath_;
641 };
642
643 const_iterator begin() { return cbegin(); }
644 const_iterator end() { return cend(); }
645 const_iterator cbegin() { return const_iterator::Create(derived_); }
646 const_iterator cend() { return const_iterator{}; }
647
648private:
649 const DerivedTypeSpec &derived_;
650};
651
652extern template class ComponentIterator<ComponentKind::Ordered>;
653extern template class ComponentIterator<ComponentKind::Direct>;
654extern template class ComponentIterator<ComponentKind::Ultimate>;
655extern template class ComponentIterator<ComponentKind::Potential>;
656extern template class ComponentIterator<ComponentKind::Scope>;
657extern template class ComponentIterator<ComponentKind::PotentialAndPointer>;
658using OrderedComponentIterator = ComponentIterator<ComponentKind::Ordered>;
659using DirectComponentIterator = ComponentIterator<ComponentKind::Direct>;
660using UltimateComponentIterator = ComponentIterator<ComponentKind::Ultimate>;
661using PotentialComponentIterator = ComponentIterator<ComponentKind::Potential>;
662using ScopeComponentIterator = ComponentIterator<ComponentKind::Scope>;
663using PotentialAndPointerComponentIterator =
664 ComponentIterator<ComponentKind::PotentialAndPointer>;
665
666// Common component searches, the iterator returned is referring to the first
667// component, according to the order defined for the related ComponentIterator,
668// that verifies the property from the name.
669// If no component verifies the property, an end iterator (casting to false)
670// is returned. Otherwise, the returned iterator casts to true and can be
671// dereferenced.
672PotentialComponentIterator::const_iterator FindEventOrLockPotentialComponent(
673 const DerivedTypeSpec &, bool ignoreCoarrays = false);
674PotentialComponentIterator::const_iterator FindNotifyPotentialComponent(
675 const DerivedTypeSpec &, bool ignoreCoarrays = false);
676PotentialComponentIterator::const_iterator FindCoarrayPotentialComponent(
677 const DerivedTypeSpec &);
678PotentialAndPointerComponentIterator::const_iterator
679FindPointerPotentialComponent(const DerivedTypeSpec &);
680UltimateComponentIterator::const_iterator FindCoarrayUltimateComponent(
681 const DerivedTypeSpec &);
682UltimateComponentIterator::const_iterator FindPointerUltimateComponent(
683 const DerivedTypeSpec &);
684UltimateComponentIterator::const_iterator FindAllocatableUltimateComponent(
685 const DerivedTypeSpec &);
686DirectComponentIterator::const_iterator FindAllocatableOrPointerDirectComponent(
687 const DerivedTypeSpec &);
688PotentialComponentIterator::const_iterator
689FindPolymorphicAllocatablePotentialComponent(const DerivedTypeSpec &);
690UltimateComponentIterator::const_iterator
691FindCUDADeviceAllocatableUltimateComponent(const DerivedTypeSpec &);
692
693// The LabelEnforce class (given a set of labels) provides an error message if
694// there is a branch to a label which is not in the given set.
695class LabelEnforce {
696public:
697 LabelEnforce(SemanticsContext &context, std::set<parser::Label> &&labels,
698 parser::CharBlock constructSourcePosition, const char *construct)
699 : context_{context}, labels_{labels},
700 constructSourcePosition_{constructSourcePosition}, construct_{
701 construct} {}
702 template <typename T> bool Pre(const T &) { return true; }
703 template <typename T> bool Pre(const parser::Statement<T> &statement) {
704 currentStatementSourcePosition_ = statement.source;
705 return true;
706 }
707
708 template <typename T> void Post(const T &) {}
709
710 void Post(const parser::GotoStmt &gotoStmt);
711 void Post(const parser::ComputedGotoStmt &computedGotoStmt);
712 void Post(const parser::ArithmeticIfStmt &arithmeticIfStmt);
713 void Post(const parser::AssignStmt &assignStmt);
714 void Post(const parser::AssignedGotoStmt &assignedGotoStmt);
715 void Post(const parser::AltReturnSpec &altReturnSpec);
716 void Post(const parser::ErrLabel &errLabel);
717 void Post(const parser::EndLabel &endLabel);
718 void Post(const parser::EorLabel &eorLabel);
719 void CheckLabelUse(const parser::Label &labelUsed);
720
721private:
722 SemanticsContext &context_;
723 std::set<parser::Label> labels_;
724 parser::CharBlock currentStatementSourcePosition_{nullptr};
725 parser::CharBlock constructSourcePosition_{nullptr};
726 const char *construct_{nullptr};
727
728 parser::MessageFormattedText GetEnclosingConstructMsg();
729 void SayWithConstruct(SemanticsContext &context,
730 parser::CharBlock stmtLocation, parser::MessageFormattedText &&message,
731 parser::CharBlock constructLocation);
732};
733// Return the (possibly null) name of the ConstructNode
734const std::optional<parser::Name> &MaybeGetNodeName(
735 const ConstructNode &construct);
736
737// Convert evaluate::GetShape() result into an ArraySpec
738std::optional<ArraySpec> ToArraySpec(
739 evaluate::FoldingContext &, const evaluate::Shape &);
740std::optional<ArraySpec> ToArraySpec(
741 evaluate::FoldingContext &, const std::optional<evaluate::Shape> &);
742
743// Searches a derived type and a scope for a particular defined I/O procedure.
744bool HasDefinedIo(
745 common::DefinedIo, const DerivedTypeSpec &, const Scope * = nullptr);
746
747// Some intrinsic operators have more than one name (e.g. `operator(.eq.)` and
748// `operator(==)`). GetAllNames() returns them all, including symbolName.
749std::forward_list<std::string> GetAllNames(
750 const SemanticsContext &, const SourceName &);
751
752// Determines the derived type of a procedure's initial "dtv" dummy argument,
753// assuming that the procedure is a specific procedure of a defined I/O
754// generic interface,
755const DerivedTypeSpec *GetDtvArgDerivedType(const Symbol &);
756
757// If "expr" exists and is a designator for a deferred length
758// character allocatable whose semantics might change under Fortran 202X,
759// emit a portability warning.
760void WarnOnDeferredLengthCharacterScalar(SemanticsContext &, const SomeExpr *,
761 parser::CharBlock at, const char *what);
762
763bool CouldBeDataPointerValuedFunction(const Symbol *);
764
765template <typename R, typename T>
766std::optional<R> GetConstExpr(SemanticsContext &semanticsContext, const T &x) {
767 using DefaultCharConstantType = evaluate::Ascii;
768 if (const auto *expr{GetExpr(semanticsContext, x)}) {
769 const auto foldExpr{evaluate::Fold(
770 semanticsContext.foldingContext(), common::Clone(*expr))};
771 if constexpr (std::is_same_v<R, std::string>) {
772 return evaluate::GetScalarConstantValue<DefaultCharConstantType>(
773 foldExpr);
774 }
775 }
776 return std::nullopt;
777}
778
779// Returns "m" for a module, "m:sm" for a submodule.
780std::string GetModuleOrSubmoduleName(const Symbol &);
781
782// Return the assembly name emitted for a common block.
783std::string GetCommonBlockObjectName(const Symbol &, bool underscoring);
784
785// Check for ambiguous USE associations
786bool HadUseError(SemanticsContext &, SourceName at, const Symbol *);
787
788bool AreSameModuleSymbol(const Symbol &, const Symbol &);
789
790} // namespace Fortran::semantics
791#endif // FORTRAN_SEMANTICS_TOOLS_H_
Definition indirection.h:31
Definition common.h:217
Definition char-block.h:28
Definition tools.h:365
Definition scope.h:68
Definition semantics.h:68
Definition symbol.h:881
Definition parse-tree.h:1953
Definition parse-tree.h:3537
Definition parse-tree.h:3542
Definition parse-tree.h:3547
Definition parse-tree.h:2551
Definition parse-tree.h:1510
Definition parse-tree.h:1736
Definition tools.h:141
Definition parse-tree.h:2029
Definition parse-tree.h:362
Definition parse-tree.h:1896