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 a pointer direct component?
199bool HasPointerDirectComponent(const DerivedTypeSpec &);
200// Does this type have any defined assignment at any level (or any polymorphic
201// allocatable)?
202bool MayHaveDefinedAssignment(const DerivedTypeSpec &);
203
204bool IsInBlankCommon(const Symbol &);
205bool IsAssumedLengthCharacter(const Symbol &);
206bool IsExternal(const Symbol &);
207bool IsModuleProcedure(const Symbol &);
208bool HasCoarray(const parser::Expr &);
209bool IsAssumedType(const Symbol &);
210bool IsEnumerationType(const Symbol &);
211bool IsEnumerationType(const DerivedTypeSpec &);
212bool IsPolymorphic(const Symbol &);
213bool IsUnlimitedPolymorphic(const Symbol &);
214bool IsPolymorphicAllocatable(const Symbol &);
215
216bool IsDeviceAllocatable(const Symbol &symbol);
217
218inline bool IsCUDADeviceContext(const Scope *scope) {
219 if (scope) {
220 if (const Symbol * symbol{scope->symbol()}) {
221 if (const auto *subp{symbol->detailsIf<SubprogramDetails>()}) {
222 if (auto attrs{subp->cudaSubprogramAttrs()}) {
223 return *attrs != common::CUDASubprogramAttrs::Host;
224 }
225 }
226 }
227 }
228 return false;
229}
230
231inline bool HasCUDAAttr(const Symbol &sym) {
232 if (const auto *details{sym.GetUltimate().detailsIf<ObjectEntityDetails>()}) {
233 if (details->cudaDataAttr()) {
234 return true;
235 }
236 }
237 return false;
238}
239
240bool HasCUDAComponent(const Symbol &sym);
241bool IsCUDAAddressSpaceAgnostic(
242 const evaluate::characteristics::DummyDataObject &);
243
244inline bool IsCUDADevice(const Symbol &sym) {
245 if (const auto *details{sym.GetUltimate().detailsIf<ObjectEntityDetails>()}) {
246 return details->cudaDataAttr() &&
247 *details->cudaDataAttr() == common::CUDADataAttr::Device;
248 }
249 return false;
250}
251
252inline bool IsCUDAShared(const Symbol &sym) {
253 if (const auto *details{sym.GetUltimate().detailsIf<ObjectEntityDetails>()}) {
254 return details->cudaDataAttr() &&
255 *details->cudaDataAttr() == common::CUDADataAttr::Shared;
256 }
257 return false;
258}
259
260inline bool NeedCUDAAlloc(const Symbol &sym) {
261 if (IsDummy(sym)) {
262 return false;
263 }
264 if (const auto *details{sym.GetUltimate().detailsIf<ObjectEntityDetails>()}) {
265 if (details->cudaDataAttr() &&
266 (*details->cudaDataAttr() == common::CUDADataAttr::Device ||
267 *details->cudaDataAttr() == common::CUDADataAttr::Managed ||
268 *details->cudaDataAttr() == common::CUDADataAttr::Unified ||
269 *details->cudaDataAttr() == common::CUDADataAttr::Shared ||
270 *details->cudaDataAttr() == common::CUDADataAttr::Pinned)) {
271 return true;
272 }
273 }
274 return false;
275}
276
277bool CanCUDASymbolBeGlobal(const Symbol &sym);
278
279const Scope *FindCUDADeviceContext(const Scope *);
280std::optional<common::CUDADataAttr> GetCUDADataAttr(const Symbol *);
281
282bool IsAccessible(const Symbol &, const Scope &);
283
284// Return an error if a symbol is not accessible from a scope
285std::optional<parser::MessageFormattedText> CheckAccessibleSymbol(
286 const Scope &, const Symbol &, bool inStructureConstructor = false);
287
288// Analysis of image control statements
289bool IsImageControlStmt(const parser::ExecutableConstruct &);
290// Get the location of the image control statement in this ExecutableConstruct
291parser::CharBlock GetImageControlStmtLocation(
292 const parser::ExecutableConstruct &);
293// Image control statements that reference coarrays need an extra message
294// to clarify why they're image control statements. This function returns
295// std::nullopt for ExecutableConstructs that do not require an extra message.
296std::optional<parser::MessageFixedText> GetImageControlStmtCoarrayMsg(
297 const parser::ExecutableConstruct &);
298
299// Returns the complete list of derived type parameter symbols in
300// the order in which their declarations appear in the derived type
301// definitions (parents first).
302SymbolVector OrderParameterDeclarations(const Symbol &);
303// Returns the complete list of derived type parameter names in the
304// order defined by 7.5.3.2.
305SymbolVector OrderParameterNames(const Symbol &);
306
307// Return an existing or new derived type instance
308const DeclTypeSpec &FindOrInstantiateDerivedType(Scope &, DerivedTypeSpec &&,
309 DeclTypeSpec::Category = DeclTypeSpec::TypeDerived);
310
311// Clone a derived type's component scope for OpenACC use_device with CUDA
312// Fortran: each component named in `path` (e.g. a%b%c -> {b,c}) gets a
313// distinct component symbol with cudaDataAttr Device in a new DerivedTypeSpec.
314// Returns nullptr if `path` is empty or `origType` is not derived.
315const DeclTypeSpec *CloneDerivedTypeForUseDevice(Scope &containingScope,
316 SemanticsContext &, const DeclTypeSpec &origType,
317 llvm::ArrayRef<SourceName> path);
318
319// When a subprogram defined in a submodule defines a separate module
320// procedure whose interface is defined in an ancestor (sub)module,
321// returns a pointer to that interface, else null.
322const Symbol *FindSeparateModuleSubprogramInterface(const Symbol *);
323
324// Determines whether an object might be visible outside a
325// pure function (C1594); returns a non-null Symbol pointer for
326// diagnostic purposes if so.
327const Symbol *FindExternallyVisibleObject(
328 const Symbol &, const Scope &, bool isPointerDefinition);
329
330template <typename A>
331const Symbol *FindExternallyVisibleObject(const A &, const Scope &) {
332 return nullptr; // default base case
333}
334
335template <typename T>
336const Symbol *FindExternallyVisibleObject(
337 const evaluate::Designator<T> &designator, const Scope &scope) {
338 if (const Symbol * symbol{designator.GetBaseObject().symbol()}) {
339 return FindExternallyVisibleObject(*symbol, scope, false);
340 } else if (std::holds_alternative<evaluate::CoarrayRef>(designator.u)) {
341 // Coindexed values are visible even if their image-local objects are not.
342 return designator.GetBaseObject().symbol();
343 } else {
344 return nullptr;
345 }
346}
347
348template <typename T>
349const Symbol *FindExternallyVisibleObject(
350 const evaluate::Expr<T> &expr, const Scope &scope) {
351 return common::visit(
352 [&](const auto &x) { return FindExternallyVisibleObject(x, scope); },
353 expr.u);
354}
355
356// Applies GetUltimate(), then if the symbol is a generic procedure shadowing a
357// specific procedure of the same name, return it instead.
358const Symbol &BypassGeneric(const Symbol &);
359
360using SomeExpr = evaluate::Expr<evaluate::SomeType>;
361
362bool ExprHasTypeCategory(
363 const SomeExpr &expr, const common::TypeCategory &type);
364bool ExprTypeKindIsDefault(
365 const SomeExpr &expr, const SemanticsContext &context);
366
367class GetExprHelper {
368public:
369 explicit GetExprHelper(SemanticsContext *context) : context_{context} {}
370 GetExprHelper() : crashIfNoExpr_{true} {}
371
372 // Specializations for parse tree nodes that have a typedExpr member.
373 const SomeExpr *Get(const parser::Expr &);
374 const SomeExpr *Get(const parser::Variable &);
375 const SomeExpr *Get(const parser::DataStmtConstant &);
376 const SomeExpr *Get(const parser::AllocateObject &);
377 const SomeExpr *Get(const parser::PointerObject &);
378
379 template <typename T> const SomeExpr *Get(const common::Indirection<T> &x) {
380 return Get(x.value());
381 }
382 template <typename T> const SomeExpr *Get(const std::optional<T> &x) {
383 return x ? Get(*x) : nullptr;
384 }
385 template <typename T> const SomeExpr *Get(const T &x) {
386 static_assert(
387 !parser::HasTypedExpr<T>::value, "explicit Get overload must be added");
388 if constexpr (ConstraintTrait<T>) {
389 return Get(x.thing);
390 } else if constexpr (WrapperTrait<T>) {
391 return Get(x.v);
392 } else {
393 return nullptr;
394 }
395 }
396
397private:
398 SemanticsContext *context_{nullptr};
399 const bool crashIfNoExpr_{false};
400};
401
402// If a SemanticsContext is passed, even if null, it is possible for a null
403// pointer to be returned in the event of an expression that had fatal errors.
404// Use these first two forms in semantics checks for best error recovery.
405// If a SemanticsContext is not passed, a missing expression will
406// cause a crash.
407template <typename T>
408const SomeExpr *GetExpr(SemanticsContext *context, const T &x) {
409 return GetExprHelper{context}.Get(x);
410}
411template <typename T>
412const SomeExpr *GetExpr(SemanticsContext &context, const T &x) {
413 return GetExprHelper{&context}.Get(x);
414}
415template <typename T> const SomeExpr *GetExpr(const T &x) {
416 return GetExprHelper{}.Get(x);
417}
418
419const evaluate::Assignment *GetAssignment(const parser::AssignmentStmt &);
420const evaluate::Assignment *GetAssignment(
421 const parser::PointerAssignmentStmt &);
422
423template <typename T> std::optional<std::int64_t> GetIntValue(const T &x) {
424 if (const auto *expr{GetExpr(nullptr, x)}) {
425 return evaluate::ToInt64(*expr);
426 } else {
427 return std::nullopt;
428 }
429}
430
431template <typename T> bool IsZero(const T &expr) {
432 auto value{GetIntValue(expr)};
433 return value && *value == 0;
434}
435
436// 15.2.2
437enum class ProcedureDefinitionClass {
438 None,
439 Intrinsic,
440 External,
441 Internal,
442 Module,
443 Dummy,
444 Pointer,
445 StatementFunction
446};
447
448ProcedureDefinitionClass ClassifyProcedure(const Symbol &);
449
450// Returns a list of storage associations due to EQUIVALENCE in a
451// scope; each storage association is a list of symbol references
452// in ascending order of scope offset. Note that the scope may have
453// more EquivalenceSets than this function's result has storage
454// associations; these are closures over equivalences.
455std::list<std::list<SymbolRef>> GetStorageAssociations(const Scope &);
456
457// Derived type component iterator that provides a C++ LegacyForwardIterator
458// iterator over the Ordered, Direct, Ultimate or Potential components of a
459// DerivedTypeSpec. These iterators can be used with STL algorithms
460// accepting LegacyForwardIterator.
461// The kind of component is a template argument of the iterator factory
462// ComponentIterator.
463//
464// - Ordered components are the components from the component order defined
465// in 7.5.4.7, except that the parent component IS added between the parent
466// component order and the components in order of declaration.
467// This "deviation" is important for structure-constructor analysis.
468// For this kind of iterator, the component tree is recursively visited in the
469// following order:
470// - first, the Ordered components of the parent type (if relevant)
471// - then, the parent component (if relevant, different from 7.5.4.7!)
472// - then, the components in declaration order (without visiting subcomponents)
473//
474// - Ultimate, Direct and Potential components are as defined in 7.5.1.
475// - Ultimate components of a derived type are the closure of its components
476// of intrinsic type, its ALLOCATABLE or POINTER components, and the
477// ultimate components of its non-ALLOCATABLE non-POINTER derived type
478// components. (No ultimate component has a derived type unless it is
479// ALLOCATABLE or POINTER.)
480// - Direct components of a derived type are all of its components, and all
481// of the direct components of its non-ALLOCATABLE non-POINTER derived type
482// components. (Direct components are always present.)
483// - Potential subobject components of a derived type are the closure of
484// its non-POINTER components and the potential subobject components of
485// its non-POINTER derived type components. (The lifetime of each
486// potential subobject component is that of the entire instance.)
487// - PotentialAndPointer subobject components of a derived type are the
488// closure of its components (including POINTERs) and the
489// PotentialAndPointer subobject components of its non-POINTER derived type
490// components.
491//
492// type t1 ultimate components: x, a, p
493// real x direct components: x, a, p
494// real, allocatable :: a potential components: x, a
495// real, pointer :: p potential & pointers: x, a, p
496// end type
497// type t2 ultimate components: y, c%x, c%a, c%p, b
498// real y direct components: y, c, c%x, c%a, c%p, b
499// type(t1) :: c potential components: y, c, c%x, c%a, b, b%x, b%a
500// type(t1), allocatable :: b potential & pointers: potentials + c%p + b%p
501// end type
502//
503// Parent and procedure components are considered against these definitions.
504// For this kind of iterator, the component tree is recursively visited in the
505// following order:
506// - the parent component first (if relevant)
507// - then, the components of the parent type (if relevant)
508// + visiting the component and then, if it is derived type data component,
509// visiting the subcomponents before visiting the next
510// component in declaration order.
511// - then, components in declaration order, similarly to components of parent
512// type.
513// Here, the parent component is visited first so that search for a component
514// verifying a property will never descend into a component that already
515// verifies the property (this helps giving clearer feedback).
516//
517// ComponentIterator::const_iterator remain valid during the whole lifetime of
518// the DerivedTypeSpec passed by reference to the ComponentIterator factory.
519// Their validity is independent of the ComponentIterator factory lifetime.
520//
521// For safety and simplicity, the iterators are read only and can only be
522// incremented. This could be changed if desired.
523//
524// Note that iterators are made in such a way that one can easily test and build
525// info message in the following way:
526// ComponentIterator<ComponentKind::...> comp{derived}
527// if (auto it{std::find_if(comp.begin(), comp.end(), predicate)}) {
528// msg = it.BuildResultDesignatorName() + " verifies predicates";
529// const Symbol *component{*it};
530// ....
531// }
532
533ENUM_CLASS(ComponentKind, Ordered, Direct, Ultimate, Potential, Scope,
534 PotentialAndPointer)
535
536template <ComponentKind componentKind> class ComponentIterator {
537public:
538 ComponentIterator(const DerivedTypeSpec &derived) : derived_{derived} {}
539 class const_iterator {
540 public:
541 using iterator_category = std::forward_iterator_tag;
542 using value_type = SymbolRef;
543 using difference_type = void;
544 using pointer = const Symbol *;
545 using reference = const Symbol &;
546
547 static const_iterator Create(const DerivedTypeSpec &);
548
549 const_iterator &operator++() {
550 Increment();
551 return *this;
552 }
553 const_iterator operator++(int) {
554 const_iterator tmp(*this);
555 Increment();
556 return tmp;
557 }
558 reference operator*() const {
559 CHECK(!componentPath_.empty());
560 return DEREF(componentPath_.back().component());
561 }
562 pointer operator->() const { return &**this; }
563
564 bool operator==(const const_iterator &other) const {
565 return componentPath_ == other.componentPath_;
566 }
567 bool operator!=(const const_iterator &other) const {
568 return !(*this == other);
569 }
570
571 // bool() operator indicates if the iterator can be dereferenced without
572 // having to check against an end() iterator.
573 explicit operator bool() const { return !componentPath_.empty(); }
574
575 // Returns the current sequence of components, including parent components.
576 SymbolVector GetComponentPath() const;
577
578 // Builds a designator name of the referenced component for messages.
579 // The designator helps when the component referred to by the iterator
580 // may be "buried" into other components. This gives the full
581 // path inside the iterated derived type: e.g "%a%b%c%ultimate"
582 // when it->name() only gives "ultimate". Parent components are
583 // part of the path for clarity, even though they could be
584 // skipped.
585 std::string BuildResultDesignatorName() const;
586
587 private:
588 using name_iterator =
589 std::conditional_t<componentKind == ComponentKind::Scope,
590 typename Scope::const_iterator,
591 typename std::list<SourceName>::const_iterator>;
592
593 class ComponentPathNode {
594 public:
595 explicit ComponentPathNode(const DerivedTypeSpec &derived)
596 : derived_{derived} {
597 if constexpr (componentKind == ComponentKind::Scope) {
598 const Scope &scope{DEREF(derived.GetScope())};
599 nameIterator_ = scope.cbegin();
600 nameEnd_ = scope.cend();
601 } else {
602 const std::list<SourceName> &nameList{
603 derived.typeSymbol().get<DerivedTypeDetails>().componentNames()};
604 nameIterator_ = nameList.cbegin();
605 nameEnd_ = nameList.cend();
606 }
607 }
608 const Symbol *component() const { return component_; }
609 void set_component(const Symbol &component) { component_ = &component; }
610 bool visited() const { return visited_; }
611 void set_visited(bool yes) { visited_ = yes; }
612 bool descended() const { return descended_; }
613 void set_descended(bool yes) { descended_ = yes; }
614 name_iterator &nameIterator() { return nameIterator_; }
615 name_iterator nameEnd() { return nameEnd_; }
616 const Symbol &GetTypeSymbol() const { return derived_->typeSymbol(); }
617 const Scope &GetScope() const {
618 return derived_->scope() ? *derived_->scope()
619 : DEREF(GetTypeSymbol().scope());
620 }
621 bool operator==(const ComponentPathNode &that) const {
622 return &*derived_ == &*that.derived_ &&
623 nameIterator_ == that.nameIterator_ &&
624 component_ == that.component_;
625 }
626
627 private:
628 common::Reference<const DerivedTypeSpec> derived_;
629 name_iterator nameEnd_;
630 name_iterator nameIterator_;
631 const Symbol *component_{nullptr}; // until Increment()
632 bool visited_{false};
633 bool descended_{false};
634 };
635
636 const DerivedTypeSpec *PlanComponentTraversal(
637 const Symbol &component) const;
638 // Advances to the next relevant symbol, if any. Afterwards, the
639 // iterator will either be at its end or contain no null component().
640 void Increment();
641
642 std::vector<ComponentPathNode> componentPath_;
643 };
644
645 const_iterator begin() { return cbegin(); }
646 const_iterator end() { return cend(); }
647 const_iterator cbegin() { return const_iterator::Create(derived_); }
648 const_iterator cend() { return const_iterator{}; }
649
650private:
651 const DerivedTypeSpec &derived_;
652};
653
654extern template class ComponentIterator<ComponentKind::Ordered>;
655extern template class ComponentIterator<ComponentKind::Direct>;
656extern template class ComponentIterator<ComponentKind::Ultimate>;
657extern template class ComponentIterator<ComponentKind::Potential>;
658extern template class ComponentIterator<ComponentKind::Scope>;
659extern template class ComponentIterator<ComponentKind::PotentialAndPointer>;
660using OrderedComponentIterator = ComponentIterator<ComponentKind::Ordered>;
661using DirectComponentIterator = ComponentIterator<ComponentKind::Direct>;
662using UltimateComponentIterator = ComponentIterator<ComponentKind::Ultimate>;
663using PotentialComponentIterator = ComponentIterator<ComponentKind::Potential>;
664using ScopeComponentIterator = ComponentIterator<ComponentKind::Scope>;
665using PotentialAndPointerComponentIterator =
666 ComponentIterator<ComponentKind::PotentialAndPointer>;
667
668// Common component searches, the iterator returned is referring to the first
669// component, according to the order defined for the related ComponentIterator,
670// that verifies the property from the name.
671// If no component verifies the property, an end iterator (casting to false)
672// is returned. Otherwise, the returned iterator casts to true and can be
673// dereferenced.
674PotentialComponentIterator::const_iterator FindEventOrLockPotentialComponent(
675 const DerivedTypeSpec &, bool ignoreCoarrays = false);
676PotentialComponentIterator::const_iterator FindNotifyPotentialComponent(
677 const DerivedTypeSpec &, bool ignoreCoarrays = false);
678PotentialComponentIterator::const_iterator FindCoarrayPotentialComponent(
679 const DerivedTypeSpec &);
680PotentialAndPointerComponentIterator::const_iterator
681FindPointerPotentialComponent(const DerivedTypeSpec &);
682UltimateComponentIterator::const_iterator FindCoarrayUltimateComponent(
683 const DerivedTypeSpec &);
684UltimateComponentIterator::const_iterator FindPointerUltimateComponent(
685 const DerivedTypeSpec &);
686UltimateComponentIterator::const_iterator FindAllocatableUltimateComponent(
687 const DerivedTypeSpec &);
688DirectComponentIterator::const_iterator FindAllocatableOrPointerDirectComponent(
689 const DerivedTypeSpec &);
690PotentialComponentIterator::const_iterator
691FindPolymorphicAllocatablePotentialComponent(const DerivedTypeSpec &);
692UltimateComponentIterator::const_iterator
693FindCUDADeviceAllocatableUltimateComponent(const DerivedTypeSpec &);
694
695// The LabelEnforce class (given a set of labels) provides an error message if
696// there is a branch to a label which is not in the given set.
697class LabelEnforce {
698public:
699 LabelEnforce(SemanticsContext &context, std::set<parser::Label> &&labels,
700 parser::CharBlock constructSourcePosition, const char *construct)
701 : context_{context}, labels_{labels},
702 constructSourcePosition_{constructSourcePosition}, construct_{
703 construct} {}
704 template <typename T> bool Pre(const T &) { return true; }
705 template <typename T> bool Pre(const parser::Statement<T> &statement) {
706 currentStatementSourcePosition_ = statement.source;
707 return true;
708 }
709
710 template <typename T> void Post(const T &) {}
711
712 void Post(const parser::GotoStmt &gotoStmt);
713 void Post(const parser::ComputedGotoStmt &computedGotoStmt);
714 void Post(const parser::ArithmeticIfStmt &arithmeticIfStmt);
715 void Post(const parser::AssignStmt &assignStmt);
716 void Post(const parser::AssignedGotoStmt &assignedGotoStmt);
717 void Post(const parser::AltReturnSpec &altReturnSpec);
718 void Post(const parser::ErrLabel &errLabel);
719 void Post(const parser::EndLabel &endLabel);
720 void Post(const parser::EorLabel &eorLabel);
721 void CheckLabelUse(const parser::Label &labelUsed);
722
723private:
724 SemanticsContext &context_;
725 std::set<parser::Label> labels_;
726 parser::CharBlock currentStatementSourcePosition_{nullptr};
727 parser::CharBlock constructSourcePosition_{nullptr};
728 const char *construct_{nullptr};
729
730 parser::MessageFormattedText GetEnclosingConstructMsg();
731 void SayWithConstruct(SemanticsContext &context,
732 parser::CharBlock stmtLocation, parser::MessageFormattedText &&message,
733 parser::CharBlock constructLocation);
734};
735// Return the (possibly null) name of the ConstructNode
736const std::optional<parser::Name> &MaybeGetNodeName(
737 const ConstructNode &construct);
738
739// Convert evaluate::GetShape() result into an ArraySpec
740std::optional<ArraySpec> ToArraySpec(
741 evaluate::FoldingContext &, const evaluate::Shape &);
742std::optional<ArraySpec> ToArraySpec(
743 evaluate::FoldingContext &, const std::optional<evaluate::Shape> &);
744
745// Searches a derived type and a scope for a particular defined I/O procedure.
746bool HasDefinedIo(
747 common::DefinedIo, const DerivedTypeSpec &, const Scope * = nullptr);
748
749// Some intrinsic operators have more than one name (e.g. `operator(.eq.)` and
750// `operator(==)`). GetAllNames() returns them all, including symbolName.
751std::forward_list<std::string> GetAllNames(
752 const SemanticsContext &, const SourceName &);
753
754// Determines the derived type of a procedure's initial "dtv" dummy argument,
755// assuming that the procedure is a specific procedure of a defined I/O
756// generic interface,
757const DerivedTypeSpec *GetDtvArgDerivedType(const Symbol &);
758
759// If "expr" exists and is a designator for a deferred length
760// character allocatable whose semantics might change under Fortran 202X,
761// emit a portability warning.
762void WarnOnDeferredLengthCharacterScalar(SemanticsContext &, const SomeExpr *,
763 parser::CharBlock at, const char *what);
764
765bool CouldBeDataPointerValuedFunction(const Symbol *);
766
767template <typename R, typename T>
768std::optional<R> GetConstExpr(SemanticsContext &semanticsContext, const T &x) {
769 using DefaultCharConstantType = evaluate::Ascii;
770 if (const auto *expr{GetExpr(semanticsContext, x)}) {
771 const auto foldExpr{evaluate::Fold(
772 semanticsContext.foldingContext(), common::Clone(*expr))};
773 if constexpr (std::is_same_v<R, std::string>) {
774 return evaluate::GetScalarConstantValue<DefaultCharConstantType>(
775 foldExpr);
776 }
777 }
778 return std::nullopt;
779}
780
781// Returns "m" for a module, "m:sm" for a submodule.
782std::string GetModuleOrSubmoduleName(const Symbol &);
783
784// Return the assembly name emitted for a common block.
785std::string GetCommonBlockObjectName(const Symbol &, bool underscoring);
786
787// Check for ambiguous USE associations
788bool HadUseError(SemanticsContext &, SourceName at, const Symbol *);
789
790bool AreSameModuleSymbol(const Symbol &, const Symbol &);
791
792} // namespace Fortran::semantics
793#endif // FORTRAN_SEMANTICS_TOOLS_H_
Definition indirection.h:31
Definition common.h:217
Definition char-block.h:26
Definition tools.h:367
Definition scope.h:68
Definition semantics.h:67
Definition symbol.h:910
Definition parse-tree.h:1955
Definition parse-tree.h:3544
Definition parse-tree.h:3549
Definition parse-tree.h:3554
Definition parse-tree.h:2553
Definition parse-tree.h:1512
Definition parse-tree.h:1738
Definition tools.h:145
Definition parse-tree.h:2031
Definition parse-tree.h:362
Definition parse-tree.h:1898