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