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