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