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