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