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