xref: /llvm-project/flang/lib/Semantics/resolve-names.cpp (revision 0f973ac783aa100cfbce1cd2c6e8a3a8f648fae7)
1 //===-- lib/Semantics/resolve-names.cpp -----------------------------------===//
2 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3 // See https://llvm.org/LICENSE.txt for license information.
4 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5 //
6 //===----------------------------------------------------------------------===//
7 
8 #include "resolve-names.h"
9 #include "assignment.h"
10 #include "definable.h"
11 #include "mod-file.h"
12 #include "pointer-assignment.h"
13 #include "program-tree.h"
14 #include "resolve-directives.h"
15 #include "resolve-names-utils.h"
16 #include "rewrite-parse-tree.h"
17 #include "flang/Common/Fortran.h"
18 #include "flang/Common/default-kinds.h"
19 #include "flang/Common/indirection.h"
20 #include "flang/Common/restorer.h"
21 #include "flang/Common/visit.h"
22 #include "flang/Evaluate/characteristics.h"
23 #include "flang/Evaluate/check-expression.h"
24 #include "flang/Evaluate/common.h"
25 #include "flang/Evaluate/fold-designator.h"
26 #include "flang/Evaluate/fold.h"
27 #include "flang/Evaluate/intrinsics.h"
28 #include "flang/Evaluate/tools.h"
29 #include "flang/Evaluate/type.h"
30 #include "flang/Parser/parse-tree-visitor.h"
31 #include "flang/Parser/parse-tree.h"
32 #include "flang/Parser/tools.h"
33 #include "flang/Semantics/attr.h"
34 #include "flang/Semantics/expression.h"
35 #include "flang/Semantics/scope.h"
36 #include "flang/Semantics/semantics.h"
37 #include "flang/Semantics/symbol.h"
38 #include "flang/Semantics/tools.h"
39 #include "flang/Semantics/type.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include <list>
42 #include <map>
43 #include <set>
44 #include <stack>
45 
46 namespace Fortran::semantics {
47 
48 using namespace parser::literals;
49 
50 template <typename T> using Indirection = common::Indirection<T>;
51 using Message = parser::Message;
52 using Messages = parser::Messages;
53 using MessageFixedText = parser::MessageFixedText;
54 using MessageFormattedText = parser::MessageFormattedText;
55 
56 class ResolveNamesVisitor;
57 class ScopeHandler;
58 
59 // ImplicitRules maps initial character of identifier to the DeclTypeSpec
60 // representing the implicit type; std::nullopt if none.
61 // It also records the presence of IMPLICIT NONE statements.
62 // When inheritFromParent is set, defaults come from the parent rules.
63 class ImplicitRules {
64 public:
65   ImplicitRules(SemanticsContext &context, const ImplicitRules *parent)
66       : parent_{parent}, context_{context},
67         inheritFromParent_{parent != nullptr} {}
68   bool isImplicitNoneType() const;
69   bool isImplicitNoneExternal() const;
70   void set_isImplicitNoneType(bool x) { isImplicitNoneType_ = x; }
71   void set_isImplicitNoneExternal(bool x) { isImplicitNoneExternal_ = x; }
72   void set_inheritFromParent(bool x) { inheritFromParent_ = x; }
73   // Get the implicit type for this name. May be null.
74   const DeclTypeSpec *GetType(
75       SourceName, bool respectImplicitNone = true) const;
76   // Record the implicit type for the range of characters [fromLetter,
77   // toLetter].
78   void SetTypeMapping(const DeclTypeSpec &type, parser::Location fromLetter,
79       parser::Location toLetter);
80 
81 private:
82   static char Incr(char ch);
83 
84   const ImplicitRules *parent_;
85   SemanticsContext &context_;
86   bool inheritFromParent_{false}; // look in parent if not specified here
87   bool isImplicitNoneType_{
88       context_.IsEnabled(common::LanguageFeature::ImplicitNoneTypeAlways)};
89   bool isImplicitNoneExternal_{false};
90   // map_ contains the mapping between letters and types that were defined
91   // by the IMPLICIT statements of the related scope. It does not contain
92   // the default Fortran mappings nor the mapping defined in parents.
93   std::map<char, common::Reference<const DeclTypeSpec>> map_;
94 
95   friend llvm::raw_ostream &operator<<(
96       llvm::raw_ostream &, const ImplicitRules &);
97   friend void ShowImplicitRule(
98       llvm::raw_ostream &, const ImplicitRules &, char);
99 };
100 
101 // scope -> implicit rules for that scope
102 using ImplicitRulesMap = std::map<const Scope *, ImplicitRules>;
103 
104 // Track statement source locations and save messages.
105 class MessageHandler {
106 public:
107   MessageHandler() { DIE("MessageHandler: default-constructed"); }
108   explicit MessageHandler(SemanticsContext &c) : context_{&c} {}
109   Messages &messages() { return context_->messages(); };
110   const std::optional<SourceName> &currStmtSource() {
111     return context_->location();
112   }
113   void set_currStmtSource(const std::optional<SourceName> &source) {
114     context_->set_location(source);
115   }
116 
117   // Emit a message associated with the current statement source.
118   Message &Say(MessageFixedText &&);
119   Message &Say(MessageFormattedText &&);
120   // Emit a message about a SourceName
121   Message &Say(const SourceName &, MessageFixedText &&);
122   // Emit a formatted message associated with a source location.
123   template <typename... A>
124   Message &Say(const SourceName &source, MessageFixedText &&msg, A &&...args) {
125     return context_->Say(source, std::move(msg), std::forward<A>(args)...);
126   }
127 
128 private:
129   SemanticsContext *context_;
130 };
131 
132 // Inheritance graph for the parse tree visitation classes that follow:
133 //   BaseVisitor
134 //   + AttrsVisitor
135 //   | + DeclTypeSpecVisitor
136 //   |   + ImplicitRulesVisitor
137 //   |     + ScopeHandler ------------------+
138 //   |       + ModuleVisitor -------------+ |
139 //   |       + GenericHandler -------+    | |
140 //   |       | + InterfaceVisitor    |    | |
141 //   |       +-+ SubprogramVisitor ==|==+ | |
142 //   + ArraySpecVisitor              |  | | |
143 //     + DeclarationVisitor <--------+  | | |
144 //       + ConstructVisitor             | | |
145 //         + ResolveNamesVisitor <------+-+-+
146 
147 class BaseVisitor {
148 public:
149   BaseVisitor() { DIE("BaseVisitor: default-constructed"); }
150   BaseVisitor(
151       SemanticsContext &c, ResolveNamesVisitor &v, ImplicitRulesMap &rules)
152       : implicitRulesMap_{&rules}, this_{&v}, context_{&c}, messageHandler_{c} {
153   }
154   template <typename T> void Walk(const T &);
155 
156   MessageHandler &messageHandler() { return messageHandler_; }
157   const std::optional<SourceName> &currStmtSource() {
158     return context_->location();
159   }
160   SemanticsContext &context() const { return *context_; }
161   evaluate::FoldingContext &GetFoldingContext() const {
162     return context_->foldingContext();
163   }
164   bool IsIntrinsic(
165       const SourceName &name, std::optional<Symbol::Flag> flag) const {
166     if (!flag) {
167       return context_->intrinsics().IsIntrinsic(name.ToString());
168     } else if (flag == Symbol::Flag::Function) {
169       return context_->intrinsics().IsIntrinsicFunction(name.ToString());
170     } else if (flag == Symbol::Flag::Subroutine) {
171       return context_->intrinsics().IsIntrinsicSubroutine(name.ToString());
172     } else {
173       DIE("expected Subroutine or Function flag");
174     }
175   }
176 
177   bool InModuleFile() const {
178     return GetFoldingContext().moduleFileName().has_value();
179   }
180 
181   // Make a placeholder symbol for a Name that otherwise wouldn't have one.
182   // It is not in any scope and always has MiscDetails.
183   void MakePlaceholder(const parser::Name &, MiscDetails::Kind);
184 
185   template <typename T> common::IfNoLvalue<T, T> FoldExpr(T &&expr) {
186     return evaluate::Fold(GetFoldingContext(), std::move(expr));
187   }
188 
189   template <typename T> MaybeExpr EvaluateExpr(const T &expr) {
190     return FoldExpr(AnalyzeExpr(*context_, expr));
191   }
192 
193   template <typename T>
194   MaybeExpr EvaluateNonPointerInitializer(
195       const Symbol &symbol, const T &expr, parser::CharBlock source) {
196     if (!context().HasError(symbol)) {
197       if (auto maybeExpr{AnalyzeExpr(*context_, expr)}) {
198         auto restorer{GetFoldingContext().messages().SetLocation(source)};
199         return evaluate::NonPointerInitializationExpr(
200             symbol, std::move(*maybeExpr), GetFoldingContext());
201       }
202     }
203     return std::nullopt;
204   }
205 
206   template <typename T> MaybeIntExpr EvaluateIntExpr(const T &expr) {
207     return semantics::EvaluateIntExpr(*context_, expr);
208   }
209 
210   template <typename T>
211   MaybeSubscriptIntExpr EvaluateSubscriptIntExpr(const T &expr) {
212     if (MaybeIntExpr maybeIntExpr{EvaluateIntExpr(expr)}) {
213       return FoldExpr(evaluate::ConvertToType<evaluate::SubscriptInteger>(
214           std::move(*maybeIntExpr)));
215     } else {
216       return std::nullopt;
217     }
218   }
219 
220   template <typename... A> Message &Say(A &&...args) {
221     return messageHandler_.Say(std::forward<A>(args)...);
222   }
223   template <typename... A>
224   Message &Say(
225       const parser::Name &name, MessageFixedText &&text, const A &...args) {
226     return messageHandler_.Say(name.source, std::move(text), args...);
227   }
228 
229 protected:
230   ImplicitRulesMap *implicitRulesMap_{nullptr};
231 
232 private:
233   ResolveNamesVisitor *this_;
234   SemanticsContext *context_;
235   MessageHandler messageHandler_;
236 };
237 
238 // Provide Post methods to collect attributes into a member variable.
239 class AttrsVisitor : public virtual BaseVisitor {
240 public:
241   bool BeginAttrs(); // always returns true
242   Attrs GetAttrs();
243   std::optional<common::CUDADataAttr> cudaDataAttr() { return cudaDataAttr_; }
244   Attrs EndAttrs();
245   bool SetPassNameOn(Symbol &);
246   void SetBindNameOn(Symbol &);
247   void Post(const parser::LanguageBindingSpec &);
248   bool Pre(const parser::IntentSpec &);
249   bool Pre(const parser::Pass &);
250 
251   bool CheckAndSet(Attr);
252 
253 // Simple case: encountering CLASSNAME causes ATTRNAME to be set.
254 #define HANDLE_ATTR_CLASS(CLASSNAME, ATTRNAME) \
255   bool Pre(const parser::CLASSNAME &) { \
256     CheckAndSet(Attr::ATTRNAME); \
257     return false; \
258   }
259   HANDLE_ATTR_CLASS(PrefixSpec::Elemental, ELEMENTAL)
260   HANDLE_ATTR_CLASS(PrefixSpec::Impure, IMPURE)
261   HANDLE_ATTR_CLASS(PrefixSpec::Module, MODULE)
262   HANDLE_ATTR_CLASS(PrefixSpec::Non_Recursive, NON_RECURSIVE)
263   HANDLE_ATTR_CLASS(PrefixSpec::Pure, PURE)
264   HANDLE_ATTR_CLASS(PrefixSpec::Recursive, RECURSIVE)
265   HANDLE_ATTR_CLASS(TypeAttrSpec::BindC, BIND_C)
266   HANDLE_ATTR_CLASS(BindAttr::Deferred, DEFERRED)
267   HANDLE_ATTR_CLASS(BindAttr::Non_Overridable, NON_OVERRIDABLE)
268   HANDLE_ATTR_CLASS(Abstract, ABSTRACT)
269   HANDLE_ATTR_CLASS(Allocatable, ALLOCATABLE)
270   HANDLE_ATTR_CLASS(Asynchronous, ASYNCHRONOUS)
271   HANDLE_ATTR_CLASS(Contiguous, CONTIGUOUS)
272   HANDLE_ATTR_CLASS(External, EXTERNAL)
273   HANDLE_ATTR_CLASS(Intrinsic, INTRINSIC)
274   HANDLE_ATTR_CLASS(NoPass, NOPASS)
275   HANDLE_ATTR_CLASS(Optional, OPTIONAL)
276   HANDLE_ATTR_CLASS(Parameter, PARAMETER)
277   HANDLE_ATTR_CLASS(Pointer, POINTER)
278   HANDLE_ATTR_CLASS(Protected, PROTECTED)
279   HANDLE_ATTR_CLASS(Save, SAVE)
280   HANDLE_ATTR_CLASS(Target, TARGET)
281   HANDLE_ATTR_CLASS(Value, VALUE)
282   HANDLE_ATTR_CLASS(Volatile, VOLATILE)
283 #undef HANDLE_ATTR_CLASS
284   bool Pre(const common::CUDADataAttr);
285 
286 protected:
287   std::optional<Attrs> attrs_;
288   std::optional<common::CUDADataAttr> cudaDataAttr_;
289 
290   Attr AccessSpecToAttr(const parser::AccessSpec &x) {
291     switch (x.v) {
292     case parser::AccessSpec::Kind::Public:
293       return Attr::PUBLIC;
294     case parser::AccessSpec::Kind::Private:
295       return Attr::PRIVATE;
296     }
297     llvm_unreachable("Switch covers all cases"); // suppress g++ warning
298   }
299   Attr IntentSpecToAttr(const parser::IntentSpec &x) {
300     switch (x.v) {
301     case parser::IntentSpec::Intent::In:
302       return Attr::INTENT_IN;
303     case parser::IntentSpec::Intent::Out:
304       return Attr::INTENT_OUT;
305     case parser::IntentSpec::Intent::InOut:
306       return Attr::INTENT_INOUT;
307     }
308     llvm_unreachable("Switch covers all cases"); // suppress g++ warning
309   }
310 
311 private:
312   bool IsDuplicateAttr(Attr);
313   bool HaveAttrConflict(Attr, Attr, Attr);
314   bool IsConflictingAttr(Attr);
315 
316   MaybeExpr bindName_; // from BIND(C, NAME="...")
317   bool isCDefined_{false}; // BIND(C, NAME="...", CDEFINED) extension
318   std::optional<SourceName> passName_; // from PASS(...)
319 };
320 
321 // Find and create types from declaration-type-spec nodes.
322 class DeclTypeSpecVisitor : public AttrsVisitor {
323 public:
324   using AttrsVisitor::Post;
325   using AttrsVisitor::Pre;
326   void Post(const parser::IntrinsicTypeSpec::DoublePrecision &);
327   void Post(const parser::IntrinsicTypeSpec::DoubleComplex &);
328   void Post(const parser::DeclarationTypeSpec::ClassStar &);
329   void Post(const parser::DeclarationTypeSpec::TypeStar &);
330   bool Pre(const parser::TypeGuardStmt &);
331   void Post(const parser::TypeGuardStmt &);
332   void Post(const parser::TypeSpec &);
333 
334   // Walk the parse tree of a type spec and return the DeclTypeSpec for it.
335   template <typename T>
336   const DeclTypeSpec *ProcessTypeSpec(const T &x, bool allowForward = false) {
337     auto restorer{common::ScopedSet(state_, State{})};
338     set_allowForwardReferenceToDerivedType(allowForward);
339     BeginDeclTypeSpec();
340     Walk(x);
341     const auto *type{GetDeclTypeSpec()};
342     EndDeclTypeSpec();
343     return type;
344   }
345 
346 protected:
347   struct State {
348     bool expectDeclTypeSpec{false}; // should see decl-type-spec only when true
349     const DeclTypeSpec *declTypeSpec{nullptr};
350     struct {
351       DerivedTypeSpec *type{nullptr};
352       DeclTypeSpec::Category category{DeclTypeSpec::TypeDerived};
353     } derived;
354     bool allowForwardReferenceToDerivedType{false};
355   };
356 
357   bool allowForwardReferenceToDerivedType() const {
358     return state_.allowForwardReferenceToDerivedType;
359   }
360   void set_allowForwardReferenceToDerivedType(bool yes) {
361     state_.allowForwardReferenceToDerivedType = yes;
362   }
363 
364   const DeclTypeSpec *GetDeclTypeSpec();
365   void BeginDeclTypeSpec();
366   void EndDeclTypeSpec();
367   void SetDeclTypeSpec(const DeclTypeSpec &);
368   void SetDeclTypeSpecCategory(DeclTypeSpec::Category);
369   DeclTypeSpec::Category GetDeclTypeSpecCategory() const {
370     return state_.derived.category;
371   }
372   KindExpr GetKindParamExpr(
373       TypeCategory, const std::optional<parser::KindSelector> &);
374   void CheckForAbstractType(const Symbol &typeSymbol);
375 
376 private:
377   State state_;
378 
379   void MakeNumericType(TypeCategory, int kind);
380 };
381 
382 // Visit ImplicitStmt and related parse tree nodes and updates implicit rules.
383 class ImplicitRulesVisitor : public DeclTypeSpecVisitor {
384 public:
385   using DeclTypeSpecVisitor::Post;
386   using DeclTypeSpecVisitor::Pre;
387   using ImplicitNoneNameSpec = parser::ImplicitStmt::ImplicitNoneNameSpec;
388 
389   void Post(const parser::ParameterStmt &);
390   bool Pre(const parser::ImplicitStmt &);
391   bool Pre(const parser::LetterSpec &);
392   bool Pre(const parser::ImplicitSpec &);
393   void Post(const parser::ImplicitSpec &);
394 
395   const DeclTypeSpec *GetType(
396       SourceName name, bool respectImplicitNoneType = true) {
397     return implicitRules_->GetType(name, respectImplicitNoneType);
398   }
399   bool isImplicitNoneType() const {
400     return implicitRules_->isImplicitNoneType();
401   }
402   bool isImplicitNoneType(const Scope &scope) const {
403     return implicitRulesMap_->at(&scope).isImplicitNoneType();
404   }
405   bool isImplicitNoneExternal() const {
406     return implicitRules_->isImplicitNoneExternal();
407   }
408   void set_inheritFromParent(bool x) {
409     implicitRules_->set_inheritFromParent(x);
410   }
411 
412 protected:
413   void BeginScope(const Scope &);
414   void SetScope(const Scope &);
415 
416 private:
417   // implicit rules in effect for current scope
418   ImplicitRules *implicitRules_{nullptr};
419   std::optional<SourceName> prevImplicit_;
420   std::optional<SourceName> prevImplicitNone_;
421   std::optional<SourceName> prevImplicitNoneType_;
422   std::optional<SourceName> prevParameterStmt_;
423 
424   bool HandleImplicitNone(const std::list<ImplicitNoneNameSpec> &nameSpecs);
425 };
426 
427 // Track array specifications. They can occur in AttrSpec, EntityDecl,
428 // ObjectDecl, DimensionStmt, CommonBlockObject, BasedPointer, and
429 // ComponentDecl.
430 // 1. INTEGER, DIMENSION(10) :: x
431 // 2. INTEGER :: x(10)
432 // 3. ALLOCATABLE :: x(:)
433 // 4. DIMENSION :: x(10)
434 // 5. COMMON x(10)
435 // 6. POINTER(p,x(10))
436 class ArraySpecVisitor : public virtual BaseVisitor {
437 public:
438   void Post(const parser::ArraySpec &);
439   void Post(const parser::ComponentArraySpec &);
440   void Post(const parser::CoarraySpec &);
441   void Post(const parser::AttrSpec &) { PostAttrSpec(); }
442   void Post(const parser::ComponentAttrSpec &) { PostAttrSpec(); }
443 
444 protected:
445   const ArraySpec &arraySpec();
446   void set_arraySpec(const ArraySpec arraySpec) { arraySpec_ = arraySpec; }
447   const ArraySpec &coarraySpec();
448   void BeginArraySpec();
449   void EndArraySpec();
450   void ClearArraySpec() { arraySpec_.clear(); }
451   void ClearCoarraySpec() { coarraySpec_.clear(); }
452 
453 private:
454   // arraySpec_/coarraySpec_ are populated from any ArraySpec/CoarraySpec
455   ArraySpec arraySpec_;
456   ArraySpec coarraySpec_;
457   // When an ArraySpec is under an AttrSpec or ComponentAttrSpec, it is moved
458   // into attrArraySpec_
459   ArraySpec attrArraySpec_;
460   ArraySpec attrCoarraySpec_;
461 
462   void PostAttrSpec();
463 };
464 
465 // Manages a stack of function result information.  We defer the processing
466 // of a type specification that appears in the prefix of a FUNCTION statement
467 // until the function result variable appears in the specification part
468 // or the end of the specification part.  This allows for forward references
469 // in the type specification to resolve to local names.
470 class FuncResultStack {
471 public:
472   explicit FuncResultStack(ScopeHandler &scopeHandler)
473       : scopeHandler_{scopeHandler} {}
474   ~FuncResultStack();
475 
476   struct FuncInfo {
477     FuncInfo(const Scope &s, SourceName at) : scope{s}, source{at} {}
478     const Scope &scope;
479     SourceName source;
480     // Parse tree of the type specification in the FUNCTION prefix
481     const parser::DeclarationTypeSpec *parsedType{nullptr};
482     // Name of the function RESULT in the FUNCTION suffix, if any
483     const parser::Name *resultName{nullptr};
484     // Result symbol
485     Symbol *resultSymbol{nullptr};
486     bool inFunctionStmt{false}; // true between Pre/Post of FunctionStmt
487   };
488 
489   // Completes the definition of the top function's result.
490   void CompleteFunctionResultType();
491   // Completes the definition of a symbol if it is the top function's result.
492   void CompleteTypeIfFunctionResult(Symbol &);
493 
494   FuncInfo *Top() { return stack_.empty() ? nullptr : &stack_.back(); }
495   FuncInfo &Push(const Scope &scope, SourceName at) {
496     return stack_.emplace_back(scope, at);
497   }
498   void Pop();
499 
500 private:
501   ScopeHandler &scopeHandler_;
502   std::vector<FuncInfo> stack_;
503 };
504 
505 // Manage a stack of Scopes
506 class ScopeHandler : public ImplicitRulesVisitor {
507 public:
508   using ImplicitRulesVisitor::Post;
509   using ImplicitRulesVisitor::Pre;
510 
511   Scope &currScope() { return DEREF(currScope_); }
512   // The enclosing host procedure if current scope is in an internal procedure
513   Scope *GetHostProcedure();
514   // The innermost enclosing program unit scope, ignoring BLOCK and other
515   // construct scopes.
516   Scope &InclusiveScope();
517   // The enclosing scope, skipping derived types.
518   Scope &NonDerivedTypeScope();
519 
520   // Create a new scope and push it on the scope stack.
521   void PushScope(Scope::Kind kind, Symbol *symbol);
522   void PushScope(Scope &scope);
523   void PopScope();
524   void SetScope(Scope &);
525 
526   template <typename T> bool Pre(const parser::Statement<T> &x) {
527     messageHandler().set_currStmtSource(x.source);
528     currScope_->AddSourceRange(x.source);
529     return true;
530   }
531   template <typename T> void Post(const parser::Statement<T> &) {
532     messageHandler().set_currStmtSource(std::nullopt);
533   }
534 
535   // Special messages: already declared; referencing symbol's declaration;
536   // about a type; two names & locations
537   void SayAlreadyDeclared(const parser::Name &, Symbol &);
538   void SayAlreadyDeclared(const SourceName &, Symbol &);
539   void SayAlreadyDeclared(const SourceName &, const SourceName &);
540   void SayWithReason(
541       const parser::Name &, Symbol &, MessageFixedText &&, Message &&);
542   template <typename... A>
543   Message &SayWithDecl(
544       const parser::Name &, Symbol &, MessageFixedText &&, A &&...args);
545   void SayLocalMustBeVariable(const parser::Name &, Symbol &);
546   Message &SayDerivedType(
547       const SourceName &, MessageFixedText &&, const Scope &);
548   Message &Say2(const SourceName &, MessageFixedText &&, const SourceName &,
549       MessageFixedText &&);
550   Message &Say2(
551       const SourceName &, MessageFixedText &&, Symbol &, MessageFixedText &&);
552   Message &Say2(
553       const parser::Name &, MessageFixedText &&, Symbol &, MessageFixedText &&);
554 
555   // Search for symbol by name in current, parent derived type, and
556   // containing scopes
557   Symbol *FindSymbol(const parser::Name &);
558   Symbol *FindSymbol(const Scope &, const parser::Name &);
559   // Search for name only in scope, not in enclosing scopes.
560   Symbol *FindInScope(const Scope &, const parser::Name &);
561   Symbol *FindInScope(const Scope &, const SourceName &);
562   template <typename T> Symbol *FindInScope(const T &name) {
563     return FindInScope(currScope(), name);
564   }
565   // Search for name in a derived type scope and its parents.
566   Symbol *FindInTypeOrParents(const Scope &, const parser::Name &);
567   Symbol *FindInTypeOrParents(const parser::Name &);
568   Symbol *FindInScopeOrBlockConstructs(const Scope &, SourceName);
569   Symbol *FindSeparateModuleProcedureInterface(const parser::Name &);
570   void EraseSymbol(const parser::Name &);
571   void EraseSymbol(const Symbol &symbol) { currScope().erase(symbol.name()); }
572   // Make a new symbol with the name and attrs of an existing one
573   Symbol &CopySymbol(const SourceName &, const Symbol &);
574 
575   // Make symbols in the current or named scope
576   Symbol &MakeSymbol(Scope &, const SourceName &, Attrs);
577   Symbol &MakeSymbol(const SourceName &, Attrs = Attrs{});
578   Symbol &MakeSymbol(const parser::Name &, Attrs = Attrs{});
579   Symbol &MakeHostAssocSymbol(const parser::Name &, const Symbol &);
580 
581   template <typename D>
582   common::IfNoLvalue<Symbol &, D> MakeSymbol(
583       const parser::Name &name, D &&details) {
584     return MakeSymbol(name, Attrs{}, std::move(details));
585   }
586 
587   template <typename D>
588   common::IfNoLvalue<Symbol &, D> MakeSymbol(
589       const parser::Name &name, const Attrs &attrs, D &&details) {
590     return Resolve(name, MakeSymbol(name.source, attrs, std::move(details)));
591   }
592 
593   template <typename D>
594   common::IfNoLvalue<Symbol &, D> MakeSymbol(
595       const SourceName &name, const Attrs &attrs, D &&details) {
596     // Note: don't use FindSymbol here. If this is a derived type scope,
597     // we want to detect whether the name is already declared as a component.
598     auto *symbol{FindInScope(name)};
599     if (!symbol) {
600       symbol = &MakeSymbol(name, attrs);
601       symbol->set_details(std::move(details));
602       return *symbol;
603     }
604     if constexpr (std::is_same_v<DerivedTypeDetails, D>) {
605       if (auto *d{symbol->detailsIf<GenericDetails>()}) {
606         if (!d->specific()) {
607           // derived type with same name as a generic
608           auto *derivedType{d->derivedType()};
609           if (!derivedType) {
610             derivedType =
611                 &currScope().MakeSymbol(name, attrs, std::move(details));
612             d->set_derivedType(*derivedType);
613           } else if (derivedType->CanReplaceDetails(details)) {
614             // was forward-referenced
615             CheckDuplicatedAttrs(name, *symbol, attrs);
616             SetExplicitAttrs(*derivedType, attrs);
617             derivedType->set_details(std::move(details));
618           } else {
619             SayAlreadyDeclared(name, *derivedType);
620           }
621           return *derivedType;
622         }
623       }
624     } else if constexpr (std::is_same_v<ProcEntityDetails, D>) {
625       if (auto *d{symbol->detailsIf<GenericDetails>()}) {
626         if (!d->derivedType()) {
627           // procedure pointer with same name as a generic
628           auto *specific{d->specific()};
629           if (!specific) {
630             specific = &currScope().MakeSymbol(name, attrs, std::move(details));
631             d->set_specific(*specific);
632           } else {
633             SayAlreadyDeclared(name, *specific);
634           }
635           return *specific;
636         }
637       }
638     }
639     if (symbol->CanReplaceDetails(details)) {
640       // update the existing symbol
641       CheckDuplicatedAttrs(name, *symbol, attrs);
642       SetExplicitAttrs(*symbol, attrs);
643       if constexpr (std::is_same_v<SubprogramDetails, D>) {
644         // Dummy argument defined by explicit interface?
645         details.set_isDummy(IsDummy(*symbol));
646       }
647       symbol->set_details(std::move(details));
648       return *symbol;
649     } else if constexpr (std::is_same_v<UnknownDetails, D>) {
650       CheckDuplicatedAttrs(name, *symbol, attrs);
651       SetExplicitAttrs(*symbol, attrs);
652       return *symbol;
653     } else {
654       if (!CheckPossibleBadForwardRef(*symbol)) {
655         if (name.empty() && symbol->name().empty()) {
656           // report the error elsewhere
657           return *symbol;
658         }
659         Symbol &errSym{*symbol};
660         if (auto *d{symbol->detailsIf<GenericDetails>()}) {
661           if (d->specific()) {
662             errSym = *d->specific();
663           } else if (d->derivedType()) {
664             errSym = *d->derivedType();
665           }
666         }
667         SayAlreadyDeclared(name, errSym);
668       }
669       // replace the old symbol with a new one with correct details
670       EraseSymbol(*symbol);
671       auto &result{MakeSymbol(name, attrs, std::move(details))};
672       context().SetError(result);
673       return result;
674     }
675   }
676 
677   void MakeExternal(Symbol &);
678 
679   // C815 duplicated attribute checking; returns false on error
680   bool CheckDuplicatedAttr(SourceName, Symbol &, Attr);
681   bool CheckDuplicatedAttrs(SourceName, Symbol &, Attrs);
682 
683   void SetExplicitAttr(Symbol &symbol, Attr attr) const {
684     symbol.attrs().set(attr);
685     symbol.implicitAttrs().reset(attr);
686   }
687   void SetExplicitAttrs(Symbol &symbol, Attrs attrs) const {
688     symbol.attrs() |= attrs;
689     symbol.implicitAttrs() &= ~attrs;
690   }
691   void SetImplicitAttr(Symbol &symbol, Attr attr) const {
692     symbol.attrs().set(attr);
693     symbol.implicitAttrs().set(attr);
694   }
695   void SetCUDADataAttr(
696       SourceName, Symbol &, std::optional<common::CUDADataAttr>);
697 
698 protected:
699   FuncResultStack &funcResultStack() { return funcResultStack_; }
700 
701   // Apply the implicit type rules to this symbol.
702   void ApplyImplicitRules(Symbol &, bool allowForwardReference = false);
703   bool ImplicitlyTypeForwardRef(Symbol &);
704   void AcquireIntrinsicProcedureFlags(Symbol &);
705   const DeclTypeSpec *GetImplicitType(
706       Symbol &, bool respectImplicitNoneType = true);
707   void CheckEntryDummyUse(SourceName, Symbol *);
708   bool ConvertToObjectEntity(Symbol &);
709   bool ConvertToProcEntity(Symbol &, std::optional<SourceName> = std::nullopt);
710 
711   const DeclTypeSpec &MakeNumericType(
712       TypeCategory, const std::optional<parser::KindSelector> &);
713   const DeclTypeSpec &MakeNumericType(TypeCategory, int);
714   const DeclTypeSpec &MakeLogicalType(
715       const std::optional<parser::KindSelector> &);
716   const DeclTypeSpec &MakeLogicalType(int);
717   void NotePossibleBadForwardRef(const parser::Name &);
718   std::optional<SourceName> HadForwardRef(const Symbol &) const;
719   bool CheckPossibleBadForwardRef(const Symbol &);
720 
721   bool inSpecificationPart_{false};
722   bool deferImplicitTyping_{false};
723   bool inEquivalenceStmt_{false};
724 
725   // Some information is collected from a specification part for deferred
726   // processing in DeclarationPartVisitor functions (e.g., CheckSaveStmts())
727   // that are called by ResolveNamesVisitor::FinishSpecificationPart().  Since
728   // specification parts can nest (e.g., INTERFACE bodies), the collected
729   // information that is not contained in the scope needs to be packaged
730   // and restorable.
731   struct SpecificationPartState {
732     std::set<SourceName> forwardRefs;
733     // Collect equivalence sets and process at end of specification part
734     std::vector<const std::list<parser::EquivalenceObject> *> equivalenceSets;
735     // Names of all common block objects in the scope
736     std::set<SourceName> commonBlockObjects;
737     // Info about SAVE statements and attributes in current scope
738     struct {
739       std::optional<SourceName> saveAll; // "SAVE" without entity list
740       std::set<SourceName> entities; // names of entities with save attr
741       std::set<SourceName> commons; // names of common blocks with save attr
742     } saveInfo;
743   } specPartState_;
744 
745   // Some declaration processing can and should be deferred to
746   // ResolveExecutionParts() to avoid prematurely creating implicitly-typed
747   // local symbols that should be host associations.
748   struct DeferredDeclarationState {
749     // The content of each namelist group
750     std::list<const parser::NamelistStmt::Group *> namelistGroups;
751   };
752   DeferredDeclarationState *GetDeferredDeclarationState(bool add = false) {
753     if (!add && deferred_.find(&currScope()) == deferred_.end()) {
754       return nullptr;
755     } else {
756       return &deferred_.emplace(&currScope(), DeferredDeclarationState{})
757                   .first->second;
758     }
759   }
760 
761 private:
762   Scope *currScope_{nullptr};
763   FuncResultStack funcResultStack_{*this};
764   std::map<Scope *, DeferredDeclarationState> deferred_;
765 };
766 
767 class ModuleVisitor : public virtual ScopeHandler {
768 public:
769   bool Pre(const parser::AccessStmt &);
770   bool Pre(const parser::Only &);
771   bool Pre(const parser::Rename::Names &);
772   bool Pre(const parser::Rename::Operators &);
773   bool Pre(const parser::UseStmt &);
774   void Post(const parser::UseStmt &);
775 
776   void BeginModule(const parser::Name &, bool isSubmodule);
777   bool BeginSubmodule(const parser::Name &, const parser::ParentIdentifier &);
778   void ApplyDefaultAccess();
779   Symbol &AddGenericUse(GenericDetails &, const SourceName &, const Symbol &);
780   void AddAndCheckModuleUse(SourceName, bool isIntrinsic);
781   void CollectUseRenames(const parser::UseStmt &);
782   void ClearUseRenames() { useRenames_.clear(); }
783   void ClearUseOnly() { useOnly_.clear(); }
784   void ClearModuleUses() {
785     intrinsicUses_.clear();
786     nonIntrinsicUses_.clear();
787   }
788 
789 private:
790   // The location of the last AccessStmt without access-ids, if any.
791   std::optional<SourceName> prevAccessStmt_;
792   // The scope of the module during a UseStmt
793   Scope *useModuleScope_{nullptr};
794   // Names that have appeared in a rename clause of USE statements
795   std::set<std::pair<SourceName, SourceName>> useRenames_;
796   // Names that have appeared in an ONLY clause of a USE statement
797   std::set<std::pair<SourceName, Scope *>> useOnly_;
798   // Intrinsic and non-intrinsic (explicit or not) module names that
799   // have appeared in USE statements; used for C1406 warnings.
800   std::set<SourceName> intrinsicUses_;
801   std::set<SourceName> nonIntrinsicUses_;
802 
803   Symbol &SetAccess(const SourceName &, Attr attr, Symbol * = nullptr);
804   // A rename in a USE statement: local => use
805   struct SymbolRename {
806     Symbol *local{nullptr};
807     Symbol *use{nullptr};
808   };
809   // Record a use from useModuleScope_ of use Name/Symbol as local Name/Symbol
810   SymbolRename AddUse(const SourceName &localName, const SourceName &useName);
811   SymbolRename AddUse(const SourceName &, const SourceName &, Symbol *);
812   void DoAddUse(
813       SourceName, SourceName, Symbol &localSymbol, const Symbol &useSymbol);
814   void AddUse(const GenericSpecInfo &);
815   // Record a name appearing as the target of a USE rename clause
816   void AddUseRename(SourceName name, SourceName moduleName) {
817     useRenames_.emplace(std::make_pair(name, moduleName));
818   }
819   bool IsUseRenamed(const SourceName &name) const {
820     return useModuleScope_ && useModuleScope_->symbol() &&
821         useRenames_.find({name, useModuleScope_->symbol()->name()}) !=
822         useRenames_.end();
823   }
824   // Record a name appearing in a USE ONLY clause
825   void AddUseOnly(const SourceName &name) {
826     useOnly_.emplace(std::make_pair(name, useModuleScope_));
827   }
828   bool IsUseOnly(const SourceName &name) const {
829     return useOnly_.find({name, useModuleScope_}) != useOnly_.end();
830   }
831   Scope *FindModule(const parser::Name &, std::optional<bool> isIntrinsic,
832       Scope *ancestor = nullptr);
833 };
834 
835 class GenericHandler : public virtual ScopeHandler {
836 protected:
837   using ProcedureKind = parser::ProcedureStmt::Kind;
838   void ResolveSpecificsInGeneric(Symbol &, bool isEndOfSpecificationPart);
839   void DeclaredPossibleSpecificProc(Symbol &);
840 
841   // Mappings of generics to their as-yet specific proc names and kinds
842   using SpecificProcMapType =
843       std::multimap<Symbol *, std::pair<const parser::Name *, ProcedureKind>>;
844   SpecificProcMapType specificsForGenericProcs_;
845   // inversion of SpecificProcMapType: maps pending proc names to generics
846   using GenericProcMapType = std::multimap<SourceName, Symbol *>;
847   GenericProcMapType genericsForSpecificProcs_;
848 };
849 
850 class InterfaceVisitor : public virtual ScopeHandler,
851                          public virtual GenericHandler {
852 public:
853   bool Pre(const parser::InterfaceStmt &);
854   void Post(const parser::InterfaceStmt &);
855   void Post(const parser::EndInterfaceStmt &);
856   bool Pre(const parser::GenericSpec &);
857   bool Pre(const parser::ProcedureStmt &);
858   bool Pre(const parser::GenericStmt &);
859   void Post(const parser::GenericStmt &);
860 
861   bool inInterfaceBlock() const;
862   bool isGeneric() const;
863   bool isAbstract() const;
864 
865 protected:
866   Symbol &GetGenericSymbol() { return DEREF(genericInfo_.top().symbol); }
867   // Add to generic the symbol for the subprogram with the same name
868   void CheckGenericProcedures(Symbol &);
869 
870 private:
871   // A new GenericInfo is pushed for each interface block and generic stmt
872   struct GenericInfo {
873     GenericInfo(bool isInterface, bool isAbstract = false)
874         : isInterface{isInterface}, isAbstract{isAbstract} {}
875     bool isInterface; // in interface block
876     bool isAbstract; // in abstract interface block
877     Symbol *symbol{nullptr}; // the generic symbol being defined
878   };
879   std::stack<GenericInfo> genericInfo_;
880   const GenericInfo &GetGenericInfo() const { return genericInfo_.top(); }
881   void SetGenericSymbol(Symbol &symbol) { genericInfo_.top().symbol = &symbol; }
882   void AddSpecificProcs(const std::list<parser::Name> &, ProcedureKind);
883   void ResolveNewSpecifics();
884 };
885 
886 class SubprogramVisitor : public virtual ScopeHandler, public InterfaceVisitor {
887 public:
888   bool HandleStmtFunction(const parser::StmtFunctionStmt &);
889   bool Pre(const parser::SubroutineStmt &);
890   bool Pre(const parser::FunctionStmt &);
891   void Post(const parser::FunctionStmt &);
892   bool Pre(const parser::EntryStmt &);
893   void Post(const parser::EntryStmt &);
894   bool Pre(const parser::InterfaceBody::Subroutine &);
895   void Post(const parser::InterfaceBody::Subroutine &);
896   bool Pre(const parser::InterfaceBody::Function &);
897   void Post(const parser::InterfaceBody::Function &);
898   bool Pre(const parser::Suffix &);
899   bool Pre(const parser::PrefixSpec &);
900   bool Pre(const parser::PrefixSpec::Attributes &);
901   void Post(const parser::PrefixSpec::Launch_Bounds &);
902   void Post(const parser::PrefixSpec::Cluster_Dims &);
903 
904   bool BeginSubprogram(const parser::Name &, Symbol::Flag,
905       bool hasModulePrefix = false,
906       const parser::LanguageBindingSpec * = nullptr,
907       const ProgramTree::EntryStmtList * = nullptr);
908   bool BeginMpSubprogram(const parser::Name &);
909   void PushBlockDataScope(const parser::Name &);
910   void EndSubprogram(std::optional<parser::CharBlock> stmtSource = std::nullopt,
911       const std::optional<parser::LanguageBindingSpec> * = nullptr,
912       const ProgramTree::EntryStmtList * = nullptr);
913 
914 protected:
915   // Set when we see a stmt function that is really an array element assignment
916   bool misparsedStmtFuncFound_{false};
917 
918 private:
919   // Edits an existing symbol created for earlier calls to a subprogram or ENTRY
920   // so that it can be replaced by a later definition.
921   bool HandlePreviousCalls(const parser::Name &, Symbol &, Symbol::Flag);
922   void CheckExtantProc(const parser::Name &, Symbol::Flag);
923   // Create a subprogram symbol in the current scope and push a new scope.
924   Symbol &PushSubprogramScope(const parser::Name &, Symbol::Flag,
925       const parser::LanguageBindingSpec * = nullptr,
926       bool hasModulePrefix = false);
927   Symbol *GetSpecificFromGeneric(const parser::Name &);
928   Symbol &PostSubprogramStmt();
929   void CreateDummyArgument(SubprogramDetails &, const parser::Name &);
930   void CreateEntry(const parser::EntryStmt &stmt, Symbol &subprogram);
931   void PostEntryStmt(const parser::EntryStmt &stmt);
932   void HandleLanguageBinding(Symbol *,
933       std::optional<parser::CharBlock> stmtSource,
934       const std::optional<parser::LanguageBindingSpec> *);
935 };
936 
937 class DeclarationVisitor : public ArraySpecVisitor,
938                            public virtual GenericHandler {
939 public:
940   using ArraySpecVisitor::Post;
941   using ScopeHandler::Post;
942   using ScopeHandler::Pre;
943 
944   bool Pre(const parser::Initialization &);
945   void Post(const parser::EntityDecl &);
946   void Post(const parser::ObjectDecl &);
947   void Post(const parser::PointerDecl &);
948   bool Pre(const parser::BindStmt &) { return BeginAttrs(); }
949   void Post(const parser::BindStmt &) { EndAttrs(); }
950   bool Pre(const parser::BindEntity &);
951   bool Pre(const parser::OldParameterStmt &);
952   bool Pre(const parser::NamedConstantDef &);
953   bool Pre(const parser::NamedConstant &);
954   void Post(const parser::EnumDef &);
955   bool Pre(const parser::Enumerator &);
956   bool Pre(const parser::AccessSpec &);
957   bool Pre(const parser::AsynchronousStmt &);
958   bool Pre(const parser::ContiguousStmt &);
959   bool Pre(const parser::ExternalStmt &);
960   bool Pre(const parser::IntentStmt &);
961   bool Pre(const parser::IntrinsicStmt &);
962   bool Pre(const parser::OptionalStmt &);
963   bool Pre(const parser::ProtectedStmt &);
964   bool Pre(const parser::ValueStmt &);
965   bool Pre(const parser::VolatileStmt &);
966   bool Pre(const parser::AllocatableStmt &) {
967     objectDeclAttr_ = Attr::ALLOCATABLE;
968     return true;
969   }
970   void Post(const parser::AllocatableStmt &) { objectDeclAttr_ = std::nullopt; }
971   bool Pre(const parser::TargetStmt &) {
972     objectDeclAttr_ = Attr::TARGET;
973     return true;
974   }
975   bool Pre(const parser::CUDAAttributesStmt &);
976   void Post(const parser::TargetStmt &) { objectDeclAttr_ = std::nullopt; }
977   void Post(const parser::DimensionStmt::Declaration &);
978   void Post(const parser::CodimensionDecl &);
979   bool Pre(const parser::TypeDeclarationStmt &);
980   void Post(const parser::TypeDeclarationStmt &);
981   void Post(const parser::IntegerTypeSpec &);
982   void Post(const parser::IntrinsicTypeSpec::Real &);
983   void Post(const parser::IntrinsicTypeSpec::Complex &);
984   void Post(const parser::IntrinsicTypeSpec::Logical &);
985   void Post(const parser::IntrinsicTypeSpec::Character &);
986   void Post(const parser::CharSelector::LengthAndKind &);
987   void Post(const parser::CharLength &);
988   void Post(const parser::LengthSelector &);
989   bool Pre(const parser::KindParam &);
990   bool Pre(const parser::VectorTypeSpec &);
991   void Post(const parser::VectorTypeSpec &);
992   bool Pre(const parser::DeclarationTypeSpec::Type &);
993   void Post(const parser::DeclarationTypeSpec::Type &);
994   bool Pre(const parser::DeclarationTypeSpec::Class &);
995   void Post(const parser::DeclarationTypeSpec::Class &);
996   void Post(const parser::DeclarationTypeSpec::Record &);
997   void Post(const parser::DerivedTypeSpec &);
998   bool Pre(const parser::DerivedTypeDef &);
999   bool Pre(const parser::DerivedTypeStmt &);
1000   void Post(const parser::DerivedTypeStmt &);
1001   bool Pre(const parser::TypeParamDefStmt &) { return BeginDecl(); }
1002   void Post(const parser::TypeParamDefStmt &);
1003   bool Pre(const parser::TypeAttrSpec::Extends &);
1004   bool Pre(const parser::PrivateStmt &);
1005   bool Pre(const parser::SequenceStmt &);
1006   bool Pre(const parser::ComponentDefStmt &) { return BeginDecl(); }
1007   void Post(const parser::ComponentDefStmt &) { EndDecl(); }
1008   void Post(const parser::ComponentDecl &);
1009   void Post(const parser::FillDecl &);
1010   bool Pre(const parser::ProcedureDeclarationStmt &);
1011   void Post(const parser::ProcedureDeclarationStmt &);
1012   bool Pre(const parser::DataComponentDefStmt &); // returns false
1013   bool Pre(const parser::ProcComponentDefStmt &);
1014   void Post(const parser::ProcComponentDefStmt &);
1015   bool Pre(const parser::ProcPointerInit &);
1016   void Post(const parser::ProcInterface &);
1017   void Post(const parser::ProcDecl &);
1018   bool Pre(const parser::TypeBoundProcedurePart &);
1019   void Post(const parser::TypeBoundProcedurePart &);
1020   void Post(const parser::ContainsStmt &);
1021   bool Pre(const parser::TypeBoundProcBinding &) { return BeginAttrs(); }
1022   void Post(const parser::TypeBoundProcBinding &) { EndAttrs(); }
1023   void Post(const parser::TypeBoundProcedureStmt::WithoutInterface &);
1024   void Post(const parser::TypeBoundProcedureStmt::WithInterface &);
1025   bool Pre(const parser::FinalProcedureStmt &);
1026   bool Pre(const parser::TypeBoundGenericStmt &);
1027   bool Pre(const parser::StructureDef &); // returns false
1028   bool Pre(const parser::Union::UnionStmt &);
1029   bool Pre(const parser::StructureField &);
1030   void Post(const parser::StructureField &);
1031   bool Pre(const parser::AllocateStmt &);
1032   void Post(const parser::AllocateStmt &);
1033   bool Pre(const parser::StructureConstructor &);
1034   bool Pre(const parser::NamelistStmt::Group &);
1035   bool Pre(const parser::IoControlSpec &);
1036   bool Pre(const parser::CommonStmt::Block &);
1037   bool Pre(const parser::CommonBlockObject &);
1038   void Post(const parser::CommonBlockObject &);
1039   bool Pre(const parser::EquivalenceStmt &);
1040   bool Pre(const parser::SaveStmt &);
1041   bool Pre(const parser::BasedPointer &);
1042   void Post(const parser::BasedPointer &);
1043 
1044   void PointerInitialization(
1045       const parser::Name &, const parser::InitialDataTarget &);
1046   void PointerInitialization(
1047       const parser::Name &, const parser::ProcPointerInit &);
1048   void NonPointerInitialization(
1049       const parser::Name &, const parser::ConstantExpr &);
1050   void CheckExplicitInterface(const parser::Name &);
1051   void CheckBindings(const parser::TypeBoundProcedureStmt::WithoutInterface &);
1052 
1053   const parser::Name *ResolveDesignator(const parser::Designator &);
1054   int GetVectorElementKind(
1055       TypeCategory category, const std::optional<parser::KindSelector> &kind);
1056 
1057 protected:
1058   bool BeginDecl();
1059   void EndDecl();
1060   Symbol &DeclareObjectEntity(const parser::Name &, Attrs = Attrs{});
1061   // Make sure that there's an entity in an enclosing scope called Name
1062   Symbol &FindOrDeclareEnclosingEntity(const parser::Name &);
1063   // Declare a LOCAL/LOCAL_INIT/REDUCE entity while setting a locality flag. If
1064   // there isn't a type specified it comes from the entity in the containing
1065   // scope, or implicit rules.
1066   void DeclareLocalEntity(const parser::Name &, Symbol::Flag);
1067   // Declare a statement entity (i.e., an implied DO loop index for
1068   // a DATA statement or an array constructor).  If there isn't an explict
1069   // type specified, implicit rules apply. Return pointer to the new symbol,
1070   // or nullptr on error.
1071   Symbol *DeclareStatementEntity(const parser::DoVariable &,
1072       const std::optional<parser::IntegerTypeSpec> &);
1073   Symbol &MakeCommonBlockSymbol(const parser::Name &);
1074   Symbol &MakeCommonBlockSymbol(const std::optional<parser::Name> &);
1075   bool CheckUseError(const parser::Name &);
1076   void CheckAccessibility(const SourceName &, bool, Symbol &);
1077   void CheckCommonBlocks();
1078   void CheckSaveStmts();
1079   void CheckEquivalenceSets();
1080   bool CheckNotInBlock(const char *);
1081   bool NameIsKnownOrIntrinsic(const parser::Name &);
1082   void FinishNamelists();
1083 
1084   // Each of these returns a pointer to a resolved Name (i.e. with symbol)
1085   // or nullptr in case of error.
1086   const parser::Name *ResolveStructureComponent(
1087       const parser::StructureComponent &);
1088   const parser::Name *ResolveDataRef(const parser::DataRef &);
1089   const parser::Name *ResolveName(const parser::Name &);
1090   bool PassesSharedLocalityChecks(const parser::Name &name, Symbol &symbol);
1091   Symbol *NoteInterfaceName(const parser::Name &);
1092   bool IsUplevelReference(const Symbol &);
1093 
1094   std::optional<SourceName> BeginCheckOnIndexUseInOwnBounds(
1095       const parser::DoVariable &name) {
1096     std::optional<SourceName> result{checkIndexUseInOwnBounds_};
1097     checkIndexUseInOwnBounds_ = name.thing.thing.source;
1098     return result;
1099   }
1100   void EndCheckOnIndexUseInOwnBounds(const std::optional<SourceName> &restore) {
1101     checkIndexUseInOwnBounds_ = restore;
1102   }
1103   void NoteScalarSpecificationArgument(const Symbol &symbol) {
1104     mustBeScalar_.emplace(symbol);
1105   }
1106   // Declare an object or procedure entity.
1107   // T is one of: EntityDetails, ObjectEntityDetails, ProcEntityDetails
1108   template <typename T>
1109   Symbol &DeclareEntity(const parser::Name &name, Attrs attrs) {
1110     Symbol &symbol{MakeSymbol(name, attrs)};
1111     if (context().HasError(symbol) || symbol.has<T>()) {
1112       return symbol; // OK or error already reported
1113     } else if (symbol.has<UnknownDetails>()) {
1114       symbol.set_details(T{});
1115       return symbol;
1116     } else if (auto *details{symbol.detailsIf<EntityDetails>()}) {
1117       symbol.set_details(T{std::move(*details)});
1118       return symbol;
1119     } else if (std::is_same_v<EntityDetails, T> &&
1120         (symbol.has<ObjectEntityDetails>() ||
1121             symbol.has<ProcEntityDetails>())) {
1122       return symbol; // OK
1123     } else if (auto *details{symbol.detailsIf<UseDetails>()}) {
1124       Say(name.source,
1125           "'%s' is use-associated from module '%s' and cannot be re-declared"_err_en_US,
1126           name.source, GetUsedModule(*details).name());
1127     } else if (auto *details{symbol.detailsIf<SubprogramNameDetails>()}) {
1128       if (details->kind() == SubprogramKind::Module) {
1129         Say2(name,
1130             "Declaration of '%s' conflicts with its use as module procedure"_err_en_US,
1131             symbol, "Module procedure definition"_en_US);
1132       } else if (details->kind() == SubprogramKind::Internal) {
1133         Say2(name,
1134             "Declaration of '%s' conflicts with its use as internal procedure"_err_en_US,
1135             symbol, "Internal procedure definition"_en_US);
1136       } else {
1137         DIE("unexpected kind");
1138       }
1139     } else if (std::is_same_v<ObjectEntityDetails, T> &&
1140         symbol.has<ProcEntityDetails>()) {
1141       SayWithDecl(
1142           name, symbol, "'%s' is already declared as a procedure"_err_en_US);
1143     } else if (std::is_same_v<ProcEntityDetails, T> &&
1144         symbol.has<ObjectEntityDetails>()) {
1145       if (FindCommonBlockContaining(symbol)) {
1146         SayWithDecl(name, symbol,
1147             "'%s' may not be a procedure as it is in a COMMON block"_err_en_US);
1148       } else {
1149         SayWithDecl(
1150             name, symbol, "'%s' is already declared as an object"_err_en_US);
1151       }
1152     } else if (!CheckPossibleBadForwardRef(symbol)) {
1153       SayAlreadyDeclared(name, symbol);
1154     }
1155     context().SetError(symbol);
1156     return symbol;
1157   }
1158 
1159 private:
1160   // The attribute corresponding to the statement containing an ObjectDecl
1161   std::optional<Attr> objectDeclAttr_;
1162   // Info about current character type while walking DeclTypeSpec.
1163   // Also captures any "*length" specifier on an individual declaration.
1164   struct {
1165     std::optional<ParamValue> length;
1166     std::optional<KindExpr> kind;
1167   } charInfo_;
1168   // Info about current derived type or STRUCTURE while walking
1169   // DerivedTypeDef / StructureDef
1170   struct {
1171     const parser::Name *extends{nullptr}; // EXTENDS(name)
1172     bool privateComps{false}; // components are private by default
1173     bool privateBindings{false}; // bindings are private by default
1174     bool sawContains{false}; // currently processing bindings
1175     bool sequence{false}; // is a sequence type
1176     const Symbol *type{nullptr}; // derived type being defined
1177     bool isStructure{false}; // is a DEC STRUCTURE
1178   } derivedTypeInfo_;
1179   // In a ProcedureDeclarationStmt or ProcComponentDefStmt, this is
1180   // the interface name, if any.
1181   const parser::Name *interfaceName_{nullptr};
1182   // Map type-bound generic to binding names of its specific bindings
1183   std::multimap<Symbol *, const parser::Name *> genericBindings_;
1184   // Info about current ENUM
1185   struct EnumeratorState {
1186     // Enum value must hold inside a C_INT (7.6.2).
1187     std::optional<int> value{0};
1188   } enumerationState_;
1189   // Set for OldParameterStmt processing
1190   bool inOldStyleParameterStmt_{false};
1191   // Set when walking DATA & array constructor implied DO loop bounds
1192   // to warn about use of the implied DO intex therein.
1193   std::optional<SourceName> checkIndexUseInOwnBounds_;
1194   bool isVectorType_{false};
1195   UnorderedSymbolSet mustBeScalar_;
1196 
1197   bool HandleAttributeStmt(Attr, const std::list<parser::Name> &);
1198   Symbol &HandleAttributeStmt(Attr, const parser::Name &);
1199   Symbol &DeclareUnknownEntity(const parser::Name &, Attrs);
1200   Symbol &DeclareProcEntity(
1201       const parser::Name &, Attrs, const Symbol *interface);
1202   void SetType(const parser::Name &, const DeclTypeSpec &);
1203   std::optional<DerivedTypeSpec> ResolveDerivedType(const parser::Name &);
1204   std::optional<DerivedTypeSpec> ResolveExtendsType(
1205       const parser::Name &, const parser::Name *);
1206   Symbol *MakeTypeSymbol(const SourceName &, Details &&);
1207   Symbol *MakeTypeSymbol(const parser::Name &, Details &&);
1208   bool OkToAddComponent(const parser::Name &, const Symbol *extends = nullptr);
1209   ParamValue GetParamValue(
1210       const parser::TypeParamValue &, common::TypeParamAttr attr);
1211   void CheckCommonBlockDerivedType(
1212       const SourceName &, const Symbol &, UnorderedSymbolSet &);
1213   Attrs HandleSaveName(const SourceName &, Attrs);
1214   void AddSaveName(std::set<SourceName> &, const SourceName &);
1215   bool HandleUnrestrictedSpecificIntrinsicFunction(const parser::Name &);
1216   const parser::Name *FindComponent(const parser::Name *, const parser::Name &);
1217   void Initialization(const parser::Name &, const parser::Initialization &,
1218       bool inComponentDecl);
1219   bool PassesLocalityChecks(
1220       const parser::Name &name, Symbol &symbol, Symbol::Flag flag);
1221   bool CheckForHostAssociatedImplicit(const parser::Name &);
1222   bool HasCycle(const Symbol &, const Symbol *interface);
1223   bool MustBeScalar(const Symbol &symbol) const {
1224     return mustBeScalar_.find(symbol) != mustBeScalar_.end();
1225   }
1226   void DeclareIntrinsic(const parser::Name &);
1227 };
1228 
1229 // Resolve construct entities and statement entities.
1230 // Check that construct names don't conflict with other names.
1231 class ConstructVisitor : public virtual DeclarationVisitor {
1232 public:
1233   bool Pre(const parser::ConcurrentHeader &);
1234   bool Pre(const parser::LocalitySpec::Local &);
1235   bool Pre(const parser::LocalitySpec::LocalInit &);
1236   bool Pre(const parser::LocalitySpec::Reduce &);
1237   bool Pre(const parser::LocalitySpec::Shared &);
1238   bool Pre(const parser::AcSpec &);
1239   bool Pre(const parser::AcImpliedDo &);
1240   bool Pre(const parser::DataImpliedDo &);
1241   bool Pre(const parser::DataIDoObject &);
1242   bool Pre(const parser::DataStmtObject &);
1243   bool Pre(const parser::DataStmtValue &);
1244   bool Pre(const parser::DoConstruct &);
1245   void Post(const parser::DoConstruct &);
1246   bool Pre(const parser::ForallConstruct &);
1247   void Post(const parser::ForallConstruct &);
1248   bool Pre(const parser::ForallStmt &);
1249   void Post(const parser::ForallStmt &);
1250   bool Pre(const parser::BlockConstruct &);
1251   void Post(const parser::Selector &);
1252   void Post(const parser::AssociateStmt &);
1253   void Post(const parser::EndAssociateStmt &);
1254   bool Pre(const parser::Association &);
1255   void Post(const parser::SelectTypeStmt &);
1256   void Post(const parser::SelectRankStmt &);
1257   bool Pre(const parser::SelectTypeConstruct &);
1258   void Post(const parser::SelectTypeConstruct &);
1259   bool Pre(const parser::SelectTypeConstruct::TypeCase &);
1260   void Post(const parser::SelectTypeConstruct::TypeCase &);
1261   // Creates Block scopes with neither symbol name nor symbol details.
1262   bool Pre(const parser::SelectRankConstruct::RankCase &);
1263   void Post(const parser::SelectRankConstruct::RankCase &);
1264   bool Pre(const parser::TypeGuardStmt::Guard &);
1265   void Post(const parser::TypeGuardStmt::Guard &);
1266   void Post(const parser::SelectRankCaseStmt::Rank &);
1267   bool Pre(const parser::ChangeTeamStmt &);
1268   void Post(const parser::EndChangeTeamStmt &);
1269   void Post(const parser::CoarrayAssociation &);
1270 
1271   // Definitions of construct names
1272   bool Pre(const parser::WhereConstructStmt &x) { return CheckDef(x.t); }
1273   bool Pre(const parser::ForallConstructStmt &x) { return CheckDef(x.t); }
1274   bool Pre(const parser::CriticalStmt &x) { return CheckDef(x.t); }
1275   bool Pre(const parser::LabelDoStmt &) {
1276     return false; // error recovery
1277   }
1278   bool Pre(const parser::NonLabelDoStmt &x) { return CheckDef(x.t); }
1279   bool Pre(const parser::IfThenStmt &x) { return CheckDef(x.t); }
1280   bool Pre(const parser::SelectCaseStmt &x) { return CheckDef(x.t); }
1281   bool Pre(const parser::SelectRankConstruct &);
1282   void Post(const parser::SelectRankConstruct &);
1283   bool Pre(const parser::SelectRankStmt &x) {
1284     return CheckDef(std::get<0>(x.t));
1285   }
1286   bool Pre(const parser::SelectTypeStmt &x) {
1287     return CheckDef(std::get<0>(x.t));
1288   }
1289 
1290   // References to construct names
1291   void Post(const parser::MaskedElsewhereStmt &x) { CheckRef(x.t); }
1292   void Post(const parser::ElsewhereStmt &x) { CheckRef(x.v); }
1293   void Post(const parser::EndWhereStmt &x) { CheckRef(x.v); }
1294   void Post(const parser::EndForallStmt &x) { CheckRef(x.v); }
1295   void Post(const parser::EndCriticalStmt &x) { CheckRef(x.v); }
1296   void Post(const parser::EndDoStmt &x) { CheckRef(x.v); }
1297   void Post(const parser::ElseIfStmt &x) { CheckRef(x.t); }
1298   void Post(const parser::ElseStmt &x) { CheckRef(x.v); }
1299   void Post(const parser::EndIfStmt &x) { CheckRef(x.v); }
1300   void Post(const parser::CaseStmt &x) { CheckRef(x.t); }
1301   void Post(const parser::EndSelectStmt &x) { CheckRef(x.v); }
1302   void Post(const parser::SelectRankCaseStmt &x) { CheckRef(x.t); }
1303   void Post(const parser::TypeGuardStmt &x) { CheckRef(x.t); }
1304   void Post(const parser::CycleStmt &x) { CheckRef(x.v); }
1305   void Post(const parser::ExitStmt &x) { CheckRef(x.v); }
1306 
1307   void HandleImpliedAsynchronousInScope(const parser::Block &);
1308 
1309 private:
1310   // R1105 selector -> expr | variable
1311   // expr is set in either case unless there were errors
1312   struct Selector {
1313     Selector() {}
1314     Selector(const SourceName &source, MaybeExpr &&expr)
1315         : source{source}, expr{std::move(expr)} {}
1316     operator bool() const { return expr.has_value(); }
1317     parser::CharBlock source;
1318     MaybeExpr expr;
1319   };
1320   // association -> [associate-name =>] selector
1321   struct Association {
1322     const parser::Name *name{nullptr};
1323     Selector selector;
1324   };
1325   std::vector<Association> associationStack_;
1326   Association *currentAssociation_{nullptr};
1327 
1328   template <typename T> bool CheckDef(const T &t) {
1329     return CheckDef(std::get<std::optional<parser::Name>>(t));
1330   }
1331   template <typename T> void CheckRef(const T &t) {
1332     CheckRef(std::get<std::optional<parser::Name>>(t));
1333   }
1334   bool CheckDef(const std::optional<parser::Name> &);
1335   void CheckRef(const std::optional<parser::Name> &);
1336   const DeclTypeSpec &ToDeclTypeSpec(evaluate::DynamicType &&);
1337   const DeclTypeSpec &ToDeclTypeSpec(
1338       evaluate::DynamicType &&, MaybeSubscriptIntExpr &&length);
1339   Symbol *MakeAssocEntity();
1340   void SetTypeFromAssociation(Symbol &);
1341   void SetAttrsFromAssociation(Symbol &);
1342   Selector ResolveSelector(const parser::Selector &);
1343   void ResolveIndexName(const parser::ConcurrentControl &control);
1344   void SetCurrentAssociation(std::size_t n);
1345   Association &GetCurrentAssociation();
1346   void PushAssociation();
1347   void PopAssociation(std::size_t count = 1);
1348 };
1349 
1350 // Create scopes for OpenACC constructs
1351 class AccVisitor : public virtual DeclarationVisitor {
1352 public:
1353   void AddAccSourceRange(const parser::CharBlock &);
1354 
1355   static bool NeedsScope(const parser::OpenACCBlockConstruct &);
1356 
1357   bool Pre(const parser::OpenACCBlockConstruct &);
1358   void Post(const parser::OpenACCBlockConstruct &);
1359   bool Pre(const parser::OpenACCCombinedConstruct &);
1360   void Post(const parser::OpenACCCombinedConstruct &);
1361   bool Pre(const parser::AccBeginBlockDirective &x) {
1362     AddAccSourceRange(x.source);
1363     return true;
1364   }
1365   void Post(const parser::AccBeginBlockDirective &) {
1366     messageHandler().set_currStmtSource(std::nullopt);
1367   }
1368   bool Pre(const parser::AccEndBlockDirective &x) {
1369     AddAccSourceRange(x.source);
1370     return true;
1371   }
1372   void Post(const parser::AccEndBlockDirective &) {
1373     messageHandler().set_currStmtSource(std::nullopt);
1374   }
1375   bool Pre(const parser::AccBeginLoopDirective &x) {
1376     AddAccSourceRange(x.source);
1377     return true;
1378   }
1379   void Post(const parser::AccBeginLoopDirective &x) {
1380     messageHandler().set_currStmtSource(std::nullopt);
1381   }
1382 };
1383 
1384 bool AccVisitor::NeedsScope(const parser::OpenACCBlockConstruct &x) {
1385   const auto &beginBlockDir{std::get<parser::AccBeginBlockDirective>(x.t)};
1386   const auto &beginDir{std::get<parser::AccBlockDirective>(beginBlockDir.t)};
1387   switch (beginDir.v) {
1388   case llvm::acc::Directive::ACCD_data:
1389   case llvm::acc::Directive::ACCD_host_data:
1390   case llvm::acc::Directive::ACCD_kernels:
1391   case llvm::acc::Directive::ACCD_parallel:
1392   case llvm::acc::Directive::ACCD_serial:
1393     return true;
1394   default:
1395     return false;
1396   }
1397 }
1398 
1399 void AccVisitor::AddAccSourceRange(const parser::CharBlock &source) {
1400   messageHandler().set_currStmtSource(source);
1401   currScope().AddSourceRange(source);
1402 }
1403 
1404 bool AccVisitor::Pre(const parser::OpenACCBlockConstruct &x) {
1405   if (NeedsScope(x)) {
1406     PushScope(Scope::Kind::OpenACCConstruct, nullptr);
1407   }
1408   return true;
1409 }
1410 
1411 void AccVisitor::Post(const parser::OpenACCBlockConstruct &x) {
1412   if (NeedsScope(x)) {
1413     PopScope();
1414   }
1415 }
1416 
1417 bool AccVisitor::Pre(const parser::OpenACCCombinedConstruct &x) {
1418   PushScope(Scope::Kind::OpenACCConstruct, nullptr);
1419   return true;
1420 }
1421 
1422 void AccVisitor::Post(const parser::OpenACCCombinedConstruct &x) { PopScope(); }
1423 
1424 // Create scopes for OpenMP constructs
1425 class OmpVisitor : public virtual DeclarationVisitor {
1426 public:
1427   void AddOmpSourceRange(const parser::CharBlock &);
1428 
1429   static bool NeedsScope(const parser::OpenMPBlockConstruct &);
1430 
1431   bool Pre(const parser::OpenMPRequiresConstruct &x) {
1432     AddOmpSourceRange(x.source);
1433     return true;
1434   }
1435   bool Pre(const parser::OmpSimpleStandaloneDirective &x) {
1436     AddOmpSourceRange(x.source);
1437     return true;
1438   }
1439   bool Pre(const parser::OpenMPBlockConstruct &);
1440   void Post(const parser::OpenMPBlockConstruct &);
1441   bool Pre(const parser::OmpBeginBlockDirective &x) {
1442     AddOmpSourceRange(x.source);
1443     return true;
1444   }
1445   void Post(const parser::OmpBeginBlockDirective &) {
1446     messageHandler().set_currStmtSource(std::nullopt);
1447   }
1448   bool Pre(const parser::OmpEndBlockDirective &x) {
1449     AddOmpSourceRange(x.source);
1450     return true;
1451   }
1452   void Post(const parser::OmpEndBlockDirective &) {
1453     messageHandler().set_currStmtSource(std::nullopt);
1454   }
1455 
1456   bool Pre(const parser::OpenMPLoopConstruct &) {
1457     PushScope(Scope::Kind::OtherConstruct, nullptr);
1458     return true;
1459   }
1460   void Post(const parser::OpenMPLoopConstruct &) { PopScope(); }
1461   bool Pre(const parser::OmpBeginLoopDirective &x) {
1462     AddOmpSourceRange(x.source);
1463     return true;
1464   }
1465   void Post(const parser::OmpBeginLoopDirective &) {
1466     messageHandler().set_currStmtSource(std::nullopt);
1467   }
1468   bool Pre(const parser::OmpEndLoopDirective &x) {
1469     AddOmpSourceRange(x.source);
1470     return true;
1471   }
1472   void Post(const parser::OmpEndLoopDirective &) {
1473     messageHandler().set_currStmtSource(std::nullopt);
1474   }
1475 
1476   bool Pre(const parser::OpenMPSectionsConstruct &) {
1477     PushScope(Scope::Kind::OtherConstruct, nullptr);
1478     return true;
1479   }
1480   void Post(const parser::OpenMPSectionsConstruct &) { PopScope(); }
1481   bool Pre(const parser::OmpBeginSectionsDirective &x) {
1482     AddOmpSourceRange(x.source);
1483     return true;
1484   }
1485   void Post(const parser::OmpBeginSectionsDirective &) {
1486     messageHandler().set_currStmtSource(std::nullopt);
1487   }
1488   bool Pre(const parser::OmpEndSectionsDirective &x) {
1489     AddOmpSourceRange(x.source);
1490     return true;
1491   }
1492   void Post(const parser::OmpEndSectionsDirective &) {
1493     messageHandler().set_currStmtSource(std::nullopt);
1494   }
1495   bool Pre(const parser::OmpCriticalDirective &x) {
1496     AddOmpSourceRange(x.source);
1497     return true;
1498   }
1499   void Post(const parser::OmpCriticalDirective &) {
1500     messageHandler().set_currStmtSource(std::nullopt);
1501   }
1502   bool Pre(const parser::OmpEndCriticalDirective &x) {
1503     AddOmpSourceRange(x.source);
1504     return true;
1505   }
1506   void Post(const parser::OmpEndCriticalDirective &) {
1507     messageHandler().set_currStmtSource(std::nullopt);
1508   }
1509 };
1510 
1511 bool OmpVisitor::NeedsScope(const parser::OpenMPBlockConstruct &x) {
1512   const auto &beginBlockDir{std::get<parser::OmpBeginBlockDirective>(x.t)};
1513   const auto &beginDir{std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
1514   switch (beginDir.v) {
1515   case llvm::omp::Directive::OMPD_master:
1516   case llvm::omp::Directive::OMPD_ordered:
1517   case llvm::omp::Directive::OMPD_taskgroup:
1518     return false;
1519   default:
1520     return true;
1521   }
1522 }
1523 
1524 void OmpVisitor::AddOmpSourceRange(const parser::CharBlock &source) {
1525   messageHandler().set_currStmtSource(source);
1526   currScope().AddSourceRange(source);
1527 }
1528 
1529 bool OmpVisitor::Pre(const parser::OpenMPBlockConstruct &x) {
1530   if (NeedsScope(x)) {
1531     PushScope(Scope::Kind::OtherConstruct, nullptr);
1532   }
1533   return true;
1534 }
1535 
1536 void OmpVisitor::Post(const parser::OpenMPBlockConstruct &x) {
1537   if (NeedsScope(x)) {
1538     PopScope();
1539   }
1540 }
1541 
1542 // Walk the parse tree and resolve names to symbols.
1543 class ResolveNamesVisitor : public virtual ScopeHandler,
1544                             public ModuleVisitor,
1545                             public SubprogramVisitor,
1546                             public ConstructVisitor,
1547                             public OmpVisitor,
1548                             public AccVisitor {
1549 public:
1550   using AccVisitor::Post;
1551   using AccVisitor::Pre;
1552   using ArraySpecVisitor::Post;
1553   using ConstructVisitor::Post;
1554   using ConstructVisitor::Pre;
1555   using DeclarationVisitor::Post;
1556   using DeclarationVisitor::Pre;
1557   using ImplicitRulesVisitor::Post;
1558   using ImplicitRulesVisitor::Pre;
1559   using InterfaceVisitor::Post;
1560   using InterfaceVisitor::Pre;
1561   using ModuleVisitor::Post;
1562   using ModuleVisitor::Pre;
1563   using OmpVisitor::Post;
1564   using OmpVisitor::Pre;
1565   using ScopeHandler::Post;
1566   using ScopeHandler::Pre;
1567   using SubprogramVisitor::Post;
1568   using SubprogramVisitor::Pre;
1569 
1570   ResolveNamesVisitor(
1571       SemanticsContext &context, ImplicitRulesMap &rules, Scope &top)
1572       : BaseVisitor{context, *this, rules}, topScope_{top} {
1573     PushScope(top);
1574   }
1575 
1576   Scope &topScope() const { return topScope_; }
1577 
1578   // Default action for a parse tree node is to visit children.
1579   template <typename T> bool Pre(const T &) { return true; }
1580   template <typename T> void Post(const T &) {}
1581 
1582   bool Pre(const parser::SpecificationPart &);
1583   bool Pre(const parser::Program &);
1584   void Post(const parser::Program &);
1585   bool Pre(const parser::ImplicitStmt &);
1586   void Post(const parser::PointerObject &);
1587   void Post(const parser::AllocateObject &);
1588   bool Pre(const parser::PointerAssignmentStmt &);
1589   void Post(const parser::Designator &);
1590   void Post(const parser::SubstringInquiry &);
1591   template <typename A, typename B>
1592   void Post(const parser::LoopBounds<A, B> &x) {
1593     ResolveName(*parser::Unwrap<parser::Name>(x.name));
1594   }
1595   void Post(const parser::ProcComponentRef &);
1596   bool Pre(const parser::FunctionReference &);
1597   bool Pre(const parser::CallStmt &);
1598   bool Pre(const parser::ImportStmt &);
1599   void Post(const parser::TypeGuardStmt &);
1600   bool Pre(const parser::StmtFunctionStmt &);
1601   bool Pre(const parser::DefinedOpName &);
1602   bool Pre(const parser::ProgramUnit &);
1603   void Post(const parser::AssignStmt &);
1604   void Post(const parser::AssignedGotoStmt &);
1605   void Post(const parser::CompilerDirective &);
1606 
1607   // These nodes should never be reached: they are handled in ProgramUnit
1608   bool Pre(const parser::MainProgram &) {
1609     llvm_unreachable("This node is handled in ProgramUnit");
1610   }
1611   bool Pre(const parser::FunctionSubprogram &) {
1612     llvm_unreachable("This node is handled in ProgramUnit");
1613   }
1614   bool Pre(const parser::SubroutineSubprogram &) {
1615     llvm_unreachable("This node is handled in ProgramUnit");
1616   }
1617   bool Pre(const parser::SeparateModuleSubprogram &) {
1618     llvm_unreachable("This node is handled in ProgramUnit");
1619   }
1620   bool Pre(const parser::Module &) {
1621     llvm_unreachable("This node is handled in ProgramUnit");
1622   }
1623   bool Pre(const parser::Submodule &) {
1624     llvm_unreachable("This node is handled in ProgramUnit");
1625   }
1626   bool Pre(const parser::BlockData &) {
1627     llvm_unreachable("This node is handled in ProgramUnit");
1628   }
1629 
1630   void NoteExecutablePartCall(Symbol::Flag, SourceName, bool hasCUDAChevrons);
1631 
1632   friend void ResolveSpecificationParts(SemanticsContext &, const Symbol &);
1633 
1634 private:
1635   // Kind of procedure we are expecting to see in a ProcedureDesignator
1636   std::optional<Symbol::Flag> expectedProcFlag_;
1637   std::optional<SourceName> prevImportStmt_;
1638   Scope &topScope_;
1639 
1640   void PreSpecificationConstruct(const parser::SpecificationConstruct &);
1641   void CreateCommonBlockSymbols(const parser::CommonStmt &);
1642   void CreateObjectSymbols(const std::list<parser::ObjectDecl> &, Attr);
1643   void CreateGeneric(const parser::GenericSpec &);
1644   void FinishSpecificationPart(const std::list<parser::DeclarationConstruct> &);
1645   void AnalyzeStmtFunctionStmt(const parser::StmtFunctionStmt &);
1646   void CheckImports();
1647   void CheckImport(const SourceName &, const SourceName &);
1648   void HandleCall(Symbol::Flag, const parser::Call &);
1649   void HandleProcedureName(Symbol::Flag, const parser::Name &);
1650   bool CheckImplicitNoneExternal(const SourceName &, const Symbol &);
1651   bool SetProcFlag(const parser::Name &, Symbol &, Symbol::Flag);
1652   void ResolveSpecificationParts(ProgramTree &);
1653   void AddSubpNames(ProgramTree &);
1654   bool BeginScopeForNode(const ProgramTree &);
1655   void EndScopeForNode(const ProgramTree &);
1656   void FinishSpecificationParts(const ProgramTree &);
1657   void FinishExecutionParts(const ProgramTree &);
1658   void FinishDerivedTypeInstantiation(Scope &);
1659   void ResolveExecutionParts(const ProgramTree &);
1660   void UseCUDABuiltinNames();
1661   void HandleDerivedTypesInImplicitStmts(const parser::ImplicitPart &,
1662       const std::list<parser::DeclarationConstruct> &);
1663 };
1664 
1665 // ImplicitRules implementation
1666 
1667 bool ImplicitRules::isImplicitNoneType() const {
1668   if (isImplicitNoneType_) {
1669     return true;
1670   } else if (map_.empty() && inheritFromParent_) {
1671     return parent_->isImplicitNoneType();
1672   } else {
1673     return false; // default if not specified
1674   }
1675 }
1676 
1677 bool ImplicitRules::isImplicitNoneExternal() const {
1678   if (isImplicitNoneExternal_) {
1679     return true;
1680   } else if (inheritFromParent_) {
1681     return parent_->isImplicitNoneExternal();
1682   } else {
1683     return false; // default if not specified
1684   }
1685 }
1686 
1687 const DeclTypeSpec *ImplicitRules::GetType(
1688     SourceName name, bool respectImplicitNoneType) const {
1689   char ch{name.begin()[0]};
1690   if (isImplicitNoneType_ && respectImplicitNoneType) {
1691     return nullptr;
1692   } else if (auto it{map_.find(ch)}; it != map_.end()) {
1693     return &*it->second;
1694   } else if (inheritFromParent_) {
1695     return parent_->GetType(name, respectImplicitNoneType);
1696   } else if (ch >= 'i' && ch <= 'n') {
1697     return &context_.MakeNumericType(TypeCategory::Integer);
1698   } else if (ch >= 'a' && ch <= 'z') {
1699     return &context_.MakeNumericType(TypeCategory::Real);
1700   } else {
1701     return nullptr;
1702   }
1703 }
1704 
1705 void ImplicitRules::SetTypeMapping(const DeclTypeSpec &type,
1706     parser::Location fromLetter, parser::Location toLetter) {
1707   for (char ch = *fromLetter; ch; ch = ImplicitRules::Incr(ch)) {
1708     auto res{map_.emplace(ch, type)};
1709     if (!res.second) {
1710       context_.Say(parser::CharBlock{fromLetter},
1711           "More than one implicit type specified for '%c'"_err_en_US, ch);
1712     }
1713     if (ch == *toLetter) {
1714       break;
1715     }
1716   }
1717 }
1718 
1719 // Return the next char after ch in a way that works for ASCII or EBCDIC.
1720 // Return '\0' for the char after 'z'.
1721 char ImplicitRules::Incr(char ch) {
1722   switch (ch) {
1723   case 'i':
1724     return 'j';
1725   case 'r':
1726     return 's';
1727   case 'z':
1728     return '\0';
1729   default:
1730     return ch + 1;
1731   }
1732 }
1733 
1734 llvm::raw_ostream &operator<<(
1735     llvm::raw_ostream &o, const ImplicitRules &implicitRules) {
1736   o << "ImplicitRules:\n";
1737   for (char ch = 'a'; ch; ch = ImplicitRules::Incr(ch)) {
1738     ShowImplicitRule(o, implicitRules, ch);
1739   }
1740   ShowImplicitRule(o, implicitRules, '_');
1741   ShowImplicitRule(o, implicitRules, '$');
1742   ShowImplicitRule(o, implicitRules, '@');
1743   return o;
1744 }
1745 void ShowImplicitRule(
1746     llvm::raw_ostream &o, const ImplicitRules &implicitRules, char ch) {
1747   auto it{implicitRules.map_.find(ch)};
1748   if (it != implicitRules.map_.end()) {
1749     o << "  " << ch << ": " << *it->second << '\n';
1750   }
1751 }
1752 
1753 template <typename T> void BaseVisitor::Walk(const T &x) {
1754   parser::Walk(x, *this_);
1755 }
1756 
1757 void BaseVisitor::MakePlaceholder(
1758     const parser::Name &name, MiscDetails::Kind kind) {
1759   if (!name.symbol) {
1760     name.symbol = &context_->globalScope().MakeSymbol(
1761         name.source, Attrs{}, MiscDetails{kind});
1762   }
1763 }
1764 
1765 // AttrsVisitor implementation
1766 
1767 bool AttrsVisitor::BeginAttrs() {
1768   CHECK(!attrs_ && !cudaDataAttr_);
1769   attrs_ = Attrs{};
1770   return true;
1771 }
1772 Attrs AttrsVisitor::GetAttrs() {
1773   CHECK(attrs_);
1774   return *attrs_;
1775 }
1776 Attrs AttrsVisitor::EndAttrs() {
1777   Attrs result{GetAttrs()};
1778   attrs_.reset();
1779   cudaDataAttr_.reset();
1780   passName_ = std::nullopt;
1781   bindName_.reset();
1782   isCDefined_ = false;
1783   return result;
1784 }
1785 
1786 bool AttrsVisitor::SetPassNameOn(Symbol &symbol) {
1787   if (!passName_) {
1788     return false;
1789   }
1790   common::visit(common::visitors{
1791                     [&](ProcEntityDetails &x) { x.set_passName(*passName_); },
1792                     [&](ProcBindingDetails &x) { x.set_passName(*passName_); },
1793                     [](auto &) { common::die("unexpected pass name"); },
1794                 },
1795       symbol.details());
1796   return true;
1797 }
1798 
1799 void AttrsVisitor::SetBindNameOn(Symbol &symbol) {
1800   if ((!attrs_ || !attrs_->test(Attr::BIND_C)) &&
1801       !symbol.attrs().test(Attr::BIND_C)) {
1802     return;
1803   }
1804   symbol.SetIsCDefined(isCDefined_);
1805   std::optional<std::string> label{
1806       evaluate::GetScalarConstantValue<evaluate::Ascii>(bindName_)};
1807   // 18.9.2(2): discard leading and trailing blanks
1808   if (label) {
1809     symbol.SetIsExplicitBindName(true);
1810     auto first{label->find_first_not_of(" ")};
1811     if (first == std::string::npos) {
1812       // Empty NAME= means no binding at all (18.10.2p2)
1813       return;
1814     }
1815     auto last{label->find_last_not_of(" ")};
1816     label = label->substr(first, last - first + 1);
1817   } else if (symbol.GetIsExplicitBindName()) {
1818     // don't try to override explicit binding name with default
1819     return;
1820   } else if (ClassifyProcedure(symbol) == ProcedureDefinitionClass::Internal) {
1821     // BIND(C) does not give an implicit binding label to internal procedures.
1822     return;
1823   } else {
1824     label = symbol.name().ToString();
1825   }
1826   // Checks whether a symbol has two Bind names.
1827   std::string oldBindName;
1828   if (const auto *bindName{symbol.GetBindName()}) {
1829     oldBindName = *bindName;
1830   }
1831   symbol.SetBindName(std::move(*label));
1832   if (!oldBindName.empty()) {
1833     if (const std::string * newBindName{symbol.GetBindName()}) {
1834       if (oldBindName != *newBindName) {
1835         Say(symbol.name(),
1836             "The entity '%s' has multiple BIND names ('%s' and '%s')"_err_en_US,
1837             symbol.name(), oldBindName, *newBindName);
1838       }
1839     }
1840   }
1841 }
1842 
1843 void AttrsVisitor::Post(const parser::LanguageBindingSpec &x) {
1844   if (CheckAndSet(Attr::BIND_C)) {
1845     if (const auto &name{
1846             std::get<std::optional<parser::ScalarDefaultCharConstantExpr>>(
1847                 x.t)}) {
1848       bindName_ = EvaluateExpr(*name);
1849     }
1850     isCDefined_ = std::get<bool>(x.t);
1851   }
1852 }
1853 bool AttrsVisitor::Pre(const parser::IntentSpec &x) {
1854   CheckAndSet(IntentSpecToAttr(x));
1855   return false;
1856 }
1857 bool AttrsVisitor::Pre(const parser::Pass &x) {
1858   if (CheckAndSet(Attr::PASS)) {
1859     if (x.v) {
1860       passName_ = x.v->source;
1861       MakePlaceholder(*x.v, MiscDetails::Kind::PassName);
1862     }
1863   }
1864   return false;
1865 }
1866 
1867 // C730, C743, C755, C778, C1543 say no attribute or prefix repetitions
1868 bool AttrsVisitor::IsDuplicateAttr(Attr attrName) {
1869   CHECK(attrs_);
1870   if (attrs_->test(attrName)) {
1871     context().Warn(common::LanguageFeature::RedundantAttribute,
1872         currStmtSource().value(),
1873         "Attribute '%s' cannot be used more than once"_warn_en_US,
1874         AttrToString(attrName));
1875     return true;
1876   }
1877   return false;
1878 }
1879 
1880 // See if attrName violates a constraint cause by a conflict.  attr1 and attr2
1881 // name attributes that cannot be used on the same declaration
1882 bool AttrsVisitor::HaveAttrConflict(Attr attrName, Attr attr1, Attr attr2) {
1883   CHECK(attrs_);
1884   if ((attrName == attr1 && attrs_->test(attr2)) ||
1885       (attrName == attr2 && attrs_->test(attr1))) {
1886     Say(currStmtSource().value(),
1887         "Attributes '%s' and '%s' conflict with each other"_err_en_US,
1888         AttrToString(attr1), AttrToString(attr2));
1889     return true;
1890   }
1891   return false;
1892 }
1893 // C759, C1543
1894 bool AttrsVisitor::IsConflictingAttr(Attr attrName) {
1895   return HaveAttrConflict(attrName, Attr::INTENT_IN, Attr::INTENT_INOUT) ||
1896       HaveAttrConflict(attrName, Attr::INTENT_IN, Attr::INTENT_OUT) ||
1897       HaveAttrConflict(attrName, Attr::INTENT_INOUT, Attr::INTENT_OUT) ||
1898       HaveAttrConflict(attrName, Attr::PASS, Attr::NOPASS) || // C781
1899       HaveAttrConflict(attrName, Attr::PURE, Attr::IMPURE) ||
1900       HaveAttrConflict(attrName, Attr::PUBLIC, Attr::PRIVATE) ||
1901       HaveAttrConflict(attrName, Attr::RECURSIVE, Attr::NON_RECURSIVE);
1902 }
1903 bool AttrsVisitor::CheckAndSet(Attr attrName) {
1904   if (IsConflictingAttr(attrName) || IsDuplicateAttr(attrName)) {
1905     return false;
1906   }
1907   attrs_->set(attrName);
1908   return true;
1909 }
1910 bool AttrsVisitor::Pre(const common::CUDADataAttr x) {
1911   if (cudaDataAttr_.value_or(x) != x) {
1912     Say(currStmtSource().value(),
1913         "CUDA data attributes '%s' and '%s' may not both be specified"_err_en_US,
1914         common::EnumToString(*cudaDataAttr_), common::EnumToString(x));
1915   }
1916   cudaDataAttr_ = x;
1917   return false;
1918 }
1919 
1920 // DeclTypeSpecVisitor implementation
1921 
1922 const DeclTypeSpec *DeclTypeSpecVisitor::GetDeclTypeSpec() {
1923   return state_.declTypeSpec;
1924 }
1925 
1926 void DeclTypeSpecVisitor::BeginDeclTypeSpec() {
1927   CHECK(!state_.expectDeclTypeSpec);
1928   CHECK(!state_.declTypeSpec);
1929   state_.expectDeclTypeSpec = true;
1930 }
1931 void DeclTypeSpecVisitor::EndDeclTypeSpec() {
1932   CHECK(state_.expectDeclTypeSpec);
1933   state_ = {};
1934 }
1935 
1936 void DeclTypeSpecVisitor::SetDeclTypeSpecCategory(
1937     DeclTypeSpec::Category category) {
1938   CHECK(state_.expectDeclTypeSpec);
1939   state_.derived.category = category;
1940 }
1941 
1942 bool DeclTypeSpecVisitor::Pre(const parser::TypeGuardStmt &) {
1943   BeginDeclTypeSpec();
1944   return true;
1945 }
1946 void DeclTypeSpecVisitor::Post(const parser::TypeGuardStmt &) {
1947   EndDeclTypeSpec();
1948 }
1949 
1950 void DeclTypeSpecVisitor::Post(const parser::TypeSpec &typeSpec) {
1951   // Record the resolved DeclTypeSpec in the parse tree for use by
1952   // expression semantics if the DeclTypeSpec is a valid TypeSpec.
1953   // The grammar ensures that it's an intrinsic or derived type spec,
1954   // not TYPE(*) or CLASS(*) or CLASS(T).
1955   if (const DeclTypeSpec * spec{state_.declTypeSpec}) {
1956     switch (spec->category()) {
1957     case DeclTypeSpec::Numeric:
1958     case DeclTypeSpec::Logical:
1959     case DeclTypeSpec::Character:
1960       typeSpec.declTypeSpec = spec;
1961       break;
1962     case DeclTypeSpec::TypeDerived:
1963       if (const DerivedTypeSpec * derived{spec->AsDerived()}) {
1964         CheckForAbstractType(derived->typeSymbol()); // C703
1965         typeSpec.declTypeSpec = spec;
1966       }
1967       break;
1968     default:
1969       CRASH_NO_CASE;
1970     }
1971   }
1972 }
1973 
1974 void DeclTypeSpecVisitor::Post(
1975     const parser::IntrinsicTypeSpec::DoublePrecision &) {
1976   MakeNumericType(TypeCategory::Real, context().doublePrecisionKind());
1977 }
1978 void DeclTypeSpecVisitor::Post(
1979     const parser::IntrinsicTypeSpec::DoubleComplex &) {
1980   MakeNumericType(TypeCategory::Complex, context().doublePrecisionKind());
1981 }
1982 void DeclTypeSpecVisitor::MakeNumericType(TypeCategory category, int kind) {
1983   SetDeclTypeSpec(context().MakeNumericType(category, kind));
1984 }
1985 
1986 void DeclTypeSpecVisitor::CheckForAbstractType(const Symbol &typeSymbol) {
1987   if (typeSymbol.attrs().test(Attr::ABSTRACT)) {
1988     Say("ABSTRACT derived type may not be used here"_err_en_US);
1989   }
1990 }
1991 
1992 void DeclTypeSpecVisitor::Post(const parser::DeclarationTypeSpec::ClassStar &) {
1993   SetDeclTypeSpec(context().globalScope().MakeClassStarType());
1994 }
1995 void DeclTypeSpecVisitor::Post(const parser::DeclarationTypeSpec::TypeStar &) {
1996   SetDeclTypeSpec(context().globalScope().MakeTypeStarType());
1997 }
1998 
1999 // Check that we're expecting to see a DeclTypeSpec (and haven't seen one yet)
2000 // and save it in state_.declTypeSpec.
2001 void DeclTypeSpecVisitor::SetDeclTypeSpec(const DeclTypeSpec &declTypeSpec) {
2002   CHECK(state_.expectDeclTypeSpec);
2003   CHECK(!state_.declTypeSpec);
2004   state_.declTypeSpec = &declTypeSpec;
2005 }
2006 
2007 KindExpr DeclTypeSpecVisitor::GetKindParamExpr(
2008     TypeCategory category, const std::optional<parser::KindSelector> &kind) {
2009   return AnalyzeKindSelector(context(), category, kind);
2010 }
2011 
2012 // MessageHandler implementation
2013 
2014 Message &MessageHandler::Say(MessageFixedText &&msg) {
2015   return context_->Say(currStmtSource().value(), std::move(msg));
2016 }
2017 Message &MessageHandler::Say(MessageFormattedText &&msg) {
2018   return context_->Say(currStmtSource().value(), std::move(msg));
2019 }
2020 Message &MessageHandler::Say(const SourceName &name, MessageFixedText &&msg) {
2021   return Say(name, std::move(msg), name);
2022 }
2023 
2024 // ImplicitRulesVisitor implementation
2025 
2026 void ImplicitRulesVisitor::Post(const parser::ParameterStmt &) {
2027   prevParameterStmt_ = currStmtSource();
2028 }
2029 
2030 bool ImplicitRulesVisitor::Pre(const parser::ImplicitStmt &x) {
2031   bool result{
2032       common::visit(common::visitors{
2033                         [&](const std::list<ImplicitNoneNameSpec> &y) {
2034                           return HandleImplicitNone(y);
2035                         },
2036                         [&](const std::list<parser::ImplicitSpec> &) {
2037                           if (prevImplicitNoneType_) {
2038                             Say("IMPLICIT statement after IMPLICIT NONE or "
2039                                 "IMPLICIT NONE(TYPE) statement"_err_en_US);
2040                             return false;
2041                           }
2042                           implicitRules_->set_isImplicitNoneType(false);
2043                           return true;
2044                         },
2045                     },
2046           x.u)};
2047   prevImplicit_ = currStmtSource();
2048   return result;
2049 }
2050 
2051 bool ImplicitRulesVisitor::Pre(const parser::LetterSpec &x) {
2052   auto loLoc{std::get<parser::Location>(x.t)};
2053   auto hiLoc{loLoc};
2054   if (auto hiLocOpt{std::get<std::optional<parser::Location>>(x.t)}) {
2055     hiLoc = *hiLocOpt;
2056     if (*hiLoc < *loLoc) {
2057       Say(hiLoc, "'%s' does not follow '%s' alphabetically"_err_en_US,
2058           std::string(hiLoc, 1), std::string(loLoc, 1));
2059       return false;
2060     }
2061   }
2062   implicitRules_->SetTypeMapping(*GetDeclTypeSpec(), loLoc, hiLoc);
2063   return false;
2064 }
2065 
2066 bool ImplicitRulesVisitor::Pre(const parser::ImplicitSpec &) {
2067   BeginDeclTypeSpec();
2068   set_allowForwardReferenceToDerivedType(true);
2069   return true;
2070 }
2071 
2072 void ImplicitRulesVisitor::Post(const parser::ImplicitSpec &) {
2073   set_allowForwardReferenceToDerivedType(false);
2074   EndDeclTypeSpec();
2075 }
2076 
2077 void ImplicitRulesVisitor::SetScope(const Scope &scope) {
2078   implicitRules_ = &DEREF(implicitRulesMap_).at(&scope);
2079   prevImplicit_ = std::nullopt;
2080   prevImplicitNone_ = std::nullopt;
2081   prevImplicitNoneType_ = std::nullopt;
2082   prevParameterStmt_ = std::nullopt;
2083 }
2084 void ImplicitRulesVisitor::BeginScope(const Scope &scope) {
2085   // find or create implicit rules for this scope
2086   DEREF(implicitRulesMap_).try_emplace(&scope, context(), implicitRules_);
2087   SetScope(scope);
2088 }
2089 
2090 // TODO: for all of these errors, reference previous statement too
2091 bool ImplicitRulesVisitor::HandleImplicitNone(
2092     const std::list<ImplicitNoneNameSpec> &nameSpecs) {
2093   if (prevImplicitNone_) {
2094     Say("More than one IMPLICIT NONE statement"_err_en_US);
2095     Say(*prevImplicitNone_, "Previous IMPLICIT NONE statement"_en_US);
2096     return false;
2097   }
2098   if (prevParameterStmt_) {
2099     Say("IMPLICIT NONE statement after PARAMETER statement"_err_en_US);
2100     return false;
2101   }
2102   prevImplicitNone_ = currStmtSource();
2103   bool implicitNoneTypeNever{
2104       context().IsEnabled(common::LanguageFeature::ImplicitNoneTypeNever)};
2105   if (nameSpecs.empty()) {
2106     if (!implicitNoneTypeNever) {
2107       prevImplicitNoneType_ = currStmtSource();
2108       implicitRules_->set_isImplicitNoneType(true);
2109       if (prevImplicit_) {
2110         Say("IMPLICIT NONE statement after IMPLICIT statement"_err_en_US);
2111         return false;
2112       }
2113     }
2114   } else {
2115     int sawType{0};
2116     int sawExternal{0};
2117     for (const auto noneSpec : nameSpecs) {
2118       switch (noneSpec) {
2119       case ImplicitNoneNameSpec::External:
2120         implicitRules_->set_isImplicitNoneExternal(true);
2121         ++sawExternal;
2122         break;
2123       case ImplicitNoneNameSpec::Type:
2124         if (!implicitNoneTypeNever) {
2125           prevImplicitNoneType_ = currStmtSource();
2126           implicitRules_->set_isImplicitNoneType(true);
2127           if (prevImplicit_) {
2128             Say("IMPLICIT NONE(TYPE) after IMPLICIT statement"_err_en_US);
2129             return false;
2130           }
2131           ++sawType;
2132         }
2133         break;
2134       }
2135     }
2136     if (sawType > 1) {
2137       Say("TYPE specified more than once in IMPLICIT NONE statement"_err_en_US);
2138       return false;
2139     }
2140     if (sawExternal > 1) {
2141       Say("EXTERNAL specified more than once in IMPLICIT NONE statement"_err_en_US);
2142       return false;
2143     }
2144   }
2145   return true;
2146 }
2147 
2148 // ArraySpecVisitor implementation
2149 
2150 void ArraySpecVisitor::Post(const parser::ArraySpec &x) {
2151   CHECK(arraySpec_.empty());
2152   arraySpec_ = AnalyzeArraySpec(context(), x);
2153 }
2154 void ArraySpecVisitor::Post(const parser::ComponentArraySpec &x) {
2155   CHECK(arraySpec_.empty());
2156   arraySpec_ = AnalyzeArraySpec(context(), x);
2157 }
2158 void ArraySpecVisitor::Post(const parser::CoarraySpec &x) {
2159   CHECK(coarraySpec_.empty());
2160   coarraySpec_ = AnalyzeCoarraySpec(context(), x);
2161 }
2162 
2163 const ArraySpec &ArraySpecVisitor::arraySpec() {
2164   return !arraySpec_.empty() ? arraySpec_ : attrArraySpec_;
2165 }
2166 const ArraySpec &ArraySpecVisitor::coarraySpec() {
2167   return !coarraySpec_.empty() ? coarraySpec_ : attrCoarraySpec_;
2168 }
2169 void ArraySpecVisitor::BeginArraySpec() {
2170   CHECK(arraySpec_.empty());
2171   CHECK(coarraySpec_.empty());
2172   CHECK(attrArraySpec_.empty());
2173   CHECK(attrCoarraySpec_.empty());
2174 }
2175 void ArraySpecVisitor::EndArraySpec() {
2176   CHECK(arraySpec_.empty());
2177   CHECK(coarraySpec_.empty());
2178   attrArraySpec_.clear();
2179   attrCoarraySpec_.clear();
2180 }
2181 void ArraySpecVisitor::PostAttrSpec() {
2182   // Save dimension/codimension from attrs so we can process array/coarray-spec
2183   // on the entity-decl
2184   if (!arraySpec_.empty()) {
2185     if (attrArraySpec_.empty()) {
2186       attrArraySpec_ = arraySpec_;
2187       arraySpec_.clear();
2188     } else {
2189       Say(currStmtSource().value(),
2190           "Attribute 'DIMENSION' cannot be used more than once"_err_en_US);
2191     }
2192   }
2193   if (!coarraySpec_.empty()) {
2194     if (attrCoarraySpec_.empty()) {
2195       attrCoarraySpec_ = coarraySpec_;
2196       coarraySpec_.clear();
2197     } else {
2198       Say(currStmtSource().value(),
2199           "Attribute 'CODIMENSION' cannot be used more than once"_err_en_US);
2200     }
2201   }
2202 }
2203 
2204 // FuncResultStack implementation
2205 
2206 FuncResultStack::~FuncResultStack() { CHECK(stack_.empty()); }
2207 
2208 void FuncResultStack::CompleteFunctionResultType() {
2209   // If the function has a type in the prefix, process it now.
2210   FuncInfo *info{Top()};
2211   if (info && &info->scope == &scopeHandler_.currScope()) {
2212     if (info->parsedType && info->resultSymbol) {
2213       scopeHandler_.messageHandler().set_currStmtSource(info->source);
2214       if (const auto *type{
2215               scopeHandler_.ProcessTypeSpec(*info->parsedType, true)}) {
2216         Symbol &symbol{*info->resultSymbol};
2217         if (!scopeHandler_.context().HasError(symbol)) {
2218           if (symbol.GetType()) {
2219             scopeHandler_.Say(symbol.name(),
2220                 "Function cannot have both an explicit type prefix and a RESULT suffix"_err_en_US);
2221             scopeHandler_.context().SetError(symbol);
2222           } else {
2223             symbol.SetType(*type);
2224           }
2225         }
2226       }
2227       info->parsedType = nullptr;
2228     }
2229   }
2230 }
2231 
2232 // Called from ConvertTo{Object/Proc}Entity to cope with any appearance
2233 // of the function result in a specification expression.
2234 void FuncResultStack::CompleteTypeIfFunctionResult(Symbol &symbol) {
2235   if (FuncInfo * info{Top()}) {
2236     if (info->resultSymbol == &symbol) {
2237       CompleteFunctionResultType();
2238     }
2239   }
2240 }
2241 
2242 void FuncResultStack::Pop() {
2243   if (!stack_.empty() && &stack_.back().scope == &scopeHandler_.currScope()) {
2244     stack_.pop_back();
2245   }
2246 }
2247 
2248 // ScopeHandler implementation
2249 
2250 void ScopeHandler::SayAlreadyDeclared(const parser::Name &name, Symbol &prev) {
2251   SayAlreadyDeclared(name.source, prev);
2252 }
2253 void ScopeHandler::SayAlreadyDeclared(const SourceName &name, Symbol &prev) {
2254   if (context().HasError(prev)) {
2255     // don't report another error about prev
2256   } else {
2257     if (const auto *details{prev.detailsIf<UseDetails>()}) {
2258       Say(name, "'%s' is already declared in this scoping unit"_err_en_US)
2259           .Attach(details->location(),
2260               "It is use-associated with '%s' in module '%s'"_en_US,
2261               details->symbol().name(), GetUsedModule(*details).name());
2262     } else {
2263       SayAlreadyDeclared(name, prev.name());
2264     }
2265     context().SetError(prev);
2266   }
2267 }
2268 void ScopeHandler::SayAlreadyDeclared(
2269     const SourceName &name1, const SourceName &name2) {
2270   if (name1.begin() < name2.begin()) {
2271     SayAlreadyDeclared(name2, name1);
2272   } else {
2273     Say(name1, "'%s' is already declared in this scoping unit"_err_en_US)
2274         .Attach(name2, "Previous declaration of '%s'"_en_US, name2);
2275   }
2276 }
2277 
2278 void ScopeHandler::SayWithReason(const parser::Name &name, Symbol &symbol,
2279     MessageFixedText &&msg1, Message &&msg2) {
2280   bool isFatal{msg1.IsFatal()};
2281   Say(name, std::move(msg1), symbol.name()).Attach(std::move(msg2));
2282   context().SetError(symbol, isFatal);
2283 }
2284 
2285 template <typename... A>
2286 Message &ScopeHandler::SayWithDecl(const parser::Name &name, Symbol &symbol,
2287     MessageFixedText &&msg, A &&...args) {
2288   auto &message{
2289       Say(name.source, std::move(msg), symbol.name(), std::forward<A>(args)...)
2290           .Attach(symbol.name(),
2291               symbol.test(Symbol::Flag::Implicit)
2292                   ? "Implicit declaration of '%s'"_en_US
2293                   : "Declaration of '%s'"_en_US,
2294               name.source)};
2295   if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}) {
2296     if (auto usedAsProc{proc->usedAsProcedureHere()}) {
2297       if (usedAsProc->begin() != symbol.name().begin()) {
2298         message.Attach(*usedAsProc, "Referenced as a procedure"_en_US);
2299       }
2300     }
2301   }
2302   return message;
2303 }
2304 
2305 void ScopeHandler::SayLocalMustBeVariable(
2306     const parser::Name &name, Symbol &symbol) {
2307   SayWithDecl(name, symbol,
2308       "The name '%s' must be a variable to appear"
2309       " in a locality-spec"_err_en_US);
2310 }
2311 
2312 Message &ScopeHandler::SayDerivedType(
2313     const SourceName &name, MessageFixedText &&msg, const Scope &type) {
2314   const Symbol &typeSymbol{DEREF(type.GetSymbol())};
2315   return Say(name, std::move(msg), name, typeSymbol.name())
2316       .Attach(typeSymbol.name(), "Declaration of derived type '%s'"_en_US,
2317           typeSymbol.name());
2318 }
2319 Message &ScopeHandler::Say2(const SourceName &name1, MessageFixedText &&msg1,
2320     const SourceName &name2, MessageFixedText &&msg2) {
2321   return Say(name1, std::move(msg1)).Attach(name2, std::move(msg2), name2);
2322 }
2323 Message &ScopeHandler::Say2(const SourceName &name, MessageFixedText &&msg1,
2324     Symbol &symbol, MessageFixedText &&msg2) {
2325   bool isFatal{msg1.IsFatal()};
2326   Message &result{Say2(name, std::move(msg1), symbol.name(), std::move(msg2))};
2327   context().SetError(symbol, isFatal);
2328   return result;
2329 }
2330 Message &ScopeHandler::Say2(const parser::Name &name, MessageFixedText &&msg1,
2331     Symbol &symbol, MessageFixedText &&msg2) {
2332   bool isFatal{msg1.IsFatal()};
2333   Message &result{
2334       Say2(name.source, std::move(msg1), symbol.name(), std::move(msg2))};
2335   context().SetError(symbol, isFatal);
2336   return result;
2337 }
2338 
2339 // This is essentially GetProgramUnitContaining(), but it can return
2340 // a mutable Scope &, it ignores statement functions, and it fails
2341 // gracefully for error recovery (returning the original Scope).
2342 template <typename T> static T &GetInclusiveScope(T &scope) {
2343   for (T *s{&scope}; !s->IsGlobal(); s = &s->parent()) {
2344     switch (s->kind()) {
2345     case Scope::Kind::Module:
2346     case Scope::Kind::MainProgram:
2347     case Scope::Kind::Subprogram:
2348     case Scope::Kind::BlockData:
2349       if (!s->IsStmtFunction()) {
2350         return *s;
2351       }
2352       break;
2353     default:;
2354     }
2355   }
2356   return scope;
2357 }
2358 
2359 Scope &ScopeHandler::InclusiveScope() { return GetInclusiveScope(currScope()); }
2360 
2361 Scope *ScopeHandler::GetHostProcedure() {
2362   Scope &parent{InclusiveScope().parent()};
2363   switch (parent.kind()) {
2364   case Scope::Kind::Subprogram:
2365     return &parent;
2366   case Scope::Kind::MainProgram:
2367     return &parent;
2368   default:
2369     return nullptr;
2370   }
2371 }
2372 
2373 Scope &ScopeHandler::NonDerivedTypeScope() {
2374   return currScope_->IsDerivedType() ? currScope_->parent() : *currScope_;
2375 }
2376 
2377 void ScopeHandler::PushScope(Scope::Kind kind, Symbol *symbol) {
2378   PushScope(currScope().MakeScope(kind, symbol));
2379 }
2380 void ScopeHandler::PushScope(Scope &scope) {
2381   currScope_ = &scope;
2382   auto kind{currScope_->kind()};
2383   if (kind != Scope::Kind::BlockConstruct &&
2384       kind != Scope::Kind::OtherConstruct) {
2385     BeginScope(scope);
2386   }
2387   // The name of a module or submodule cannot be "used" in its scope,
2388   // as we read 19.3.1(2), so we allow the name to be used as a local
2389   // identifier in the module or submodule too.  Same with programs
2390   // (14.1(3)) and BLOCK DATA.
2391   if (!currScope_->IsDerivedType() && kind != Scope::Kind::Module &&
2392       kind != Scope::Kind::MainProgram && kind != Scope::Kind::BlockData) {
2393     if (auto *symbol{scope.symbol()}) {
2394       // Create a dummy symbol so we can't create another one with the same
2395       // name. It might already be there if we previously pushed the scope.
2396       SourceName name{symbol->name()};
2397       if (!FindInScope(scope, name)) {
2398         auto &newSymbol{MakeSymbol(name)};
2399         if (kind == Scope::Kind::Subprogram) {
2400           // Allow for recursive references.  If this symbol is a function
2401           // without an explicit RESULT(), this new symbol will be discarded
2402           // and replaced with an object of the same name.
2403           newSymbol.set_details(HostAssocDetails{*symbol});
2404         } else {
2405           newSymbol.set_details(MiscDetails{MiscDetails::Kind::ScopeName});
2406         }
2407       }
2408     }
2409   }
2410 }
2411 void ScopeHandler::PopScope() {
2412   CHECK(currScope_ && !currScope_->IsGlobal());
2413   // Entities that are not yet classified as objects or procedures are now
2414   // assumed to be objects.
2415   // TODO: Statement functions
2416   for (auto &pair : currScope()) {
2417     ConvertToObjectEntity(*pair.second);
2418   }
2419   funcResultStack_.Pop();
2420   // If popping back into a global scope, pop back to the main global scope.
2421   SetScope(currScope_->parent().IsGlobal() ? context().globalScope()
2422                                            : currScope_->parent());
2423 }
2424 void ScopeHandler::SetScope(Scope &scope) {
2425   currScope_ = &scope;
2426   ImplicitRulesVisitor::SetScope(InclusiveScope());
2427 }
2428 
2429 Symbol *ScopeHandler::FindSymbol(const parser::Name &name) {
2430   return FindSymbol(currScope(), name);
2431 }
2432 Symbol *ScopeHandler::FindSymbol(const Scope &scope, const parser::Name &name) {
2433   if (scope.IsDerivedType()) {
2434     if (Symbol * symbol{scope.FindComponent(name.source)}) {
2435       if (symbol->has<TypeParamDetails>()) {
2436         return Resolve(name, symbol);
2437       }
2438     }
2439     return FindSymbol(scope.parent(), name);
2440   } else {
2441     // In EQUIVALENCE statements only resolve names in the local scope, see
2442     // 19.5.1.4, paragraph 2, item (10)
2443     return Resolve(name,
2444         inEquivalenceStmt_ ? FindInScope(scope, name)
2445                            : scope.FindSymbol(name.source));
2446   }
2447 }
2448 
2449 Symbol &ScopeHandler::MakeSymbol(
2450     Scope &scope, const SourceName &name, Attrs attrs) {
2451   if (Symbol * symbol{FindInScope(scope, name)}) {
2452     CheckDuplicatedAttrs(name, *symbol, attrs);
2453     SetExplicitAttrs(*symbol, attrs);
2454     return *symbol;
2455   } else {
2456     const auto pair{scope.try_emplace(name, attrs, UnknownDetails{})};
2457     CHECK(pair.second); // name was not found, so must be able to add
2458     return *pair.first->second;
2459   }
2460 }
2461 Symbol &ScopeHandler::MakeSymbol(const SourceName &name, Attrs attrs) {
2462   return MakeSymbol(currScope(), name, attrs);
2463 }
2464 Symbol &ScopeHandler::MakeSymbol(const parser::Name &name, Attrs attrs) {
2465   return Resolve(name, MakeSymbol(name.source, attrs));
2466 }
2467 Symbol &ScopeHandler::MakeHostAssocSymbol(
2468     const parser::Name &name, const Symbol &hostSymbol) {
2469   Symbol &symbol{*NonDerivedTypeScope()
2470                       .try_emplace(name.source, HostAssocDetails{hostSymbol})
2471                       .first->second};
2472   name.symbol = &symbol;
2473   symbol.attrs() = hostSymbol.attrs(); // TODO: except PRIVATE, PUBLIC?
2474   // These attributes can be redundantly reapplied without error
2475   // on the host-associated name, at most once (C815).
2476   symbol.implicitAttrs() =
2477       symbol.attrs() & Attrs{Attr::ASYNCHRONOUS, Attr::VOLATILE};
2478   // SAVE statement in the inner scope will create a new symbol.
2479   // If the host variable is used via host association,
2480   // we have to propagate whether SAVE is implicit in the host scope.
2481   // Otherwise, verifications that do not allow explicit SAVE
2482   // attribute would fail.
2483   symbol.implicitAttrs() |= hostSymbol.implicitAttrs() & Attrs{Attr::SAVE};
2484   symbol.flags() = hostSymbol.flags();
2485   return symbol;
2486 }
2487 Symbol &ScopeHandler::CopySymbol(const SourceName &name, const Symbol &symbol) {
2488   CHECK(!FindInScope(name));
2489   return MakeSymbol(currScope(), name, symbol.attrs());
2490 }
2491 
2492 // Look for name only in scope, not in enclosing scopes.
2493 Symbol *ScopeHandler::FindInScope(
2494     const Scope &scope, const parser::Name &name) {
2495   return Resolve(name, FindInScope(scope, name.source));
2496 }
2497 Symbol *ScopeHandler::FindInScope(const Scope &scope, const SourceName &name) {
2498   // all variants of names, e.g. "operator(.ne.)" for "operator(/=)"
2499   for (const std::string &n : GetAllNames(context(), name)) {
2500     auto it{scope.find(SourceName{n})};
2501     if (it != scope.end()) {
2502       return &*it->second;
2503     }
2504   }
2505   return nullptr;
2506 }
2507 
2508 // Find a component or type parameter by name in a derived type or its parents.
2509 Symbol *ScopeHandler::FindInTypeOrParents(
2510     const Scope &scope, const parser::Name &name) {
2511   return Resolve(name, scope.FindComponent(name.source));
2512 }
2513 Symbol *ScopeHandler::FindInTypeOrParents(const parser::Name &name) {
2514   return FindInTypeOrParents(currScope(), name);
2515 }
2516 Symbol *ScopeHandler::FindInScopeOrBlockConstructs(
2517     const Scope &scope, SourceName name) {
2518   if (Symbol * symbol{FindInScope(scope, name)}) {
2519     return symbol;
2520   }
2521   for (const Scope &child : scope.children()) {
2522     if (child.kind() == Scope::Kind::BlockConstruct) {
2523       if (Symbol * symbol{FindInScopeOrBlockConstructs(child, name)}) {
2524         return symbol;
2525       }
2526     }
2527   }
2528   return nullptr;
2529 }
2530 
2531 void ScopeHandler::EraseSymbol(const parser::Name &name) {
2532   currScope().erase(name.source);
2533   name.symbol = nullptr;
2534 }
2535 
2536 static bool NeedsType(const Symbol &symbol) {
2537   return !symbol.GetType() &&
2538       common::visit(common::visitors{
2539                         [](const EntityDetails &) { return true; },
2540                         [](const ObjectEntityDetails &) { return true; },
2541                         [](const AssocEntityDetails &) { return true; },
2542                         [&](const ProcEntityDetails &p) {
2543                           return symbol.test(Symbol::Flag::Function) &&
2544                               !symbol.attrs().test(Attr::INTRINSIC) &&
2545                               !p.type() && !p.procInterface();
2546                         },
2547                         [](const auto &) { return false; },
2548                     },
2549           symbol.details());
2550 }
2551 
2552 void ScopeHandler::ApplyImplicitRules(
2553     Symbol &symbol, bool allowForwardReference) {
2554   funcResultStack_.CompleteTypeIfFunctionResult(symbol);
2555   if (context().HasError(symbol) || !NeedsType(symbol)) {
2556     return;
2557   }
2558   if (const DeclTypeSpec * type{GetImplicitType(symbol)}) {
2559     symbol.set(Symbol::Flag::Implicit);
2560     symbol.SetType(*type);
2561     return;
2562   }
2563   if (symbol.has<ProcEntityDetails>() && !symbol.attrs().test(Attr::EXTERNAL)) {
2564     std::optional<Symbol::Flag> functionOrSubroutineFlag;
2565     if (symbol.test(Symbol::Flag::Function)) {
2566       functionOrSubroutineFlag = Symbol::Flag::Function;
2567     } else if (symbol.test(Symbol::Flag::Subroutine)) {
2568       functionOrSubroutineFlag = Symbol::Flag::Subroutine;
2569     }
2570     if (IsIntrinsic(symbol.name(), functionOrSubroutineFlag)) {
2571       // type will be determined in expression semantics
2572       AcquireIntrinsicProcedureFlags(symbol);
2573       return;
2574     }
2575   }
2576   if (allowForwardReference && ImplicitlyTypeForwardRef(symbol)) {
2577     return;
2578   }
2579   if (const auto *entity{symbol.detailsIf<EntityDetails>()};
2580       entity && entity->isDummy()) {
2581     // Dummy argument, no declaration or reference; if it turns
2582     // out to be a subroutine, it's fine, and if it is a function
2583     // or object, it'll be caught later.
2584     return;
2585   }
2586   if (deferImplicitTyping_) {
2587     return;
2588   }
2589   if (!context().HasError(symbol)) {
2590     Say(symbol.name(), "No explicit type declared for '%s'"_err_en_US);
2591     context().SetError(symbol);
2592   }
2593 }
2594 
2595 // Extension: Allow forward references to scalar integer dummy arguments
2596 // or variables in COMMON to appear in specification expressions under
2597 // IMPLICIT NONE(TYPE) when what would otherwise have been their implicit
2598 // type is default INTEGER.
2599 bool ScopeHandler::ImplicitlyTypeForwardRef(Symbol &symbol) {
2600   if (!inSpecificationPart_ || context().HasError(symbol) ||
2601       !(IsDummy(symbol) || FindCommonBlockContaining(symbol)) ||
2602       symbol.Rank() != 0 ||
2603       !context().languageFeatures().IsEnabled(
2604           common::LanguageFeature::ForwardRefImplicitNone)) {
2605     return false;
2606   }
2607   const DeclTypeSpec *type{
2608       GetImplicitType(symbol, false /*ignore IMPLICIT NONE*/)};
2609   if (!type || !type->IsNumeric(TypeCategory::Integer)) {
2610     return false;
2611   }
2612   auto kind{evaluate::ToInt64(type->numericTypeSpec().kind())};
2613   if (!kind || *kind != context().GetDefaultKind(TypeCategory::Integer)) {
2614     return false;
2615   }
2616   if (!ConvertToObjectEntity(symbol)) {
2617     return false;
2618   }
2619   // TODO: check no INTENT(OUT) if dummy?
2620   context().Warn(common::LanguageFeature::ForwardRefImplicitNone, symbol.name(),
2621       "'%s' was used without (or before) being explicitly typed"_warn_en_US,
2622       symbol.name());
2623   symbol.set(Symbol::Flag::Implicit);
2624   symbol.SetType(*type);
2625   return true;
2626 }
2627 
2628 // Ensure that the symbol for an intrinsic procedure is marked with
2629 // the INTRINSIC attribute.  Also set PURE &/or ELEMENTAL as
2630 // appropriate.
2631 void ScopeHandler::AcquireIntrinsicProcedureFlags(Symbol &symbol) {
2632   SetImplicitAttr(symbol, Attr::INTRINSIC);
2633   switch (context().intrinsics().GetIntrinsicClass(symbol.name().ToString())) {
2634   case evaluate::IntrinsicClass::elementalFunction:
2635   case evaluate::IntrinsicClass::elementalSubroutine:
2636     SetExplicitAttr(symbol, Attr::ELEMENTAL);
2637     SetExplicitAttr(symbol, Attr::PURE);
2638     break;
2639   case evaluate::IntrinsicClass::impureSubroutine:
2640     break;
2641   default:
2642     SetExplicitAttr(symbol, Attr::PURE);
2643   }
2644 }
2645 
2646 const DeclTypeSpec *ScopeHandler::GetImplicitType(
2647     Symbol &symbol, bool respectImplicitNoneType) {
2648   const Scope *scope{&symbol.owner()};
2649   if (scope->IsGlobal()) {
2650     scope = &currScope();
2651   }
2652   scope = &GetInclusiveScope(*scope);
2653   const auto *type{implicitRulesMap_->at(scope).GetType(
2654       symbol.name(), respectImplicitNoneType)};
2655   if (type) {
2656     if (const DerivedTypeSpec * derived{type->AsDerived()}) {
2657       // Resolve any forward-referenced derived type; a quick no-op else.
2658       auto &instantiatable{*const_cast<DerivedTypeSpec *>(derived)};
2659       instantiatable.Instantiate(currScope());
2660     }
2661   }
2662   return type;
2663 }
2664 
2665 void ScopeHandler::CheckEntryDummyUse(SourceName source, Symbol *symbol) {
2666   if (!inSpecificationPart_ && symbol &&
2667       symbol->test(Symbol::Flag::EntryDummyArgument)) {
2668     Say(source,
2669         "Dummy argument '%s' may not be used before its ENTRY statement"_err_en_US,
2670         symbol->name());
2671     symbol->set(Symbol::Flag::EntryDummyArgument, false);
2672   }
2673 }
2674 
2675 // Convert symbol to be a ObjectEntity or return false if it can't be.
2676 bool ScopeHandler::ConvertToObjectEntity(Symbol &symbol) {
2677   if (symbol.has<ObjectEntityDetails>()) {
2678     // nothing to do
2679   } else if (symbol.has<UnknownDetails>()) {
2680     // These are attributes that a name could have picked up from
2681     // an attribute statement or type declaration statement.
2682     if (symbol.attrs().HasAny({Attr::EXTERNAL, Attr::INTRINSIC})) {
2683       return false;
2684     }
2685     symbol.set_details(ObjectEntityDetails{});
2686   } else if (auto *details{symbol.detailsIf<EntityDetails>()}) {
2687     if (symbol.attrs().HasAny({Attr::EXTERNAL, Attr::INTRINSIC})) {
2688       return false;
2689     }
2690     funcResultStack_.CompleteTypeIfFunctionResult(symbol);
2691     symbol.set_details(ObjectEntityDetails{std::move(*details)});
2692   } else if (auto *useDetails{symbol.detailsIf<UseDetails>()}) {
2693     return useDetails->symbol().has<ObjectEntityDetails>();
2694   } else if (auto *hostDetails{symbol.detailsIf<HostAssocDetails>()}) {
2695     return hostDetails->symbol().has<ObjectEntityDetails>();
2696   } else {
2697     return false;
2698   }
2699   return true;
2700 }
2701 // Convert symbol to be a ProcEntity or return false if it can't be.
2702 bool ScopeHandler::ConvertToProcEntity(
2703     Symbol &symbol, std::optional<SourceName> usedHere) {
2704   if (symbol.has<ProcEntityDetails>()) {
2705   } else if (symbol.has<UnknownDetails>()) {
2706     symbol.set_details(ProcEntityDetails{});
2707   } else if (auto *details{symbol.detailsIf<EntityDetails>()}) {
2708     if (IsFunctionResult(symbol) &&
2709         !(IsPointer(symbol) && symbol.attrs().test(Attr::EXTERNAL))) {
2710       // Don't turn function result into a procedure pointer unless both
2711       // POINTER and EXTERNAL
2712       return false;
2713     }
2714     funcResultStack_.CompleteTypeIfFunctionResult(symbol);
2715     symbol.set_details(ProcEntityDetails{std::move(*details)});
2716     if (symbol.GetType() && !symbol.test(Symbol::Flag::Implicit)) {
2717       CHECK(!symbol.test(Symbol::Flag::Subroutine));
2718       symbol.set(Symbol::Flag::Function);
2719     }
2720   } else if (auto *useDetails{symbol.detailsIf<UseDetails>()}) {
2721     return useDetails->symbol().has<ProcEntityDetails>();
2722   } else if (auto *hostDetails{symbol.detailsIf<HostAssocDetails>()}) {
2723     return hostDetails->symbol().has<ProcEntityDetails>();
2724   } else {
2725     return false;
2726   }
2727   auto &proc{symbol.get<ProcEntityDetails>()};
2728   if (usedHere && !proc.usedAsProcedureHere()) {
2729     proc.set_usedAsProcedureHere(*usedHere);
2730   }
2731   return true;
2732 }
2733 
2734 const DeclTypeSpec &ScopeHandler::MakeNumericType(
2735     TypeCategory category, const std::optional<parser::KindSelector> &kind) {
2736   KindExpr value{GetKindParamExpr(category, kind)};
2737   if (auto known{evaluate::ToInt64(value)}) {
2738     return MakeNumericType(category, static_cast<int>(*known));
2739   } else {
2740     return currScope_->MakeNumericType(category, std::move(value));
2741   }
2742 }
2743 
2744 const DeclTypeSpec &ScopeHandler::MakeNumericType(
2745     TypeCategory category, int kind) {
2746   return context().MakeNumericType(category, kind);
2747 }
2748 
2749 const DeclTypeSpec &ScopeHandler::MakeLogicalType(
2750     const std::optional<parser::KindSelector> &kind) {
2751   KindExpr value{GetKindParamExpr(TypeCategory::Logical, kind)};
2752   if (auto known{evaluate::ToInt64(value)}) {
2753     return MakeLogicalType(static_cast<int>(*known));
2754   } else {
2755     return currScope_->MakeLogicalType(std::move(value));
2756   }
2757 }
2758 
2759 const DeclTypeSpec &ScopeHandler::MakeLogicalType(int kind) {
2760   return context().MakeLogicalType(kind);
2761 }
2762 
2763 void ScopeHandler::NotePossibleBadForwardRef(const parser::Name &name) {
2764   if (inSpecificationPart_ && !deferImplicitTyping_ && name.symbol) {
2765     auto kind{currScope().kind()};
2766     if ((kind == Scope::Kind::Subprogram && !currScope().IsStmtFunction()) ||
2767         kind == Scope::Kind::BlockConstruct) {
2768       bool isHostAssociated{&name.symbol->owner() == &currScope()
2769               ? name.symbol->has<HostAssocDetails>()
2770               : name.symbol->owner().Contains(currScope())};
2771       if (isHostAssociated) {
2772         specPartState_.forwardRefs.insert(name.source);
2773       }
2774     }
2775   }
2776 }
2777 
2778 std::optional<SourceName> ScopeHandler::HadForwardRef(
2779     const Symbol &symbol) const {
2780   auto iter{specPartState_.forwardRefs.find(symbol.name())};
2781   if (iter != specPartState_.forwardRefs.end()) {
2782     return *iter;
2783   }
2784   return std::nullopt;
2785 }
2786 
2787 bool ScopeHandler::CheckPossibleBadForwardRef(const Symbol &symbol) {
2788   if (!context().HasError(symbol)) {
2789     if (auto fwdRef{HadForwardRef(symbol)}) {
2790       const Symbol *outer{symbol.owner().FindSymbol(symbol.name())};
2791       if (outer && symbol.has<UseDetails>() &&
2792           &symbol.GetUltimate() == &outer->GetUltimate()) {
2793         // e.g. IMPORT of host's USE association
2794         return false;
2795       }
2796       Say(*fwdRef,
2797           "Forward reference to '%s' is not allowed in the same specification part"_err_en_US,
2798           *fwdRef)
2799           .Attach(symbol.name(), "Later declaration of '%s'"_en_US, *fwdRef);
2800       context().SetError(symbol);
2801       return true;
2802     }
2803     if ((IsDummy(symbol) || FindCommonBlockContaining(symbol)) &&
2804         isImplicitNoneType() && symbol.test(Symbol::Flag::Implicit) &&
2805         !context().HasError(symbol)) {
2806       // Dummy or COMMON was implicitly typed despite IMPLICIT NONE(TYPE) in
2807       // ApplyImplicitRules() due to use in a specification expression,
2808       // and no explicit type declaration appeared later.
2809       Say(symbol.name(), "No explicit type declared for '%s'"_err_en_US);
2810       context().SetError(symbol);
2811       return true;
2812     }
2813   }
2814   return false;
2815 }
2816 
2817 void ScopeHandler::MakeExternal(Symbol &symbol) {
2818   if (!symbol.attrs().test(Attr::EXTERNAL)) {
2819     SetImplicitAttr(symbol, Attr::EXTERNAL);
2820     if (symbol.attrs().test(Attr::INTRINSIC)) { // C840
2821       Say(symbol.name(),
2822           "Symbol '%s' cannot have both EXTERNAL and INTRINSIC attributes"_err_en_US,
2823           symbol.name());
2824     }
2825   }
2826 }
2827 
2828 bool ScopeHandler::CheckDuplicatedAttr(
2829     SourceName name, Symbol &symbol, Attr attr) {
2830   if (attr == Attr::SAVE) {
2831     // checked elsewhere
2832   } else if (symbol.attrs().test(attr)) { // C815
2833     if (symbol.implicitAttrs().test(attr)) {
2834       // Implied attribute is now confirmed explicitly
2835       symbol.implicitAttrs().reset(attr);
2836     } else {
2837       Say(name, "%s attribute was already specified on '%s'"_err_en_US,
2838           EnumToString(attr), name);
2839       return false;
2840     }
2841   }
2842   return true;
2843 }
2844 
2845 bool ScopeHandler::CheckDuplicatedAttrs(
2846     SourceName name, Symbol &symbol, Attrs attrs) {
2847   bool ok{true};
2848   attrs.IterateOverMembers(
2849       [&](Attr x) { ok &= CheckDuplicatedAttr(name, symbol, x); });
2850   return ok;
2851 }
2852 
2853 void ScopeHandler::SetCUDADataAttr(SourceName source, Symbol &symbol,
2854     std::optional<common::CUDADataAttr> attr) {
2855   if (attr) {
2856     ConvertToObjectEntity(symbol);
2857     if (auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
2858       if (*attr != object->cudaDataAttr().value_or(*attr)) {
2859         Say(source,
2860             "'%s' already has another CUDA data attribute ('%s')"_err_en_US,
2861             symbol.name(),
2862             std::string{common::EnumToString(*object->cudaDataAttr())}.c_str());
2863       } else {
2864         object->set_cudaDataAttr(attr);
2865       }
2866     } else {
2867       Say(source,
2868           "'%s' is not an object and may not have a CUDA data attribute"_err_en_US,
2869           symbol.name());
2870     }
2871   }
2872 }
2873 
2874 // ModuleVisitor implementation
2875 
2876 bool ModuleVisitor::Pre(const parser::Only &x) {
2877   common::visit(common::visitors{
2878                     [&](const Indirection<parser::GenericSpec> &generic) {
2879                       GenericSpecInfo genericSpecInfo{generic.value()};
2880                       AddUseOnly(genericSpecInfo.symbolName());
2881                       AddUse(genericSpecInfo);
2882                     },
2883                     [&](const parser::Name &name) {
2884                       AddUseOnly(name.source);
2885                       Resolve(name, AddUse(name.source, name.source).use);
2886                     },
2887                     [&](const parser::Rename &rename) { Walk(rename); },
2888                 },
2889       x.u);
2890   return false;
2891 }
2892 
2893 void ModuleVisitor::CollectUseRenames(const parser::UseStmt &useStmt) {
2894   auto doRename{[&](const parser::Rename &rename) {
2895     if (const auto *names{std::get_if<parser::Rename::Names>(&rename.u)}) {
2896       AddUseRename(std::get<1>(names->t).source, useStmt.moduleName.source);
2897     }
2898   }};
2899   common::visit(
2900       common::visitors{
2901           [&](const std::list<parser::Rename> &renames) {
2902             for (const auto &rename : renames) {
2903               doRename(rename);
2904             }
2905           },
2906           [&](const std::list<parser::Only> &onlys) {
2907             for (const auto &only : onlys) {
2908               if (const auto *rename{std::get_if<parser::Rename>(&only.u)}) {
2909                 doRename(*rename);
2910               }
2911             }
2912           },
2913       },
2914       useStmt.u);
2915 }
2916 
2917 bool ModuleVisitor::Pre(const parser::Rename::Names &x) {
2918   const auto &localName{std::get<0>(x.t)};
2919   const auto &useName{std::get<1>(x.t)};
2920   SymbolRename rename{AddUse(localName.source, useName.source)};
2921   Resolve(useName, rename.use);
2922   Resolve(localName, rename.local);
2923   return false;
2924 }
2925 bool ModuleVisitor::Pre(const parser::Rename::Operators &x) {
2926   const parser::DefinedOpName &local{std::get<0>(x.t)};
2927   const parser::DefinedOpName &use{std::get<1>(x.t)};
2928   GenericSpecInfo localInfo{local};
2929   GenericSpecInfo useInfo{use};
2930   if (IsIntrinsicOperator(context(), local.v.source)) {
2931     Say(local.v,
2932         "Intrinsic operator '%s' may not be used as a defined operator"_err_en_US);
2933   } else if (IsLogicalConstant(context(), local.v.source)) {
2934     Say(local.v,
2935         "Logical constant '%s' may not be used as a defined operator"_err_en_US);
2936   } else {
2937     SymbolRename rename{AddUse(localInfo.symbolName(), useInfo.symbolName())};
2938     useInfo.Resolve(rename.use);
2939     localInfo.Resolve(rename.local);
2940   }
2941   return false;
2942 }
2943 
2944 // Set useModuleScope_ to the Scope of the module being used.
2945 bool ModuleVisitor::Pre(const parser::UseStmt &x) {
2946   std::optional<bool> isIntrinsic;
2947   if (x.nature) {
2948     isIntrinsic = *x.nature == parser::UseStmt::ModuleNature::Intrinsic;
2949   } else if (currScope().IsModule() && currScope().symbol() &&
2950       currScope().symbol()->attrs().test(Attr::INTRINSIC)) {
2951     // Intrinsic modules USE only other intrinsic modules
2952     isIntrinsic = true;
2953   }
2954   useModuleScope_ = FindModule(x.moduleName, isIntrinsic);
2955   if (!useModuleScope_) {
2956     return false;
2957   }
2958   AddAndCheckModuleUse(x.moduleName.source,
2959       useModuleScope_->parent().kind() == Scope::Kind::IntrinsicModules);
2960   // use the name from this source file
2961   useModuleScope_->symbol()->ReplaceName(x.moduleName.source);
2962   return true;
2963 }
2964 
2965 void ModuleVisitor::Post(const parser::UseStmt &x) {
2966   if (const auto *list{std::get_if<std::list<parser::Rename>>(&x.u)}) {
2967     // Not a use-only: collect the names that were used in renames,
2968     // then add a use for each public name that was not renamed.
2969     std::set<SourceName> useNames;
2970     for (const auto &rename : *list) {
2971       common::visit(common::visitors{
2972                         [&](const parser::Rename::Names &names) {
2973                           useNames.insert(std::get<1>(names.t).source);
2974                         },
2975                         [&](const parser::Rename::Operators &ops) {
2976                           useNames.insert(std::get<1>(ops.t).v.source);
2977                         },
2978                     },
2979           rename.u);
2980     }
2981     for (const auto &[name, symbol] : *useModuleScope_) {
2982       if (symbol->attrs().test(Attr::PUBLIC) && !IsUseRenamed(symbol->name()) &&
2983           (!symbol->implicitAttrs().test(Attr::INTRINSIC) ||
2984               symbol->has<UseDetails>()) &&
2985           !symbol->has<MiscDetails>() && useNames.count(name) == 0) {
2986         SourceName location{x.moduleName.source};
2987         if (auto *localSymbol{FindInScope(name)}) {
2988           DoAddUse(location, localSymbol->name(), *localSymbol, *symbol);
2989         } else {
2990           DoAddUse(location, location, CopySymbol(name, *symbol), *symbol);
2991         }
2992       }
2993     }
2994   }
2995   useModuleScope_ = nullptr;
2996 }
2997 
2998 ModuleVisitor::SymbolRename ModuleVisitor::AddUse(
2999     const SourceName &localName, const SourceName &useName) {
3000   return AddUse(localName, useName, FindInScope(*useModuleScope_, useName));
3001 }
3002 
3003 ModuleVisitor::SymbolRename ModuleVisitor::AddUse(
3004     const SourceName &localName, const SourceName &useName, Symbol *useSymbol) {
3005   if (!useModuleScope_) {
3006     return {}; // error occurred finding module
3007   }
3008   if (!useSymbol) {
3009     Say(useName, "'%s' not found in module '%s'"_err_en_US, MakeOpName(useName),
3010         useModuleScope_->GetName().value());
3011     return {};
3012   }
3013   if (useSymbol->attrs().test(Attr::PRIVATE) &&
3014       !FindModuleFileContaining(currScope())) {
3015     // Privacy is not enforced in module files so that generic interfaces
3016     // can be resolved to private specific procedures in specification
3017     // expressions.
3018     Say(useName, "'%s' is PRIVATE in '%s'"_err_en_US, MakeOpName(useName),
3019         useModuleScope_->GetName().value());
3020     return {};
3021   }
3022   auto &localSymbol{MakeSymbol(localName)};
3023   DoAddUse(useName, localName, localSymbol, *useSymbol);
3024   return {&localSymbol, useSymbol};
3025 }
3026 
3027 // symbol must be either a Use or a Generic formed by merging two uses.
3028 // Convert it to a UseError with this additional location.
3029 static bool ConvertToUseError(
3030     Symbol &symbol, const SourceName &location, const Scope &module) {
3031   const auto *useDetails{symbol.detailsIf<UseDetails>()};
3032   if (!useDetails) {
3033     if (auto *genericDetails{symbol.detailsIf<GenericDetails>()}) {
3034       if (!genericDetails->uses().empty()) {
3035         useDetails = &genericDetails->uses().at(0)->get<UseDetails>();
3036       }
3037     }
3038   }
3039   if (useDetails) {
3040     symbol.set_details(
3041         UseErrorDetails{*useDetails}.add_occurrence(location, module));
3042     return true;
3043   } else {
3044     return false;
3045   }
3046 }
3047 
3048 void ModuleVisitor::DoAddUse(SourceName location, SourceName localName,
3049     Symbol &originalLocal, const Symbol &useSymbol) {
3050   Symbol *localSymbol{&originalLocal};
3051   if (auto *details{localSymbol->detailsIf<UseErrorDetails>()}) {
3052     details->add_occurrence(location, *useModuleScope_);
3053     return;
3054   }
3055   const Symbol &useUltimate{useSymbol.GetUltimate()};
3056   const auto *useGeneric{useUltimate.detailsIf<GenericDetails>()};
3057   if (localSymbol->has<UnknownDetails>()) {
3058     if (useGeneric &&
3059         ((useGeneric->specific() &&
3060              IsProcedurePointer(*useGeneric->specific())) ||
3061             (useGeneric->derivedType() &&
3062                 useUltimate.name() != localSymbol->name()))) {
3063       // We are use-associating a generic that either shadows a procedure
3064       // pointer or shadows a derived type with a distinct name.
3065       // Local references that might be made to the procedure pointer should
3066       // use a UseDetails symbol for proper data addressing, and a derived
3067       // type needs to be in scope with its local name.  So create an
3068       // empty local generic now into which the use-associated generic may
3069       // be copied.
3070       localSymbol->set_details(GenericDetails{});
3071       localSymbol->get<GenericDetails>().set_kind(useGeneric->kind());
3072     } else { // just create UseDetails
3073       localSymbol->set_details(UseDetails{localName, useSymbol});
3074       localSymbol->attrs() =
3075           useSymbol.attrs() & ~Attrs{Attr::PUBLIC, Attr::PRIVATE, Attr::SAVE};
3076       localSymbol->implicitAttrs() =
3077           localSymbol->attrs() & Attrs{Attr::ASYNCHRONOUS, Attr::VOLATILE};
3078       localSymbol->flags() = useSymbol.flags();
3079       return;
3080     }
3081   }
3082 
3083   Symbol &localUltimate{localSymbol->GetUltimate()};
3084   if (&localUltimate == &useUltimate) {
3085     // use-associating the same symbol again -- ok
3086     return;
3087   }
3088 
3089   // There are many possible combinations of symbol types that could arrive
3090   // with the same (local) name vie USE association from distinct modules.
3091   // Fortran allows a generic interface to share its name with a derived type,
3092   // or with the name of a non-generic procedure (which should be one of the
3093   // generic's specific procedures).  Implementing all these possibilities is
3094   // complicated.
3095   // Error cases are converted into UseErrorDetails symbols to trigger error
3096   // messages when/if bad combinations are actually used later in the program.
3097   // The error cases are:
3098   //   - two distinct derived types
3099   //   - two distinct non-generic procedures
3100   //   - a generic and a non-generic that is not already one of its specifics
3101   //   - anything other than a derived type, non-generic procedure, or
3102   //     generic procedure being combined with something other than an
3103   //     prior USE association of itself
3104   auto *localGeneric{localUltimate.detailsIf<GenericDetails>()};
3105   Symbol *localDerivedType{nullptr};
3106   if (localUltimate.has<DerivedTypeDetails>()) {
3107     localDerivedType = &localUltimate;
3108   } else if (localGeneric) {
3109     if (auto *dt{localGeneric->derivedType()};
3110         dt && !dt->attrs().test(Attr::PRIVATE)) {
3111       localDerivedType = dt;
3112     }
3113   }
3114   const Symbol *useDerivedType{nullptr};
3115   if (useUltimate.has<DerivedTypeDetails>()) {
3116     useDerivedType = &useUltimate;
3117   } else if (useGeneric) {
3118     if (const auto *dt{useGeneric->derivedType()};
3119         dt && !dt->attrs().test(Attr::PRIVATE)) {
3120       useDerivedType = dt;
3121     }
3122   }
3123 
3124   Symbol *localProcedure{nullptr};
3125   if (localGeneric) {
3126     if (localGeneric->specific() &&
3127         !localGeneric->specific()->attrs().test(Attr::PRIVATE)) {
3128       localProcedure = localGeneric->specific();
3129     }
3130   } else if (IsProcedure(localUltimate)) {
3131     localProcedure = &localUltimate;
3132   }
3133   const Symbol *useProcedure{nullptr};
3134   if (useGeneric) {
3135     if (useGeneric->specific() &&
3136         !useGeneric->specific()->attrs().test(Attr::PRIVATE)) {
3137       useProcedure = useGeneric->specific();
3138     }
3139   } else if (IsProcedure(useUltimate)) {
3140     useProcedure = &useUltimate;
3141   }
3142 
3143   // Creates a UseErrorDetails symbol in the current scope for a
3144   // current UseDetails symbol, but leaves the UseDetails in the
3145   // scope's name map.
3146   auto CreateLocalUseError{[&]() {
3147     EraseSymbol(*localSymbol);
3148     CHECK(localSymbol->has<UseDetails>());
3149     UseErrorDetails details{localSymbol->get<UseDetails>()};
3150     details.add_occurrence(location, *useModuleScope_);
3151     Symbol *newSymbol{&MakeSymbol(localName, Attrs{}, std::move(details))};
3152     // Restore *localSymbol in currScope
3153     auto iter{currScope().find(localName)};
3154     CHECK(iter != currScope().end() && &*iter->second == newSymbol);
3155     iter->second = MutableSymbolRef{*localSymbol};
3156     return newSymbol;
3157   }};
3158 
3159   // When two derived types arrived, try to combine them.
3160   const Symbol *combinedDerivedType{nullptr};
3161   if (!useDerivedType) {
3162     combinedDerivedType = localDerivedType;
3163   } else if (!localDerivedType) {
3164     if (useDerivedType->name() == localName) {
3165       combinedDerivedType = useDerivedType;
3166     } else {
3167       combinedDerivedType =
3168           &currScope().MakeSymbol(localSymbol->name(), useDerivedType->attrs(),
3169               UseDetails{localSymbol->name(), *useDerivedType});
3170     }
3171   } else if (&localDerivedType->GetUltimate() ==
3172       &useDerivedType->GetUltimate()) {
3173     combinedDerivedType = localDerivedType;
3174   } else {
3175     const Scope *localScope{localDerivedType->GetUltimate().scope()};
3176     const Scope *useScope{useDerivedType->GetUltimate().scope()};
3177     if (localScope && useScope && localScope->derivedTypeSpec() &&
3178         useScope->derivedTypeSpec() &&
3179         evaluate::AreSameDerivedType(
3180             *localScope->derivedTypeSpec(), *useScope->derivedTypeSpec())) {
3181       combinedDerivedType = localDerivedType;
3182     } else {
3183       // Create a local UseErrorDetails for the ambiguous derived type
3184       if (localGeneric) {
3185         combinedDerivedType = CreateLocalUseError();
3186       } else {
3187         ConvertToUseError(*localSymbol, location, *useModuleScope_);
3188         combinedDerivedType = localSymbol;
3189       }
3190     }
3191     if (!localGeneric && !useGeneric) {
3192       return; // both symbols are derived types; done
3193     }
3194   }
3195 
3196   auto AreSameProcedure{[&](const Symbol &p1, const Symbol &p2) {
3197     if (&p1 == &p2) {
3198       return true;
3199     } else if (p1.name() != p2.name()) {
3200       return false;
3201     } else if (p1.attrs().test(Attr::INTRINSIC) ||
3202         p2.attrs().test(Attr::INTRINSIC)) {
3203       return p1.attrs().test(Attr::INTRINSIC) &&
3204           p2.attrs().test(Attr::INTRINSIC);
3205     } else if (!IsProcedure(p1) || !IsProcedure(p2)) {
3206       return false;
3207     } else if (IsPointer(p1) || IsPointer(p2)) {
3208       return false;
3209     } else if (const auto *subp{p1.detailsIf<SubprogramDetails>()};
3210                subp && !subp->isInterface()) {
3211       return false; // defined in module, not an external
3212     } else if (const auto *subp{p2.detailsIf<SubprogramDetails>()};
3213                subp && !subp->isInterface()) {
3214       return false; // defined in module, not an external
3215     } else {
3216       // Both are external interfaces, perhaps to the same procedure
3217       auto class1{ClassifyProcedure(p1)};
3218       auto class2{ClassifyProcedure(p2)};
3219       if (class1 == ProcedureDefinitionClass::External &&
3220           class2 == ProcedureDefinitionClass::External) {
3221         auto chars1{evaluate::characteristics::Procedure::Characterize(
3222             p1, GetFoldingContext())};
3223         auto chars2{evaluate::characteristics::Procedure::Characterize(
3224             p2, GetFoldingContext())};
3225         // same procedure interface defined identically in two modules?
3226         return chars1 && chars2 && *chars1 == *chars2;
3227       } else {
3228         return false;
3229       }
3230     }
3231   }};
3232 
3233   // When two non-generic procedures arrived, try to combine them.
3234   const Symbol *combinedProcedure{nullptr};
3235   if (!localProcedure) {
3236     combinedProcedure = useProcedure;
3237   } else if (!useProcedure) {
3238     combinedProcedure = localProcedure;
3239   } else {
3240     if (AreSameProcedure(
3241             localProcedure->GetUltimate(), useProcedure->GetUltimate())) {
3242       if (!localGeneric && !useGeneric) {
3243         return; // both symbols are non-generic procedures
3244       }
3245       combinedProcedure = localProcedure;
3246     }
3247   }
3248 
3249   // Prepare to merge generics
3250   bool cantCombine{false};
3251   if (localGeneric) {
3252     if (useGeneric || useDerivedType) {
3253     } else if (&useUltimate == &BypassGeneric(localUltimate).GetUltimate()) {
3254       return; // nothing to do; used subprogram is local's specific
3255     } else if (useUltimate.attrs().test(Attr::INTRINSIC) &&
3256         useUltimate.name() == localSymbol->name()) {
3257       return; // local generic can extend intrinsic
3258     } else {
3259       for (const auto &ref : localGeneric->specificProcs()) {
3260         if (&ref->GetUltimate() == &useUltimate) {
3261           return; // used non-generic is already a specific of local generic
3262         }
3263       }
3264       cantCombine = true;
3265     }
3266   } else if (useGeneric) {
3267     if (localDerivedType) {
3268     } else if (&localUltimate == &BypassGeneric(useUltimate).GetUltimate() ||
3269         (localSymbol->attrs().test(Attr::INTRINSIC) &&
3270             localUltimate.name() == useUltimate.name())) {
3271       // Local is the specific of the used generic or an intrinsic with the
3272       // same name; replace it.
3273       EraseSymbol(*localSymbol);
3274       Symbol &newSymbol{MakeSymbol(localName,
3275           useUltimate.attrs() & ~Attrs{Attr::PUBLIC, Attr::PRIVATE},
3276           UseDetails{localName, useUltimate})};
3277       newSymbol.flags() = useSymbol.flags();
3278       return;
3279     } else {
3280       for (const auto &ref : useGeneric->specificProcs()) {
3281         if (&ref->GetUltimate() == &localUltimate) {
3282           return; // local non-generic is already a specific of used generic
3283         }
3284       }
3285       cantCombine = true;
3286     }
3287   } else {
3288     cantCombine = true;
3289   }
3290 
3291   // If symbols are not combinable, create a use error.
3292   if (cantCombine) {
3293     if (!ConvertToUseError(*localSymbol, location, *useModuleScope_)) {
3294       Say(location,
3295           "Cannot use-associate '%s'; it is already declared in this scope"_err_en_US,
3296           localName)
3297           .Attach(localSymbol->name(), "Previous declaration of '%s'"_en_US,
3298               localName);
3299     }
3300     return;
3301   }
3302 
3303   // At this point, there must be at least one generic interface.
3304   CHECK(localGeneric || (useGeneric && (localDerivedType || localProcedure)));
3305 
3306   // Ensure that a use-associated specific procedure that is a procedure
3307   // pointer is properly represented as a USE association of an entity.
3308   if (IsProcedurePointer(useProcedure)) {
3309     Symbol &combined{currScope().MakeSymbol(localSymbol->name(),
3310         useProcedure->attrs(), UseDetails{localName, *useProcedure})};
3311     combined.flags() |= useProcedure->flags();
3312     combinedProcedure = &combined;
3313   }
3314 
3315   if (localGeneric) {
3316     // Create a local copy of a previously use-associated generic so that
3317     // it can be locally extended without corrupting the original.
3318     if (localSymbol->has<UseDetails>()) {
3319       GenericDetails generic;
3320       generic.CopyFrom(DEREF(localGeneric));
3321       EraseSymbol(*localSymbol);
3322       Symbol &newSymbol{MakeSymbol(
3323           localSymbol->name(), localSymbol->attrs(), std::move(generic))};
3324       newSymbol.flags() = localSymbol->flags();
3325       localGeneric = &newSymbol.get<GenericDetails>();
3326       localGeneric->AddUse(*localSymbol);
3327       localSymbol = &newSymbol;
3328     }
3329     if (useGeneric) {
3330       // Combine two use-associated generics
3331       localSymbol->attrs() =
3332           useSymbol.attrs() & ~Attrs{Attr::PUBLIC, Attr::PRIVATE};
3333       localSymbol->flags() = useSymbol.flags();
3334       AddGenericUse(*localGeneric, localName, useUltimate);
3335       localGeneric->clear_derivedType();
3336       localGeneric->CopyFrom(*useGeneric);
3337     }
3338     localGeneric->clear_derivedType();
3339     if (combinedDerivedType) {
3340       localGeneric->set_derivedType(*const_cast<Symbol *>(combinedDerivedType));
3341     }
3342     localGeneric->clear_specific();
3343     if (combinedProcedure) {
3344       localGeneric->set_specific(*const_cast<Symbol *>(combinedProcedure));
3345     }
3346   } else {
3347     CHECK(localSymbol->has<UseDetails>());
3348     // Create a local copy of the use-associated generic, then extend it
3349     // with the combined derived type &/or non-generic procedure.
3350     GenericDetails generic;
3351     generic.CopyFrom(*useGeneric);
3352     EraseSymbol(*localSymbol);
3353     Symbol &newSymbol{MakeSymbol(localName,
3354         useUltimate.attrs() & ~Attrs{Attr::PUBLIC, Attr::PRIVATE},
3355         std::move(generic))};
3356     newSymbol.flags() = useUltimate.flags();
3357     auto &newUseGeneric{newSymbol.get<GenericDetails>()};
3358     AddGenericUse(newUseGeneric, localName, useUltimate);
3359     newUseGeneric.AddUse(*localSymbol);
3360     if (combinedDerivedType) {
3361       if (const auto *oldDT{newUseGeneric.derivedType()}) {
3362         CHECK(&oldDT->GetUltimate() == &combinedDerivedType->GetUltimate());
3363       } else {
3364         newUseGeneric.set_derivedType(
3365             *const_cast<Symbol *>(combinedDerivedType));
3366       }
3367     }
3368     if (combinedProcedure) {
3369       newUseGeneric.set_specific(*const_cast<Symbol *>(combinedProcedure));
3370     }
3371   }
3372 }
3373 
3374 void ModuleVisitor::AddUse(const GenericSpecInfo &info) {
3375   if (useModuleScope_) {
3376     const auto &name{info.symbolName()};
3377     auto rename{AddUse(name, name, FindInScope(*useModuleScope_, name))};
3378     info.Resolve(rename.use);
3379   }
3380 }
3381 
3382 // Create a UseDetails symbol for this USE and add it to generic
3383 Symbol &ModuleVisitor::AddGenericUse(
3384     GenericDetails &generic, const SourceName &name, const Symbol &useSymbol) {
3385   Symbol &newSymbol{
3386       currScope().MakeSymbol(name, {}, UseDetails{name, useSymbol})};
3387   generic.AddUse(newSymbol);
3388   return newSymbol;
3389 }
3390 
3391 // Enforce F'2023 C1406 as a warning
3392 void ModuleVisitor::AddAndCheckModuleUse(SourceName name, bool isIntrinsic) {
3393   if (isIntrinsic) {
3394     if (auto iter{nonIntrinsicUses_.find(name)};
3395         iter != nonIntrinsicUses_.end()) {
3396       if (auto *msg{context().Warn(common::LanguageFeature::MiscUseExtensions,
3397               name,
3398               "Should not USE the intrinsic module '%s' in the same scope as a USE of the non-intrinsic module"_port_en_US,
3399               name)}) {
3400         msg->Attach(*iter, "Previous USE of '%s'"_en_US, *iter);
3401       }
3402     }
3403     intrinsicUses_.insert(name);
3404   } else {
3405     if (auto iter{intrinsicUses_.find(name)}; iter != intrinsicUses_.end()) {
3406       if (auto *msg{context().Warn(common::LanguageFeature::MiscUseExtensions,
3407               name,
3408               "Should not USE the non-intrinsic module '%s' in the same scope as a USE of the intrinsic module"_port_en_US,
3409               name)}) {
3410         msg->Attach(*iter, "Previous USE of '%s'"_en_US, *iter);
3411       }
3412     }
3413     nonIntrinsicUses_.insert(name);
3414   }
3415 }
3416 
3417 bool ModuleVisitor::BeginSubmodule(
3418     const parser::Name &name, const parser::ParentIdentifier &parentId) {
3419   const auto &ancestorName{std::get<parser::Name>(parentId.t)};
3420   Scope *parentScope{nullptr};
3421   Scope *ancestor{FindModule(ancestorName, false /*not intrinsic*/)};
3422   if (ancestor) {
3423     if (const auto &parentName{
3424             std::get<std::optional<parser::Name>>(parentId.t)}) {
3425       parentScope = FindModule(*parentName, false /*not intrinsic*/, ancestor);
3426     } else {
3427       parentScope = ancestor;
3428     }
3429   }
3430   if (parentScope) {
3431     PushScope(*parentScope);
3432   } else {
3433     // Error recovery: there's no ancestor scope, so create a dummy one to
3434     // hold the submodule's scope.
3435     SourceName dummyName{context().GetTempName(currScope())};
3436     Symbol &dummySymbol{MakeSymbol(dummyName, Attrs{}, ModuleDetails{false})};
3437     PushScope(Scope::Kind::Module, &dummySymbol);
3438     parentScope = &currScope();
3439   }
3440   BeginModule(name, true);
3441   set_inheritFromParent(false); // submodules don't inherit parents' implicits
3442   if (ancestor && !ancestor->AddSubmodule(name.source, currScope())) {
3443     Say(name, "Module '%s' already has a submodule named '%s'"_err_en_US,
3444         ancestorName.source, name.source);
3445   }
3446   return true;
3447 }
3448 
3449 void ModuleVisitor::BeginModule(const parser::Name &name, bool isSubmodule) {
3450   // Submodule symbols are not visible in their parents' scopes.
3451   Symbol &symbol{isSubmodule ? Resolve(name,
3452                                    currScope().MakeSymbol(name.source, Attrs{},
3453                                        ModuleDetails{true}))
3454                              : MakeSymbol(name, ModuleDetails{false})};
3455   auto &details{symbol.get<ModuleDetails>()};
3456   PushScope(Scope::Kind::Module, &symbol);
3457   details.set_scope(&currScope());
3458   prevAccessStmt_ = std::nullopt;
3459 }
3460 
3461 // Find a module or submodule by name and return its scope.
3462 // If ancestor is present, look for a submodule of that ancestor module.
3463 // May have to read a .mod file to find it.
3464 // If an error occurs, report it and return nullptr.
3465 Scope *ModuleVisitor::FindModule(const parser::Name &name,
3466     std::optional<bool> isIntrinsic, Scope *ancestor) {
3467   ModFileReader reader{context()};
3468   Scope *scope{
3469       reader.Read(name.source, isIntrinsic, ancestor, /*silent=*/false)};
3470   if (!scope) {
3471     return nullptr;
3472   }
3473   if (DoesScopeContain(scope, currScope())) { // 14.2.2(1)
3474     Say(name, "Module '%s' cannot USE itself"_err_en_US);
3475   }
3476   Resolve(name, scope->symbol());
3477   return scope;
3478 }
3479 
3480 void ModuleVisitor::ApplyDefaultAccess() {
3481   const auto *moduleDetails{
3482       DEREF(currScope().symbol()).detailsIf<ModuleDetails>()};
3483   CHECK(moduleDetails);
3484   Attr defaultAttr{
3485       DEREF(moduleDetails).isDefaultPrivate() ? Attr::PRIVATE : Attr::PUBLIC};
3486   for (auto &pair : currScope()) {
3487     Symbol &symbol{*pair.second};
3488     if (!symbol.attrs().HasAny({Attr::PUBLIC, Attr::PRIVATE})) {
3489       Attr attr{defaultAttr};
3490       if (auto *generic{symbol.detailsIf<GenericDetails>()}) {
3491         if (generic->derivedType()) {
3492           // If a generic interface has a derived type of the same
3493           // name that has an explicit accessibility attribute, then
3494           // the generic must have the same accessibility.
3495           if (generic->derivedType()->attrs().test(Attr::PUBLIC)) {
3496             attr = Attr::PUBLIC;
3497           } else if (generic->derivedType()->attrs().test(Attr::PRIVATE)) {
3498             attr = Attr::PRIVATE;
3499           }
3500         }
3501       }
3502       SetImplicitAttr(symbol, attr);
3503     }
3504   }
3505 }
3506 
3507 // InterfaceVistor implementation
3508 
3509 bool InterfaceVisitor::Pre(const parser::InterfaceStmt &x) {
3510   bool isAbstract{std::holds_alternative<parser::Abstract>(x.u)};
3511   genericInfo_.emplace(/*isInterface*/ true, isAbstract);
3512   return BeginAttrs();
3513 }
3514 
3515 void InterfaceVisitor::Post(const parser::InterfaceStmt &) { EndAttrs(); }
3516 
3517 void InterfaceVisitor::Post(const parser::EndInterfaceStmt &) {
3518   ResolveNewSpecifics();
3519   genericInfo_.pop();
3520 }
3521 
3522 // Create a symbol in genericSymbol_ for this GenericSpec.
3523 bool InterfaceVisitor::Pre(const parser::GenericSpec &x) {
3524   if (auto *symbol{FindInScope(GenericSpecInfo{x}.symbolName())}) {
3525     SetGenericSymbol(*symbol);
3526   }
3527   return false;
3528 }
3529 
3530 bool InterfaceVisitor::Pre(const parser::ProcedureStmt &x) {
3531   if (!isGeneric()) {
3532     Say("A PROCEDURE statement is only allowed in a generic interface block"_err_en_US);
3533   } else {
3534     auto kind{std::get<parser::ProcedureStmt::Kind>(x.t)};
3535     const auto &names{std::get<std::list<parser::Name>>(x.t)};
3536     AddSpecificProcs(names, kind);
3537   }
3538   return false;
3539 }
3540 
3541 bool InterfaceVisitor::Pre(const parser::GenericStmt &) {
3542   genericInfo_.emplace(/*isInterface*/ false);
3543   return BeginAttrs();
3544 }
3545 void InterfaceVisitor::Post(const parser::GenericStmt &x) {
3546   auto attrs{EndAttrs()};
3547   if (Symbol * symbol{GetGenericInfo().symbol}) {
3548     SetExplicitAttrs(*symbol, attrs);
3549   }
3550   const auto &names{std::get<std::list<parser::Name>>(x.t)};
3551   AddSpecificProcs(names, ProcedureKind::Procedure);
3552   ResolveNewSpecifics();
3553   genericInfo_.pop();
3554 }
3555 
3556 bool InterfaceVisitor::inInterfaceBlock() const {
3557   return !genericInfo_.empty() && GetGenericInfo().isInterface;
3558 }
3559 bool InterfaceVisitor::isGeneric() const {
3560   return !genericInfo_.empty() && GetGenericInfo().symbol;
3561 }
3562 bool InterfaceVisitor::isAbstract() const {
3563   return !genericInfo_.empty() && GetGenericInfo().isAbstract;
3564 }
3565 
3566 void InterfaceVisitor::AddSpecificProcs(
3567     const std::list<parser::Name> &names, ProcedureKind kind) {
3568   if (Symbol * symbol{GetGenericInfo().symbol};
3569       symbol && symbol->has<GenericDetails>()) {
3570     for (const auto &name : names) {
3571       specificsForGenericProcs_.emplace(symbol, std::make_pair(&name, kind));
3572       genericsForSpecificProcs_.emplace(name.source, symbol);
3573     }
3574   }
3575 }
3576 
3577 // By now we should have seen all specific procedures referenced by name in
3578 // this generic interface. Resolve those names to symbols.
3579 void GenericHandler::ResolveSpecificsInGeneric(
3580     Symbol &generic, bool isEndOfSpecificationPart) {
3581   auto &details{generic.get<GenericDetails>()};
3582   UnorderedSymbolSet symbolsSeen;
3583   for (const Symbol &symbol : details.specificProcs()) {
3584     symbolsSeen.insert(symbol.GetUltimate());
3585   }
3586   auto range{specificsForGenericProcs_.equal_range(&generic)};
3587   SpecificProcMapType retain;
3588   for (auto it{range.first}; it != range.second; ++it) {
3589     const parser::Name *name{it->second.first};
3590     auto kind{it->second.second};
3591     const Symbol *symbol{isEndOfSpecificationPart
3592             ? FindSymbol(*name)
3593             : FindInScope(generic.owner(), *name)};
3594     ProcedureDefinitionClass defClass{ProcedureDefinitionClass::None};
3595     const Symbol *specific{symbol};
3596     const Symbol *ultimate{nullptr};
3597     if (symbol) {
3598       // Subtlety: when *symbol is a use- or host-association, the specific
3599       // procedure that is recorded in the GenericDetails below must be *symbol,
3600       // not the specific procedure shadowed by a generic, because that specific
3601       // procedure may be a symbol from another module and its name unavailable
3602       // to emit to a module file.
3603       const Symbol &bypassed{BypassGeneric(*symbol)};
3604       if (symbol == &symbol->GetUltimate()) {
3605         specific = &bypassed;
3606       }
3607       ultimate = &bypassed.GetUltimate();
3608       defClass = ClassifyProcedure(*ultimate);
3609     }
3610     std::optional<MessageFixedText> error;
3611     if (defClass == ProcedureDefinitionClass::Module) {
3612       // ok
3613     } else if (kind == ProcedureKind::ModuleProcedure) {
3614       error = "'%s' is not a module procedure"_err_en_US;
3615     } else {
3616       switch (defClass) {
3617       case ProcedureDefinitionClass::Intrinsic:
3618       case ProcedureDefinitionClass::External:
3619       case ProcedureDefinitionClass::Internal:
3620       case ProcedureDefinitionClass::Dummy:
3621       case ProcedureDefinitionClass::Pointer:
3622         break;
3623       case ProcedureDefinitionClass::None:
3624         error = "'%s' is not a procedure"_err_en_US;
3625         break;
3626       default:
3627         error =
3628             "'%s' is not a procedure that can appear in a generic interface"_err_en_US;
3629         break;
3630       }
3631     }
3632     if (error) {
3633       if (isEndOfSpecificationPart) {
3634         Say(*name, std::move(*error));
3635       } else {
3636         // possible forward reference, catch it later
3637         retain.emplace(&generic, std::make_pair(name, kind));
3638       }
3639     } else if (!ultimate) {
3640     } else if (symbolsSeen.insert(*ultimate).second /*true if added*/) {
3641       // When a specific procedure is a USE association, that association
3642       // is saved in the generic's specifics, not its ultimate symbol,
3643       // so that module file output of interfaces can distinguish them.
3644       details.AddSpecificProc(*specific, name->source);
3645     } else if (specific == ultimate) {
3646       Say(name->source,
3647           "Procedure '%s' is already specified in generic '%s'"_err_en_US,
3648           name->source, MakeOpName(generic.name()));
3649     } else {
3650       Say(name->source,
3651           "Procedure '%s' from module '%s' is already specified in generic '%s'"_err_en_US,
3652           ultimate->name(), ultimate->owner().GetName().value(),
3653           MakeOpName(generic.name()));
3654     }
3655   }
3656   specificsForGenericProcs_.erase(range.first, range.second);
3657   specificsForGenericProcs_.merge(std::move(retain));
3658 }
3659 
3660 void GenericHandler::DeclaredPossibleSpecificProc(Symbol &proc) {
3661   auto range{genericsForSpecificProcs_.equal_range(proc.name())};
3662   for (auto iter{range.first}; iter != range.second; ++iter) {
3663     ResolveSpecificsInGeneric(*iter->second, false);
3664   }
3665 }
3666 
3667 void InterfaceVisitor::ResolveNewSpecifics() {
3668   if (Symbol * generic{genericInfo_.top().symbol};
3669       generic && generic->has<GenericDetails>()) {
3670     ResolveSpecificsInGeneric(*generic, false);
3671   }
3672 }
3673 
3674 // Mixed interfaces are allowed by the standard.
3675 // If there is a derived type with the same name, they must all be functions.
3676 void InterfaceVisitor::CheckGenericProcedures(Symbol &generic) {
3677   ResolveSpecificsInGeneric(generic, true);
3678   auto &details{generic.get<GenericDetails>()};
3679   if (auto *proc{details.CheckSpecific()}) {
3680     context().Warn(common::UsageWarning::HomonymousSpecific,
3681         proc->name().begin() > generic.name().begin() ? proc->name()
3682                                                       : generic.name(),
3683         "'%s' should not be the name of both a generic interface and a procedure unless it is a specific procedure of the generic"_warn_en_US,
3684         generic.name());
3685   }
3686   auto &specifics{details.specificProcs()};
3687   if (specifics.empty()) {
3688     if (details.derivedType()) {
3689       generic.set(Symbol::Flag::Function);
3690     }
3691     return;
3692   }
3693   const Symbol *function{nullptr};
3694   const Symbol *subroutine{nullptr};
3695   for (const Symbol &specific : specifics) {
3696     if (!function && specific.test(Symbol::Flag::Function)) {
3697       function = &specific;
3698     } else if (!subroutine && specific.test(Symbol::Flag::Subroutine)) {
3699       subroutine = &specific;
3700       if (details.derivedType() &&
3701           context().ShouldWarn(
3702               common::LanguageFeature::SubroutineAndFunctionSpecifics) &&
3703           !InModuleFile()) {
3704         SayDerivedType(generic.name(),
3705             "Generic interface '%s' should only contain functions due to derived type with same name"_warn_en_US,
3706             *details.derivedType()->GetUltimate().scope())
3707             .set_languageFeature(
3708                 common::LanguageFeature::SubroutineAndFunctionSpecifics);
3709       }
3710     }
3711     if (function && subroutine) { // F'2023 C1514
3712       if (auto *msg{context().Warn(
3713               common::LanguageFeature::SubroutineAndFunctionSpecifics,
3714               generic.name(),
3715               "Generic interface '%s' has both a function and a subroutine"_warn_en_US,
3716               generic.name())}) {
3717         msg->Attach(function->name(), "Function declaration"_en_US)
3718             .Attach(subroutine->name(), "Subroutine declaration"_en_US);
3719       }
3720       break;
3721     }
3722   }
3723   if (function && !subroutine) {
3724     generic.set(Symbol::Flag::Function);
3725   } else if (subroutine && !function) {
3726     generic.set(Symbol::Flag::Subroutine);
3727   }
3728 }
3729 
3730 // SubprogramVisitor implementation
3731 
3732 // Return false if it is actually an assignment statement.
3733 bool SubprogramVisitor::HandleStmtFunction(const parser::StmtFunctionStmt &x) {
3734   const auto &name{std::get<parser::Name>(x.t)};
3735   const DeclTypeSpec *resultType{nullptr};
3736   // Look up name: provides return type or tells us if it's an array
3737   if (auto *symbol{FindSymbol(name)}) {
3738     Symbol &ultimate{symbol->GetUltimate()};
3739     if (ultimate.has<ObjectEntityDetails>() ||
3740         ultimate.has<AssocEntityDetails>() ||
3741         CouldBeDataPointerValuedFunction(&ultimate) ||
3742         (&symbol->owner() == &currScope() && IsFunctionResult(*symbol))) {
3743       misparsedStmtFuncFound_ = true;
3744       return false;
3745     }
3746     if (IsHostAssociated(*symbol, currScope())) {
3747       context().Warn(common::LanguageFeature::StatementFunctionExtensions,
3748           name.source,
3749           "Name '%s' from host scope should have a type declaration before its local statement function definition"_port_en_US,
3750           name.source);
3751       MakeSymbol(name, Attrs{}, UnknownDetails{});
3752     } else if (auto *entity{ultimate.detailsIf<EntityDetails>()};
3753                entity && !ultimate.has<ProcEntityDetails>()) {
3754       resultType = entity->type();
3755       ultimate.details() = UnknownDetails{}; // will be replaced below
3756     } else {
3757       misparsedStmtFuncFound_ = true;
3758     }
3759   }
3760   if (misparsedStmtFuncFound_) {
3761     Say(name,
3762         "'%s' has not been declared as an array or pointer-valued function"_err_en_US);
3763     return false;
3764   }
3765   auto &symbol{PushSubprogramScope(name, Symbol::Flag::Function)};
3766   symbol.set(Symbol::Flag::StmtFunction);
3767   EraseSymbol(symbol); // removes symbol added by PushSubprogramScope
3768   auto &details{symbol.get<SubprogramDetails>()};
3769   for (const auto &dummyName : std::get<std::list<parser::Name>>(x.t)) {
3770     ObjectEntityDetails dummyDetails{true};
3771     if (auto *dummySymbol{FindInScope(currScope().parent(), dummyName)}) {
3772       if (auto *d{dummySymbol->GetType()}) {
3773         dummyDetails.set_type(*d);
3774       }
3775     }
3776     Symbol &dummy{MakeSymbol(dummyName, std::move(dummyDetails))};
3777     ApplyImplicitRules(dummy);
3778     details.add_dummyArg(dummy);
3779   }
3780   ObjectEntityDetails resultDetails;
3781   if (resultType) {
3782     resultDetails.set_type(*resultType);
3783   }
3784   resultDetails.set_funcResult(true);
3785   Symbol &result{MakeSymbol(name, std::move(resultDetails))};
3786   result.flags().set(Symbol::Flag::StmtFunction);
3787   ApplyImplicitRules(result);
3788   details.set_result(result);
3789   // The analysis of the expression that constitutes the body of the
3790   // statement function is deferred to FinishSpecificationPart() so that
3791   // all declarations and implicit typing are complete.
3792   PopScope();
3793   return true;
3794 }
3795 
3796 bool SubprogramVisitor::Pre(const parser::Suffix &suffix) {
3797   if (suffix.resultName) {
3798     if (IsFunction(currScope())) {
3799       if (FuncResultStack::FuncInfo * info{funcResultStack().Top()}) {
3800         if (info->inFunctionStmt) {
3801           info->resultName = &suffix.resultName.value();
3802         } else {
3803           // will check the result name in Post(EntryStmt)
3804         }
3805       }
3806     } else {
3807       Message &msg{Say(*suffix.resultName,
3808           "RESULT(%s) may appear only in a function"_err_en_US)};
3809       if (const Symbol * subprogram{InclusiveScope().symbol()}) {
3810         msg.Attach(subprogram->name(), "Containing subprogram"_en_US);
3811       }
3812     }
3813   }
3814   // LanguageBindingSpec deferred to Post(EntryStmt) or, for FunctionStmt,
3815   // all the way to EndSubprogram().
3816   return false;
3817 }
3818 
3819 bool SubprogramVisitor::Pre(const parser::PrefixSpec &x) {
3820   // Save this to process after UseStmt and ImplicitPart
3821   if (const auto *parsedType{std::get_if<parser::DeclarationTypeSpec>(&x.u)}) {
3822     if (FuncResultStack::FuncInfo * info{funcResultStack().Top()}) {
3823       if (info->parsedType) { // C1543
3824         Say(currStmtSource().value_or(info->source),
3825             "FUNCTION prefix cannot specify the type more than once"_err_en_US);
3826       } else {
3827         info->parsedType = parsedType;
3828         if (auto at{currStmtSource()}) {
3829           info->source = *at;
3830         }
3831       }
3832     } else {
3833       Say(currStmtSource().value(),
3834           "SUBROUTINE prefix cannot specify a type"_err_en_US);
3835     }
3836     return false;
3837   } else {
3838     return true;
3839   }
3840 }
3841 
3842 bool SubprogramVisitor::Pre(const parser::PrefixSpec::Attributes &attrs) {
3843   if (auto *subp{currScope().symbol()
3844               ? currScope().symbol()->detailsIf<SubprogramDetails>()
3845               : nullptr}) {
3846     for (auto attr : attrs.v) {
3847       if (auto current{subp->cudaSubprogramAttrs()}) {
3848         if (attr == *current ||
3849             (*current == common::CUDASubprogramAttrs::HostDevice &&
3850                 (attr == common::CUDASubprogramAttrs::Host ||
3851                     attr == common::CUDASubprogramAttrs::Device))) {
3852           context().Warn(common::LanguageFeature::RedundantAttribute,
3853               currStmtSource().value(),
3854               "ATTRIBUTES(%s) appears more than once"_warn_en_US,
3855               common::EnumToString(attr));
3856         } else if ((attr == common::CUDASubprogramAttrs::Host ||
3857                        attr == common::CUDASubprogramAttrs::Device) &&
3858             (*current == common::CUDASubprogramAttrs::Host ||
3859                 *current == common::CUDASubprogramAttrs::Device ||
3860                 *current == common::CUDASubprogramAttrs::HostDevice)) {
3861           // HOST,DEVICE or DEVICE,HOST -> HostDevice
3862           subp->set_cudaSubprogramAttrs(
3863               common::CUDASubprogramAttrs::HostDevice);
3864         } else {
3865           Say(currStmtSource().value(),
3866               "ATTRIBUTES(%s) conflicts with earlier ATTRIBUTES(%s)"_err_en_US,
3867               common::EnumToString(attr), common::EnumToString(*current));
3868         }
3869       } else {
3870         subp->set_cudaSubprogramAttrs(attr);
3871       }
3872     }
3873     if (auto attrs{subp->cudaSubprogramAttrs()}) {
3874       if (*attrs == common::CUDASubprogramAttrs::Global ||
3875           *attrs == common::CUDASubprogramAttrs::Device) {
3876         const Scope &scope{currScope()};
3877         const Scope *mod{FindModuleContaining(scope)};
3878         if (mod && mod->GetName().value() == "cudadevice") {
3879           return false;
3880         }
3881         // Implicitly USE the cudadevice module by copying its symbols in the
3882         // current scope.
3883         const Scope &cudaDeviceScope{context().GetCUDADeviceScope()};
3884         for (auto sym : cudaDeviceScope.GetSymbols()) {
3885           if (!currScope().FindSymbol(sym->name())) {
3886             auto &localSymbol{MakeSymbol(
3887                 sym->name(), Attrs{}, UseDetails{sym->name(), *sym})};
3888             localSymbol.flags() = sym->flags();
3889           }
3890         }
3891       }
3892     }
3893   }
3894   return false;
3895 }
3896 
3897 void SubprogramVisitor::Post(const parser::PrefixSpec::Launch_Bounds &x) {
3898   std::vector<std::int64_t> bounds;
3899   bool ok{true};
3900   for (const auto &sicx : x.v) {
3901     if (auto value{evaluate::ToInt64(EvaluateExpr(sicx))}) {
3902       bounds.push_back(*value);
3903     } else {
3904       ok = false;
3905     }
3906   }
3907   if (!ok || bounds.size() < 2 || bounds.size() > 3) {
3908     Say(currStmtSource().value(),
3909         "Operands of LAUNCH_BOUNDS() must be 2 or 3 integer constants"_err_en_US);
3910   } else if (auto *subp{currScope().symbol()
3911                      ? currScope().symbol()->detailsIf<SubprogramDetails>()
3912                      : nullptr}) {
3913     if (subp->cudaLaunchBounds().empty()) {
3914       subp->set_cudaLaunchBounds(std::move(bounds));
3915     } else {
3916       Say(currStmtSource().value(),
3917           "LAUNCH_BOUNDS() may only appear once"_err_en_US);
3918     }
3919   }
3920 }
3921 
3922 void SubprogramVisitor::Post(const parser::PrefixSpec::Cluster_Dims &x) {
3923   std::vector<std::int64_t> dims;
3924   bool ok{true};
3925   for (const auto &sicx : x.v) {
3926     if (auto value{evaluate::ToInt64(EvaluateExpr(sicx))}) {
3927       dims.push_back(*value);
3928     } else {
3929       ok = false;
3930     }
3931   }
3932   if (!ok || dims.size() != 3) {
3933     Say(currStmtSource().value(),
3934         "Operands of CLUSTER_DIMS() must be three integer constants"_err_en_US);
3935   } else if (auto *subp{currScope().symbol()
3936                      ? currScope().symbol()->detailsIf<SubprogramDetails>()
3937                      : nullptr}) {
3938     if (subp->cudaClusterDims().empty()) {
3939       subp->set_cudaClusterDims(std::move(dims));
3940     } else {
3941       Say(currStmtSource().value(),
3942           "CLUSTER_DIMS() may only appear once"_err_en_US);
3943     }
3944   }
3945 }
3946 
3947 static bool HasModulePrefix(const std::list<parser::PrefixSpec> &prefixes) {
3948   for (const auto &prefix : prefixes) {
3949     if (std::holds_alternative<parser::PrefixSpec::Module>(prefix.u)) {
3950       return true;
3951     }
3952   }
3953   return false;
3954 }
3955 
3956 bool SubprogramVisitor::Pre(const parser::InterfaceBody::Subroutine &x) {
3957   const auto &stmtTuple{
3958       std::get<parser::Statement<parser::SubroutineStmt>>(x.t).statement.t};
3959   return BeginSubprogram(std::get<parser::Name>(stmtTuple),
3960       Symbol::Flag::Subroutine,
3961       HasModulePrefix(std::get<std::list<parser::PrefixSpec>>(stmtTuple)));
3962 }
3963 void SubprogramVisitor::Post(const parser::InterfaceBody::Subroutine &x) {
3964   const auto &stmt{std::get<parser::Statement<parser::SubroutineStmt>>(x.t)};
3965   EndSubprogram(stmt.source,
3966       &std::get<std::optional<parser::LanguageBindingSpec>>(stmt.statement.t));
3967 }
3968 bool SubprogramVisitor::Pre(const parser::InterfaceBody::Function &x) {
3969   const auto &stmtTuple{
3970       std::get<parser::Statement<parser::FunctionStmt>>(x.t).statement.t};
3971   return BeginSubprogram(std::get<parser::Name>(stmtTuple),
3972       Symbol::Flag::Function,
3973       HasModulePrefix(std::get<std::list<parser::PrefixSpec>>(stmtTuple)));
3974 }
3975 void SubprogramVisitor::Post(const parser::InterfaceBody::Function &x) {
3976   const auto &stmt{std::get<parser::Statement<parser::FunctionStmt>>(x.t)};
3977   const auto &maybeSuffix{
3978       std::get<std::optional<parser::Suffix>>(stmt.statement.t)};
3979   EndSubprogram(stmt.source, maybeSuffix ? &maybeSuffix->binding : nullptr);
3980 }
3981 
3982 bool SubprogramVisitor::Pre(const parser::SubroutineStmt &stmt) {
3983   BeginAttrs();
3984   Walk(std::get<std::list<parser::PrefixSpec>>(stmt.t));
3985   Walk(std::get<parser::Name>(stmt.t));
3986   Walk(std::get<std::list<parser::DummyArg>>(stmt.t));
3987   // Don't traverse the LanguageBindingSpec now; it's deferred to EndSubprogram.
3988   Symbol &symbol{PostSubprogramStmt()};
3989   SubprogramDetails &details{symbol.get<SubprogramDetails>()};
3990   for (const auto &dummyArg : std::get<std::list<parser::DummyArg>>(stmt.t)) {
3991     if (const auto *dummyName{std::get_if<parser::Name>(&dummyArg.u)}) {
3992       CreateDummyArgument(details, *dummyName);
3993     } else {
3994       details.add_alternateReturn();
3995     }
3996   }
3997   return false;
3998 }
3999 bool SubprogramVisitor::Pre(const parser::FunctionStmt &) {
4000   FuncResultStack::FuncInfo &info{DEREF(funcResultStack().Top())};
4001   CHECK(!info.inFunctionStmt);
4002   info.inFunctionStmt = true;
4003   if (auto at{currStmtSource()}) {
4004     info.source = *at;
4005   }
4006   return BeginAttrs();
4007 }
4008 bool SubprogramVisitor::Pre(const parser::EntryStmt &) { return BeginAttrs(); }
4009 
4010 void SubprogramVisitor::Post(const parser::FunctionStmt &stmt) {
4011   const auto &name{std::get<parser::Name>(stmt.t)};
4012   Symbol &symbol{PostSubprogramStmt()};
4013   SubprogramDetails &details{symbol.get<SubprogramDetails>()};
4014   for (const auto &dummyName : std::get<std::list<parser::Name>>(stmt.t)) {
4015     CreateDummyArgument(details, dummyName);
4016   }
4017   const parser::Name *funcResultName;
4018   FuncResultStack::FuncInfo &info{DEREF(funcResultStack().Top())};
4019   CHECK(info.inFunctionStmt);
4020   info.inFunctionStmt = false;
4021   bool distinctResultName{
4022       info.resultName && info.resultName->source != name.source};
4023   if (distinctResultName) {
4024     // Note that RESULT is ignored if it has the same name as the function.
4025     // The symbol created by PushScope() is retained as a place-holder
4026     // for error detection.
4027     funcResultName = info.resultName;
4028   } else {
4029     EraseSymbol(name); // was added by PushScope()
4030     funcResultName = &name;
4031   }
4032   if (details.isFunction()) {
4033     CHECK(context().HasError(currScope().symbol()));
4034   } else {
4035     // RESULT(x) can be the same explicitly-named RESULT(x) as an ENTRY
4036     // statement.
4037     Symbol *result{nullptr};
4038     if (distinctResultName) {
4039       if (auto iter{currScope().find(funcResultName->source)};
4040           iter != currScope().end()) {
4041         Symbol &entryResult{*iter->second};
4042         if (IsFunctionResult(entryResult)) {
4043           result = &entryResult;
4044         }
4045       }
4046     }
4047     if (result) {
4048       Resolve(*funcResultName, *result);
4049     } else {
4050       // add function result to function scope
4051       EntityDetails funcResultDetails;
4052       funcResultDetails.set_funcResult(true);
4053       result = &MakeSymbol(*funcResultName, std::move(funcResultDetails));
4054     }
4055     info.resultSymbol = result;
4056     details.set_result(*result);
4057   }
4058   // C1560.
4059   if (info.resultName && !distinctResultName) {
4060     context().Warn(common::UsageWarning::HomonymousResult,
4061         info.resultName->source,
4062         "The function name should not appear in RESULT; references to '%s' "
4063         "inside the function will be considered as references to the "
4064         "result only"_warn_en_US,
4065         name.source);
4066     // RESULT name was ignored above, the only side effect from doing so will be
4067     // the inability to make recursive calls. The related parser::Name is still
4068     // resolved to the created function result symbol because every parser::Name
4069     // should be resolved to avoid internal errors.
4070     Resolve(*info.resultName, info.resultSymbol);
4071   }
4072   name.symbol = &symbol; // must not be function result symbol
4073   // Clear the RESULT() name now in case an ENTRY statement in the implicit-part
4074   // has a RESULT() suffix.
4075   info.resultName = nullptr;
4076 }
4077 
4078 Symbol &SubprogramVisitor::PostSubprogramStmt() {
4079   Symbol &symbol{*currScope().symbol()};
4080   SetExplicitAttrs(symbol, EndAttrs());
4081   if (symbol.attrs().test(Attr::MODULE)) {
4082     symbol.attrs().set(Attr::EXTERNAL, false);
4083     symbol.implicitAttrs().set(Attr::EXTERNAL, false);
4084   }
4085   return symbol;
4086 }
4087 
4088 void SubprogramVisitor::Post(const parser::EntryStmt &stmt) {
4089   if (const auto &suffix{std::get<std::optional<parser::Suffix>>(stmt.t)}) {
4090     Walk(suffix->binding);
4091   }
4092   PostEntryStmt(stmt);
4093   EndAttrs();
4094 }
4095 
4096 void SubprogramVisitor::CreateDummyArgument(
4097     SubprogramDetails &details, const parser::Name &name) {
4098   Symbol *dummy{FindInScope(name)};
4099   if (dummy) {
4100     if (IsDummy(*dummy)) {
4101       if (dummy->test(Symbol::Flag::EntryDummyArgument)) {
4102         dummy->set(Symbol::Flag::EntryDummyArgument, false);
4103       } else {
4104         Say(name,
4105             "'%s' appears more than once as a dummy argument name in this subprogram"_err_en_US,
4106             name.source);
4107         return;
4108       }
4109     } else {
4110       SayWithDecl(name, *dummy,
4111           "'%s' may not appear as a dummy argument name in this subprogram"_err_en_US);
4112       return;
4113     }
4114   } else {
4115     dummy = &MakeSymbol(name, EntityDetails{true});
4116   }
4117   details.add_dummyArg(DEREF(dummy));
4118 }
4119 
4120 void SubprogramVisitor::CreateEntry(
4121     const parser::EntryStmt &stmt, Symbol &subprogram) {
4122   const auto &entryName{std::get<parser::Name>(stmt.t)};
4123   Scope &outer{currScope().parent()};
4124   Symbol::Flag subpFlag{subprogram.test(Symbol::Flag::Function)
4125           ? Symbol::Flag::Function
4126           : Symbol::Flag::Subroutine};
4127   Attrs attrs;
4128   const auto &suffix{std::get<std::optional<parser::Suffix>>(stmt.t)};
4129   bool hasGlobalBindingName{outer.IsGlobal() && suffix && suffix->binding &&
4130       std::get<std::optional<parser::ScalarDefaultCharConstantExpr>>(
4131           suffix->binding->t)
4132           .has_value()};
4133   if (!hasGlobalBindingName) {
4134     if (Symbol * extant{FindSymbol(outer, entryName)}) {
4135       if (!HandlePreviousCalls(entryName, *extant, subpFlag)) {
4136         if (outer.IsTopLevel()) {
4137           Say2(entryName,
4138               "'%s' is already defined as a global identifier"_err_en_US,
4139               *extant, "Previous definition of '%s'"_en_US);
4140         } else {
4141           SayAlreadyDeclared(entryName, *extant);
4142         }
4143         return;
4144       }
4145       attrs = extant->attrs();
4146     }
4147   }
4148   std::optional<SourceName> distinctResultName;
4149   if (suffix && suffix->resultName &&
4150       suffix->resultName->source != entryName.source) {
4151     distinctResultName = suffix->resultName->source;
4152   }
4153   if (outer.IsModule() && !attrs.test(Attr::PRIVATE)) {
4154     attrs.set(Attr::PUBLIC);
4155   }
4156   Symbol *entrySymbol{nullptr};
4157   if (hasGlobalBindingName) {
4158     // Hide the entry's symbol in a new anonymous global scope so
4159     // that its name doesn't clash with anything.
4160     Symbol &symbol{MakeSymbol(outer, context().GetTempName(outer), Attrs{})};
4161     symbol.set_details(MiscDetails{MiscDetails::Kind::ScopeName});
4162     Scope &hidden{outer.MakeScope(Scope::Kind::Global, &symbol)};
4163     entrySymbol = &MakeSymbol(hidden, entryName.source, attrs);
4164   } else {
4165     entrySymbol = FindInScope(outer, entryName.source);
4166     if (entrySymbol) {
4167       if (auto *generic{entrySymbol->detailsIf<GenericDetails>()}) {
4168         if (auto *specific{generic->specific()}) {
4169           // Forward reference to ENTRY from a generic interface
4170           entrySymbol = specific;
4171           CheckDuplicatedAttrs(entryName.source, *entrySymbol, attrs);
4172           SetExplicitAttrs(*entrySymbol, attrs);
4173         }
4174       }
4175     } else {
4176       entrySymbol = &MakeSymbol(outer, entryName.source, attrs);
4177     }
4178   }
4179   SubprogramDetails entryDetails;
4180   entryDetails.set_entryScope(currScope());
4181   entrySymbol->set(subpFlag);
4182   if (subpFlag == Symbol::Flag::Function) {
4183     Symbol *result{nullptr};
4184     EntityDetails resultDetails;
4185     resultDetails.set_funcResult(true);
4186     if (distinctResultName) {
4187       // An explicit RESULT() can also be an explicit RESULT()
4188       // of the function or another ENTRY.
4189       if (auto iter{currScope().find(suffix->resultName->source)};
4190           iter != currScope().end()) {
4191         result = &*iter->second;
4192       }
4193       if (!result) {
4194         result =
4195             &MakeSymbol(*distinctResultName, Attrs{}, std::move(resultDetails));
4196       } else if (!result->has<EntityDetails>()) {
4197         Say(*distinctResultName,
4198             "ENTRY cannot have RESULT(%s) that is not a variable"_err_en_US,
4199             *distinctResultName)
4200             .Attach(result->name(), "Existing declaration of '%s'"_en_US,
4201                 result->name());
4202         result = nullptr;
4203       }
4204       if (result) {
4205         Resolve(*suffix->resultName, *result);
4206       }
4207     } else {
4208       result = &MakeSymbol(entryName.source, Attrs{}, std::move(resultDetails));
4209     }
4210     if (result) {
4211       entryDetails.set_result(*result);
4212     }
4213   }
4214   if (subpFlag == Symbol::Flag::Subroutine || distinctResultName) {
4215     Symbol &assoc{MakeSymbol(entryName.source)};
4216     assoc.set_details(HostAssocDetails{*entrySymbol});
4217     assoc.set(Symbol::Flag::Subroutine);
4218   }
4219   Resolve(entryName, *entrySymbol);
4220   std::set<SourceName> dummies;
4221   for (const auto &dummyArg : std::get<std::list<parser::DummyArg>>(stmt.t)) {
4222     if (const auto *dummyName{std::get_if<parser::Name>(&dummyArg.u)}) {
4223       auto pair{dummies.insert(dummyName->source)};
4224       if (!pair.second) {
4225         Say(*dummyName,
4226             "'%s' appears more than once as a dummy argument name in this ENTRY statement"_err_en_US,
4227             dummyName->source);
4228         continue;
4229       }
4230       Symbol *dummy{FindInScope(*dummyName)};
4231       if (dummy) {
4232         if (!IsDummy(*dummy)) {
4233           evaluate::AttachDeclaration(
4234               Say(*dummyName,
4235                   "'%s' may not appear as a dummy argument name in this ENTRY statement"_err_en_US,
4236                   dummyName->source),
4237               *dummy);
4238           continue;
4239         }
4240       } else {
4241         dummy = &MakeSymbol(*dummyName, EntityDetails{true});
4242         dummy->set(Symbol::Flag::EntryDummyArgument);
4243       }
4244       entryDetails.add_dummyArg(DEREF(dummy));
4245     } else if (subpFlag == Symbol::Flag::Function) { // C1573
4246       Say(entryName,
4247           "ENTRY in a function may not have an alternate return dummy argument"_err_en_US);
4248       break;
4249     } else {
4250       entryDetails.add_alternateReturn();
4251     }
4252   }
4253   entrySymbol->set_details(std::move(entryDetails));
4254 }
4255 
4256 void SubprogramVisitor::PostEntryStmt(const parser::EntryStmt &stmt) {
4257   // The entry symbol should have already been created and resolved
4258   // in CreateEntry(), called by BeginSubprogram(), with one exception (below).
4259   const auto &name{std::get<parser::Name>(stmt.t)};
4260   Scope &inclusiveScope{InclusiveScope()};
4261   if (!name.symbol) {
4262     if (inclusiveScope.kind() != Scope::Kind::Subprogram) {
4263       Say(name.source,
4264           "ENTRY '%s' may appear only in a subroutine or function"_err_en_US,
4265           name.source);
4266     } else if (FindSeparateModuleSubprogramInterface(inclusiveScope.symbol())) {
4267       Say(name.source,
4268           "ENTRY '%s' may not appear in a separate module procedure"_err_en_US,
4269           name.source);
4270     } else {
4271       // C1571 - entry is nested, so was not put into the program tree; error
4272       // is emitted from MiscChecker in semantics.cpp.
4273     }
4274     return;
4275   }
4276   Symbol &entrySymbol{*name.symbol};
4277   if (context().HasError(entrySymbol)) {
4278     return;
4279   }
4280   if (!entrySymbol.has<SubprogramDetails>()) {
4281     SayAlreadyDeclared(name, entrySymbol);
4282     return;
4283   }
4284   SubprogramDetails &entryDetails{entrySymbol.get<SubprogramDetails>()};
4285   CHECK(entryDetails.entryScope() == &inclusiveScope);
4286   SetCUDADataAttr(name.source, entrySymbol, cudaDataAttr());
4287   entrySymbol.attrs() |= GetAttrs();
4288   SetBindNameOn(entrySymbol);
4289   for (const auto &dummyArg : std::get<std::list<parser::DummyArg>>(stmt.t)) {
4290     if (const auto *dummyName{std::get_if<parser::Name>(&dummyArg.u)}) {
4291       if (Symbol * dummy{FindInScope(*dummyName)}) {
4292         if (dummy->test(Symbol::Flag::EntryDummyArgument)) {
4293           const auto *subp{dummy->detailsIf<SubprogramDetails>()};
4294           if (subp && subp->isInterface()) { // ok
4295           } else if (!dummy->has<EntityDetails>() &&
4296               !dummy->has<ObjectEntityDetails>() &&
4297               !dummy->has<ProcEntityDetails>()) {
4298             SayWithDecl(*dummyName, *dummy,
4299                 "ENTRY dummy argument '%s' was previously declared as an item that may not be used as a dummy argument"_err_en_US);
4300           }
4301           dummy->set(Symbol::Flag::EntryDummyArgument, false);
4302         }
4303       }
4304     }
4305   }
4306 }
4307 
4308 Symbol *ScopeHandler::FindSeparateModuleProcedureInterface(
4309     const parser::Name &name) {
4310   auto *symbol{FindSymbol(name)};
4311   if (symbol && symbol->has<SubprogramNameDetails>()) {
4312     const Scope *parent{nullptr};
4313     if (currScope().IsSubmodule()) {
4314       parent = currScope().symbol()->get<ModuleDetails>().parent();
4315     }
4316     symbol = parent ? FindSymbol(*parent, name) : nullptr;
4317   }
4318   if (symbol) {
4319     if (auto *generic{symbol->detailsIf<GenericDetails>()}) {
4320       symbol = generic->specific();
4321     }
4322   }
4323   if (const Symbol * defnIface{FindSeparateModuleSubprogramInterface(symbol)}) {
4324     // Error recovery in case of multiple definitions
4325     symbol = const_cast<Symbol *>(defnIface);
4326   }
4327   if (!IsSeparateModuleProcedureInterface(symbol)) {
4328     Say(name, "'%s' was not declared a separate module procedure"_err_en_US);
4329     symbol = nullptr;
4330   }
4331   return symbol;
4332 }
4333 
4334 // A subprogram declared with MODULE PROCEDURE
4335 bool SubprogramVisitor::BeginMpSubprogram(const parser::Name &name) {
4336   Symbol *symbol{FindSeparateModuleProcedureInterface(name)};
4337   if (!symbol) {
4338     return false;
4339   }
4340   if (symbol->owner() == currScope() && symbol->scope()) {
4341     // This is a MODULE PROCEDURE whose interface appears in its host.
4342     // Convert the module procedure's interface into a subprogram.
4343     SetScope(DEREF(symbol->scope()));
4344     symbol->get<SubprogramDetails>().set_isInterface(false);
4345     name.symbol = symbol;
4346   } else {
4347     // Copy the interface into a new subprogram scope.
4348     EraseSymbol(name);
4349     Symbol &newSymbol{MakeSymbol(name, SubprogramDetails{})};
4350     PushScope(Scope::Kind::Subprogram, &newSymbol);
4351     auto &newSubprogram{newSymbol.get<SubprogramDetails>()};
4352     newSubprogram.set_moduleInterface(*symbol);
4353     auto &subprogram{symbol->get<SubprogramDetails>()};
4354     if (const auto *name{subprogram.bindName()}) {
4355       newSubprogram.set_bindName(std::string{*name});
4356     }
4357     newSymbol.attrs() |= symbol->attrs();
4358     newSymbol.set(symbol->test(Symbol::Flag::Subroutine)
4359             ? Symbol::Flag::Subroutine
4360             : Symbol::Flag::Function);
4361     MapSubprogramToNewSymbols(*symbol, newSymbol, currScope());
4362   }
4363   return true;
4364 }
4365 
4366 // A subprogram or interface declared with SUBROUTINE or FUNCTION
4367 bool SubprogramVisitor::BeginSubprogram(const parser::Name &name,
4368     Symbol::Flag subpFlag, bool hasModulePrefix,
4369     const parser::LanguageBindingSpec *bindingSpec,
4370     const ProgramTree::EntryStmtList *entryStmts) {
4371   bool isValid{true};
4372   if (hasModulePrefix && !currScope().IsModule() &&
4373       !currScope().IsSubmodule()) { // C1547
4374     Say(name,
4375         "'%s' is a MODULE procedure which must be declared within a "
4376         "MODULE or SUBMODULE"_err_en_US);
4377     // Don't return here because it can be useful to have the scope set for
4378     // other semantic checks run before we print the errors
4379     isValid = false;
4380   }
4381   Symbol *moduleInterface{nullptr};
4382   if (isValid && hasModulePrefix && !inInterfaceBlock()) {
4383     moduleInterface = FindSeparateModuleProcedureInterface(name);
4384     if (moduleInterface && &moduleInterface->owner() == &currScope()) {
4385       // Subprogram is MODULE FUNCTION or MODULE SUBROUTINE with an interface
4386       // previously defined in the same scope.
4387       if (GenericDetails *
4388           generic{DEREF(FindSymbol(name)).detailsIf<GenericDetails>()}) {
4389         generic->clear_specific();
4390         name.symbol = nullptr;
4391       } else {
4392         EraseSymbol(name);
4393       }
4394     }
4395   }
4396   Symbol &newSymbol{
4397       PushSubprogramScope(name, subpFlag, bindingSpec, hasModulePrefix)};
4398   if (moduleInterface) {
4399     newSymbol.get<SubprogramDetails>().set_moduleInterface(*moduleInterface);
4400     if (moduleInterface->attrs().test(Attr::PRIVATE)) {
4401       SetImplicitAttr(newSymbol, Attr::PRIVATE);
4402     } else if (moduleInterface->attrs().test(Attr::PUBLIC)) {
4403       SetImplicitAttr(newSymbol, Attr::PUBLIC);
4404     }
4405   }
4406   if (entryStmts) {
4407     for (const auto &ref : *entryStmts) {
4408       CreateEntry(*ref, newSymbol);
4409     }
4410   }
4411   return true;
4412 }
4413 
4414 void SubprogramVisitor::HandleLanguageBinding(Symbol *symbol,
4415     std::optional<parser::CharBlock> stmtSource,
4416     const std::optional<parser::LanguageBindingSpec> *binding) {
4417   if (binding && *binding && symbol) {
4418     // Finally process the BIND(C,NAME=name) now that symbols in the name
4419     // expression will resolve to local names if needed.
4420     auto flagRestorer{common::ScopedSet(inSpecificationPart_, false)};
4421     auto originalStmtSource{messageHandler().currStmtSource()};
4422     messageHandler().set_currStmtSource(stmtSource);
4423     BeginAttrs();
4424     Walk(**binding);
4425     SetBindNameOn(*symbol);
4426     symbol->attrs() |= EndAttrs();
4427     messageHandler().set_currStmtSource(originalStmtSource);
4428   }
4429 }
4430 
4431 void SubprogramVisitor::EndSubprogram(
4432     std::optional<parser::CharBlock> stmtSource,
4433     const std::optional<parser::LanguageBindingSpec> *binding,
4434     const ProgramTree::EntryStmtList *entryStmts) {
4435   HandleLanguageBinding(currScope().symbol(), stmtSource, binding);
4436   if (entryStmts) {
4437     for (const auto &ref : *entryStmts) {
4438       const parser::EntryStmt &entryStmt{*ref};
4439       if (const auto &suffix{
4440               std::get<std::optional<parser::Suffix>>(entryStmt.t)}) {
4441         const auto &name{std::get<parser::Name>(entryStmt.t)};
4442         HandleLanguageBinding(name.symbol, name.source, &suffix->binding);
4443       }
4444     }
4445   }
4446   if (inInterfaceBlock() && currScope().symbol()) {
4447     DeclaredPossibleSpecificProc(*currScope().symbol());
4448   }
4449   PopScope();
4450 }
4451 
4452 bool SubprogramVisitor::HandlePreviousCalls(
4453     const parser::Name &name, Symbol &symbol, Symbol::Flag subpFlag) {
4454   // If the extant symbol is a generic, check its homonymous specific
4455   // procedure instead if it has one.
4456   if (auto *generic{symbol.detailsIf<GenericDetails>()}) {
4457     return generic->specific() &&
4458         HandlePreviousCalls(name, *generic->specific(), subpFlag);
4459   } else if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}; proc &&
4460              !proc->isDummy() &&
4461              !symbol.attrs().HasAny(Attrs{Attr::INTRINSIC, Attr::POINTER})) {
4462     // There's a symbol created for previous calls to this subprogram or
4463     // ENTRY's name.  We have to replace that symbol in situ to avoid the
4464     // obligation to rewrite symbol pointers in the parse tree.
4465     if (!symbol.test(subpFlag)) {
4466       auto other{subpFlag == Symbol::Flag::Subroutine
4467               ? Symbol::Flag::Function
4468               : Symbol::Flag::Subroutine};
4469       // External statements issue an explicit EXTERNAL attribute.
4470       if (symbol.attrs().test(Attr::EXTERNAL) &&
4471           !symbol.implicitAttrs().test(Attr::EXTERNAL)) {
4472         // Warn if external statement previously declared.
4473         context().Warn(common::LanguageFeature::RedundantAttribute, name.source,
4474             "EXTERNAL attribute was already specified on '%s'"_warn_en_US,
4475             name.source);
4476       } else if (symbol.test(other)) {
4477         Say2(name,
4478             subpFlag == Symbol::Flag::Function
4479                 ? "'%s' was previously called as a subroutine"_err_en_US
4480                 : "'%s' was previously called as a function"_err_en_US,
4481             symbol, "Previous call of '%s'"_en_US);
4482       } else {
4483         symbol.set(subpFlag);
4484       }
4485     }
4486     EntityDetails entity;
4487     if (proc->type()) {
4488       entity.set_type(*proc->type());
4489     }
4490     symbol.details() = std::move(entity);
4491     return true;
4492   } else {
4493     return symbol.has<UnknownDetails>() || symbol.has<SubprogramNameDetails>();
4494   }
4495 }
4496 
4497 void SubprogramVisitor::CheckExtantProc(
4498     const parser::Name &name, Symbol::Flag subpFlag) {
4499   if (auto *prev{FindSymbol(name)}) {
4500     if (IsDummy(*prev)) {
4501     } else if (auto *entity{prev->detailsIf<EntityDetails>()};
4502                IsPointer(*prev) && entity && !entity->type()) {
4503       // POINTER attribute set before interface
4504     } else if (inInterfaceBlock() && currScope() != prev->owner()) {
4505       // Procedures in an INTERFACE block do not resolve to symbols
4506       // in scopes between the global scope and the current scope.
4507     } else if (!HandlePreviousCalls(name, *prev, subpFlag)) {
4508       SayAlreadyDeclared(name, *prev);
4509     }
4510   }
4511 }
4512 
4513 Symbol &SubprogramVisitor::PushSubprogramScope(const parser::Name &name,
4514     Symbol::Flag subpFlag, const parser::LanguageBindingSpec *bindingSpec,
4515     bool hasModulePrefix) {
4516   Symbol *symbol{GetSpecificFromGeneric(name)};
4517   if (!symbol) {
4518     if (bindingSpec && currScope().IsGlobal() &&
4519         std::get<std::optional<parser::ScalarDefaultCharConstantExpr>>(
4520             bindingSpec->t)
4521             .has_value()) {
4522       // Create this new top-level subprogram with a binding label
4523       // in a new global scope, so that its symbol's name won't clash
4524       // with another symbol that has a distinct binding label.
4525       PushScope(Scope::Kind::Global,
4526           &MakeSymbol(context().GetTempName(currScope()), Attrs{},
4527               MiscDetails{MiscDetails::Kind::ScopeName}));
4528     }
4529     CheckExtantProc(name, subpFlag);
4530     symbol = &MakeSymbol(name, SubprogramDetails{});
4531   }
4532   symbol->ReplaceName(name.source);
4533   symbol->set(subpFlag);
4534   PushScope(Scope::Kind::Subprogram, symbol);
4535   if (subpFlag == Symbol::Flag::Function) {
4536     funcResultStack().Push(currScope(), name.source);
4537   }
4538   if (inInterfaceBlock()) {
4539     auto &details{symbol->get<SubprogramDetails>()};
4540     details.set_isInterface();
4541     if (isAbstract()) {
4542       SetExplicitAttr(*symbol, Attr::ABSTRACT);
4543     } else if (hasModulePrefix) {
4544       SetExplicitAttr(*symbol, Attr::MODULE);
4545     } else {
4546       MakeExternal(*symbol);
4547     }
4548     if (isGeneric()) {
4549       Symbol &genericSymbol{GetGenericSymbol()};
4550       if (auto *details{genericSymbol.detailsIf<GenericDetails>()}) {
4551         details->AddSpecificProc(*symbol, name.source);
4552       } else {
4553         CHECK(context().HasError(genericSymbol));
4554       }
4555     }
4556     set_inheritFromParent(false); // interfaces don't inherit, even if MODULE
4557   }
4558   if (Symbol * found{FindSymbol(name)};
4559       found && found->has<HostAssocDetails>()) {
4560     found->set(subpFlag); // PushScope() created symbol
4561   }
4562   return *symbol;
4563 }
4564 
4565 void SubprogramVisitor::PushBlockDataScope(const parser::Name &name) {
4566   if (auto *prev{FindSymbol(name)}) {
4567     if (prev->attrs().test(Attr::EXTERNAL) && prev->has<ProcEntityDetails>()) {
4568       if (prev->test(Symbol::Flag::Subroutine) ||
4569           prev->test(Symbol::Flag::Function)) {
4570         Say2(name, "BLOCK DATA '%s' has been called"_err_en_US, *prev,
4571             "Previous call of '%s'"_en_US);
4572       }
4573       EraseSymbol(name);
4574     }
4575   }
4576   if (name.source.empty()) {
4577     // Don't let unnamed BLOCK DATA conflict with unnamed PROGRAM
4578     PushScope(Scope::Kind::BlockData, nullptr);
4579   } else {
4580     PushScope(Scope::Kind::BlockData, &MakeSymbol(name, SubprogramDetails{}));
4581   }
4582 }
4583 
4584 // If name is a generic, return specific subprogram with the same name.
4585 Symbol *SubprogramVisitor::GetSpecificFromGeneric(const parser::Name &name) {
4586   // Search for the name but don't resolve it
4587   if (auto *symbol{currScope().FindSymbol(name.source)}) {
4588     if (symbol->has<SubprogramNameDetails>()) {
4589       if (inInterfaceBlock()) {
4590         // Subtle: clear any MODULE flag so that the new interface
4591         // symbol doesn't inherit it and ruin the ability to check it.
4592         symbol->attrs().reset(Attr::MODULE);
4593       }
4594     } else if (auto *details{symbol->detailsIf<GenericDetails>()}) {
4595       // found generic, want specific procedure
4596       auto *specific{details->specific()};
4597       Attrs moduleAttr;
4598       if (inInterfaceBlock()) {
4599         if (specific) {
4600           // Defining an interface in a generic of the same name which is
4601           // already shadowing another procedure.  In some cases, the shadowed
4602           // procedure is about to be replaced.
4603           if (specific->has<SubprogramNameDetails>() &&
4604               specific->attrs().test(Attr::MODULE)) {
4605             // The shadowed procedure is a separate module procedure that is
4606             // actually defined later in this (sub)module.
4607             // Define its interface now as a new symbol.
4608             moduleAttr.set(Attr::MODULE);
4609             specific = nullptr;
4610           } else if (&specific->owner() != &symbol->owner()) {
4611             // The shadowed procedure was from an enclosing scope and will be
4612             // overridden by this interface definition.
4613             specific = nullptr;
4614           }
4615           if (!specific) {
4616             details->clear_specific();
4617           }
4618         } else if (const auto *dType{details->derivedType()}) {
4619           if (&dType->owner() != &symbol->owner()) {
4620             // The shadowed derived type was from an enclosing scope and
4621             // will be overridden by this interface definition.
4622             details->clear_derivedType();
4623           }
4624         }
4625       }
4626       if (!specific) {
4627         specific = &currScope().MakeSymbol(
4628             name.source, std::move(moduleAttr), SubprogramDetails{});
4629         if (details->derivedType()) {
4630           // A specific procedure with the same name as a derived type
4631           SayAlreadyDeclared(name, *details->derivedType());
4632         } else {
4633           details->set_specific(Resolve(name, *specific));
4634         }
4635       } else if (isGeneric()) {
4636         SayAlreadyDeclared(name, *specific);
4637       }
4638       if (specific->has<SubprogramNameDetails>()) {
4639         specific->set_details(Details{SubprogramDetails{}});
4640       }
4641       return specific;
4642     }
4643   }
4644   return nullptr;
4645 }
4646 
4647 // DeclarationVisitor implementation
4648 
4649 bool DeclarationVisitor::BeginDecl() {
4650   BeginDeclTypeSpec();
4651   BeginArraySpec();
4652   return BeginAttrs();
4653 }
4654 void DeclarationVisitor::EndDecl() {
4655   EndDeclTypeSpec();
4656   EndArraySpec();
4657   EndAttrs();
4658 }
4659 
4660 bool DeclarationVisitor::CheckUseError(const parser::Name &name) {
4661   return HadUseError(context(), name.source, name.symbol);
4662 }
4663 
4664 // Report error if accessibility of symbol doesn't match isPrivate.
4665 void DeclarationVisitor::CheckAccessibility(
4666     const SourceName &name, bool isPrivate, Symbol &symbol) {
4667   if (symbol.attrs().test(Attr::PRIVATE) != isPrivate) {
4668     Say2(name,
4669         "'%s' does not have the same accessibility as its previous declaration"_err_en_US,
4670         symbol, "Previous declaration of '%s'"_en_US);
4671   }
4672 }
4673 
4674 bool DeclarationVisitor::Pre(const parser::TypeDeclarationStmt &x) {
4675   BeginDecl();
4676   // If INTRINSIC appears as an attr-spec, handle it now as if the
4677   // names had appeared on an INTRINSIC attribute statement beforehand.
4678   for (const auto &attr : std::get<std::list<parser::AttrSpec>>(x.t)) {
4679     if (std::holds_alternative<parser::Intrinsic>(attr.u)) {
4680       for (const auto &decl : std::get<std::list<parser::EntityDecl>>(x.t)) {
4681         DeclareIntrinsic(parser::GetFirstName(decl));
4682       }
4683       break;
4684     }
4685   }
4686   return true;
4687 }
4688 void DeclarationVisitor::Post(const parser::TypeDeclarationStmt &) {
4689   EndDecl();
4690 }
4691 
4692 void DeclarationVisitor::Post(const parser::DimensionStmt::Declaration &x) {
4693   DeclareObjectEntity(std::get<parser::Name>(x.t));
4694 }
4695 void DeclarationVisitor::Post(const parser::CodimensionDecl &x) {
4696   DeclareObjectEntity(std::get<parser::Name>(x.t));
4697 }
4698 
4699 bool DeclarationVisitor::Pre(const parser::Initialization &) {
4700   // Defer inspection of initializers to Initialization() so that the
4701   // symbol being initialized will be available within the initialization
4702   // expression.
4703   return false;
4704 }
4705 
4706 void DeclarationVisitor::Post(const parser::EntityDecl &x) {
4707   const auto &name{std::get<parser::ObjectName>(x.t)};
4708   Attrs attrs{attrs_ ? HandleSaveName(name.source, *attrs_) : Attrs{}};
4709   attrs.set(Attr::INTRINSIC, false); // dealt with in Pre(TypeDeclarationStmt)
4710   Symbol &symbol{DeclareUnknownEntity(name, attrs)};
4711   symbol.ReplaceName(name.source);
4712   SetCUDADataAttr(name.source, symbol, cudaDataAttr());
4713   if (const auto &init{std::get<std::optional<parser::Initialization>>(x.t)}) {
4714     ConvertToObjectEntity(symbol) || ConvertToProcEntity(symbol);
4715     symbol.set(
4716         Symbol::Flag::EntryDummyArgument, false); // forestall excessive errors
4717     Initialization(name, *init, false);
4718   } else if (attrs.test(Attr::PARAMETER)) { // C882, C883
4719     Say(name, "Missing initialization for parameter '%s'"_err_en_US);
4720   }
4721   if (auto *scopeSymbol{currScope().symbol()})
4722     if (auto *details{scopeSymbol->detailsIf<DerivedTypeDetails>()})
4723       if (details->isDECStructure())
4724         details->add_component(symbol);
4725 }
4726 
4727 void DeclarationVisitor::Post(const parser::PointerDecl &x) {
4728   const auto &name{std::get<parser::Name>(x.t)};
4729   if (const auto &deferredShapeSpecs{
4730           std::get<std::optional<parser::DeferredShapeSpecList>>(x.t)}) {
4731     CHECK(arraySpec().empty());
4732     BeginArraySpec();
4733     set_arraySpec(AnalyzeDeferredShapeSpecList(context(), *deferredShapeSpecs));
4734     Symbol &symbol{DeclareObjectEntity(name, Attrs{Attr::POINTER})};
4735     symbol.ReplaceName(name.source);
4736     EndArraySpec();
4737   } else {
4738     if (const auto *symbol{FindInScope(name)}) {
4739       const auto *subp{symbol->detailsIf<SubprogramDetails>()};
4740       if (!symbol->has<UseDetails>() && // error caught elsewhere
4741           !symbol->has<ObjectEntityDetails>() &&
4742           !symbol->has<ProcEntityDetails>() &&
4743           !symbol->CanReplaceDetails(ObjectEntityDetails{}) &&
4744           !symbol->CanReplaceDetails(ProcEntityDetails{}) &&
4745           !(subp && subp->isInterface())) {
4746         Say(name, "'%s' cannot have the POINTER attribute"_err_en_US);
4747       }
4748     }
4749     HandleAttributeStmt(Attr::POINTER, std::get<parser::Name>(x.t));
4750   }
4751 }
4752 
4753 bool DeclarationVisitor::Pre(const parser::BindEntity &x) {
4754   auto kind{std::get<parser::BindEntity::Kind>(x.t)};
4755   auto &name{std::get<parser::Name>(x.t)};
4756   Symbol *symbol;
4757   if (kind == parser::BindEntity::Kind::Object) {
4758     symbol = &HandleAttributeStmt(Attr::BIND_C, name);
4759   } else {
4760     symbol = &MakeCommonBlockSymbol(name);
4761     SetExplicitAttr(*symbol, Attr::BIND_C);
4762   }
4763   // 8.6.4(1)
4764   // Some entities such as named constant or module name need to checked
4765   // elsewhere. This is to skip the ICE caused by setting Bind name for non-name
4766   // things such as data type and also checks for procedures.
4767   if (symbol->has<CommonBlockDetails>() || symbol->has<ObjectEntityDetails>() ||
4768       symbol->has<EntityDetails>()) {
4769     SetBindNameOn(*symbol);
4770   } else {
4771     Say(name,
4772         "Only variable and named common block can be in BIND statement"_err_en_US);
4773   }
4774   return false;
4775 }
4776 bool DeclarationVisitor::Pre(const parser::OldParameterStmt &x) {
4777   inOldStyleParameterStmt_ = true;
4778   Walk(x.v);
4779   inOldStyleParameterStmt_ = false;
4780   return false;
4781 }
4782 bool DeclarationVisitor::Pre(const parser::NamedConstantDef &x) {
4783   auto &name{std::get<parser::NamedConstant>(x.t).v};
4784   auto &symbol{HandleAttributeStmt(Attr::PARAMETER, name)};
4785   ConvertToObjectEntity(symbol);
4786   auto *details{symbol.detailsIf<ObjectEntityDetails>()};
4787   if (!details || symbol.test(Symbol::Flag::CrayPointer) ||
4788       symbol.test(Symbol::Flag::CrayPointee)) {
4789     SayWithDecl(
4790         name, symbol, "PARAMETER attribute not allowed on '%s'"_err_en_US);
4791     return false;
4792   }
4793   const auto &expr{std::get<parser::ConstantExpr>(x.t)};
4794   if (details->init() || symbol.test(Symbol::Flag::InDataStmt)) {
4795     Say(name, "Named constant '%s' already has a value"_err_en_US);
4796   }
4797   if (inOldStyleParameterStmt_) {
4798     // non-standard extension PARAMETER statement (no parentheses)
4799     Walk(expr);
4800     auto folded{EvaluateExpr(expr)};
4801     if (details->type()) {
4802       SayWithDecl(name, symbol,
4803           "Alternative style PARAMETER '%s' must not already have an explicit type"_err_en_US);
4804     } else if (folded) {
4805       auto at{expr.thing.value().source};
4806       if (evaluate::IsActuallyConstant(*folded)) {
4807         if (const auto *type{currScope().GetType(*folded)}) {
4808           if (type->IsPolymorphic()) {
4809             Say(at, "The expression must not be polymorphic"_err_en_US);
4810           } else if (auto shape{ToArraySpec(
4811                          GetFoldingContext(), evaluate::GetShape(*folded))}) {
4812             // The type of the named constant is assumed from the expression.
4813             details->set_type(*type);
4814             details->set_init(std::move(*folded));
4815             details->set_shape(std::move(*shape));
4816           } else {
4817             Say(at, "The expression must have constant shape"_err_en_US);
4818           }
4819         } else {
4820           Say(at, "The expression must have a known type"_err_en_US);
4821         }
4822       } else {
4823         Say(at, "The expression must be a constant of known type"_err_en_US);
4824       }
4825     }
4826   } else {
4827     // standard-conforming PARAMETER statement (with parentheses)
4828     ApplyImplicitRules(symbol);
4829     Walk(expr);
4830     if (auto converted{EvaluateNonPointerInitializer(
4831             symbol, expr, expr.thing.value().source)}) {
4832       details->set_init(std::move(*converted));
4833     }
4834   }
4835   return false;
4836 }
4837 bool DeclarationVisitor::Pre(const parser::NamedConstant &x) {
4838   const parser::Name &name{x.v};
4839   if (!FindSymbol(name)) {
4840     Say(name, "Named constant '%s' not found"_err_en_US);
4841   } else {
4842     CheckUseError(name);
4843   }
4844   return false;
4845 }
4846 
4847 bool DeclarationVisitor::Pre(const parser::Enumerator &enumerator) {
4848   const parser::Name &name{std::get<parser::NamedConstant>(enumerator.t).v};
4849   Symbol *symbol{FindInScope(name)};
4850   if (symbol && !symbol->has<UnknownDetails>()) {
4851     // Contrary to named constants appearing in a PARAMETER statement,
4852     // enumerator names should not have their type, dimension or any other
4853     // attributes defined before they are declared in the enumerator statement,
4854     // with the exception of accessibility.
4855     // This is not explicitly forbidden by the standard, but they are scalars
4856     // which type is left for the compiler to chose, so do not let users try to
4857     // tamper with that.
4858     SayAlreadyDeclared(name, *symbol);
4859     symbol = nullptr;
4860   } else {
4861     // Enumerators are treated as PARAMETER (section 7.6 paragraph (4))
4862     symbol = &MakeSymbol(name, Attrs{Attr::PARAMETER}, ObjectEntityDetails{});
4863     symbol->SetType(context().MakeNumericType(
4864         TypeCategory::Integer, evaluate::CInteger::kind));
4865   }
4866 
4867   if (auto &init{std::get<std::optional<parser::ScalarIntConstantExpr>>(
4868           enumerator.t)}) {
4869     Walk(*init); // Resolve names in expression before evaluation.
4870     if (auto value{EvaluateInt64(context(), *init)}) {
4871       // Cast all init expressions to C_INT so that they can then be
4872       // safely incremented (see 7.6 Note 2).
4873       enumerationState_.value = static_cast<int>(*value);
4874     } else {
4875       Say(name,
4876           "Enumerator value could not be computed "
4877           "from the given expression"_err_en_US);
4878       // Prevent resolution of next enumerators value
4879       enumerationState_.value = std::nullopt;
4880     }
4881   }
4882 
4883   if (symbol) {
4884     if (enumerationState_.value) {
4885       symbol->get<ObjectEntityDetails>().set_init(SomeExpr{
4886           evaluate::Expr<evaluate::CInteger>{*enumerationState_.value}});
4887     } else {
4888       context().SetError(*symbol);
4889     }
4890   }
4891 
4892   if (enumerationState_.value) {
4893     (*enumerationState_.value)++;
4894   }
4895   return false;
4896 }
4897 
4898 void DeclarationVisitor::Post(const parser::EnumDef &) {
4899   enumerationState_ = EnumeratorState{};
4900 }
4901 
4902 bool DeclarationVisitor::Pre(const parser::AccessSpec &x) {
4903   Attr attr{AccessSpecToAttr(x)};
4904   if (!NonDerivedTypeScope().IsModule()) { // C817
4905     Say(currStmtSource().value(),
4906         "%s attribute may only appear in the specification part of a module"_err_en_US,
4907         EnumToString(attr));
4908   }
4909   CheckAndSet(attr);
4910   return false;
4911 }
4912 
4913 bool DeclarationVisitor::Pre(const parser::AsynchronousStmt &x) {
4914   return HandleAttributeStmt(Attr::ASYNCHRONOUS, x.v);
4915 }
4916 bool DeclarationVisitor::Pre(const parser::ContiguousStmt &x) {
4917   return HandleAttributeStmt(Attr::CONTIGUOUS, x.v);
4918 }
4919 bool DeclarationVisitor::Pre(const parser::ExternalStmt &x) {
4920   HandleAttributeStmt(Attr::EXTERNAL, x.v);
4921   for (const auto &name : x.v) {
4922     auto *symbol{FindSymbol(name)};
4923     if (!ConvertToProcEntity(DEREF(symbol), name.source)) {
4924       // Check if previous symbol is an interface.
4925       if (auto *details{symbol->detailsIf<SubprogramDetails>()}) {
4926         if (details->isInterface()) {
4927           // Warn if interface previously declared.
4928           context().Warn(common::LanguageFeature::RedundantAttribute,
4929               name.source,
4930               "EXTERNAL attribute was already specified on '%s'"_warn_en_US,
4931               name.source);
4932         }
4933       } else {
4934         SayWithDecl(
4935             name, *symbol, "EXTERNAL attribute not allowed on '%s'"_err_en_US);
4936       }
4937     } else if (symbol->attrs().test(Attr::INTRINSIC)) { // C840
4938       Say(symbol->name(),
4939           "Symbol '%s' cannot have both INTRINSIC and EXTERNAL attributes"_err_en_US,
4940           symbol->name());
4941     }
4942   }
4943   return false;
4944 }
4945 bool DeclarationVisitor::Pre(const parser::IntentStmt &x) {
4946   auto &intentSpec{std::get<parser::IntentSpec>(x.t)};
4947   auto &names{std::get<std::list<parser::Name>>(x.t)};
4948   return CheckNotInBlock("INTENT") && // C1107
4949       HandleAttributeStmt(IntentSpecToAttr(intentSpec), names);
4950 }
4951 bool DeclarationVisitor::Pre(const parser::IntrinsicStmt &x) {
4952   for (const auto &name : x.v) {
4953     DeclareIntrinsic(name);
4954   }
4955   return false;
4956 }
4957 void DeclarationVisitor::DeclareIntrinsic(const parser::Name &name) {
4958   HandleAttributeStmt(Attr::INTRINSIC, name);
4959   if (!IsIntrinsic(name.source, std::nullopt)) {
4960     Say(name.source, "'%s' is not a known intrinsic procedure"_err_en_US);
4961   }
4962   auto &symbol{DEREF(FindSymbol(name))};
4963   if (symbol.has<GenericDetails>()) {
4964     // Generic interface is extending intrinsic; ok
4965   } else if (!ConvertToProcEntity(symbol, name.source)) {
4966     SayWithDecl(
4967         name, symbol, "INTRINSIC attribute not allowed on '%s'"_err_en_US);
4968   } else if (symbol.attrs().test(Attr::EXTERNAL)) { // C840
4969     Say(symbol.name(),
4970         "Symbol '%s' cannot have both EXTERNAL and INTRINSIC attributes"_err_en_US,
4971         symbol.name());
4972   } else {
4973     if (symbol.GetType()) {
4974       // These warnings are worded so that they should make sense in either
4975       // order.
4976       if (auto *msg{context().Warn(
4977               common::UsageWarning::IgnoredIntrinsicFunctionType, symbol.name(),
4978               "Explicit type declaration ignored for intrinsic function '%s'"_warn_en_US,
4979               symbol.name())}) {
4980         msg->Attach(name.source,
4981             "INTRINSIC statement for explicitly-typed '%s'"_en_US, name.source);
4982       }
4983     }
4984     if (!symbol.test(Symbol::Flag::Function) &&
4985         !symbol.test(Symbol::Flag::Subroutine)) {
4986       if (context().intrinsics().IsIntrinsicFunction(name.source.ToString())) {
4987         symbol.set(Symbol::Flag::Function);
4988       } else if (context().intrinsics().IsIntrinsicSubroutine(
4989                      name.source.ToString())) {
4990         symbol.set(Symbol::Flag::Subroutine);
4991       }
4992     }
4993   }
4994 }
4995 bool DeclarationVisitor::Pre(const parser::OptionalStmt &x) {
4996   return CheckNotInBlock("OPTIONAL") && // C1107
4997       HandleAttributeStmt(Attr::OPTIONAL, x.v);
4998 }
4999 bool DeclarationVisitor::Pre(const parser::ProtectedStmt &x) {
5000   return HandleAttributeStmt(Attr::PROTECTED, x.v);
5001 }
5002 bool DeclarationVisitor::Pre(const parser::ValueStmt &x) {
5003   return CheckNotInBlock("VALUE") && // C1107
5004       HandleAttributeStmt(Attr::VALUE, x.v);
5005 }
5006 bool DeclarationVisitor::Pre(const parser::VolatileStmt &x) {
5007   return HandleAttributeStmt(Attr::VOLATILE, x.v);
5008 }
5009 bool DeclarationVisitor::Pre(const parser::CUDAAttributesStmt &x) {
5010   auto attr{std::get<common::CUDADataAttr>(x.t)};
5011   for (const auto &name : std::get<std::list<parser::Name>>(x.t)) {
5012     auto *symbol{FindInScope(name)};
5013     if (symbol && symbol->has<UseDetails>()) {
5014       Say(currStmtSource().value(),
5015           "Cannot apply CUDA data attribute to use-associated '%s'"_err_en_US,
5016           name.source);
5017     } else {
5018       if (!symbol) {
5019         symbol = &MakeSymbol(name, ObjectEntityDetails{});
5020       }
5021       SetCUDADataAttr(name.source, *symbol, attr);
5022     }
5023   }
5024   return false;
5025 }
5026 // Handle a statement that sets an attribute on a list of names.
5027 bool DeclarationVisitor::HandleAttributeStmt(
5028     Attr attr, const std::list<parser::Name> &names) {
5029   for (const auto &name : names) {
5030     HandleAttributeStmt(attr, name);
5031   }
5032   return false;
5033 }
5034 Symbol &DeclarationVisitor::HandleAttributeStmt(
5035     Attr attr, const parser::Name &name) {
5036   auto *symbol{FindInScope(name)};
5037   if (attr == Attr::ASYNCHRONOUS || attr == Attr::VOLATILE) {
5038     // these can be set on a symbol that is host-assoc or use-assoc
5039     if (!symbol &&
5040         (currScope().kind() == Scope::Kind::Subprogram ||
5041             currScope().kind() == Scope::Kind::BlockConstruct)) {
5042       if (auto *hostSymbol{FindSymbol(name)}) {
5043         symbol = &MakeHostAssocSymbol(name, *hostSymbol);
5044       }
5045     }
5046   } else if (symbol && symbol->has<UseDetails>()) {
5047     if (symbol->GetUltimate().attrs().test(attr)) {
5048       context().Warn(common::LanguageFeature::RedundantAttribute,
5049           currStmtSource().value(),
5050           "Use-associated '%s' already has '%s' attribute"_warn_en_US,
5051           name.source, EnumToString(attr));
5052     } else {
5053       Say(currStmtSource().value(),
5054           "Cannot change %s attribute on use-associated '%s'"_err_en_US,
5055           EnumToString(attr), name.source);
5056     }
5057     return *symbol;
5058   }
5059   if (!symbol) {
5060     symbol = &MakeSymbol(name, EntityDetails{});
5061   }
5062   if (CheckDuplicatedAttr(name.source, *symbol, attr)) {
5063     HandleSaveName(name.source, Attrs{attr});
5064     SetExplicitAttr(*symbol, attr);
5065   }
5066   return *symbol;
5067 }
5068 // C1107
5069 bool DeclarationVisitor::CheckNotInBlock(const char *stmt) {
5070   if (currScope().kind() == Scope::Kind::BlockConstruct) {
5071     Say(MessageFormattedText{
5072         "%s statement is not allowed in a BLOCK construct"_err_en_US, stmt});
5073     return false;
5074   } else {
5075     return true;
5076   }
5077 }
5078 
5079 void DeclarationVisitor::Post(const parser::ObjectDecl &x) {
5080   CHECK(objectDeclAttr_);
5081   const auto &name{std::get<parser::ObjectName>(x.t)};
5082   DeclareObjectEntity(name, Attrs{*objectDeclAttr_});
5083 }
5084 
5085 // Declare an entity not yet known to be an object or proc.
5086 Symbol &DeclarationVisitor::DeclareUnknownEntity(
5087     const parser::Name &name, Attrs attrs) {
5088   if (!arraySpec().empty() || !coarraySpec().empty()) {
5089     return DeclareObjectEntity(name, attrs);
5090   } else {
5091     Symbol &symbol{DeclareEntity<EntityDetails>(name, attrs)};
5092     if (auto *type{GetDeclTypeSpec()}) {
5093       SetType(name, *type);
5094     }
5095     charInfo_.length.reset();
5096     if (symbol.attrs().test(Attr::EXTERNAL)) {
5097       ConvertToProcEntity(symbol);
5098     } else if (symbol.attrs().HasAny(Attrs{Attr::ALLOCATABLE,
5099                    Attr::ASYNCHRONOUS, Attr::CONTIGUOUS, Attr::PARAMETER,
5100                    Attr::SAVE, Attr::TARGET, Attr::VALUE, Attr::VOLATILE})) {
5101       ConvertToObjectEntity(symbol);
5102     }
5103     if (attrs.test(Attr::BIND_C)) {
5104       SetBindNameOn(symbol);
5105     }
5106     return symbol;
5107   }
5108 }
5109 
5110 bool DeclarationVisitor::HasCycle(
5111     const Symbol &procSymbol, const Symbol *interface) {
5112   SourceOrderedSymbolSet procsInCycle;
5113   procsInCycle.insert(procSymbol);
5114   while (interface) {
5115     if (procsInCycle.count(*interface) > 0) {
5116       for (const auto &procInCycle : procsInCycle) {
5117         Say(procInCycle->name(),
5118             "The interface for procedure '%s' is recursively defined"_err_en_US,
5119             procInCycle->name());
5120         context().SetError(*procInCycle);
5121       }
5122       return true;
5123     } else if (const auto *procDetails{
5124                    interface->detailsIf<ProcEntityDetails>()}) {
5125       procsInCycle.insert(*interface);
5126       interface = procDetails->procInterface();
5127     } else {
5128       break;
5129     }
5130   }
5131   return false;
5132 }
5133 
5134 Symbol &DeclarationVisitor::DeclareProcEntity(
5135     const parser::Name &name, Attrs attrs, const Symbol *interface) {
5136   Symbol *proc{nullptr};
5137   if (auto *extant{FindInScope(name)}) {
5138     if (auto *d{extant->detailsIf<GenericDetails>()}; d && !d->derivedType()) {
5139       // procedure pointer with same name as a generic
5140       if (auto *specific{d->specific()}) {
5141         SayAlreadyDeclared(name, *specific);
5142       } else {
5143         // Create the ProcEntityDetails symbol in the scope as the "specific()"
5144         // symbol behind an existing GenericDetails symbol of the same name.
5145         proc = &Resolve(name,
5146             currScope().MakeSymbol(name.source, attrs, ProcEntityDetails{}));
5147         d->set_specific(*proc);
5148       }
5149     }
5150   }
5151   Symbol &symbol{proc ? *proc : DeclareEntity<ProcEntityDetails>(name, attrs)};
5152   if (auto *details{symbol.detailsIf<ProcEntityDetails>()}) {
5153     if (context().HasError(symbol)) {
5154     } else if (HasCycle(symbol, interface)) {
5155       return symbol;
5156     } else if (interface && (details->procInterface() || details->type())) {
5157       SayWithDecl(name, symbol,
5158           "The interface for procedure '%s' has already been declared"_err_en_US);
5159       context().SetError(symbol);
5160     } else if (interface) {
5161       details->set_procInterfaces(
5162           *interface, BypassGeneric(interface->GetUltimate()));
5163       if (interface->test(Symbol::Flag::Function)) {
5164         symbol.set(Symbol::Flag::Function);
5165       } else if (interface->test(Symbol::Flag::Subroutine)) {
5166         symbol.set(Symbol::Flag::Subroutine);
5167       }
5168     } else if (auto *type{GetDeclTypeSpec()}) {
5169       SetType(name, *type);
5170       symbol.set(Symbol::Flag::Function);
5171     }
5172     SetBindNameOn(symbol);
5173     SetPassNameOn(symbol);
5174   }
5175   return symbol;
5176 }
5177 
5178 Symbol &DeclarationVisitor::DeclareObjectEntity(
5179     const parser::Name &name, Attrs attrs) {
5180   Symbol &symbol{DeclareEntity<ObjectEntityDetails>(name, attrs)};
5181   if (auto *details{symbol.detailsIf<ObjectEntityDetails>()}) {
5182     if (auto *type{GetDeclTypeSpec()}) {
5183       SetType(name, *type);
5184     }
5185     if (!arraySpec().empty()) {
5186       if (details->IsArray()) {
5187         if (!context().HasError(symbol)) {
5188           Say(name,
5189               "The dimensions of '%s' have already been declared"_err_en_US);
5190           context().SetError(symbol);
5191         }
5192       } else if (MustBeScalar(symbol)) {
5193         context().Warn(common::UsageWarning::PreviousScalarUse, name.source,
5194             "'%s' appeared earlier as a scalar actual argument to a specification function"_warn_en_US,
5195             name.source);
5196       } else if (details->init() || symbol.test(Symbol::Flag::InDataStmt)) {
5197         Say(name, "'%s' was initialized earlier as a scalar"_err_en_US);
5198       } else {
5199         details->set_shape(arraySpec());
5200       }
5201     }
5202     if (!coarraySpec().empty()) {
5203       if (details->IsCoarray()) {
5204         if (!context().HasError(symbol)) {
5205           Say(name,
5206               "The codimensions of '%s' have already been declared"_err_en_US);
5207           context().SetError(symbol);
5208         }
5209       } else {
5210         details->set_coshape(coarraySpec());
5211       }
5212     }
5213     SetBindNameOn(symbol);
5214   }
5215   ClearArraySpec();
5216   ClearCoarraySpec();
5217   charInfo_.length.reset();
5218   return symbol;
5219 }
5220 
5221 void DeclarationVisitor::Post(const parser::IntegerTypeSpec &x) {
5222   if (!isVectorType_) {
5223     SetDeclTypeSpec(MakeNumericType(TypeCategory::Integer, x.v));
5224   }
5225 }
5226 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Real &x) {
5227   if (!isVectorType_) {
5228     SetDeclTypeSpec(MakeNumericType(TypeCategory::Real, x.kind));
5229   }
5230 }
5231 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Complex &x) {
5232   SetDeclTypeSpec(MakeNumericType(TypeCategory::Complex, x.kind));
5233 }
5234 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Logical &x) {
5235   SetDeclTypeSpec(MakeLogicalType(x.kind));
5236 }
5237 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Character &) {
5238   if (!charInfo_.length) {
5239     charInfo_.length = ParamValue{1, common::TypeParamAttr::Len};
5240   }
5241   if (!charInfo_.kind) {
5242     charInfo_.kind =
5243         KindExpr{context().GetDefaultKind(TypeCategory::Character)};
5244   }
5245   SetDeclTypeSpec(currScope().MakeCharacterType(
5246       std::move(*charInfo_.length), std::move(*charInfo_.kind)));
5247   charInfo_ = {};
5248 }
5249 void DeclarationVisitor::Post(const parser::CharSelector::LengthAndKind &x) {
5250   charInfo_.kind = EvaluateSubscriptIntExpr(x.kind);
5251   std::optional<std::int64_t> intKind{ToInt64(charInfo_.kind)};
5252   if (intKind &&
5253       !context().targetCharacteristics().IsTypeEnabled(
5254           TypeCategory::Character, *intKind)) { // C715, C719
5255     Say(currStmtSource().value(),
5256         "KIND value (%jd) not valid for CHARACTER"_err_en_US, *intKind);
5257     charInfo_.kind = std::nullopt; // prevent further errors
5258   }
5259   if (x.length) {
5260     charInfo_.length = GetParamValue(*x.length, common::TypeParamAttr::Len);
5261   }
5262 }
5263 void DeclarationVisitor::Post(const parser::CharLength &x) {
5264   if (const auto *length{std::get_if<std::uint64_t>(&x.u)}) {
5265     charInfo_.length = ParamValue{
5266         static_cast<ConstantSubscript>(*length), common::TypeParamAttr::Len};
5267   } else {
5268     charInfo_.length = GetParamValue(
5269         std::get<parser::TypeParamValue>(x.u), common::TypeParamAttr::Len);
5270   }
5271 }
5272 void DeclarationVisitor::Post(const parser::LengthSelector &x) {
5273   if (const auto *param{std::get_if<parser::TypeParamValue>(&x.u)}) {
5274     charInfo_.length = GetParamValue(*param, common::TypeParamAttr::Len);
5275   }
5276 }
5277 
5278 bool DeclarationVisitor::Pre(const parser::KindParam &x) {
5279   if (const auto *kind{std::get_if<
5280           parser::Scalar<parser::Integer<parser::Constant<parser::Name>>>>(
5281           &x.u)}) {
5282     const parser::Name &name{kind->thing.thing.thing};
5283     if (!FindSymbol(name)) {
5284       Say(name, "Parameter '%s' not found"_err_en_US);
5285     }
5286   }
5287   return false;
5288 }
5289 
5290 int DeclarationVisitor::GetVectorElementKind(
5291     TypeCategory category, const std::optional<parser::KindSelector> &kind) {
5292   KindExpr value{GetKindParamExpr(category, kind)};
5293   if (auto known{evaluate::ToInt64(value)}) {
5294     return static_cast<int>(*known);
5295   }
5296   common::die("Vector element kind must be known at compile-time");
5297 }
5298 
5299 bool DeclarationVisitor::Pre(const parser::VectorTypeSpec &) {
5300   // PowerPC vector types are allowed only on Power architectures.
5301   if (!currScope().context().targetCharacteristics().isPPC()) {
5302     Say(currStmtSource().value(),
5303         "Vector type is only supported for PowerPC"_err_en_US);
5304     isVectorType_ = false;
5305     return false;
5306   }
5307   isVectorType_ = true;
5308   return true;
5309 }
5310 // Create semantic::DerivedTypeSpec for Vector types here.
5311 void DeclarationVisitor::Post(const parser::VectorTypeSpec &x) {
5312   llvm::StringRef typeName;
5313   llvm::SmallVector<ParamValue> typeParams;
5314   DerivedTypeSpec::Category vectorCategory;
5315 
5316   isVectorType_ = false;
5317   common::visit(
5318       common::visitors{
5319           [&](const parser::IntrinsicVectorTypeSpec &y) {
5320             vectorCategory = DerivedTypeSpec::Category::IntrinsicVector;
5321             int vecElemKind = 0;
5322             typeName = "__builtin_ppc_intrinsic_vector";
5323             common::visit(
5324                 common::visitors{
5325                     [&](const parser::IntegerTypeSpec &z) {
5326                       vecElemKind = GetVectorElementKind(
5327                           TypeCategory::Integer, std::move(z.v));
5328                       typeParams.push_back(ParamValue(
5329                           static_cast<common::ConstantSubscript>(
5330                               common::VectorElementCategory::Integer),
5331                           common::TypeParamAttr::Kind));
5332                     },
5333                     [&](const parser::IntrinsicTypeSpec::Real &z) {
5334                       vecElemKind = GetVectorElementKind(
5335                           TypeCategory::Real, std::move(z.kind));
5336                       typeParams.push_back(
5337                           ParamValue(static_cast<common::ConstantSubscript>(
5338                                          common::VectorElementCategory::Real),
5339                               common::TypeParamAttr::Kind));
5340                     },
5341                     [&](const parser::UnsignedTypeSpec &z) {
5342                       vecElemKind = GetVectorElementKind(
5343                           TypeCategory::Integer, std::move(z.v));
5344                       typeParams.push_back(ParamValue(
5345                           static_cast<common::ConstantSubscript>(
5346                               common::VectorElementCategory::Unsigned),
5347                           common::TypeParamAttr::Kind));
5348                     },
5349                 },
5350                 y.v.u);
5351             typeParams.push_back(
5352                 ParamValue(static_cast<common::ConstantSubscript>(vecElemKind),
5353                     common::TypeParamAttr::Kind));
5354           },
5355           [&](const parser::VectorTypeSpec::PairVectorTypeSpec &y) {
5356             vectorCategory = DerivedTypeSpec::Category::PairVector;
5357             typeName = "__builtin_ppc_pair_vector";
5358           },
5359           [&](const parser::VectorTypeSpec::QuadVectorTypeSpec &y) {
5360             vectorCategory = DerivedTypeSpec::Category::QuadVector;
5361             typeName = "__builtin_ppc_quad_vector";
5362           },
5363       },
5364       x.u);
5365 
5366   auto ppcBuiltinTypesScope = currScope().context().GetPPCBuiltinTypesScope();
5367   if (!ppcBuiltinTypesScope) {
5368     common::die("INTERNAL: The __ppc_types module was not found ");
5369   }
5370 
5371   auto iter{ppcBuiltinTypesScope->find(
5372       semantics::SourceName{typeName.data(), typeName.size()})};
5373   if (iter == ppcBuiltinTypesScope->cend()) {
5374     common::die("INTERNAL: The __ppc_types module does not define "
5375                 "the type '%s'",
5376         typeName.data());
5377   }
5378 
5379   const semantics::Symbol &typeSymbol{*iter->second};
5380   DerivedTypeSpec vectorDerivedType{typeName.data(), typeSymbol};
5381   vectorDerivedType.set_category(vectorCategory);
5382   if (typeParams.size()) {
5383     vectorDerivedType.AddRawParamValue(nullptr, std::move(typeParams[0]));
5384     vectorDerivedType.AddRawParamValue(nullptr, std::move(typeParams[1]));
5385     vectorDerivedType.CookParameters(GetFoldingContext());
5386   }
5387 
5388   if (const DeclTypeSpec *
5389       extant{ppcBuiltinTypesScope->FindInstantiatedDerivedType(
5390           vectorDerivedType, DeclTypeSpec::Category::TypeDerived)}) {
5391     // This derived type and parameter expressions (if any) are already present
5392     // in the __ppc_intrinsics scope.
5393     SetDeclTypeSpec(*extant);
5394   } else {
5395     DeclTypeSpec &type{ppcBuiltinTypesScope->MakeDerivedType(
5396         DeclTypeSpec::Category::TypeDerived, std::move(vectorDerivedType))};
5397     DerivedTypeSpec &derived{type.derivedTypeSpec()};
5398     auto restorer{
5399         GetFoldingContext().messages().SetLocation(currStmtSource().value())};
5400     derived.Instantiate(*ppcBuiltinTypesScope);
5401     SetDeclTypeSpec(type);
5402   }
5403 }
5404 
5405 bool DeclarationVisitor::Pre(const parser::DeclarationTypeSpec::Type &) {
5406   CHECK(GetDeclTypeSpecCategory() == DeclTypeSpec::Category::TypeDerived);
5407   return true;
5408 }
5409 
5410 void DeclarationVisitor::Post(const parser::DeclarationTypeSpec::Type &type) {
5411   const parser::Name &derivedName{std::get<parser::Name>(type.derived.t)};
5412   if (const Symbol * derivedSymbol{derivedName.symbol}) {
5413     CheckForAbstractType(*derivedSymbol); // C706
5414   }
5415 }
5416 
5417 bool DeclarationVisitor::Pre(const parser::DeclarationTypeSpec::Class &) {
5418   SetDeclTypeSpecCategory(DeclTypeSpec::Category::ClassDerived);
5419   return true;
5420 }
5421 
5422 void DeclarationVisitor::Post(
5423     const parser::DeclarationTypeSpec::Class &parsedClass) {
5424   const auto &typeName{std::get<parser::Name>(parsedClass.derived.t)};
5425   if (auto spec{ResolveDerivedType(typeName)};
5426       spec && !IsExtensibleType(&*spec)) { // C705
5427     SayWithDecl(typeName, *typeName.symbol,
5428         "Non-extensible derived type '%s' may not be used with CLASS"
5429         " keyword"_err_en_US);
5430   }
5431 }
5432 
5433 void DeclarationVisitor::Post(const parser::DerivedTypeSpec &x) {
5434   const auto &typeName{std::get<parser::Name>(x.t)};
5435   auto spec{ResolveDerivedType(typeName)};
5436   if (!spec) {
5437     return;
5438   }
5439   bool seenAnyName{false};
5440   for (const auto &typeParamSpec :
5441       std::get<std::list<parser::TypeParamSpec>>(x.t)) {
5442     const auto &optKeyword{
5443         std::get<std::optional<parser::Keyword>>(typeParamSpec.t)};
5444     std::optional<SourceName> name;
5445     if (optKeyword) {
5446       seenAnyName = true;
5447       name = optKeyword->v.source;
5448     } else if (seenAnyName) {
5449       Say(typeName.source, "Type parameter value must have a name"_err_en_US);
5450       continue;
5451     }
5452     const auto &value{std::get<parser::TypeParamValue>(typeParamSpec.t)};
5453     // The expressions in a derived type specifier whose values define
5454     // non-defaulted type parameters are evaluated (folded) in the enclosing
5455     // scope.  The KIND/LEN distinction is resolved later in
5456     // DerivedTypeSpec::CookParameters().
5457     ParamValue param{GetParamValue(value, common::TypeParamAttr::Kind)};
5458     if (!param.isExplicit() || param.GetExplicit()) {
5459       spec->AddRawParamValue(
5460           common::GetPtrFromOptional(optKeyword), std::move(param));
5461     }
5462   }
5463   // The DerivedTypeSpec *spec is used initially as a search key.
5464   // If it turns out to have the same name and actual parameter
5465   // value expressions as another DerivedTypeSpec in the current
5466   // scope does, then we'll use that extant spec; otherwise, when this
5467   // spec is distinct from all derived types previously instantiated
5468   // in the current scope, this spec will be moved into that collection.
5469   const auto &dtDetails{spec->typeSymbol().get<DerivedTypeDetails>()};
5470   auto category{GetDeclTypeSpecCategory()};
5471   if (dtDetails.isForwardReferenced()) {
5472     DeclTypeSpec &type{currScope().MakeDerivedType(category, std::move(*spec))};
5473     SetDeclTypeSpec(type);
5474     return;
5475   }
5476   // Normalize parameters to produce a better search key.
5477   spec->CookParameters(GetFoldingContext());
5478   if (!spec->MightBeParameterized()) {
5479     spec->EvaluateParameters(context());
5480   }
5481   if (const DeclTypeSpec *
5482       extant{currScope().FindInstantiatedDerivedType(*spec, category)}) {
5483     // This derived type and parameter expressions (if any) are already present
5484     // in this scope.
5485     SetDeclTypeSpec(*extant);
5486   } else {
5487     DeclTypeSpec &type{currScope().MakeDerivedType(category, std::move(*spec))};
5488     DerivedTypeSpec &derived{type.derivedTypeSpec()};
5489     if (derived.MightBeParameterized() &&
5490         currScope().IsParameterizedDerivedType()) {
5491       // Defer instantiation; use the derived type's definition's scope.
5492       derived.set_scope(DEREF(spec->typeSymbol().scope()));
5493     } else if (&currScope() == spec->typeSymbol().scope()) {
5494       // Direct recursive use of a type in the definition of one of its
5495       // components: defer instantiation
5496     } else {
5497       auto restorer{
5498           GetFoldingContext().messages().SetLocation(currStmtSource().value())};
5499       derived.Instantiate(currScope());
5500     }
5501     SetDeclTypeSpec(type);
5502   }
5503   // Capture the DerivedTypeSpec in the parse tree for use in building
5504   // structure constructor expressions.
5505   x.derivedTypeSpec = &GetDeclTypeSpec()->derivedTypeSpec();
5506 }
5507 
5508 void DeclarationVisitor::Post(const parser::DeclarationTypeSpec::Record &rec) {
5509   const auto &typeName{rec.v};
5510   if (auto spec{ResolveDerivedType(typeName)}) {
5511     spec->CookParameters(GetFoldingContext());
5512     spec->EvaluateParameters(context());
5513     if (const DeclTypeSpec *
5514         extant{currScope().FindInstantiatedDerivedType(
5515             *spec, DeclTypeSpec::TypeDerived)}) {
5516       SetDeclTypeSpec(*extant);
5517     } else {
5518       Say(typeName.source, "%s is not a known STRUCTURE"_err_en_US,
5519           typeName.source);
5520     }
5521   }
5522 }
5523 
5524 // The descendents of DerivedTypeDef in the parse tree are visited directly
5525 // in this Pre() routine so that recursive use of the derived type can be
5526 // supported in the components.
5527 bool DeclarationVisitor::Pre(const parser::DerivedTypeDef &x) {
5528   auto &stmt{std::get<parser::Statement<parser::DerivedTypeStmt>>(x.t)};
5529   Walk(stmt);
5530   Walk(std::get<std::list<parser::Statement<parser::TypeParamDefStmt>>>(x.t));
5531   auto &scope{currScope()};
5532   CHECK(scope.symbol());
5533   CHECK(scope.symbol()->scope() == &scope);
5534   auto &details{scope.symbol()->get<DerivedTypeDetails>()};
5535   for (auto &paramName : std::get<std::list<parser::Name>>(stmt.statement.t)) {
5536     if (auto *symbol{FindInScope(scope, paramName)}) {
5537       if (auto *details{symbol->detailsIf<TypeParamDetails>()}) {
5538         if (!details->attr()) {
5539           Say(paramName,
5540               "No definition found for type parameter '%s'"_err_en_US); // C742
5541         }
5542       }
5543     }
5544   }
5545   Walk(std::get<std::list<parser::Statement<parser::PrivateOrSequence>>>(x.t));
5546   const auto &componentDefs{
5547       std::get<std::list<parser::Statement<parser::ComponentDefStmt>>>(x.t)};
5548   Walk(componentDefs);
5549   if (derivedTypeInfo_.sequence) {
5550     details.set_sequence(true);
5551     if (componentDefs.empty()) {
5552       // F'2023 C745 - not enforced by any compiler
5553       context().Warn(common::LanguageFeature::EmptySequenceType, stmt.source,
5554           "A sequence type should have at least one component"_warn_en_US);
5555     }
5556     if (!details.paramDeclOrder().empty()) { // C740
5557       Say(stmt.source,
5558           "A sequence type may not have type parameters"_err_en_US);
5559     }
5560     if (derivedTypeInfo_.extends) { // C735
5561       Say(stmt.source,
5562           "A sequence type may not have the EXTENDS attribute"_err_en_US);
5563     }
5564   }
5565   Walk(std::get<std::optional<parser::TypeBoundProcedurePart>>(x.t));
5566   Walk(std::get<parser::Statement<parser::EndTypeStmt>>(x.t));
5567   details.set_isForwardReferenced(false);
5568   derivedTypeInfo_ = {};
5569   PopScope();
5570   return false;
5571 }
5572 
5573 bool DeclarationVisitor::Pre(const parser::DerivedTypeStmt &) {
5574   return BeginAttrs();
5575 }
5576 void DeclarationVisitor::Post(const parser::DerivedTypeStmt &x) {
5577   auto &name{std::get<parser::Name>(x.t)};
5578   // Resolve the EXTENDS() clause before creating the derived
5579   // type's symbol to foil attempts to recursively extend a type.
5580   auto *extendsName{derivedTypeInfo_.extends};
5581   std::optional<DerivedTypeSpec> extendsType{
5582       ResolveExtendsType(name, extendsName)};
5583   DerivedTypeDetails derivedTypeDetails;
5584   // Catch any premature structure constructors within the definition
5585   derivedTypeDetails.set_isForwardReferenced(true);
5586   auto &symbol{MakeSymbol(name, GetAttrs(), std::move(derivedTypeDetails))};
5587   symbol.ReplaceName(name.source);
5588   derivedTypeInfo_.type = &symbol;
5589   PushScope(Scope::Kind::DerivedType, &symbol);
5590   if (extendsType) {
5591     // Declare the "parent component"; private if the type is.
5592     // Any symbol stored in the EXTENDS() clause is temporarily
5593     // hidden so that a new symbol can be created for the parent
5594     // component without producing spurious errors about already
5595     // existing.
5596     const Symbol &extendsSymbol{extendsType->typeSymbol()};
5597     auto restorer{common::ScopedSet(extendsName->symbol, nullptr)};
5598     if (OkToAddComponent(*extendsName, &extendsSymbol)) {
5599       auto &comp{DeclareEntity<ObjectEntityDetails>(*extendsName, Attrs{})};
5600       comp.attrs().set(
5601           Attr::PRIVATE, extendsSymbol.attrs().test(Attr::PRIVATE));
5602       comp.implicitAttrs().set(
5603           Attr::PRIVATE, extendsSymbol.implicitAttrs().test(Attr::PRIVATE));
5604       comp.set(Symbol::Flag::ParentComp);
5605       DeclTypeSpec &type{currScope().MakeDerivedType(
5606           DeclTypeSpec::TypeDerived, std::move(*extendsType))};
5607       type.derivedTypeSpec().set_scope(DEREF(extendsSymbol.scope()));
5608       comp.SetType(type);
5609       DerivedTypeDetails &details{symbol.get<DerivedTypeDetails>()};
5610       details.add_component(comp);
5611     }
5612   }
5613   // Create symbols now for type parameters so that they shadow names
5614   // from the enclosing specification part.
5615   if (auto *details{symbol.detailsIf<DerivedTypeDetails>()}) {
5616     for (const auto &name : std::get<std::list<parser::Name>>(x.t)) {
5617       if (Symbol * symbol{MakeTypeSymbol(name, TypeParamDetails{})}) {
5618         details->add_paramNameOrder(*symbol);
5619       }
5620     }
5621   }
5622   EndAttrs();
5623 }
5624 
5625 void DeclarationVisitor::Post(const parser::TypeParamDefStmt &x) {
5626   auto *type{GetDeclTypeSpec()};
5627   DerivedTypeDetails *derivedDetails{nullptr};
5628   if (Symbol * dtSym{currScope().symbol()}) {
5629     derivedDetails = dtSym->detailsIf<DerivedTypeDetails>();
5630   }
5631   auto attr{std::get<common::TypeParamAttr>(x.t)};
5632   for (auto &decl : std::get<std::list<parser::TypeParamDecl>>(x.t)) {
5633     auto &name{std::get<parser::Name>(decl.t)};
5634     if (Symbol * symbol{FindInScope(currScope(), name)}) {
5635       if (auto *paramDetails{symbol->detailsIf<TypeParamDetails>()}) {
5636         if (!paramDetails->attr()) {
5637           paramDetails->set_attr(attr);
5638           SetType(name, *type);
5639           if (auto &init{std::get<std::optional<parser::ScalarIntConstantExpr>>(
5640                   decl.t)}) {
5641             if (auto maybeExpr{AnalyzeExpr(context(), *init)}) {
5642               if (auto *intExpr{std::get_if<SomeIntExpr>(&maybeExpr->u)}) {
5643                 paramDetails->set_init(std::move(*intExpr));
5644               }
5645             }
5646           }
5647           if (derivedDetails) {
5648             derivedDetails->add_paramDeclOrder(*symbol);
5649           }
5650         } else {
5651           Say(name,
5652               "Type parameter '%s' was already declared in this derived type"_err_en_US);
5653         }
5654       }
5655     } else {
5656       Say(name, "'%s' is not a parameter of this derived type"_err_en_US);
5657     }
5658   }
5659   EndDecl();
5660 }
5661 bool DeclarationVisitor::Pre(const parser::TypeAttrSpec::Extends &x) {
5662   if (derivedTypeInfo_.extends) {
5663     Say(currStmtSource().value(),
5664         "Attribute 'EXTENDS' cannot be used more than once"_err_en_US);
5665   } else {
5666     derivedTypeInfo_.extends = &x.v;
5667   }
5668   return false;
5669 }
5670 
5671 bool DeclarationVisitor::Pre(const parser::PrivateStmt &) {
5672   if (!currScope().parent().IsModule()) {
5673     Say("PRIVATE is only allowed in a derived type that is"
5674         " in a module"_err_en_US); // C766
5675   } else if (derivedTypeInfo_.sawContains) {
5676     derivedTypeInfo_.privateBindings = true;
5677   } else if (!derivedTypeInfo_.privateComps) {
5678     derivedTypeInfo_.privateComps = true;
5679   } else { // C738
5680     context().Warn(common::LanguageFeature::RedundantAttribute,
5681         "PRIVATE should not appear more than once in derived type components"_warn_en_US);
5682   }
5683   return false;
5684 }
5685 bool DeclarationVisitor::Pre(const parser::SequenceStmt &) {
5686   if (derivedTypeInfo_.sequence) { // C738
5687     context().Warn(common::LanguageFeature::RedundantAttribute,
5688         "SEQUENCE should not appear more than once in derived type components"_warn_en_US);
5689   }
5690   derivedTypeInfo_.sequence = true;
5691   return false;
5692 }
5693 void DeclarationVisitor::Post(const parser::ComponentDecl &x) {
5694   const auto &name{std::get<parser::Name>(x.t)};
5695   auto attrs{GetAttrs()};
5696   if (derivedTypeInfo_.privateComps &&
5697       !attrs.HasAny({Attr::PUBLIC, Attr::PRIVATE})) {
5698     attrs.set(Attr::PRIVATE);
5699   }
5700   if (const auto *declType{GetDeclTypeSpec()}) {
5701     if (const auto *derived{declType->AsDerived()}) {
5702       if (!attrs.HasAny({Attr::POINTER, Attr::ALLOCATABLE})) {
5703         if (derivedTypeInfo_.type == &derived->typeSymbol()) { // C744
5704           Say("Recursive use of the derived type requires "
5705               "POINTER or ALLOCATABLE"_err_en_US);
5706         }
5707       }
5708       // TODO: This would be more appropriate in CheckDerivedType()
5709       if (auto it{FindCoarrayUltimateComponent(*derived)}) { // C748
5710         std::string ultimateName{it.BuildResultDesignatorName()};
5711         // Strip off the leading "%"
5712         if (ultimateName.length() > 1) {
5713           ultimateName.erase(0, 1);
5714           if (attrs.HasAny({Attr::POINTER, Attr::ALLOCATABLE})) {
5715             evaluate::AttachDeclaration(
5716                 Say(name.source,
5717                     "A component with a POINTER or ALLOCATABLE attribute may "
5718                     "not "
5719                     "be of a type with a coarray ultimate component (named "
5720                     "'%s')"_err_en_US,
5721                     ultimateName),
5722                 derived->typeSymbol());
5723           }
5724           if (!arraySpec().empty() || !coarraySpec().empty()) {
5725             evaluate::AttachDeclaration(
5726                 Say(name.source,
5727                     "An array or coarray component may not be of a type with a "
5728                     "coarray ultimate component (named '%s')"_err_en_US,
5729                     ultimateName),
5730                 derived->typeSymbol());
5731           }
5732         }
5733       }
5734     }
5735   }
5736   if (OkToAddComponent(name)) {
5737     auto &symbol{DeclareObjectEntity(name, attrs)};
5738     SetCUDADataAttr(name.source, symbol, cudaDataAttr());
5739     if (symbol.has<ObjectEntityDetails>()) {
5740       if (auto &init{std::get<std::optional<parser::Initialization>>(x.t)}) {
5741         Initialization(name, *init, true);
5742       }
5743     }
5744     currScope().symbol()->get<DerivedTypeDetails>().add_component(symbol);
5745   }
5746   ClearArraySpec();
5747   ClearCoarraySpec();
5748 }
5749 void DeclarationVisitor::Post(const parser::FillDecl &x) {
5750   // Replace "%FILL" with a distinct generated name
5751   const auto &name{std::get<parser::Name>(x.t)};
5752   const_cast<SourceName &>(name.source) = context().GetTempName(currScope());
5753   if (OkToAddComponent(name)) {
5754     auto &symbol{DeclareObjectEntity(name, GetAttrs())};
5755     currScope().symbol()->get<DerivedTypeDetails>().add_component(symbol);
5756   }
5757   ClearArraySpec();
5758 }
5759 bool DeclarationVisitor::Pre(const parser::ProcedureDeclarationStmt &x) {
5760   CHECK(!interfaceName_);
5761   const auto &procAttrSpec{std::get<std::list<parser::ProcAttrSpec>>(x.t)};
5762   for (const parser::ProcAttrSpec &procAttr : procAttrSpec) {
5763     if (auto *bindC{std::get_if<parser::LanguageBindingSpec>(&procAttr.u)}) {
5764       if (std::get<std::optional<parser::ScalarDefaultCharConstantExpr>>(
5765               bindC->t)
5766               .has_value()) {
5767         if (std::get<std::list<parser::ProcDecl>>(x.t).size() > 1) {
5768           Say(context().location().value(),
5769               "A procedure declaration statement with a binding name may not declare multiple procedures"_err_en_US);
5770         }
5771         break;
5772       }
5773     }
5774   }
5775   return BeginDecl();
5776 }
5777 void DeclarationVisitor::Post(const parser::ProcedureDeclarationStmt &) {
5778   interfaceName_ = nullptr;
5779   EndDecl();
5780 }
5781 bool DeclarationVisitor::Pre(const parser::DataComponentDefStmt &x) {
5782   // Overrides parse tree traversal so as to handle attributes first,
5783   // so POINTER & ALLOCATABLE enable forward references to derived types.
5784   Walk(std::get<std::list<parser::ComponentAttrSpec>>(x.t));
5785   set_allowForwardReferenceToDerivedType(
5786       GetAttrs().HasAny({Attr::POINTER, Attr::ALLOCATABLE}));
5787   Walk(std::get<parser::DeclarationTypeSpec>(x.t));
5788   set_allowForwardReferenceToDerivedType(false);
5789   if (derivedTypeInfo_.sequence) { // C740
5790     if (const auto *declType{GetDeclTypeSpec()}) {
5791       if (!declType->AsIntrinsic() && !declType->IsSequenceType() &&
5792           !InModuleFile()) {
5793         if (GetAttrs().test(Attr::POINTER) &&
5794             context().IsEnabled(common::LanguageFeature::PointerInSeqType)) {
5795           context().Warn(common::LanguageFeature::PointerInSeqType,
5796               "A sequence type data component that is a pointer to a non-sequence type is not standard"_port_en_US);
5797         } else {
5798           Say("A sequence type data component must either be of an intrinsic type or a derived sequence type"_err_en_US);
5799         }
5800       }
5801     }
5802   }
5803   Walk(std::get<std::list<parser::ComponentOrFill>>(x.t));
5804   return false;
5805 }
5806 bool DeclarationVisitor::Pre(const parser::ProcComponentDefStmt &) {
5807   CHECK(!interfaceName_);
5808   return true;
5809 }
5810 void DeclarationVisitor::Post(const parser::ProcComponentDefStmt &) {
5811   interfaceName_ = nullptr;
5812 }
5813 bool DeclarationVisitor::Pre(const parser::ProcPointerInit &x) {
5814   if (auto *name{std::get_if<parser::Name>(&x.u)}) {
5815     return !NameIsKnownOrIntrinsic(*name) && !CheckUseError(*name);
5816   } else {
5817     const auto &null{DEREF(std::get_if<parser::NullInit>(&x.u))};
5818     Walk(null);
5819     if (auto nullInit{EvaluateExpr(null)}) {
5820       if (!evaluate::IsNullPointer(*nullInit)) {
5821         Say(null.v.value().source,
5822             "Procedure pointer initializer must be a name or intrinsic NULL()"_err_en_US);
5823       }
5824     }
5825     return false;
5826   }
5827 }
5828 void DeclarationVisitor::Post(const parser::ProcInterface &x) {
5829   if (auto *name{std::get_if<parser::Name>(&x.u)}) {
5830     interfaceName_ = name;
5831     NoteInterfaceName(*name);
5832   }
5833 }
5834 void DeclarationVisitor::Post(const parser::ProcDecl &x) {
5835   const auto &name{std::get<parser::Name>(x.t)};
5836   // Don't use BypassGeneric or GetUltimate on this symbol, they can
5837   // lead to unusable names in module files.
5838   const Symbol *procInterface{
5839       interfaceName_ ? interfaceName_->symbol : nullptr};
5840   auto attrs{HandleSaveName(name.source, GetAttrs())};
5841   DerivedTypeDetails *dtDetails{nullptr};
5842   if (Symbol * symbol{currScope().symbol()}) {
5843     dtDetails = symbol->detailsIf<DerivedTypeDetails>();
5844   }
5845   if (!dtDetails) {
5846     attrs.set(Attr::EXTERNAL);
5847   }
5848   Symbol &symbol{DeclareProcEntity(name, attrs, procInterface)};
5849   SetCUDADataAttr(name.source, symbol, cudaDataAttr()); // for error
5850   symbol.ReplaceName(name.source);
5851   if (dtDetails) {
5852     dtDetails->add_component(symbol);
5853   }
5854   DeclaredPossibleSpecificProc(symbol);
5855 }
5856 
5857 bool DeclarationVisitor::Pre(const parser::TypeBoundProcedurePart &) {
5858   derivedTypeInfo_.sawContains = true;
5859   return true;
5860 }
5861 
5862 // Resolve binding names from type-bound generics, saved in genericBindings_.
5863 void DeclarationVisitor::Post(const parser::TypeBoundProcedurePart &) {
5864   // track specifics seen for the current generic to detect duplicates:
5865   const Symbol *currGeneric{nullptr};
5866   std::set<SourceName> specifics;
5867   for (const auto &[generic, bindingName] : genericBindings_) {
5868     if (generic != currGeneric) {
5869       currGeneric = generic;
5870       specifics.clear();
5871     }
5872     auto [it, inserted]{specifics.insert(bindingName->source)};
5873     if (!inserted) {
5874       Say(*bindingName, // C773
5875           "Binding name '%s' was already specified for generic '%s'"_err_en_US,
5876           bindingName->source, generic->name())
5877           .Attach(*it, "Previous specification of '%s'"_en_US, *it);
5878       continue;
5879     }
5880     auto *symbol{FindInTypeOrParents(*bindingName)};
5881     if (!symbol) {
5882       Say(*bindingName, // C772
5883           "Binding name '%s' not found in this derived type"_err_en_US);
5884     } else if (!symbol->has<ProcBindingDetails>()) {
5885       SayWithDecl(*bindingName, *symbol, // C772
5886           "'%s' is not the name of a specific binding of this type"_err_en_US);
5887     } else {
5888       generic->get<GenericDetails>().AddSpecificProc(
5889           *symbol, bindingName->source);
5890     }
5891   }
5892   genericBindings_.clear();
5893 }
5894 
5895 void DeclarationVisitor::Post(const parser::ContainsStmt &) {
5896   if (derivedTypeInfo_.sequence) {
5897     Say("A sequence type may not have a CONTAINS statement"_err_en_US); // C740
5898   }
5899 }
5900 
5901 void DeclarationVisitor::Post(
5902     const parser::TypeBoundProcedureStmt::WithoutInterface &x) {
5903   if (GetAttrs().test(Attr::DEFERRED)) { // C783
5904     Say("DEFERRED is only allowed when an interface-name is provided"_err_en_US);
5905   }
5906   for (auto &declaration : x.declarations) {
5907     auto &bindingName{std::get<parser::Name>(declaration.t)};
5908     auto &optName{std::get<std::optional<parser::Name>>(declaration.t)};
5909     const parser::Name &procedureName{optName ? *optName : bindingName};
5910     Symbol *procedure{FindSymbol(procedureName)};
5911     if (!procedure) {
5912       procedure = NoteInterfaceName(procedureName);
5913     }
5914     if (procedure) {
5915       const Symbol &bindTo{BypassGeneric(*procedure)};
5916       if (auto *s{MakeTypeSymbol(bindingName, ProcBindingDetails{bindTo})}) {
5917         SetPassNameOn(*s);
5918         if (GetAttrs().test(Attr::DEFERRED)) {
5919           context().SetError(*s);
5920         }
5921       }
5922     }
5923   }
5924 }
5925 
5926 void DeclarationVisitor::CheckBindings(
5927     const parser::TypeBoundProcedureStmt::WithoutInterface &tbps) {
5928   CHECK(currScope().IsDerivedType());
5929   for (auto &declaration : tbps.declarations) {
5930     auto &bindingName{std::get<parser::Name>(declaration.t)};
5931     if (Symbol * binding{FindInScope(bindingName)}) {
5932       if (auto *details{binding->detailsIf<ProcBindingDetails>()}) {
5933         const Symbol &ultimate{details->symbol().GetUltimate()};
5934         const Symbol &procedure{BypassGeneric(ultimate)};
5935         if (&procedure != &ultimate) {
5936           details->ReplaceSymbol(procedure);
5937         }
5938         if (!CanBeTypeBoundProc(procedure)) {
5939           if (details->symbol().name() != binding->name()) {
5940             Say(binding->name(),
5941                 "The binding of '%s' ('%s') must be either an accessible "
5942                 "module procedure or an external procedure with "
5943                 "an explicit interface"_err_en_US,
5944                 binding->name(), details->symbol().name());
5945           } else {
5946             Say(binding->name(),
5947                 "'%s' must be either an accessible module procedure "
5948                 "or an external procedure with an explicit interface"_err_en_US,
5949                 binding->name());
5950           }
5951           context().SetError(*binding);
5952         }
5953       }
5954     }
5955   }
5956 }
5957 
5958 void DeclarationVisitor::Post(
5959     const parser::TypeBoundProcedureStmt::WithInterface &x) {
5960   if (!GetAttrs().test(Attr::DEFERRED)) { // C783
5961     Say("DEFERRED is required when an interface-name is provided"_err_en_US);
5962   }
5963   if (Symbol * interface{NoteInterfaceName(x.interfaceName)}) {
5964     for (auto &bindingName : x.bindingNames) {
5965       if (auto *s{
5966               MakeTypeSymbol(bindingName, ProcBindingDetails{*interface})}) {
5967         SetPassNameOn(*s);
5968         if (!GetAttrs().test(Attr::DEFERRED)) {
5969           context().SetError(*s);
5970         }
5971       }
5972     }
5973   }
5974 }
5975 
5976 bool DeclarationVisitor::Pre(const parser::FinalProcedureStmt &x) {
5977   if (currScope().IsDerivedType() && currScope().symbol()) {
5978     if (auto *details{currScope().symbol()->detailsIf<DerivedTypeDetails>()}) {
5979       for (const auto &subrName : x.v) {
5980         Symbol *symbol{FindSymbol(subrName)};
5981         if (!symbol) {
5982           // FINAL procedures must be module subroutines
5983           symbol = &MakeSymbol(
5984               currScope().parent(), subrName.source, Attrs{Attr::MODULE});
5985           Resolve(subrName, symbol);
5986           symbol->set_details(ProcEntityDetails{});
5987           symbol->set(Symbol::Flag::Subroutine);
5988         }
5989         if (auto pair{details->finals().emplace(subrName.source, *symbol)};
5990             !pair.second) { // C787
5991           Say(subrName.source,
5992               "FINAL subroutine '%s' already appeared in this derived type"_err_en_US,
5993               subrName.source)
5994               .Attach(pair.first->first,
5995                   "earlier appearance of this FINAL subroutine"_en_US);
5996         }
5997       }
5998     }
5999   }
6000   return false;
6001 }
6002 
6003 bool DeclarationVisitor::Pre(const parser::TypeBoundGenericStmt &x) {
6004   const auto &accessSpec{std::get<std::optional<parser::AccessSpec>>(x.t)};
6005   const auto &genericSpec{std::get<Indirection<parser::GenericSpec>>(x.t)};
6006   const auto &bindingNames{std::get<std::list<parser::Name>>(x.t)};
6007   GenericSpecInfo info{genericSpec.value()};
6008   SourceName symbolName{info.symbolName()};
6009   bool isPrivate{accessSpec ? accessSpec->v == parser::AccessSpec::Kind::Private
6010                             : derivedTypeInfo_.privateBindings};
6011   auto *genericSymbol{FindInScope(symbolName)};
6012   if (genericSymbol) {
6013     if (!genericSymbol->has<GenericDetails>()) {
6014       genericSymbol = nullptr; // MakeTypeSymbol will report the error below
6015     }
6016   } else {
6017     // look in ancestor types for a generic of the same name
6018     for (const auto &name : GetAllNames(context(), symbolName)) {
6019       if (Symbol * inherited{currScope().FindComponent(SourceName{name})}) {
6020         if (inherited->has<GenericDetails>()) {
6021           CheckAccessibility(symbolName, isPrivate, *inherited); // C771
6022         } else {
6023           Say(symbolName,
6024               "Type bound generic procedure '%s' may not have the same name as a non-generic symbol inherited from an ancestor type"_err_en_US)
6025               .Attach(inherited->name(), "Inherited symbol"_en_US);
6026         }
6027         break;
6028       }
6029     }
6030   }
6031   if (genericSymbol) {
6032     CheckAccessibility(symbolName, isPrivate, *genericSymbol); // C771
6033   } else {
6034     genericSymbol = MakeTypeSymbol(symbolName, GenericDetails{});
6035     if (!genericSymbol) {
6036       return false;
6037     }
6038     if (isPrivate) {
6039       SetExplicitAttr(*genericSymbol, Attr::PRIVATE);
6040     }
6041   }
6042   for (const parser::Name &bindingName : bindingNames) {
6043     genericBindings_.emplace(genericSymbol, &bindingName);
6044   }
6045   info.Resolve(genericSymbol);
6046   return false;
6047 }
6048 
6049 // DEC STRUCTUREs are handled thus to allow for nested definitions.
6050 bool DeclarationVisitor::Pre(const parser::StructureDef &def) {
6051   const auto &structureStatement{
6052       std::get<parser::Statement<parser::StructureStmt>>(def.t)};
6053   auto saveDerivedTypeInfo{derivedTypeInfo_};
6054   derivedTypeInfo_ = {};
6055   derivedTypeInfo_.isStructure = true;
6056   derivedTypeInfo_.sequence = true;
6057   Scope *previousStructure{nullptr};
6058   if (saveDerivedTypeInfo.isStructure) {
6059     previousStructure = &currScope();
6060     PopScope();
6061   }
6062   const parser::StructureStmt &structStmt{structureStatement.statement};
6063   const auto &name{std::get<std::optional<parser::Name>>(structStmt.t)};
6064   if (!name) {
6065     // Construct a distinct generated name for an anonymous structure
6066     auto &mutableName{const_cast<std::optional<parser::Name> &>(name)};
6067     mutableName.emplace(
6068         parser::Name{context().GetTempName(currScope()), nullptr});
6069   }
6070   auto &symbol{MakeSymbol(*name, DerivedTypeDetails{})};
6071   symbol.ReplaceName(name->source);
6072   symbol.get<DerivedTypeDetails>().set_sequence(true);
6073   symbol.get<DerivedTypeDetails>().set_isDECStructure(true);
6074   derivedTypeInfo_.type = &symbol;
6075   PushScope(Scope::Kind::DerivedType, &symbol);
6076   const auto &fields{std::get<std::list<parser::StructureField>>(def.t)};
6077   Walk(fields);
6078   PopScope();
6079   // Complete the definition
6080   DerivedTypeSpec derivedTypeSpec{symbol.name(), symbol};
6081   derivedTypeSpec.set_scope(DEREF(symbol.scope()));
6082   derivedTypeSpec.CookParameters(GetFoldingContext());
6083   derivedTypeSpec.EvaluateParameters(context());
6084   DeclTypeSpec &type{currScope().MakeDerivedType(
6085       DeclTypeSpec::TypeDerived, std::move(derivedTypeSpec))};
6086   type.derivedTypeSpec().Instantiate(currScope());
6087   // Restore previous structure definition context, if any
6088   derivedTypeInfo_ = saveDerivedTypeInfo;
6089   if (previousStructure) {
6090     PushScope(*previousStructure);
6091   }
6092   // Handle any entity declarations on the STRUCTURE statement
6093   const auto &decls{std::get<std::list<parser::EntityDecl>>(structStmt.t)};
6094   if (!decls.empty()) {
6095     BeginDecl();
6096     SetDeclTypeSpec(type);
6097     Walk(decls);
6098     EndDecl();
6099   }
6100   return false;
6101 }
6102 
6103 bool DeclarationVisitor::Pre(const parser::Union::UnionStmt &) {
6104   Say("support for UNION"_todo_en_US); // TODO
6105   return true;
6106 }
6107 
6108 bool DeclarationVisitor::Pre(const parser::StructureField &x) {
6109   if (std::holds_alternative<parser::Statement<parser::DataComponentDefStmt>>(
6110           x.u)) {
6111     BeginDecl();
6112   }
6113   return true;
6114 }
6115 
6116 void DeclarationVisitor::Post(const parser::StructureField &x) {
6117   if (std::holds_alternative<parser::Statement<parser::DataComponentDefStmt>>(
6118           x.u)) {
6119     EndDecl();
6120   }
6121 }
6122 
6123 bool DeclarationVisitor::Pre(const parser::AllocateStmt &) {
6124   BeginDeclTypeSpec();
6125   return true;
6126 }
6127 void DeclarationVisitor::Post(const parser::AllocateStmt &) {
6128   EndDeclTypeSpec();
6129 }
6130 
6131 bool DeclarationVisitor::Pre(const parser::StructureConstructor &x) {
6132   auto &parsedType{std::get<parser::DerivedTypeSpec>(x.t)};
6133   const DeclTypeSpec *type{ProcessTypeSpec(parsedType)};
6134   if (!type) {
6135     return false;
6136   }
6137   const DerivedTypeSpec *spec{type->AsDerived()};
6138   const Scope *typeScope{spec ? spec->scope() : nullptr};
6139   if (!typeScope) {
6140     return false;
6141   }
6142 
6143   // N.B C7102 is implicitly enforced by having inaccessible types not
6144   // being found in resolution.
6145   // More constraints are enforced in expression.cpp so that they
6146   // can apply to structure constructors that have been converted
6147   // from misparsed function references.
6148   for (const auto &component :
6149       std::get<std::list<parser::ComponentSpec>>(x.t)) {
6150     // Visit the component spec expression, but not the keyword, since
6151     // we need to resolve its symbol in the scope of the derived type.
6152     Walk(std::get<parser::ComponentDataSource>(component.t));
6153     if (const auto &kw{std::get<std::optional<parser::Keyword>>(component.t)}) {
6154       FindInTypeOrParents(*typeScope, kw->v);
6155     }
6156   }
6157   return false;
6158 }
6159 
6160 bool DeclarationVisitor::Pre(const parser::BasedPointer &) {
6161   BeginArraySpec();
6162   return true;
6163 }
6164 
6165 void DeclarationVisitor::Post(const parser::BasedPointer &bp) {
6166   const parser::ObjectName &pointerName{std::get<0>(bp.t)};
6167   auto *pointer{FindSymbol(pointerName)};
6168   if (!pointer) {
6169     pointer = &MakeSymbol(pointerName, ObjectEntityDetails{});
6170   } else if (!ConvertToObjectEntity(*pointer)) {
6171     SayWithDecl(pointerName, *pointer, "'%s' is not a variable"_err_en_US);
6172   } else if (IsNamedConstant(*pointer)) {
6173     SayWithDecl(pointerName, *pointer,
6174         "'%s' is a named constant and may not be a Cray pointer"_err_en_US);
6175   } else if (pointer->Rank() > 0) {
6176     SayWithDecl(
6177         pointerName, *pointer, "Cray pointer '%s' must be a scalar"_err_en_US);
6178   } else if (pointer->test(Symbol::Flag::CrayPointee)) {
6179     Say(pointerName,
6180         "'%s' cannot be a Cray pointer as it is already a Cray pointee"_err_en_US);
6181   }
6182   pointer->set(Symbol::Flag::CrayPointer);
6183   const DeclTypeSpec &pointerType{MakeNumericType(
6184       TypeCategory::Integer, context().defaultKinds().subscriptIntegerKind())};
6185   const auto *type{pointer->GetType()};
6186   if (!type) {
6187     pointer->SetType(pointerType);
6188   } else if (*type != pointerType) {
6189     Say(pointerName.source, "Cray pointer '%s' must have type %s"_err_en_US,
6190         pointerName.source, pointerType.AsFortran());
6191   }
6192   const parser::ObjectName &pointeeName{std::get<1>(bp.t)};
6193   DeclareObjectEntity(pointeeName);
6194   if (Symbol * pointee{pointeeName.symbol}) {
6195     if (!ConvertToObjectEntity(*pointee)) {
6196       return;
6197     }
6198     if (IsNamedConstant(*pointee)) {
6199       Say(pointeeName,
6200           "'%s' is a named constant and may not be a Cray pointee"_err_en_US);
6201       return;
6202     }
6203     if (pointee->test(Symbol::Flag::CrayPointer)) {
6204       Say(pointeeName,
6205           "'%s' cannot be a Cray pointee as it is already a Cray pointer"_err_en_US);
6206     } else if (pointee->test(Symbol::Flag::CrayPointee)) {
6207       Say(pointeeName, "'%s' was already declared as a Cray pointee"_err_en_US);
6208     } else {
6209       pointee->set(Symbol::Flag::CrayPointee);
6210     }
6211     if (const auto *pointeeType{pointee->GetType()}) {
6212       if (const auto *derived{pointeeType->AsDerived()}) {
6213         if (!IsSequenceOrBindCType(derived)) {
6214           context().Warn(common::LanguageFeature::NonSequenceCrayPointee,
6215               pointeeName.source,
6216               "Type of Cray pointee '%s' is a derived type that is neither SEQUENCE nor BIND(C)"_warn_en_US,
6217               pointeeName.source);
6218         }
6219       }
6220     }
6221     currScope().add_crayPointer(pointeeName.source, *pointer);
6222   }
6223 }
6224 
6225 bool DeclarationVisitor::Pre(const parser::NamelistStmt::Group &x) {
6226   if (!CheckNotInBlock("NAMELIST")) { // C1107
6227     return false;
6228   }
6229   const auto &groupName{std::get<parser::Name>(x.t)};
6230   auto *groupSymbol{FindInScope(groupName)};
6231   if (!groupSymbol || !groupSymbol->has<NamelistDetails>()) {
6232     groupSymbol = &MakeSymbol(groupName, NamelistDetails{});
6233     groupSymbol->ReplaceName(groupName.source);
6234   }
6235   // Name resolution of group items is deferred to FinishNamelists()
6236   // so that host association is handled correctly.
6237   GetDeferredDeclarationState(true)->namelistGroups.emplace_back(&x);
6238   return false;
6239 }
6240 
6241 void DeclarationVisitor::FinishNamelists() {
6242   if (auto *deferred{GetDeferredDeclarationState()}) {
6243     for (const parser::NamelistStmt::Group *group : deferred->namelistGroups) {
6244       if (auto *groupSymbol{FindInScope(std::get<parser::Name>(group->t))}) {
6245         if (auto *details{groupSymbol->detailsIf<NamelistDetails>()}) {
6246           for (const auto &name : std::get<std::list<parser::Name>>(group->t)) {
6247             auto *symbol{FindSymbol(name)};
6248             if (!symbol) {
6249               symbol = &MakeSymbol(name, ObjectEntityDetails{});
6250               ApplyImplicitRules(*symbol);
6251             } else if (!ConvertToObjectEntity(symbol->GetUltimate())) {
6252               SayWithDecl(name, *symbol, "'%s' is not a variable"_err_en_US);
6253               context().SetError(*groupSymbol);
6254             }
6255             symbol->GetUltimate().set(Symbol::Flag::InNamelist);
6256             details->add_object(*symbol);
6257           }
6258         }
6259       }
6260     }
6261     deferred->namelistGroups.clear();
6262   }
6263 }
6264 
6265 bool DeclarationVisitor::Pre(const parser::IoControlSpec &x) {
6266   if (const auto *name{std::get_if<parser::Name>(&x.u)}) {
6267     auto *symbol{FindSymbol(*name)};
6268     if (!symbol) {
6269       Say(*name, "Namelist group '%s' not found"_err_en_US);
6270     } else if (!symbol->GetUltimate().has<NamelistDetails>()) {
6271       SayWithDecl(
6272           *name, *symbol, "'%s' is not the name of a namelist group"_err_en_US);
6273     }
6274   }
6275   return true;
6276 }
6277 
6278 bool DeclarationVisitor::Pre(const parser::CommonStmt::Block &x) {
6279   CheckNotInBlock("COMMON"); // C1107
6280   return true;
6281 }
6282 
6283 bool DeclarationVisitor::Pre(const parser::CommonBlockObject &) {
6284   BeginArraySpec();
6285   return true;
6286 }
6287 
6288 void DeclarationVisitor::Post(const parser::CommonBlockObject &x) {
6289   const auto &name{std::get<parser::Name>(x.t)};
6290   DeclareObjectEntity(name);
6291   auto pair{specPartState_.commonBlockObjects.insert(name.source)};
6292   if (!pair.second) {
6293     const SourceName &prev{*pair.first};
6294     Say2(name.source, "'%s' is already in a COMMON block"_err_en_US, prev,
6295         "Previous occurrence of '%s' in a COMMON block"_en_US);
6296   }
6297 }
6298 
6299 bool DeclarationVisitor::Pre(const parser::EquivalenceStmt &x) {
6300   // save equivalence sets to be processed after specification part
6301   if (CheckNotInBlock("EQUIVALENCE")) { // C1107
6302     for (const std::list<parser::EquivalenceObject> &set : x.v) {
6303       specPartState_.equivalenceSets.push_back(&set);
6304     }
6305   }
6306   return false; // don't implicitly declare names yet
6307 }
6308 
6309 void DeclarationVisitor::CheckEquivalenceSets() {
6310   EquivalenceSets equivSets{context()};
6311   inEquivalenceStmt_ = true;
6312   for (const auto *set : specPartState_.equivalenceSets) {
6313     const auto &source{set->front().v.value().source};
6314     if (set->size() <= 1) { // R871
6315       Say(source, "Equivalence set must have more than one object"_err_en_US);
6316     }
6317     for (const parser::EquivalenceObject &object : *set) {
6318       const auto &designator{object.v.value()};
6319       // The designator was not resolved when it was encountered, so do it now.
6320       // AnalyzeExpr causes array sections to be changed to substrings as needed
6321       Walk(designator);
6322       if (AnalyzeExpr(context(), designator)) {
6323         equivSets.AddToSet(designator);
6324       }
6325     }
6326     equivSets.FinishSet(source);
6327   }
6328   inEquivalenceStmt_ = false;
6329   for (auto &set : equivSets.sets()) {
6330     if (!set.empty()) {
6331       currScope().add_equivalenceSet(std::move(set));
6332     }
6333   }
6334   specPartState_.equivalenceSets.clear();
6335 }
6336 
6337 bool DeclarationVisitor::Pre(const parser::SaveStmt &x) {
6338   if (x.v.empty()) {
6339     specPartState_.saveInfo.saveAll = currStmtSource();
6340     currScope().set_hasSAVE();
6341   } else {
6342     for (const parser::SavedEntity &y : x.v) {
6343       auto kind{std::get<parser::SavedEntity::Kind>(y.t)};
6344       const auto &name{std::get<parser::Name>(y.t)};
6345       if (kind == parser::SavedEntity::Kind::Common) {
6346         MakeCommonBlockSymbol(name);
6347         AddSaveName(specPartState_.saveInfo.commons, name.source);
6348       } else {
6349         HandleAttributeStmt(Attr::SAVE, name);
6350       }
6351     }
6352   }
6353   return false;
6354 }
6355 
6356 void DeclarationVisitor::CheckSaveStmts() {
6357   for (const SourceName &name : specPartState_.saveInfo.entities) {
6358     auto *symbol{FindInScope(name)};
6359     if (!symbol) {
6360       // error was reported
6361     } else if (specPartState_.saveInfo.saveAll) {
6362       // C889 - note that pgi, ifort, xlf do not enforce this constraint
6363       if (context().ShouldWarn(common::LanguageFeature::RedundantAttribute)) {
6364         Say2(name,
6365             "Explicit SAVE of '%s' is redundant due to global SAVE statement"_warn_en_US,
6366             *specPartState_.saveInfo.saveAll, "Global SAVE statement"_en_US)
6367             .set_languageFeature(common::LanguageFeature::RedundantAttribute);
6368       }
6369     } else if (!IsSaved(*symbol)) {
6370       SetExplicitAttr(*symbol, Attr::SAVE);
6371     }
6372   }
6373   for (const SourceName &name : specPartState_.saveInfo.commons) {
6374     if (auto *symbol{currScope().FindCommonBlock(name)}) {
6375       auto &objects{symbol->get<CommonBlockDetails>().objects()};
6376       if (objects.empty()) {
6377         if (currScope().kind() != Scope::Kind::BlockConstruct) {
6378           Say(name,
6379               "'%s' appears as a COMMON block in a SAVE statement but not in"
6380               " a COMMON statement"_err_en_US);
6381         } else { // C1108
6382           Say(name,
6383               "SAVE statement in BLOCK construct may not contain a"
6384               " common block name '%s'"_err_en_US);
6385         }
6386       } else {
6387         for (auto &object : symbol->get<CommonBlockDetails>().objects()) {
6388           if (!IsSaved(*object)) {
6389             SetImplicitAttr(*object, Attr::SAVE);
6390           }
6391         }
6392       }
6393     }
6394   }
6395   specPartState_.saveInfo = {};
6396 }
6397 
6398 // Record SAVEd names in specPartState_.saveInfo.entities.
6399 Attrs DeclarationVisitor::HandleSaveName(const SourceName &name, Attrs attrs) {
6400   if (attrs.test(Attr::SAVE)) {
6401     AddSaveName(specPartState_.saveInfo.entities, name);
6402   }
6403   return attrs;
6404 }
6405 
6406 // Record a name in a set of those to be saved.
6407 void DeclarationVisitor::AddSaveName(
6408     std::set<SourceName> &set, const SourceName &name) {
6409   auto pair{set.insert(name)};
6410   if (!pair.second &&
6411       context().ShouldWarn(common::LanguageFeature::RedundantAttribute)) {
6412     Say2(name, "SAVE attribute was already specified on '%s'"_warn_en_US,
6413         *pair.first, "Previous specification of SAVE attribute"_en_US)
6414         .set_languageFeature(common::LanguageFeature::RedundantAttribute);
6415   }
6416 }
6417 
6418 // Check types of common block objects, now that they are known.
6419 void DeclarationVisitor::CheckCommonBlocks() {
6420   // check for empty common blocks
6421   for (const auto &pair : currScope().commonBlocks()) {
6422     const auto &symbol{*pair.second};
6423     if (symbol.get<CommonBlockDetails>().objects().empty() &&
6424         symbol.attrs().test(Attr::BIND_C)) {
6425       Say(symbol.name(),
6426           "'%s' appears as a COMMON block in a BIND statement but not in"
6427           " a COMMON statement"_err_en_US);
6428     }
6429   }
6430   // check objects in common blocks
6431   for (const auto &name : specPartState_.commonBlockObjects) {
6432     const auto *symbol{currScope().FindSymbol(name)};
6433     if (!symbol) {
6434       continue;
6435     }
6436     const auto &attrs{symbol->attrs()};
6437     if (attrs.test(Attr::ALLOCATABLE)) {
6438       Say(name,
6439           "ALLOCATABLE object '%s' may not appear in a COMMON block"_err_en_US);
6440     } else if (attrs.test(Attr::BIND_C)) {
6441       Say(name,
6442           "Variable '%s' with BIND attribute may not appear in a COMMON block"_err_en_US);
6443     } else if (IsNamedConstant(*symbol)) {
6444       Say(name,
6445           "A named constant '%s' may not appear in a COMMON block"_err_en_US);
6446     } else if (IsDummy(*symbol)) {
6447       Say(name,
6448           "Dummy argument '%s' may not appear in a COMMON block"_err_en_US);
6449     } else if (symbol->IsFuncResult()) {
6450       Say(name,
6451           "Function result '%s' may not appear in a COMMON block"_err_en_US);
6452     } else if (const DeclTypeSpec * type{symbol->GetType()}) {
6453       if (type->category() == DeclTypeSpec::ClassStar) {
6454         Say(name,
6455             "Unlimited polymorphic pointer '%s' may not appear in a COMMON block"_err_en_US);
6456       } else if (const auto *derived{type->AsDerived()}) {
6457         if (!IsSequenceOrBindCType(derived)) {
6458           Say(name,
6459               "Derived type '%s' in COMMON block must have the BIND or"
6460               " SEQUENCE attribute"_err_en_US);
6461         }
6462         UnorderedSymbolSet typeSet;
6463         CheckCommonBlockDerivedType(name, derived->typeSymbol(), typeSet);
6464       }
6465     }
6466   }
6467   specPartState_.commonBlockObjects = {};
6468 }
6469 
6470 Symbol &DeclarationVisitor::MakeCommonBlockSymbol(const parser::Name &name) {
6471   return Resolve(name, currScope().MakeCommonBlock(name.source));
6472 }
6473 Symbol &DeclarationVisitor::MakeCommonBlockSymbol(
6474     const std::optional<parser::Name> &name) {
6475   if (name) {
6476     return MakeCommonBlockSymbol(*name);
6477   } else {
6478     return MakeCommonBlockSymbol(parser::Name{});
6479   }
6480 }
6481 
6482 bool DeclarationVisitor::NameIsKnownOrIntrinsic(const parser::Name &name) {
6483   return FindSymbol(name) || HandleUnrestrictedSpecificIntrinsicFunction(name);
6484 }
6485 
6486 // Check if this derived type can be in a COMMON block.
6487 void DeclarationVisitor::CheckCommonBlockDerivedType(const SourceName &name,
6488     const Symbol &typeSymbol, UnorderedSymbolSet &typeSet) {
6489   if (auto iter{typeSet.find(SymbolRef{typeSymbol})}; iter != typeSet.end()) {
6490     return;
6491   }
6492   typeSet.emplace(typeSymbol);
6493   if (const auto *scope{typeSymbol.scope()}) {
6494     for (const auto &pair : *scope) {
6495       const Symbol &component{*pair.second};
6496       if (component.attrs().test(Attr::ALLOCATABLE)) {
6497         Say2(name,
6498             "Derived type variable '%s' may not appear in a COMMON block"
6499             " due to ALLOCATABLE component"_err_en_US,
6500             component.name(), "Component with ALLOCATABLE attribute"_en_US);
6501         return;
6502       }
6503       const auto *details{component.detailsIf<ObjectEntityDetails>()};
6504       if (component.test(Symbol::Flag::InDataStmt) ||
6505           (details && details->init())) {
6506         Say2(name,
6507             "Derived type variable '%s' may not appear in a COMMON block due to component with default initialization"_err_en_US,
6508             component.name(), "Component with default initialization"_en_US);
6509         return;
6510       }
6511       if (details) {
6512         if (const auto *type{details->type()}) {
6513           if (const auto *derived{type->AsDerived()}) {
6514             const Symbol &derivedTypeSymbol{derived->typeSymbol()};
6515             CheckCommonBlockDerivedType(name, derivedTypeSymbol, typeSet);
6516           }
6517         }
6518       }
6519     }
6520   }
6521 }
6522 
6523 bool DeclarationVisitor::HandleUnrestrictedSpecificIntrinsicFunction(
6524     const parser::Name &name) {
6525   if (auto interface{context().intrinsics().IsSpecificIntrinsicFunction(
6526           name.source.ToString())}) {
6527     // Unrestricted specific intrinsic function names (e.g., "cos")
6528     // are acceptable as procedure interfaces.  The presence of the
6529     // INTRINSIC flag will cause this symbol to have a complete interface
6530     // recreated for it later on demand, but capturing its result type here
6531     // will make GetType() return a correct result without having to
6532     // probe the intrinsics table again.
6533     Symbol &symbol{MakeSymbol(InclusiveScope(), name.source, Attrs{})};
6534     SetImplicitAttr(symbol, Attr::INTRINSIC);
6535     CHECK(interface->functionResult.has_value());
6536     evaluate::DynamicType dyType{
6537         DEREF(interface->functionResult->GetTypeAndShape()).type()};
6538     CHECK(common::IsNumericTypeCategory(dyType.category()));
6539     const DeclTypeSpec &typeSpec{
6540         MakeNumericType(dyType.category(), dyType.kind())};
6541     ProcEntityDetails details;
6542     details.set_type(typeSpec);
6543     symbol.set_details(std::move(details));
6544     symbol.set(Symbol::Flag::Function);
6545     if (interface->IsElemental()) {
6546       SetExplicitAttr(symbol, Attr::ELEMENTAL);
6547     }
6548     if (interface->IsPure()) {
6549       SetExplicitAttr(symbol, Attr::PURE);
6550     }
6551     Resolve(name, symbol);
6552     return true;
6553   } else {
6554     return false;
6555   }
6556 }
6557 
6558 // Checks for all locality-specs: LOCAL, LOCAL_INIT, and SHARED
6559 bool DeclarationVisitor::PassesSharedLocalityChecks(
6560     const parser::Name &name, Symbol &symbol) {
6561   if (!IsVariableName(symbol)) {
6562     SayLocalMustBeVariable(name, symbol); // C1124
6563     return false;
6564   }
6565   if (symbol.owner() == currScope()) { // C1125 and C1126
6566     SayAlreadyDeclared(name, symbol);
6567     return false;
6568   }
6569   return true;
6570 }
6571 
6572 // Checks for locality-specs LOCAL, LOCAL_INIT, and REDUCE
6573 bool DeclarationVisitor::PassesLocalityChecks(
6574     const parser::Name &name, Symbol &symbol, Symbol::Flag flag) {
6575   bool isReduce{flag == Symbol::Flag::LocalityReduce};
6576   const char *specName{
6577       flag == Symbol::Flag::LocalityLocalInit ? "LOCAL_INIT" : "LOCAL"};
6578   if (IsAllocatable(symbol) && !isReduce) { // F'2023 C1130
6579     SayWithDecl(name, symbol,
6580         "ALLOCATABLE variable '%s' not allowed in a %s locality-spec"_err_en_US,
6581         specName);
6582     return false;
6583   }
6584   if (IsOptional(symbol)) { // F'2023 C1130-C1131
6585     SayWithDecl(name, symbol,
6586         "OPTIONAL argument '%s' not allowed in a locality-spec"_err_en_US);
6587     return false;
6588   }
6589   if (IsIntentIn(symbol)) { // F'2023 C1130-C1131
6590     SayWithDecl(name, symbol,
6591         "INTENT IN argument '%s' not allowed in a locality-spec"_err_en_US);
6592     return false;
6593   }
6594   if (IsFinalizable(symbol) && !isReduce) { // F'2023 C1130
6595     SayWithDecl(name, symbol,
6596         "Finalizable variable '%s' not allowed in a %s locality-spec"_err_en_US,
6597         specName);
6598     return false;
6599   }
6600   if (evaluate::IsCoarray(symbol) && !isReduce) { // F'2023 C1130
6601     SayWithDecl(name, symbol,
6602         "Coarray '%s' not allowed in a %s locality-spec"_err_en_US, specName);
6603     return false;
6604   }
6605   if (const DeclTypeSpec * type{symbol.GetType()}) {
6606     if (type->IsPolymorphic() && IsDummy(symbol) && !IsPointer(symbol) &&
6607         !isReduce) { // F'2023 C1130
6608       SayWithDecl(name, symbol,
6609           "Nonpointer polymorphic argument '%s' not allowed in a %s locality-spec"_err_en_US,
6610           specName);
6611       return false;
6612     }
6613   }
6614   if (symbol.attrs().test(Attr::ASYNCHRONOUS) && isReduce) { // F'2023 C1131
6615     SayWithDecl(name, symbol,
6616         "ASYNCHRONOUS variable '%s' not allowed in a REDUCE locality-spec"_err_en_US);
6617     return false;
6618   }
6619   if (symbol.attrs().test(Attr::VOLATILE) && isReduce) { // F'2023 C1131
6620     SayWithDecl(name, symbol,
6621         "VOLATILE variable '%s' not allowed in a REDUCE locality-spec"_err_en_US);
6622     return false;
6623   }
6624   if (IsAssumedSizeArray(symbol)) { // F'2023 C1130-C1131
6625     SayWithDecl(name, symbol,
6626         "Assumed size array '%s' not allowed in a locality-spec"_err_en_US);
6627     return false;
6628   }
6629   if (std::optional<Message> whyNot{WhyNotDefinable(
6630           name.source, currScope(), DefinabilityFlags{}, symbol)}) {
6631     SayWithReason(name, symbol,
6632         "'%s' may not appear in a locality-spec because it is not definable"_err_en_US,
6633         std::move(whyNot->set_severity(parser::Severity::Because)));
6634     return false;
6635   }
6636   return PassesSharedLocalityChecks(name, symbol);
6637 }
6638 
6639 Symbol &DeclarationVisitor::FindOrDeclareEnclosingEntity(
6640     const parser::Name &name) {
6641   Symbol *prev{FindSymbol(name)};
6642   if (!prev) {
6643     // Declare the name as an object in the enclosing scope so that
6644     // the name can't be repurposed there later as something else.
6645     prev = &MakeSymbol(InclusiveScope(), name.source, Attrs{});
6646     ConvertToObjectEntity(*prev);
6647     ApplyImplicitRules(*prev);
6648   }
6649   return *prev;
6650 }
6651 
6652 void DeclarationVisitor::DeclareLocalEntity(
6653     const parser::Name &name, Symbol::Flag flag) {
6654   Symbol &prev{FindOrDeclareEnclosingEntity(name)};
6655   if (PassesLocalityChecks(name, prev, flag)) {
6656     if (auto *symbol{&MakeHostAssocSymbol(name, prev)}) {
6657       symbol->set(flag);
6658     }
6659   }
6660 }
6661 
6662 Symbol *DeclarationVisitor::DeclareStatementEntity(
6663     const parser::DoVariable &doVar,
6664     const std::optional<parser::IntegerTypeSpec> &type) {
6665   const parser::Name &name{doVar.thing.thing};
6666   const DeclTypeSpec *declTypeSpec{nullptr};
6667   if (auto *prev{FindSymbol(name)}) {
6668     if (prev->owner() == currScope()) {
6669       SayAlreadyDeclared(name, *prev);
6670       return nullptr;
6671     }
6672     name.symbol = nullptr;
6673     // F'2023 19.4 p5 ambiguous rule about outer declarations
6674     declTypeSpec = prev->GetType();
6675   }
6676   Symbol &symbol{DeclareEntity<ObjectEntityDetails>(name, {})};
6677   if (!symbol.has<ObjectEntityDetails>()) {
6678     return nullptr; // error was reported in DeclareEntity
6679   }
6680   if (type) {
6681     declTypeSpec = ProcessTypeSpec(*type);
6682   }
6683   if (declTypeSpec) {
6684     // Subtlety: Don't let a "*length" specifier (if any is pending) affect the
6685     // declaration of this implied DO loop control variable.
6686     auto restorer{
6687         common::ScopedSet(charInfo_.length, std::optional<ParamValue>{})};
6688     SetType(name, *declTypeSpec);
6689   } else {
6690     ApplyImplicitRules(symbol);
6691   }
6692   return Resolve(name, &symbol);
6693 }
6694 
6695 // Set the type of an entity or report an error.
6696 void DeclarationVisitor::SetType(
6697     const parser::Name &name, const DeclTypeSpec &type) {
6698   CHECK(name.symbol);
6699   auto &symbol{*name.symbol};
6700   if (charInfo_.length) { // Declaration has "*length" (R723)
6701     auto length{std::move(*charInfo_.length)};
6702     charInfo_.length.reset();
6703     if (type.category() == DeclTypeSpec::Character) {
6704       auto kind{type.characterTypeSpec().kind()};
6705       // Recurse with correct type.
6706       SetType(name,
6707           currScope().MakeCharacterType(std::move(length), std::move(kind)));
6708       return;
6709     } else { // C753
6710       Say(name,
6711           "A length specifier cannot be used to declare the non-character entity '%s'"_err_en_US);
6712     }
6713   }
6714   if (auto *proc{symbol.detailsIf<ProcEntityDetails>()}) {
6715     if (proc->procInterface()) {
6716       Say(name,
6717           "'%s' has an explicit interface and may not also have a type"_err_en_US);
6718       context().SetError(symbol);
6719       return;
6720     }
6721   }
6722   auto *prevType{symbol.GetType()};
6723   if (!prevType) {
6724     if (symbol.test(Symbol::Flag::InDataStmt) && isImplicitNoneType()) {
6725       context().Warn(common::LanguageFeature::ForwardRefImplicitNoneData,
6726           name.source,
6727           "'%s' appeared in a DATA statement before its type was declared under IMPLICIT NONE(TYPE)"_port_en_US,
6728           name.source);
6729     }
6730     symbol.SetType(type);
6731   } else if (symbol.has<UseDetails>()) {
6732     // error recovery case, redeclaration of use-associated name
6733   } else if (HadForwardRef(symbol)) {
6734     // error recovery after use of host-associated name
6735   } else if (!symbol.test(Symbol::Flag::Implicit)) {
6736     SayWithDecl(
6737         name, symbol, "The type of '%s' has already been declared"_err_en_US);
6738     context().SetError(symbol);
6739   } else if (type != *prevType) {
6740     SayWithDecl(name, symbol,
6741         "The type of '%s' has already been implicitly declared"_err_en_US);
6742     context().SetError(symbol);
6743   } else {
6744     symbol.set(Symbol::Flag::Implicit, false);
6745   }
6746 }
6747 
6748 std::optional<DerivedTypeSpec> DeclarationVisitor::ResolveDerivedType(
6749     const parser::Name &name) {
6750   Scope &outer{NonDerivedTypeScope()};
6751   Symbol *symbol{FindSymbol(outer, name)};
6752   Symbol *ultimate{symbol ? &symbol->GetUltimate() : nullptr};
6753   auto *generic{ultimate ? ultimate->detailsIf<GenericDetails>() : nullptr};
6754   if (generic) {
6755     if (Symbol * genDT{generic->derivedType()}) {
6756       symbol = genDT;
6757       generic = nullptr;
6758     }
6759   }
6760   if (!symbol || symbol->has<UnknownDetails>() ||
6761       (generic && &ultimate->owner() == &outer)) {
6762     if (allowForwardReferenceToDerivedType()) {
6763       if (!symbol) {
6764         symbol = &MakeSymbol(outer, name.source, Attrs{});
6765         Resolve(name, *symbol);
6766       } else if (generic) {
6767         // forward ref to type with later homonymous generic
6768         symbol = &outer.MakeSymbol(name.source, Attrs{}, UnknownDetails{});
6769         generic->set_derivedType(*symbol);
6770         name.symbol = symbol;
6771       }
6772       DerivedTypeDetails details;
6773       details.set_isForwardReferenced(true);
6774       symbol->set_details(std::move(details));
6775     } else { // C732
6776       Say(name, "Derived type '%s' not found"_err_en_US);
6777       return std::nullopt;
6778     }
6779   } else if (&DEREF(symbol).owner() != &outer &&
6780       !ultimate->has<GenericDetails>()) {
6781     // Prevent a later declaration in this scope of a host-associated
6782     // type name.
6783     outer.add_importName(name.source);
6784   }
6785   if (CheckUseError(name)) {
6786     return std::nullopt;
6787   } else if (symbol->GetUltimate().has<DerivedTypeDetails>()) {
6788     return DerivedTypeSpec{name.source, *symbol};
6789   } else {
6790     Say(name, "'%s' is not a derived type"_err_en_US);
6791     return std::nullopt;
6792   }
6793 }
6794 
6795 std::optional<DerivedTypeSpec> DeclarationVisitor::ResolveExtendsType(
6796     const parser::Name &typeName, const parser::Name *extendsName) {
6797   if (extendsName) {
6798     if (typeName.source == extendsName->source) {
6799       Say(extendsName->source,
6800           "Derived type '%s' cannot extend itself"_err_en_US);
6801     } else if (auto dtSpec{ResolveDerivedType(*extendsName)}) {
6802       if (!dtSpec->IsForwardReferenced()) {
6803         return dtSpec;
6804       }
6805       Say(typeName.source,
6806           "Derived type '%s' cannot extend type '%s' that has not yet been defined"_err_en_US,
6807           typeName.source, extendsName->source);
6808     }
6809   }
6810   return std::nullopt;
6811 }
6812 
6813 Symbol *DeclarationVisitor::NoteInterfaceName(const parser::Name &name) {
6814   // The symbol is checked later by CheckExplicitInterface() and
6815   // CheckBindings().  It can be a forward reference.
6816   if (!NameIsKnownOrIntrinsic(name)) {
6817     Symbol &symbol{MakeSymbol(InclusiveScope(), name.source, Attrs{})};
6818     Resolve(name, symbol);
6819   }
6820   return name.symbol;
6821 }
6822 
6823 void DeclarationVisitor::CheckExplicitInterface(const parser::Name &name) {
6824   if (const Symbol * symbol{name.symbol}) {
6825     const Symbol &ultimate{symbol->GetUltimate()};
6826     if (!context().HasError(*symbol) && !context().HasError(ultimate) &&
6827         !BypassGeneric(ultimate).HasExplicitInterface()) {
6828       Say(name,
6829           "'%s' must be an abstract interface or a procedure with an explicit interface"_err_en_US,
6830           symbol->name());
6831     }
6832   }
6833 }
6834 
6835 // Create a symbol for a type parameter, component, or procedure binding in
6836 // the current derived type scope. Return false on error.
6837 Symbol *DeclarationVisitor::MakeTypeSymbol(
6838     const parser::Name &name, Details &&details) {
6839   return Resolve(name, MakeTypeSymbol(name.source, std::move(details)));
6840 }
6841 Symbol *DeclarationVisitor::MakeTypeSymbol(
6842     const SourceName &name, Details &&details) {
6843   Scope &derivedType{currScope()};
6844   CHECK(derivedType.IsDerivedType());
6845   if (auto *symbol{FindInScope(derivedType, name)}) { // C742
6846     Say2(name,
6847         "Type parameter, component, or procedure binding '%s'"
6848         " already defined in this type"_err_en_US,
6849         *symbol, "Previous definition of '%s'"_en_US);
6850     return nullptr;
6851   } else {
6852     auto attrs{GetAttrs()};
6853     // Apply binding-private-stmt if present and this is a procedure binding
6854     if (derivedTypeInfo_.privateBindings &&
6855         !attrs.HasAny({Attr::PUBLIC, Attr::PRIVATE}) &&
6856         std::holds_alternative<ProcBindingDetails>(details)) {
6857       attrs.set(Attr::PRIVATE);
6858     }
6859     Symbol &result{MakeSymbol(name, attrs, std::move(details))};
6860     SetCUDADataAttr(name, result, cudaDataAttr());
6861     return &result;
6862   }
6863 }
6864 
6865 // Return true if it is ok to declare this component in the current scope.
6866 // Otherwise, emit an error and return false.
6867 bool DeclarationVisitor::OkToAddComponent(
6868     const parser::Name &name, const Symbol *extends) {
6869   for (const Scope *scope{&currScope()}; scope;) {
6870     CHECK(scope->IsDerivedType());
6871     if (auto *prev{FindInScope(*scope, name.source)}) {
6872       std::optional<parser::MessageFixedText> msg;
6873       std::optional<common::UsageWarning> warning;
6874       if (context().HasError(*prev)) { // don't pile on
6875       } else if (extends) {
6876         msg = "Type cannot be extended as it has a component named"
6877               " '%s'"_err_en_US;
6878       } else if (CheckAccessibleSymbol(currScope(), *prev)) {
6879         // inaccessible component -- redeclaration is ok
6880         if (context().ShouldWarn(
6881                 common::UsageWarning::RedeclaredInaccessibleComponent)) {
6882           msg =
6883               "Component '%s' is inaccessibly declared in or as a parent of this derived type"_warn_en_US;
6884           warning = common::UsageWarning::RedeclaredInaccessibleComponent;
6885         }
6886       } else if (prev->test(Symbol::Flag::ParentComp)) {
6887         msg =
6888             "'%s' is a parent type of this type and so cannot be a component"_err_en_US;
6889       } else if (scope == &currScope()) {
6890         msg =
6891             "Component '%s' is already declared in this derived type"_err_en_US;
6892       } else {
6893         msg =
6894             "Component '%s' is already declared in a parent of this derived type"_err_en_US;
6895       }
6896       if (msg) {
6897         auto &said{Say2(name, std::move(*msg), *prev,
6898             "Previous declaration of '%s'"_en_US)};
6899         if (msg->severity() == parser::Severity::Error) {
6900           Resolve(name, *prev);
6901           return false;
6902         }
6903         if (warning) {
6904           said.set_usageWarning(*warning);
6905         }
6906       }
6907     }
6908     if (scope == &currScope() && extends) {
6909       // The parent component has not yet been added to the scope.
6910       scope = extends->scope();
6911     } else {
6912       scope = scope->GetDerivedTypeParent();
6913     }
6914   }
6915   return true;
6916 }
6917 
6918 ParamValue DeclarationVisitor::GetParamValue(
6919     const parser::TypeParamValue &x, common::TypeParamAttr attr) {
6920   return common::visit(
6921       common::visitors{
6922           [=](const parser::ScalarIntExpr &x) { // C704
6923             return ParamValue{EvaluateIntExpr(x), attr};
6924           },
6925           [=](const parser::Star &) { return ParamValue::Assumed(attr); },
6926           [=](const parser::TypeParamValue::Deferred &) {
6927             return ParamValue::Deferred(attr);
6928           },
6929       },
6930       x.u);
6931 }
6932 
6933 // ConstructVisitor implementation
6934 
6935 void ConstructVisitor::ResolveIndexName(
6936     const parser::ConcurrentControl &control) {
6937   const parser::Name &name{std::get<parser::Name>(control.t)};
6938   auto *prev{FindSymbol(name)};
6939   if (prev) {
6940     if (prev->owner() == currScope()) {
6941       SayAlreadyDeclared(name, *prev);
6942       return;
6943     } else if (prev->owner().kind() == Scope::Kind::Forall &&
6944         context().ShouldWarn(
6945             common::LanguageFeature::OddIndexVariableRestrictions)) {
6946       SayWithDecl(name, *prev,
6947           "Index variable '%s' should not also be an index in an enclosing FORALL or DO CONCURRENT"_port_en_US)
6948           .set_languageFeature(
6949               common::LanguageFeature::OddIndexVariableRestrictions);
6950     }
6951     name.symbol = nullptr;
6952   }
6953   auto &symbol{DeclareObjectEntity(name)};
6954   if (symbol.GetType()) {
6955     // type came from explicit type-spec
6956   } else if (!prev) {
6957     ApplyImplicitRules(symbol);
6958   } else {
6959     // Odd rules in F'2023 19.4 paras 6 & 8.
6960     Symbol &prevRoot{prev->GetUltimate()};
6961     if (const auto *type{prevRoot.GetType()}) {
6962       symbol.SetType(*type);
6963     } else {
6964       ApplyImplicitRules(symbol);
6965     }
6966     if (prevRoot.has<ObjectEntityDetails>() ||
6967         ConvertToObjectEntity(prevRoot)) {
6968       if (prevRoot.IsObjectArray() &&
6969           context().ShouldWarn(
6970               common::LanguageFeature::OddIndexVariableRestrictions)) {
6971         SayWithDecl(name, *prev,
6972             "Index variable '%s' should be scalar in the enclosing scope"_port_en_US)
6973             .set_languageFeature(
6974                 common::LanguageFeature::OddIndexVariableRestrictions);
6975       }
6976     } else if (!prevRoot.has<CommonBlockDetails>() &&
6977         context().ShouldWarn(
6978             common::LanguageFeature::OddIndexVariableRestrictions)) {
6979       SayWithDecl(name, *prev,
6980           "Index variable '%s' should be a scalar object or common block if it is present in the enclosing scope"_port_en_US)
6981           .set_languageFeature(
6982               common::LanguageFeature::OddIndexVariableRestrictions);
6983     }
6984   }
6985   EvaluateExpr(parser::Scalar{parser::Integer{common::Clone(name)}});
6986 }
6987 
6988 // We need to make sure that all of the index-names get declared before the
6989 // expressions in the loop control are evaluated so that references to the
6990 // index-names in the expressions are correctly detected.
6991 bool ConstructVisitor::Pre(const parser::ConcurrentHeader &header) {
6992   BeginDeclTypeSpec();
6993   Walk(std::get<std::optional<parser::IntegerTypeSpec>>(header.t));
6994   const auto &controls{
6995       std::get<std::list<parser::ConcurrentControl>>(header.t)};
6996   for (const auto &control : controls) {
6997     ResolveIndexName(control);
6998   }
6999   Walk(controls);
7000   Walk(std::get<std::optional<parser::ScalarLogicalExpr>>(header.t));
7001   EndDeclTypeSpec();
7002   return false;
7003 }
7004 
7005 bool ConstructVisitor::Pre(const parser::LocalitySpec::Local &x) {
7006   for (auto &name : x.v) {
7007     DeclareLocalEntity(name, Symbol::Flag::LocalityLocal);
7008   }
7009   return false;
7010 }
7011 
7012 bool ConstructVisitor::Pre(const parser::LocalitySpec::LocalInit &x) {
7013   for (auto &name : x.v) {
7014     DeclareLocalEntity(name, Symbol::Flag::LocalityLocalInit);
7015   }
7016   return false;
7017 }
7018 
7019 bool ConstructVisitor::Pre(const parser::LocalitySpec::Reduce &x) {
7020   for (const auto &name : std::get<std::list<parser::Name>>(x.t)) {
7021     DeclareLocalEntity(name, Symbol::Flag::LocalityReduce);
7022   }
7023   return false;
7024 }
7025 
7026 bool ConstructVisitor::Pre(const parser::LocalitySpec::Shared &x) {
7027   for (const auto &name : x.v) {
7028     if (!FindSymbol(name)) {
7029       context().Warn(common::UsageWarning::ImplicitShared, name.source,
7030           "Variable '%s' with SHARED locality implicitly declared"_warn_en_US,
7031           name.source);
7032     }
7033     Symbol &prev{FindOrDeclareEnclosingEntity(name)};
7034     if (PassesSharedLocalityChecks(name, prev)) {
7035       MakeHostAssocSymbol(name, prev).set(Symbol::Flag::LocalityShared);
7036     }
7037   }
7038   return false;
7039 }
7040 
7041 bool ConstructVisitor::Pre(const parser::AcSpec &x) {
7042   ProcessTypeSpec(x.type);
7043   Walk(x.values);
7044   return false;
7045 }
7046 
7047 // Section 19.4, paragraph 5 says that each ac-do-variable has the scope of the
7048 // enclosing ac-implied-do
7049 bool ConstructVisitor::Pre(const parser::AcImpliedDo &x) {
7050   auto &values{std::get<std::list<parser::AcValue>>(x.t)};
7051   auto &control{std::get<parser::AcImpliedDoControl>(x.t)};
7052   auto &type{std::get<std::optional<parser::IntegerTypeSpec>>(control.t)};
7053   auto &bounds{std::get<parser::AcImpliedDoControl::Bounds>(control.t)};
7054   // F'2018 has the scope of the implied DO variable covering the entire
7055   // implied DO production (19.4(5)), which seems wrong in cases where the name
7056   // of the implied DO variable appears in one of the bound expressions. Thus
7057   // this extension, which shrinks the scope of the variable to exclude the
7058   // expressions in the bounds.
7059   auto restore{BeginCheckOnIndexUseInOwnBounds(bounds.name)};
7060   Walk(bounds.lower);
7061   Walk(bounds.upper);
7062   Walk(bounds.step);
7063   EndCheckOnIndexUseInOwnBounds(restore);
7064   PushScope(Scope::Kind::ImpliedDos, nullptr);
7065   DeclareStatementEntity(bounds.name, type);
7066   Walk(values);
7067   PopScope();
7068   return false;
7069 }
7070 
7071 bool ConstructVisitor::Pre(const parser::DataImpliedDo &x) {
7072   auto &objects{std::get<std::list<parser::DataIDoObject>>(x.t)};
7073   auto &type{std::get<std::optional<parser::IntegerTypeSpec>>(x.t)};
7074   auto &bounds{std::get<parser::DataImpliedDo::Bounds>(x.t)};
7075   // See comment in Pre(AcImpliedDo) above.
7076   auto restore{BeginCheckOnIndexUseInOwnBounds(bounds.name)};
7077   Walk(bounds.lower);
7078   Walk(bounds.upper);
7079   Walk(bounds.step);
7080   EndCheckOnIndexUseInOwnBounds(restore);
7081   bool pushScope{currScope().kind() != Scope::Kind::ImpliedDos};
7082   if (pushScope) {
7083     PushScope(Scope::Kind::ImpliedDos, nullptr);
7084   }
7085   DeclareStatementEntity(bounds.name, type);
7086   Walk(objects);
7087   if (pushScope) {
7088     PopScope();
7089   }
7090   return false;
7091 }
7092 
7093 // Sets InDataStmt flag on a variable (or misidentified function) in a DATA
7094 // statement so that the predicate IsInitialized() will be true
7095 // during semantic analysis before the symbol's initializer is constructed.
7096 bool ConstructVisitor::Pre(const parser::DataIDoObject &x) {
7097   common::visit(
7098       common::visitors{
7099           [&](const parser::Scalar<Indirection<parser::Designator>> &y) {
7100             Walk(y.thing.value());
7101             const parser::Name &first{parser::GetFirstName(y.thing.value())};
7102             if (first.symbol) {
7103               first.symbol->set(Symbol::Flag::InDataStmt);
7104             }
7105           },
7106           [&](const Indirection<parser::DataImpliedDo> &y) { Walk(y.value()); },
7107       },
7108       x.u);
7109   return false;
7110 }
7111 
7112 bool ConstructVisitor::Pre(const parser::DataStmtObject &x) {
7113   // Subtle: DATA statements may appear in both the specification and
7114   // execution parts, but should be treated as if in the execution part
7115   // for purposes of implicit variable declaration vs. host association.
7116   // When a name first appears as an object in a DATA statement, it should
7117   // be implicitly declared locally as if it had been assigned.
7118   auto flagRestorer{common::ScopedSet(inSpecificationPart_, false)};
7119   common::visit(
7120       common::visitors{
7121           [&](const Indirection<parser::Variable> &y) {
7122             auto restorer{common::ScopedSet(deferImplicitTyping_, true)};
7123             Walk(y.value());
7124             const parser::Name &first{parser::GetFirstName(y.value())};
7125             if (first.symbol) {
7126               first.symbol->set(Symbol::Flag::InDataStmt);
7127             }
7128           },
7129           [&](const parser::DataImpliedDo &y) {
7130             PushScope(Scope::Kind::ImpliedDos, nullptr);
7131             Walk(y);
7132             PopScope();
7133           },
7134       },
7135       x.u);
7136   return false;
7137 }
7138 
7139 bool ConstructVisitor::Pre(const parser::DataStmtValue &x) {
7140   const auto &data{std::get<parser::DataStmtConstant>(x.t)};
7141   auto &mutableData{const_cast<parser::DataStmtConstant &>(data)};
7142   if (auto *elem{parser::Unwrap<parser::ArrayElement>(mutableData)}) {
7143     if (const auto *name{std::get_if<parser::Name>(&elem->base.u)}) {
7144       if (const Symbol * symbol{FindSymbol(*name)};
7145           symbol && symbol->GetUltimate().has<DerivedTypeDetails>()) {
7146         mutableData.u = elem->ConvertToStructureConstructor(
7147             DerivedTypeSpec{name->source, *symbol});
7148       }
7149     }
7150   }
7151   return true;
7152 }
7153 
7154 bool ConstructVisitor::Pre(const parser::DoConstruct &x) {
7155   if (x.IsDoConcurrent()) {
7156     // The new scope has Kind::Forall for index variable name conflict
7157     // detection with nested FORALL/DO CONCURRENT constructs in
7158     // ResolveIndexName().
7159     PushScope(Scope::Kind::Forall, nullptr);
7160   }
7161   return true;
7162 }
7163 void ConstructVisitor::Post(const parser::DoConstruct &x) {
7164   if (x.IsDoConcurrent()) {
7165     PopScope();
7166   }
7167 }
7168 
7169 bool ConstructVisitor::Pre(const parser::ForallConstruct &) {
7170   PushScope(Scope::Kind::Forall, nullptr);
7171   return true;
7172 }
7173 void ConstructVisitor::Post(const parser::ForallConstruct &) { PopScope(); }
7174 bool ConstructVisitor::Pre(const parser::ForallStmt &) {
7175   PushScope(Scope::Kind::Forall, nullptr);
7176   return true;
7177 }
7178 void ConstructVisitor::Post(const parser::ForallStmt &) { PopScope(); }
7179 
7180 bool ConstructVisitor::Pre(const parser::BlockConstruct &x) {
7181   const auto &[blockStmt, specPart, execPart, endBlockStmt] = x.t;
7182   Walk(blockStmt);
7183   CheckDef(blockStmt.statement.v);
7184   PushScope(Scope::Kind::BlockConstruct, nullptr);
7185   Walk(specPart);
7186   HandleImpliedAsynchronousInScope(execPart);
7187   Walk(execPart);
7188   Walk(endBlockStmt);
7189   PopScope();
7190   CheckRef(endBlockStmt.statement.v);
7191   return false;
7192 }
7193 
7194 void ConstructVisitor::Post(const parser::Selector &x) {
7195   GetCurrentAssociation().selector = ResolveSelector(x);
7196 }
7197 
7198 void ConstructVisitor::Post(const parser::AssociateStmt &x) {
7199   CheckDef(x.t);
7200   PushScope(Scope::Kind::OtherConstruct, nullptr);
7201   const auto assocCount{std::get<std::list<parser::Association>>(x.t).size()};
7202   for (auto nthLastAssoc{assocCount}; nthLastAssoc > 0; --nthLastAssoc) {
7203     SetCurrentAssociation(nthLastAssoc);
7204     if (auto *symbol{MakeAssocEntity()}) {
7205       const MaybeExpr &expr{GetCurrentAssociation().selector.expr};
7206       if (ExtractCoarrayRef(expr)) { // C1103
7207         Say("Selector must not be a coindexed object"_err_en_US);
7208       }
7209       if (evaluate::IsAssumedRank(expr)) {
7210         Say("Selector must not be assumed-rank"_err_en_US);
7211       }
7212       SetTypeFromAssociation(*symbol);
7213       SetAttrsFromAssociation(*symbol);
7214     }
7215   }
7216   PopAssociation(assocCount);
7217 }
7218 
7219 void ConstructVisitor::Post(const parser::EndAssociateStmt &x) {
7220   PopScope();
7221   CheckRef(x.v);
7222 }
7223 
7224 bool ConstructVisitor::Pre(const parser::Association &x) {
7225   PushAssociation();
7226   const auto &name{std::get<parser::Name>(x.t)};
7227   GetCurrentAssociation().name = &name;
7228   return true;
7229 }
7230 
7231 bool ConstructVisitor::Pre(const parser::ChangeTeamStmt &x) {
7232   CheckDef(x.t);
7233   PushScope(Scope::Kind::OtherConstruct, nullptr);
7234   PushAssociation();
7235   return true;
7236 }
7237 
7238 void ConstructVisitor::Post(const parser::CoarrayAssociation &x) {
7239   const auto &decl{std::get<parser::CodimensionDecl>(x.t)};
7240   const auto &name{std::get<parser::Name>(decl.t)};
7241   if (auto *symbol{FindInScope(name)}) {
7242     const auto &selector{std::get<parser::Selector>(x.t)};
7243     if (auto sel{ResolveSelector(selector)}) {
7244       const Symbol *whole{UnwrapWholeSymbolDataRef(sel.expr)};
7245       if (!whole || whole->Corank() == 0) {
7246         Say(sel.source, // C1116
7247             "Selector in coarray association must name a coarray"_err_en_US);
7248       } else if (auto dynType{sel.expr->GetType()}) {
7249         if (!symbol->GetType()) {
7250           symbol->SetType(ToDeclTypeSpec(std::move(*dynType)));
7251         }
7252       }
7253     }
7254   }
7255 }
7256 
7257 void ConstructVisitor::Post(const parser::EndChangeTeamStmt &x) {
7258   PopAssociation();
7259   PopScope();
7260   CheckRef(x.t);
7261 }
7262 
7263 bool ConstructVisitor::Pre(const parser::SelectTypeConstruct &) {
7264   PushAssociation();
7265   return true;
7266 }
7267 
7268 void ConstructVisitor::Post(const parser::SelectTypeConstruct &) {
7269   PopAssociation();
7270 }
7271 
7272 void ConstructVisitor::Post(const parser::SelectTypeStmt &x) {
7273   auto &association{GetCurrentAssociation()};
7274   if (const std::optional<parser::Name> &name{std::get<1>(x.t)}) {
7275     // This isn't a name in the current scope, it is in each TypeGuardStmt
7276     MakePlaceholder(*name, MiscDetails::Kind::SelectTypeAssociateName);
7277     association.name = &*name;
7278     if (ExtractCoarrayRef(association.selector.expr)) { // C1103
7279       Say("Selector must not be a coindexed object"_err_en_US);
7280     }
7281     if (association.selector.expr) {
7282       auto exprType{association.selector.expr->GetType()};
7283       if (exprType && !exprType->IsPolymorphic()) { // C1159
7284         Say(association.selector.source,
7285             "Selector '%s' in SELECT TYPE statement must be "
7286             "polymorphic"_err_en_US);
7287       }
7288     }
7289   } else {
7290     if (const Symbol *
7291         whole{UnwrapWholeSymbolDataRef(association.selector.expr)}) {
7292       ConvertToObjectEntity(const_cast<Symbol &>(*whole));
7293       if (!IsVariableName(*whole)) {
7294         Say(association.selector.source, // C901
7295             "Selector is not a variable"_err_en_US);
7296         association = {};
7297       }
7298       if (const DeclTypeSpec * type{whole->GetType()}) {
7299         if (!type->IsPolymorphic()) { // C1159
7300           Say(association.selector.source,
7301               "Selector '%s' in SELECT TYPE statement must be "
7302               "polymorphic"_err_en_US);
7303         }
7304       }
7305     } else {
7306       Say(association.selector.source, // C1157
7307           "Selector is not a named variable: 'associate-name =>' is required"_err_en_US);
7308       association = {};
7309     }
7310   }
7311 }
7312 
7313 void ConstructVisitor::Post(const parser::SelectRankStmt &x) {
7314   auto &association{GetCurrentAssociation()};
7315   if (const std::optional<parser::Name> &name{std::get<1>(x.t)}) {
7316     // This isn't a name in the current scope, it is in each SelectRankCaseStmt
7317     MakePlaceholder(*name, MiscDetails::Kind::SelectRankAssociateName);
7318     association.name = &*name;
7319   }
7320 }
7321 
7322 bool ConstructVisitor::Pre(const parser::SelectTypeConstruct::TypeCase &) {
7323   PushScope(Scope::Kind::OtherConstruct, nullptr);
7324   return true;
7325 }
7326 void ConstructVisitor::Post(const parser::SelectTypeConstruct::TypeCase &) {
7327   PopScope();
7328 }
7329 
7330 bool ConstructVisitor::Pre(const parser::SelectRankConstruct::RankCase &) {
7331   PushScope(Scope::Kind::OtherConstruct, nullptr);
7332   return true;
7333 }
7334 void ConstructVisitor::Post(const parser::SelectRankConstruct::RankCase &) {
7335   PopScope();
7336 }
7337 
7338 bool ConstructVisitor::Pre(const parser::TypeGuardStmt::Guard &x) {
7339   if (std::holds_alternative<parser::DerivedTypeSpec>(x.u)) {
7340     // CLASS IS (t)
7341     SetDeclTypeSpecCategory(DeclTypeSpec::Category::ClassDerived);
7342   }
7343   return true;
7344 }
7345 
7346 void ConstructVisitor::Post(const parser::TypeGuardStmt::Guard &x) {
7347   if (auto *symbol{MakeAssocEntity()}) {
7348     if (std::holds_alternative<parser::Default>(x.u)) {
7349       SetTypeFromAssociation(*symbol);
7350     } else if (const auto *type{GetDeclTypeSpec()}) {
7351       symbol->SetType(*type);
7352     }
7353     SetAttrsFromAssociation(*symbol);
7354   }
7355 }
7356 
7357 void ConstructVisitor::Post(const parser::SelectRankCaseStmt::Rank &x) {
7358   if (auto *symbol{MakeAssocEntity()}) {
7359     SetTypeFromAssociation(*symbol);
7360     auto &details{symbol->get<AssocEntityDetails>()};
7361     // Don't call SetAttrsFromAssociation() for SELECT RANK.
7362     Attrs selectorAttrs{
7363         evaluate::GetAttrs(GetCurrentAssociation().selector.expr)};
7364     Attrs attrsToKeep{Attr::ASYNCHRONOUS, Attr::TARGET, Attr::VOLATILE};
7365     if (const auto *rankValue{
7366             std::get_if<parser::ScalarIntConstantExpr>(&x.u)}) {
7367       // RANK(n)
7368       if (auto expr{EvaluateIntExpr(*rankValue)}) {
7369         if (auto val{evaluate::ToInt64(*expr)}) {
7370           details.set_rank(*val);
7371           attrsToKeep |= Attrs{Attr::ALLOCATABLE, Attr::POINTER};
7372         } else {
7373           Say("RANK() expression must be constant"_err_en_US);
7374         }
7375       }
7376     } else if (std::holds_alternative<parser::Star>(x.u)) {
7377       // RANK(*): assumed-size
7378       details.set_IsAssumedSize();
7379     } else {
7380       CHECK(std::holds_alternative<parser::Default>(x.u));
7381       // RANK DEFAULT: assumed-rank
7382       details.set_IsAssumedRank();
7383       attrsToKeep |= Attrs{Attr::ALLOCATABLE, Attr::POINTER};
7384     }
7385     symbol->attrs() |= selectorAttrs & attrsToKeep;
7386   }
7387 }
7388 
7389 bool ConstructVisitor::Pre(const parser::SelectRankConstruct &) {
7390   PushAssociation();
7391   return true;
7392 }
7393 
7394 void ConstructVisitor::Post(const parser::SelectRankConstruct &) {
7395   PopAssociation();
7396 }
7397 
7398 bool ConstructVisitor::CheckDef(const std::optional<parser::Name> &x) {
7399   if (x && !x->symbol) {
7400     // Construct names are not scoped by BLOCK in the standard, but many,
7401     // but not all, compilers do treat them as if they were so scoped.
7402     if (Symbol * inner{FindInScope(currScope(), *x)}) {
7403       SayAlreadyDeclared(*x, *inner);
7404     } else {
7405       if (context().ShouldWarn(common::LanguageFeature::BenignNameClash)) {
7406         if (Symbol *
7407             other{FindInScopeOrBlockConstructs(InclusiveScope(), x->source)}) {
7408           SayWithDecl(*x, *other,
7409               "The construct name '%s' should be distinct at the subprogram level"_port_en_US)
7410               .set_languageFeature(common::LanguageFeature::BenignNameClash);
7411         }
7412       }
7413       MakeSymbol(*x, MiscDetails{MiscDetails::Kind::ConstructName});
7414     }
7415   }
7416   return true;
7417 }
7418 
7419 void ConstructVisitor::CheckRef(const std::optional<parser::Name> &x) {
7420   if (x) {
7421     // Just add an occurrence of this name; checking is done in ValidateLabels
7422     FindSymbol(*x);
7423   }
7424 }
7425 
7426 // Make a symbol for the associating entity of the current association.
7427 Symbol *ConstructVisitor::MakeAssocEntity() {
7428   Symbol *symbol{nullptr};
7429   auto &association{GetCurrentAssociation()};
7430   if (association.name) {
7431     symbol = &MakeSymbol(*association.name, UnknownDetails{});
7432     if (symbol->has<AssocEntityDetails>() && symbol->owner() == currScope()) {
7433       Say(*association.name, // C1102
7434           "The associate name '%s' is already used in this associate statement"_err_en_US);
7435       return nullptr;
7436     }
7437   } else if (const Symbol *
7438       whole{UnwrapWholeSymbolDataRef(association.selector.expr)}) {
7439     symbol = &MakeSymbol(whole->name());
7440   } else {
7441     return nullptr;
7442   }
7443   if (auto &expr{association.selector.expr}) {
7444     symbol->set_details(AssocEntityDetails{common::Clone(*expr)});
7445   } else {
7446     symbol->set_details(AssocEntityDetails{});
7447   }
7448   return symbol;
7449 }
7450 
7451 // Set the type of symbol based on the current association selector.
7452 void ConstructVisitor::SetTypeFromAssociation(Symbol &symbol) {
7453   auto &details{symbol.get<AssocEntityDetails>()};
7454   const MaybeExpr *pexpr{&details.expr()};
7455   if (!*pexpr) {
7456     pexpr = &GetCurrentAssociation().selector.expr;
7457   }
7458   if (*pexpr) {
7459     const SomeExpr &expr{**pexpr};
7460     if (std::optional<evaluate::DynamicType> type{expr.GetType()}) {
7461       if (const auto *charExpr{
7462               evaluate::UnwrapExpr<evaluate::Expr<evaluate::SomeCharacter>>(
7463                   expr)}) {
7464         symbol.SetType(ToDeclTypeSpec(std::move(*type),
7465             FoldExpr(common::visit(
7466                 [](const auto &kindChar) { return kindChar.LEN(); },
7467                 charExpr->u))));
7468       } else {
7469         symbol.SetType(ToDeclTypeSpec(std::move(*type)));
7470       }
7471     } else {
7472       // BOZ literals, procedure designators, &c. are not acceptable
7473       Say(symbol.name(), "Associate name '%s' must have a type"_err_en_US);
7474     }
7475   }
7476 }
7477 
7478 // If current selector is a variable, set some of its attributes on symbol.
7479 // For ASSOCIATE, CHANGE TEAM, and SELECT TYPE only; not SELECT RANK.
7480 void ConstructVisitor::SetAttrsFromAssociation(Symbol &symbol) {
7481   Attrs attrs{evaluate::GetAttrs(GetCurrentAssociation().selector.expr)};
7482   symbol.attrs() |=
7483       attrs & Attrs{Attr::TARGET, Attr::ASYNCHRONOUS, Attr::VOLATILE};
7484   if (attrs.test(Attr::POINTER)) {
7485     SetImplicitAttr(symbol, Attr::TARGET);
7486   }
7487 }
7488 
7489 ConstructVisitor::Selector ConstructVisitor::ResolveSelector(
7490     const parser::Selector &x) {
7491   return common::visit(common::visitors{
7492                            [&](const parser::Expr &expr) {
7493                              return Selector{expr.source, EvaluateExpr(x)};
7494                            },
7495                            [&](const parser::Variable &var) {
7496                              return Selector{var.GetSource(), EvaluateExpr(x)};
7497                            },
7498                        },
7499       x.u);
7500 }
7501 
7502 // Set the current association to the nth to the last association on the
7503 // association stack.  The top of the stack is at n = 1.  This allows access
7504 // to the interior of a list of associations at the top of the stack.
7505 void ConstructVisitor::SetCurrentAssociation(std::size_t n) {
7506   CHECK(n > 0 && n <= associationStack_.size());
7507   currentAssociation_ = &associationStack_[associationStack_.size() - n];
7508 }
7509 
7510 ConstructVisitor::Association &ConstructVisitor::GetCurrentAssociation() {
7511   CHECK(currentAssociation_);
7512   return *currentAssociation_;
7513 }
7514 
7515 void ConstructVisitor::PushAssociation() {
7516   associationStack_.emplace_back(Association{});
7517   currentAssociation_ = &associationStack_.back();
7518 }
7519 
7520 void ConstructVisitor::PopAssociation(std::size_t count) {
7521   CHECK(count > 0 && count <= associationStack_.size());
7522   associationStack_.resize(associationStack_.size() - count);
7523   currentAssociation_ =
7524       associationStack_.empty() ? nullptr : &associationStack_.back();
7525 }
7526 
7527 const DeclTypeSpec &ConstructVisitor::ToDeclTypeSpec(
7528     evaluate::DynamicType &&type) {
7529   switch (type.category()) {
7530     SWITCH_COVERS_ALL_CASES
7531   case common::TypeCategory::Integer:
7532   case common::TypeCategory::Real:
7533   case common::TypeCategory::Complex:
7534     return context().MakeNumericType(type.category(), type.kind());
7535   case common::TypeCategory::Logical:
7536     return context().MakeLogicalType(type.kind());
7537   case common::TypeCategory::Derived:
7538     if (type.IsAssumedType()) {
7539       return currScope().MakeTypeStarType();
7540     } else if (type.IsUnlimitedPolymorphic()) {
7541       return currScope().MakeClassStarType();
7542     } else {
7543       return currScope().MakeDerivedType(
7544           type.IsPolymorphic() ? DeclTypeSpec::ClassDerived
7545                                : DeclTypeSpec::TypeDerived,
7546           common::Clone(type.GetDerivedTypeSpec())
7547 
7548       );
7549     }
7550   case common::TypeCategory::Character:
7551     CRASH_NO_CASE;
7552   }
7553 }
7554 
7555 const DeclTypeSpec &ConstructVisitor::ToDeclTypeSpec(
7556     evaluate::DynamicType &&type, MaybeSubscriptIntExpr &&length) {
7557   CHECK(type.category() == common::TypeCategory::Character);
7558   if (length) {
7559     return currScope().MakeCharacterType(
7560         ParamValue{SomeIntExpr{*std::move(length)}, common::TypeParamAttr::Len},
7561         KindExpr{type.kind()});
7562   } else {
7563     return currScope().MakeCharacterType(
7564         ParamValue::Deferred(common::TypeParamAttr::Len),
7565         KindExpr{type.kind()});
7566   }
7567 }
7568 
7569 class ExecutionPartSkimmerBase {
7570 public:
7571   template <typename A> bool Pre(const A &) { return true; }
7572   template <typename A> void Post(const A &) {}
7573 
7574   bool InNestedBlockConstruct() const { return blockDepth_ > 0; }
7575 
7576   bool Pre(const parser::AssociateConstruct &) {
7577     PushScope();
7578     return true;
7579   }
7580   void Post(const parser::AssociateConstruct &) { PopScope(); }
7581   bool Pre(const parser::Association &x) {
7582     Hide(std::get<parser::Name>(x.t));
7583     return true;
7584   }
7585   bool Pre(const parser::BlockConstruct &) {
7586     PushScope();
7587     ++blockDepth_;
7588     return true;
7589   }
7590   void Post(const parser::BlockConstruct &) {
7591     --blockDepth_;
7592     PopScope();
7593   }
7594   bool Pre(const parser::EntityDecl &x) {
7595     Hide(std::get<parser::ObjectName>(x.t));
7596     return true;
7597   }
7598   void Post(const parser::ImportStmt &x) {
7599     if (x.kind == common::ImportKind::None ||
7600         x.kind == common::ImportKind::Only) {
7601       if (!nestedScopes_.front().importOnly.has_value()) {
7602         nestedScopes_.front().importOnly.emplace();
7603       }
7604       for (const auto &name : x.names) {
7605         nestedScopes_.front().importOnly->emplace(name.source);
7606       }
7607     } else {
7608       // no special handling needed for explicit names or IMPORT, ALL
7609     }
7610   }
7611   void Post(const parser::UseStmt &x) {
7612     if (const auto *onlyList{std::get_if<std::list<parser::Only>>(&x.u)}) {
7613       for (const auto &only : *onlyList) {
7614         if (const auto *name{std::get_if<parser::Name>(&only.u)}) {
7615           Hide(*name);
7616         } else if (const auto *rename{std::get_if<parser::Rename>(&only.u)}) {
7617           if (const auto *names{
7618                   std::get_if<parser::Rename::Names>(&rename->u)}) {
7619             Hide(std::get<0>(names->t));
7620           }
7621         }
7622       }
7623     } else {
7624       // USE may or may not shadow symbols in host scopes
7625       nestedScopes_.front().hasUseWithoutOnly = true;
7626     }
7627   }
7628   bool Pre(const parser::DerivedTypeStmt &x) {
7629     Hide(std::get<parser::Name>(x.t));
7630     PushScope();
7631     return true;
7632   }
7633   void Post(const parser::DerivedTypeDef &) { PopScope(); }
7634   bool Pre(const parser::SelectTypeConstruct &) {
7635     PushScope();
7636     return true;
7637   }
7638   void Post(const parser::SelectTypeConstruct &) { PopScope(); }
7639   bool Pre(const parser::SelectTypeStmt &x) {
7640     if (const auto &maybeName{std::get<1>(x.t)}) {
7641       Hide(*maybeName);
7642     }
7643     return true;
7644   }
7645   bool Pre(const parser::SelectRankConstruct &) {
7646     PushScope();
7647     return true;
7648   }
7649   void Post(const parser::SelectRankConstruct &) { PopScope(); }
7650   bool Pre(const parser::SelectRankStmt &x) {
7651     if (const auto &maybeName{std::get<1>(x.t)}) {
7652       Hide(*maybeName);
7653     }
7654     return true;
7655   }
7656 
7657 protected:
7658   bool IsHidden(SourceName name) {
7659     for (const auto &scope : nestedScopes_) {
7660       if (scope.locals.find(name) != scope.locals.end()) {
7661         return true; // shadowed by nested declaration
7662       }
7663       if (scope.hasUseWithoutOnly) {
7664         break;
7665       }
7666       if (scope.importOnly &&
7667           scope.importOnly->find(name) == scope.importOnly->end()) {
7668         return true; // not imported
7669       }
7670     }
7671     return false;
7672   }
7673 
7674   void EndWalk() { CHECK(nestedScopes_.empty()); }
7675 
7676 private:
7677   void PushScope() { nestedScopes_.emplace_front(); }
7678   void PopScope() { nestedScopes_.pop_front(); }
7679   void Hide(const parser::Name &name) {
7680     nestedScopes_.front().locals.emplace(name.source);
7681   }
7682 
7683   int blockDepth_{0};
7684   struct NestedScopeInfo {
7685     bool hasUseWithoutOnly{false};
7686     std::set<SourceName> locals;
7687     std::optional<std::set<SourceName>> importOnly;
7688   };
7689   std::list<NestedScopeInfo> nestedScopes_;
7690 };
7691 
7692 class ExecutionPartAsyncIOSkimmer : public ExecutionPartSkimmerBase {
7693 public:
7694   explicit ExecutionPartAsyncIOSkimmer(SemanticsContext &context)
7695       : context_{context} {}
7696 
7697   void Walk(const parser::Block &block) {
7698     parser::Walk(block, *this);
7699     EndWalk();
7700   }
7701 
7702   const std::set<SourceName> asyncIONames() const { return asyncIONames_; }
7703 
7704   using ExecutionPartSkimmerBase::Post;
7705   using ExecutionPartSkimmerBase::Pre;
7706 
7707   bool Pre(const parser::IoControlSpec::Asynchronous &async) {
7708     if (auto folded{evaluate::Fold(
7709             context_.foldingContext(), AnalyzeExpr(context_, async.v))}) {
7710       if (auto str{
7711               evaluate::GetScalarConstantValue<evaluate::Ascii>(*folded)}) {
7712         for (char ch : *str) {
7713           if (ch != ' ') {
7714             inAsyncIO_ = ch == 'y' || ch == 'Y';
7715             break;
7716           }
7717         }
7718       }
7719     }
7720     return true;
7721   }
7722   void Post(const parser::ReadStmt &) { inAsyncIO_ = false; }
7723   void Post(const parser::WriteStmt &) { inAsyncIO_ = false; }
7724   void Post(const parser::IoControlSpec::Size &size) {
7725     if (const auto *designator{
7726             std::get_if<common::Indirection<parser::Designator>>(
7727                 &size.v.thing.thing.u)}) {
7728       NoteAsyncIODesignator(designator->value());
7729     }
7730   }
7731   void Post(const parser::InputItem &x) {
7732     if (const auto *var{std::get_if<parser::Variable>(&x.u)}) {
7733       if (const auto *designator{
7734               std::get_if<common::Indirection<parser::Designator>>(&var->u)}) {
7735         NoteAsyncIODesignator(designator->value());
7736       }
7737     }
7738   }
7739   void Post(const parser::OutputItem &x) {
7740     if (const auto *expr{std::get_if<parser::Expr>(&x.u)}) {
7741       if (const auto *designator{
7742               std::get_if<common::Indirection<parser::Designator>>(&expr->u)}) {
7743         NoteAsyncIODesignator(designator->value());
7744       }
7745     }
7746   }
7747 
7748 private:
7749   void NoteAsyncIODesignator(const parser::Designator &designator) {
7750     if (inAsyncIO_ && !InNestedBlockConstruct()) {
7751       const parser::Name &name{parser::GetFirstName(designator)};
7752       if (!IsHidden(name.source)) {
7753         asyncIONames_.insert(name.source);
7754       }
7755     }
7756   }
7757 
7758   SemanticsContext &context_;
7759   bool inAsyncIO_{false};
7760   std::set<SourceName> asyncIONames_;
7761 };
7762 
7763 // Any data list item or SIZE= specifier of an I/O data transfer statement
7764 // with ASYNCHRONOUS="YES" implicitly has the ASYNCHRONOUS attribute in the
7765 // local scope.
7766 void ConstructVisitor::HandleImpliedAsynchronousInScope(
7767     const parser::Block &block) {
7768   ExecutionPartAsyncIOSkimmer skimmer{context()};
7769   skimmer.Walk(block);
7770   for (auto name : skimmer.asyncIONames()) {
7771     if (Symbol * symbol{currScope().FindSymbol(name)}) {
7772       if (!symbol->attrs().test(Attr::ASYNCHRONOUS)) {
7773         if (&symbol->owner() != &currScope()) {
7774           symbol = &*currScope()
7775                          .try_emplace(name, HostAssocDetails{*symbol})
7776                          .first->second;
7777         }
7778         if (symbol->has<AssocEntityDetails>()) {
7779           symbol = const_cast<Symbol *>(&GetAssociationRoot(*symbol));
7780         }
7781         SetImplicitAttr(*symbol, Attr::ASYNCHRONOUS);
7782       }
7783     }
7784   }
7785 }
7786 
7787 // ResolveNamesVisitor implementation
7788 
7789 bool ResolveNamesVisitor::Pre(const parser::FunctionReference &x) {
7790   HandleCall(Symbol::Flag::Function, x.v);
7791   return false;
7792 }
7793 bool ResolveNamesVisitor::Pre(const parser::CallStmt &x) {
7794   HandleCall(Symbol::Flag::Subroutine, x.call);
7795   Walk(x.chevrons);
7796   return false;
7797 }
7798 
7799 bool ResolveNamesVisitor::Pre(const parser::ImportStmt &x) {
7800   auto &scope{currScope()};
7801   // Check C896 and C899: where IMPORT statements are allowed
7802   switch (scope.kind()) {
7803   case Scope::Kind::Module:
7804     if (scope.IsModule()) {
7805       Say("IMPORT is not allowed in a module scoping unit"_err_en_US);
7806       return false;
7807     } else if (x.kind == common::ImportKind::None) {
7808       Say("IMPORT,NONE is not allowed in a submodule scoping unit"_err_en_US);
7809       return false;
7810     }
7811     break;
7812   case Scope::Kind::MainProgram:
7813     Say("IMPORT is not allowed in a main program scoping unit"_err_en_US);
7814     return false;
7815   case Scope::Kind::Subprogram:
7816     if (scope.parent().IsGlobal()) {
7817       Say("IMPORT is not allowed in an external subprogram scoping unit"_err_en_US);
7818       return false;
7819     }
7820     break;
7821   case Scope::Kind::BlockData: // C1415 (in part)
7822     Say("IMPORT is not allowed in a BLOCK DATA subprogram"_err_en_US);
7823     return false;
7824   default:;
7825   }
7826   if (auto error{scope.SetImportKind(x.kind)}) {
7827     Say(std::move(*error));
7828   }
7829   for (auto &name : x.names) {
7830     if (Symbol * outer{FindSymbol(scope.parent(), name)}) {
7831       scope.add_importName(name.source);
7832       if (Symbol * symbol{FindInScope(name)}) {
7833         if (outer->GetUltimate() == symbol->GetUltimate()) {
7834           context().Warn(common::LanguageFeature::BenignNameClash, name.source,
7835               "The same '%s' is already present in this scope"_port_en_US,
7836               name.source);
7837         } else {
7838           Say(name,
7839               "A distinct '%s' is already present in this scope"_err_en_US)
7840               .Attach(symbol->name(), "Previous declaration of '%s'"_en_US)
7841               .Attach(outer->name(), "Declaration of '%s' in host scope"_en_US);
7842         }
7843       }
7844     } else {
7845       Say(name, "'%s' not found in host scope"_err_en_US);
7846     }
7847   }
7848   prevImportStmt_ = currStmtSource();
7849   return false;
7850 }
7851 
7852 const parser::Name *DeclarationVisitor::ResolveStructureComponent(
7853     const parser::StructureComponent &x) {
7854   return FindComponent(ResolveDataRef(x.base), x.component);
7855 }
7856 
7857 const parser::Name *DeclarationVisitor::ResolveDesignator(
7858     const parser::Designator &x) {
7859   return common::visit(
7860       common::visitors{
7861           [&](const parser::DataRef &x) { return ResolveDataRef(x); },
7862           [&](const parser::Substring &x) {
7863             Walk(std::get<parser::SubstringRange>(x.t).t);
7864             return ResolveDataRef(std::get<parser::DataRef>(x.t));
7865           },
7866       },
7867       x.u);
7868 }
7869 
7870 const parser::Name *DeclarationVisitor::ResolveDataRef(
7871     const parser::DataRef &x) {
7872   return common::visit(
7873       common::visitors{
7874           [=](const parser::Name &y) { return ResolveName(y); },
7875           [=](const Indirection<parser::StructureComponent> &y) {
7876             return ResolveStructureComponent(y.value());
7877           },
7878           [&](const Indirection<parser::ArrayElement> &y) {
7879             Walk(y.value().subscripts);
7880             const parser::Name *name{ResolveDataRef(y.value().base)};
7881             if (name && name->symbol) {
7882               if (!IsProcedure(*name->symbol)) {
7883                 ConvertToObjectEntity(*name->symbol);
7884               } else if (!context().HasError(*name->symbol)) {
7885                 SayWithDecl(*name, *name->symbol,
7886                     "Cannot reference function '%s' as data"_err_en_US);
7887                 context().SetError(*name->symbol);
7888               }
7889             }
7890             return name;
7891           },
7892           [&](const Indirection<parser::CoindexedNamedObject> &y) {
7893             Walk(y.value().imageSelector);
7894             return ResolveDataRef(y.value().base);
7895           },
7896       },
7897       x.u);
7898 }
7899 
7900 // If implicit types are allowed, ensure name is in the symbol table.
7901 // Otherwise, report an error if it hasn't been declared.
7902 const parser::Name *DeclarationVisitor::ResolveName(const parser::Name &name) {
7903   FindSymbol(name);
7904   if (CheckForHostAssociatedImplicit(name)) {
7905     NotePossibleBadForwardRef(name);
7906     return &name;
7907   }
7908   if (Symbol * symbol{name.symbol}) {
7909     if (CheckUseError(name)) {
7910       return nullptr; // reported an error
7911     }
7912     NotePossibleBadForwardRef(name);
7913     symbol->set(Symbol::Flag::ImplicitOrError, false);
7914     if (IsUplevelReference(*symbol)) {
7915       MakeHostAssocSymbol(name, *symbol);
7916     } else if (IsDummy(*symbol) ||
7917         (!symbol->GetType() && FindCommonBlockContaining(*symbol))) {
7918       CheckEntryDummyUse(name.source, symbol);
7919       ConvertToObjectEntity(*symbol);
7920       ApplyImplicitRules(*symbol);
7921     } else if (const auto *tpd{symbol->detailsIf<TypeParamDetails>()};
7922                tpd && !tpd->attr()) {
7923       Say(name,
7924           "Type parameter '%s' was referenced before being declared"_err_en_US,
7925           name.source);
7926       context().SetError(*symbol);
7927     }
7928     if (checkIndexUseInOwnBounds_ &&
7929         *checkIndexUseInOwnBounds_ == name.source && !InModuleFile()) {
7930       context().Warn(common::LanguageFeature::ImpliedDoIndexScope, name.source,
7931           "Implied DO index '%s' uses an object of the same name in its bounds expressions"_port_en_US,
7932           name.source);
7933     }
7934     return &name;
7935   }
7936   if (isImplicitNoneType() && !deferImplicitTyping_) {
7937     Say(name, "No explicit type declared for '%s'"_err_en_US);
7938     return nullptr;
7939   }
7940   // Create the symbol, then ensure that it is accessible
7941   if (checkIndexUseInOwnBounds_ && *checkIndexUseInOwnBounds_ == name.source) {
7942     Say(name,
7943         "Implied DO index '%s' uses itself in its own bounds expressions"_err_en_US,
7944         name.source);
7945   }
7946   MakeSymbol(InclusiveScope(), name.source, Attrs{});
7947   auto *symbol{FindSymbol(name)};
7948   if (!symbol) {
7949     Say(name,
7950         "'%s' from host scoping unit is not accessible due to IMPORT"_err_en_US);
7951     return nullptr;
7952   }
7953   ConvertToObjectEntity(*symbol);
7954   ApplyImplicitRules(*symbol);
7955   NotePossibleBadForwardRef(name);
7956   return &name;
7957 }
7958 
7959 // A specification expression may refer to a symbol in the host procedure that
7960 // is implicitly typed. Because specification parts are processed before
7961 // execution parts, this may be the first time we see the symbol. It can't be a
7962 // local in the current scope (because it's in a specification expression) so
7963 // either it is implicitly declared in the host procedure or it is an error.
7964 // We create a symbol in the host assuming it is the former; if that proves to
7965 // be wrong we report an error later in CheckDeclarations().
7966 bool DeclarationVisitor::CheckForHostAssociatedImplicit(
7967     const parser::Name &name) {
7968   if (!inSpecificationPart_ || inEquivalenceStmt_) {
7969     return false;
7970   }
7971   if (name.symbol) {
7972     ApplyImplicitRules(*name.symbol, true);
7973   }
7974   if (Scope * host{GetHostProcedure()}; host && !isImplicitNoneType(*host)) {
7975     Symbol *hostSymbol{nullptr};
7976     if (!name.symbol) {
7977       if (currScope().CanImport(name.source)) {
7978         hostSymbol = &MakeSymbol(*host, name.source, Attrs{});
7979         ConvertToObjectEntity(*hostSymbol);
7980         ApplyImplicitRules(*hostSymbol);
7981         hostSymbol->set(Symbol::Flag::ImplicitOrError);
7982       }
7983     } else if (name.symbol->test(Symbol::Flag::ImplicitOrError)) {
7984       hostSymbol = name.symbol;
7985     }
7986     if (hostSymbol) {
7987       Symbol &symbol{MakeHostAssocSymbol(name, *hostSymbol)};
7988       if (auto *assoc{symbol.detailsIf<HostAssocDetails>()}) {
7989         if (isImplicitNoneType()) {
7990           assoc->implicitOrExplicitTypeError = true;
7991         } else {
7992           assoc->implicitOrSpecExprError = true;
7993         }
7994         return true;
7995       }
7996     }
7997   }
7998   return false;
7999 }
8000 
8001 bool DeclarationVisitor::IsUplevelReference(const Symbol &symbol) {
8002   const Scope &symbolUnit{GetProgramUnitContaining(symbol)};
8003   if (symbolUnit == GetProgramUnitContaining(currScope())) {
8004     return false;
8005   } else {
8006     Scope::Kind kind{symbolUnit.kind()};
8007     return kind == Scope::Kind::Subprogram || kind == Scope::Kind::MainProgram;
8008   }
8009 }
8010 
8011 // base is a part-ref of a derived type; find the named component in its type.
8012 // Also handles intrinsic type parameter inquiries (%kind, %len) and
8013 // COMPLEX component references (%re, %im).
8014 const parser::Name *DeclarationVisitor::FindComponent(
8015     const parser::Name *base, const parser::Name &component) {
8016   if (!base || !base->symbol) {
8017     return nullptr;
8018   }
8019   if (auto *misc{base->symbol->detailsIf<MiscDetails>()}) {
8020     if (component.source == "kind") {
8021       if (misc->kind() == MiscDetails::Kind::ComplexPartRe ||
8022           misc->kind() == MiscDetails::Kind::ComplexPartIm ||
8023           misc->kind() == MiscDetails::Kind::KindParamInquiry ||
8024           misc->kind() == MiscDetails::Kind::LenParamInquiry) {
8025         // x%{re,im,kind,len}%kind
8026         MakePlaceholder(component, MiscDetails::Kind::KindParamInquiry);
8027         return &component;
8028       }
8029     }
8030   }
8031   CheckEntryDummyUse(base->source, base->symbol);
8032   auto &symbol{base->symbol->GetUltimate()};
8033   if (!symbol.has<AssocEntityDetails>() && !ConvertToObjectEntity(symbol)) {
8034     SayWithDecl(*base, symbol,
8035         "'%s' is not an object and may not be used as the base of a component reference or type parameter inquiry"_err_en_US);
8036     return nullptr;
8037   }
8038   auto *type{symbol.GetType()};
8039   if (!type) {
8040     return nullptr; // should have already reported error
8041   }
8042   if (const IntrinsicTypeSpec * intrinsic{type->AsIntrinsic()}) {
8043     auto category{intrinsic->category()};
8044     MiscDetails::Kind miscKind{MiscDetails::Kind::None};
8045     if (component.source == "kind") {
8046       miscKind = MiscDetails::Kind::KindParamInquiry;
8047     } else if (category == TypeCategory::Character) {
8048       if (component.source == "len") {
8049         miscKind = MiscDetails::Kind::LenParamInquiry;
8050       }
8051     } else if (category == TypeCategory::Complex) {
8052       if (component.source == "re") {
8053         miscKind = MiscDetails::Kind::ComplexPartRe;
8054       } else if (component.source == "im") {
8055         miscKind = MiscDetails::Kind::ComplexPartIm;
8056       }
8057     }
8058     if (miscKind != MiscDetails::Kind::None) {
8059       MakePlaceholder(component, miscKind);
8060       return &component;
8061     }
8062   } else if (DerivedTypeSpec * derived{type->AsDerived()}) {
8063     derived->Instantiate(currScope()); // in case of forward referenced type
8064     if (const Scope * scope{derived->scope()}) {
8065       if (Resolve(component, scope->FindComponent(component.source))) {
8066         if (auto msg{CheckAccessibleSymbol(currScope(), *component.symbol)}) {
8067           context().Say(component.source, *msg);
8068         }
8069         return &component;
8070       } else {
8071         SayDerivedType(component.source,
8072             "Component '%s' not found in derived type '%s'"_err_en_US, *scope);
8073       }
8074     }
8075     return nullptr;
8076   }
8077   if (symbol.test(Symbol::Flag::Implicit)) {
8078     Say(*base,
8079         "'%s' is not an object of derived type; it is implicitly typed"_err_en_US);
8080   } else {
8081     SayWithDecl(
8082         *base, symbol, "'%s' is not an object of derived type"_err_en_US);
8083   }
8084   return nullptr;
8085 }
8086 
8087 void DeclarationVisitor::Initialization(const parser::Name &name,
8088     const parser::Initialization &init, bool inComponentDecl) {
8089   // Traversal of the initializer was deferred to here so that the
8090   // symbol being declared can be available for use in the expression, e.g.:
8091   //   real, parameter :: x = tiny(x)
8092   if (!name.symbol) {
8093     return;
8094   }
8095   Symbol &ultimate{name.symbol->GetUltimate()};
8096   // TODO: check C762 - all bounds and type parameters of component
8097   // are colons or constant expressions if component is initialized
8098   common::visit(
8099       common::visitors{
8100           [&](const parser::ConstantExpr &expr) {
8101             Walk(expr);
8102             if (IsNamedConstant(ultimate) || inComponentDecl) {
8103               NonPointerInitialization(name, expr);
8104             } else {
8105               // Defer analysis so forward references to nested subprograms
8106               // can be properly resolved when they appear in structure
8107               // constructors.
8108               ultimate.set(Symbol::Flag::InDataStmt);
8109             }
8110           },
8111           [&](const parser::NullInit &null) { // => NULL()
8112             Walk(null);
8113             if (auto nullInit{EvaluateExpr(null)}) {
8114               if (!evaluate::IsNullPointer(*nullInit)) { // C813
8115                 Say(null.v.value().source,
8116                     "Pointer initializer must be intrinsic NULL()"_err_en_US);
8117               } else if (IsPointer(ultimate)) {
8118                 if (auto *object{ultimate.detailsIf<ObjectEntityDetails>()}) {
8119                   CHECK(!object->init());
8120                   object->set_init(std::move(*nullInit));
8121                 } else if (auto *procPtr{
8122                                ultimate.detailsIf<ProcEntityDetails>()}) {
8123                   CHECK(!procPtr->init());
8124                   procPtr->set_init(nullptr);
8125                 }
8126               } else {
8127                 Say(name,
8128                     "Non-pointer component '%s' initialized with null pointer"_err_en_US);
8129               }
8130             }
8131           },
8132           [&](const parser::InitialDataTarget &target) {
8133             // Defer analysis to the end of the specification part
8134             // so that forward references and attribute checks like SAVE
8135             // work better.
8136             auto restorer{common::ScopedSet(deferImplicitTyping_, true)};
8137             Walk(target);
8138             ultimate.set(Symbol::Flag::InDataStmt);
8139           },
8140           [&](const std::list<Indirection<parser::DataStmtValue>> &values) {
8141             // Handled later in data-to-inits conversion
8142             ultimate.set(Symbol::Flag::InDataStmt);
8143             Walk(values);
8144           },
8145       },
8146       init.u);
8147 }
8148 
8149 void DeclarationVisitor::PointerInitialization(
8150     const parser::Name &name, const parser::InitialDataTarget &target) {
8151   if (name.symbol) {
8152     Symbol &ultimate{name.symbol->GetUltimate()};
8153     if (!context().HasError(ultimate)) {
8154       if (IsPointer(ultimate)) {
8155         Walk(target);
8156         if (MaybeExpr expr{EvaluateExpr(target)}) {
8157           // Validation is done in declaration checking.
8158           if (auto *details{ultimate.detailsIf<ObjectEntityDetails>()}) {
8159             CHECK(!details->init());
8160             details->set_init(std::move(*expr));
8161             ultimate.set(Symbol::Flag::InDataStmt, false);
8162           } else if (auto *details{ultimate.detailsIf<ProcEntityDetails>()}) {
8163             // something like "REAL, EXTERNAL, POINTER :: p => t"
8164             if (evaluate::IsNullProcedurePointer(*expr)) {
8165               CHECK(!details->init());
8166               details->set_init(nullptr);
8167             } else if (const Symbol *
8168                 targetSymbol{evaluate::UnwrapWholeSymbolDataRef(*expr)}) {
8169               CHECK(!details->init());
8170               details->set_init(*targetSymbol);
8171             } else {
8172               Say(name,
8173                   "Procedure pointer '%s' must be initialized with a procedure name or NULL()"_err_en_US);
8174               context().SetError(ultimate);
8175             }
8176           }
8177         }
8178       } else {
8179         Say(name,
8180             "'%s' is not a pointer but is initialized like one"_err_en_US);
8181         context().SetError(ultimate);
8182       }
8183     }
8184   }
8185 }
8186 void DeclarationVisitor::PointerInitialization(
8187     const parser::Name &name, const parser::ProcPointerInit &target) {
8188   if (name.symbol) {
8189     Symbol &ultimate{name.symbol->GetUltimate()};
8190     if (!context().HasError(ultimate)) {
8191       if (IsProcedurePointer(ultimate)) {
8192         auto &details{ultimate.get<ProcEntityDetails>()};
8193         CHECK(!details.init());
8194         if (const auto *targetName{std::get_if<parser::Name>(&target.u)}) {
8195           Walk(target);
8196           if (!CheckUseError(*targetName) && targetName->symbol) {
8197             // Validation is done in declaration checking.
8198             details.set_init(*targetName->symbol);
8199           }
8200         } else { // explicit NULL
8201           details.set_init(nullptr);
8202         }
8203       } else {
8204         Say(name,
8205             "'%s' is not a procedure pointer but is initialized "
8206             "like one"_err_en_US);
8207         context().SetError(ultimate);
8208       }
8209     }
8210   }
8211 }
8212 
8213 void DeclarationVisitor::NonPointerInitialization(
8214     const parser::Name &name, const parser::ConstantExpr &expr) {
8215   if (!context().HasError(name.symbol)) {
8216     Symbol &ultimate{name.symbol->GetUltimate()};
8217     if (!context().HasError(ultimate)) {
8218       if (IsPointer(ultimate)) {
8219         Say(name,
8220             "'%s' is a pointer but is not initialized like one"_err_en_US);
8221       } else if (auto *details{ultimate.detailsIf<ObjectEntityDetails>()}) {
8222         if (details->init()) {
8223           SayWithDecl(name, *name.symbol,
8224               "'%s' has already been initialized"_err_en_US);
8225         } else if (IsAllocatable(ultimate)) {
8226           Say(name, "Allocatable object '%s' cannot be initialized"_err_en_US);
8227         } else if (ultimate.owner().IsParameterizedDerivedType()) {
8228           // Save the expression for per-instantiation analysis.
8229           details->set_unanalyzedPDTComponentInit(&expr.thing.value());
8230         } else if (MaybeExpr folded{EvaluateNonPointerInitializer(
8231                        ultimate, expr, expr.thing.value().source)}) {
8232           details->set_init(std::move(*folded));
8233           ultimate.set(Symbol::Flag::InDataStmt, false);
8234         }
8235       } else {
8236         Say(name, "'%s' is not an object that can be initialized"_err_en_US);
8237       }
8238     }
8239   }
8240 }
8241 
8242 void ResolveNamesVisitor::HandleCall(
8243     Symbol::Flag procFlag, const parser::Call &call) {
8244   common::visit(
8245       common::visitors{
8246           [&](const parser::Name &x) { HandleProcedureName(procFlag, x); },
8247           [&](const parser::ProcComponentRef &x) {
8248             Walk(x);
8249             const parser::Name &name{x.v.thing.component};
8250             if (Symbol * symbol{name.symbol}) {
8251               if (IsProcedure(*symbol)) {
8252                 SetProcFlag(name, *symbol, procFlag);
8253               }
8254             }
8255           },
8256       },
8257       std::get<parser::ProcedureDesignator>(call.t).u);
8258   const auto &arguments{std::get<std::list<parser::ActualArgSpec>>(call.t)};
8259   Walk(arguments);
8260   // Once an object has appeared in a specification function reference as
8261   // a whole scalar actual argument, it cannot be (re)dimensioned later.
8262   // The fact that it appeared to be a scalar may determine the resolution
8263   // or the result of an inquiry intrinsic function or generic procedure.
8264   if (inSpecificationPart_) {
8265     for (const auto &argSpec : arguments) {
8266       const auto &actual{std::get<parser::ActualArg>(argSpec.t)};
8267       if (const auto *expr{
8268               std::get_if<common::Indirection<parser::Expr>>(&actual.u)}) {
8269         if (const auto *designator{
8270                 std::get_if<common::Indirection<parser::Designator>>(
8271                     &expr->value().u)}) {
8272           if (const auto *dataRef{
8273                   std::get_if<parser::DataRef>(&designator->value().u)}) {
8274             if (const auto *name{std::get_if<parser::Name>(&dataRef->u)};
8275                 name && name->symbol) {
8276               const Symbol &symbol{*name->symbol};
8277               const auto *object{symbol.detailsIf<ObjectEntityDetails>()};
8278               if (symbol.has<EntityDetails>() ||
8279                   (object && !object->IsArray())) {
8280                 NoteScalarSpecificationArgument(symbol);
8281               }
8282             }
8283           }
8284         }
8285       }
8286     }
8287   }
8288 }
8289 
8290 void ResolveNamesVisitor::HandleProcedureName(
8291     Symbol::Flag flag, const parser::Name &name) {
8292   CHECK(flag == Symbol::Flag::Function || flag == Symbol::Flag::Subroutine);
8293   auto *symbol{FindSymbol(NonDerivedTypeScope(), name)};
8294   if (!symbol) {
8295     if (IsIntrinsic(name.source, flag)) {
8296       symbol = &MakeSymbol(InclusiveScope(), name.source, Attrs{});
8297       SetImplicitAttr(*symbol, Attr::INTRINSIC);
8298     } else if (const auto ppcBuiltinScope =
8299                    currScope().context().GetPPCBuiltinsScope()) {
8300       // Check if it is a builtin from the predefined module
8301       symbol = FindSymbol(*ppcBuiltinScope, name);
8302       if (!symbol) {
8303         symbol = &MakeSymbol(context().globalScope(), name.source, Attrs{});
8304       }
8305     } else {
8306       symbol = &MakeSymbol(context().globalScope(), name.source, Attrs{});
8307     }
8308     Resolve(name, *symbol);
8309     ConvertToProcEntity(*symbol, name.source);
8310     if (!symbol->attrs().test(Attr::INTRINSIC)) {
8311       if (CheckImplicitNoneExternal(name.source, *symbol)) {
8312         MakeExternal(*symbol);
8313         // Create a place-holder HostAssocDetails symbol to preclude later
8314         // use of this name as a local symbol; but don't actually use this new
8315         // HostAssocDetails symbol in expressions.
8316         MakeHostAssocSymbol(name, *symbol);
8317         name.symbol = symbol;
8318       }
8319     }
8320     CheckEntryDummyUse(name.source, symbol);
8321     SetProcFlag(name, *symbol, flag);
8322   } else if (CheckUseError(name)) {
8323     // error was reported
8324   } else {
8325     symbol = &symbol->GetUltimate();
8326     if (!name.symbol ||
8327         (name.symbol->has<HostAssocDetails>() && symbol->owner().IsGlobal() &&
8328             (symbol->has<ProcEntityDetails>() ||
8329                 (symbol->has<SubprogramDetails>() &&
8330                     symbol->scope() /*not ENTRY*/)))) {
8331       name.symbol = symbol;
8332     }
8333     CheckEntryDummyUse(name.source, symbol);
8334     bool convertedToProcEntity{ConvertToProcEntity(*symbol, name.source)};
8335     if (convertedToProcEntity && !symbol->attrs().test(Attr::EXTERNAL) &&
8336         IsIntrinsic(symbol->name(), flag) && !IsDummy(*symbol)) {
8337       AcquireIntrinsicProcedureFlags(*symbol);
8338     }
8339     if (!SetProcFlag(name, *symbol, flag)) {
8340       return; // reported error
8341     }
8342     CheckImplicitNoneExternal(name.source, *symbol);
8343     if (IsProcedure(*symbol) || symbol->has<DerivedTypeDetails>() ||
8344         symbol->has<AssocEntityDetails>()) {
8345       // Symbols with DerivedTypeDetails and AssocEntityDetails are accepted
8346       // here as procedure-designators because this means the related
8347       // FunctionReference are mis-parsed structure constructors or array
8348       // references that will be fixed later when analyzing expressions.
8349     } else if (symbol->has<ObjectEntityDetails>()) {
8350       // Symbols with ObjectEntityDetails are also accepted because this can be
8351       // a mis-parsed array reference that will be fixed later. Ensure that if
8352       // this is a symbol from a host procedure, a symbol with HostAssocDetails
8353       // is created for the current scope.
8354       // Operate on non ultimate symbol so that HostAssocDetails are also
8355       // created for symbols used associated in the host procedure.
8356       ResolveName(name);
8357     } else if (symbol->test(Symbol::Flag::Implicit)) {
8358       Say(name,
8359           "Use of '%s' as a procedure conflicts with its implicit definition"_err_en_US);
8360     } else {
8361       SayWithDecl(name, *symbol,
8362           "Use of '%s' as a procedure conflicts with its declaration"_err_en_US);
8363     }
8364   }
8365 }
8366 
8367 bool ResolveNamesVisitor::CheckImplicitNoneExternal(
8368     const SourceName &name, const Symbol &symbol) {
8369   if (symbol.has<ProcEntityDetails>() && isImplicitNoneExternal() &&
8370       !symbol.attrs().test(Attr::EXTERNAL) &&
8371       !symbol.attrs().test(Attr::INTRINSIC) && !symbol.HasExplicitInterface()) {
8372     Say(name,
8373         "'%s' is an external procedure without the EXTERNAL attribute in a scope with IMPLICIT NONE(EXTERNAL)"_err_en_US);
8374     return false;
8375   }
8376   return true;
8377 }
8378 
8379 // Variant of HandleProcedureName() for use while skimming the executable
8380 // part of a subprogram to catch calls to dummy procedures that are part
8381 // of the subprogram's interface, and to mark as procedures any symbols
8382 // that might otherwise have been miscategorized as objects.
8383 void ResolveNamesVisitor::NoteExecutablePartCall(
8384     Symbol::Flag flag, SourceName name, bool hasCUDAChevrons) {
8385   // Subtlety: The symbol pointers in the parse tree are not set, because
8386   // they might end up resolving elsewhere (e.g., construct entities in
8387   // SELECT TYPE).
8388   if (Symbol * symbol{currScope().FindSymbol(name)}) {
8389     Symbol::Flag other{flag == Symbol::Flag::Subroutine
8390             ? Symbol::Flag::Function
8391             : Symbol::Flag::Subroutine};
8392     if (!symbol->test(other)) {
8393       ConvertToProcEntity(*symbol, name);
8394       if (auto *details{symbol->detailsIf<ProcEntityDetails>()}) {
8395         symbol->set(flag);
8396         if (IsDummy(*symbol)) {
8397           SetImplicitAttr(*symbol, Attr::EXTERNAL);
8398         }
8399         ApplyImplicitRules(*symbol);
8400         if (hasCUDAChevrons) {
8401           details->set_isCUDAKernel();
8402         }
8403       }
8404     }
8405   }
8406 }
8407 
8408 static bool IsLocallyImplicitGlobalSymbol(
8409     const Symbol &symbol, const parser::Name &localName) {
8410   if (symbol.owner().IsGlobal()) {
8411     const auto *subp{symbol.detailsIf<SubprogramDetails>()};
8412     const Scope *scope{
8413         subp && subp->entryScope() ? subp->entryScope() : symbol.scope()};
8414     return !(scope && scope->sourceRange().Contains(localName.source));
8415   }
8416   return false;
8417 }
8418 
8419 static bool TypesMismatchIfNonNull(
8420     const DeclTypeSpec *type1, const DeclTypeSpec *type2) {
8421   return type1 && type2 && *type1 != *type2;
8422 }
8423 
8424 // Check and set the Function or Subroutine flag on symbol; false on error.
8425 bool ResolveNamesVisitor::SetProcFlag(
8426     const parser::Name &name, Symbol &symbol, Symbol::Flag flag) {
8427   if (symbol.test(Symbol::Flag::Function) && flag == Symbol::Flag::Subroutine) {
8428     SayWithDecl(
8429         name, symbol, "Cannot call function '%s' like a subroutine"_err_en_US);
8430     context().SetError(symbol);
8431     return false;
8432   } else if (symbol.test(Symbol::Flag::Subroutine) &&
8433       flag == Symbol::Flag::Function) {
8434     SayWithDecl(
8435         name, symbol, "Cannot call subroutine '%s' like a function"_err_en_US);
8436     context().SetError(symbol);
8437     return false;
8438   } else if (flag == Symbol::Flag::Function &&
8439       IsLocallyImplicitGlobalSymbol(symbol, name) &&
8440       TypesMismatchIfNonNull(symbol.GetType(), GetImplicitType(symbol))) {
8441     SayWithDecl(name, symbol,
8442         "Implicit declaration of function '%s' has a different result type than in previous declaration"_err_en_US);
8443     return false;
8444   } else if (symbol.has<ProcEntityDetails>()) {
8445     symbol.set(flag); // in case it hasn't been set yet
8446     if (flag == Symbol::Flag::Function) {
8447       ApplyImplicitRules(symbol);
8448     }
8449     if (symbol.attrs().test(Attr::INTRINSIC)) {
8450       AcquireIntrinsicProcedureFlags(symbol);
8451     }
8452   } else if (symbol.GetType() && flag == Symbol::Flag::Subroutine) {
8453     SayWithDecl(
8454         name, symbol, "Cannot call function '%s' like a subroutine"_err_en_US);
8455     context().SetError(symbol);
8456   } else if (symbol.attrs().test(Attr::INTRINSIC)) {
8457     AcquireIntrinsicProcedureFlags(symbol);
8458   }
8459   return true;
8460 }
8461 
8462 bool ModuleVisitor::Pre(const parser::AccessStmt &x) {
8463   Attr accessAttr{AccessSpecToAttr(std::get<parser::AccessSpec>(x.t))};
8464   if (!currScope().IsModule()) { // C869
8465     Say(currStmtSource().value(),
8466         "%s statement may only appear in the specification part of a module"_err_en_US,
8467         EnumToString(accessAttr));
8468     return false;
8469   }
8470   const auto &accessIds{std::get<std::list<parser::AccessId>>(x.t)};
8471   if (accessIds.empty()) {
8472     if (prevAccessStmt_) { // C869
8473       Say("The default accessibility of this module has already been declared"_err_en_US)
8474           .Attach(*prevAccessStmt_, "Previous declaration"_en_US);
8475     }
8476     prevAccessStmt_ = currStmtSource();
8477     auto *moduleDetails{DEREF(currScope().symbol()).detailsIf<ModuleDetails>()};
8478     DEREF(moduleDetails).set_isDefaultPrivate(accessAttr == Attr::PRIVATE);
8479   } else {
8480     for (const auto &accessId : accessIds) {
8481       GenericSpecInfo info{accessId.v.value()};
8482       auto *symbol{FindInScope(info.symbolName())};
8483       if (!symbol && !info.kind().IsName()) {
8484         symbol = &MakeSymbol(info.symbolName(), Attrs{}, GenericDetails{});
8485       }
8486       info.Resolve(&SetAccess(info.symbolName(), accessAttr, symbol));
8487     }
8488   }
8489   return false;
8490 }
8491 
8492 // Set the access specification for this symbol.
8493 Symbol &ModuleVisitor::SetAccess(
8494     const SourceName &name, Attr attr, Symbol *symbol) {
8495   if (!symbol) {
8496     symbol = &MakeSymbol(name);
8497   }
8498   Attrs &attrs{symbol->attrs()};
8499   if (attrs.HasAny({Attr::PUBLIC, Attr::PRIVATE})) {
8500     // PUBLIC/PRIVATE already set: make it a fatal error if it changed
8501     Attr prev{attrs.test(Attr::PUBLIC) ? Attr::PUBLIC : Attr::PRIVATE};
8502     if (attr != prev) {
8503       Say(name,
8504           "The accessibility of '%s' has already been specified as %s"_err_en_US,
8505           MakeOpName(name), EnumToString(prev));
8506     } else {
8507       context().Warn(common::LanguageFeature::RedundantAttribute, name,
8508           "The accessibility of '%s' has already been specified as %s"_warn_en_US,
8509           MakeOpName(name), EnumToString(prev));
8510     }
8511   } else {
8512     attrs.set(attr);
8513   }
8514   return *symbol;
8515 }
8516 
8517 static bool NeedsExplicitType(const Symbol &symbol) {
8518   if (symbol.has<UnknownDetails>()) {
8519     return true;
8520   } else if (const auto *details{symbol.detailsIf<EntityDetails>()}) {
8521     return !details->type();
8522   } else if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) {
8523     return !details->type();
8524   } else if (const auto *details{symbol.detailsIf<ProcEntityDetails>()}) {
8525     return !details->procInterface() && !details->type();
8526   } else {
8527     return false;
8528   }
8529 }
8530 
8531 void ResolveNamesVisitor::HandleDerivedTypesInImplicitStmts(
8532     const parser::ImplicitPart &implicitPart,
8533     const std::list<parser::DeclarationConstruct> &decls) {
8534   // Detect derived type definitions and create symbols for them now if
8535   // they appear in IMPLICIT statements so that these forward-looking
8536   // references will not be ambiguous with host associations.
8537   std::set<SourceName> implicitDerivedTypes;
8538   for (const auto &ipStmt : implicitPart.v) {
8539     if (const auto *impl{std::get_if<
8540             parser::Statement<common::Indirection<parser::ImplicitStmt>>>(
8541             &ipStmt.u)}) {
8542       if (const auto *specs{std::get_if<std::list<parser::ImplicitSpec>>(
8543               &impl->statement.value().u)}) {
8544         for (const auto &spec : *specs) {
8545           const auto &declTypeSpec{
8546               std::get<parser::DeclarationTypeSpec>(spec.t)};
8547           if (const auto *dtSpec{common::visit(
8548                   common::visitors{
8549                       [](const parser::DeclarationTypeSpec::Type &x) {
8550                         return &x.derived;
8551                       },
8552                       [](const parser::DeclarationTypeSpec::Class &x) {
8553                         return &x.derived;
8554                       },
8555                       [](const auto &) -> const parser::DerivedTypeSpec * {
8556                         return nullptr;
8557                       }},
8558                   declTypeSpec.u)}) {
8559             implicitDerivedTypes.emplace(
8560                 std::get<parser::Name>(dtSpec->t).source);
8561           }
8562         }
8563       }
8564     }
8565   }
8566   if (!implicitDerivedTypes.empty()) {
8567     for (const auto &decl : decls) {
8568       if (const auto *spec{
8569               std::get_if<parser::SpecificationConstruct>(&decl.u)}) {
8570         if (const auto *dtDef{
8571                 std::get_if<common::Indirection<parser::DerivedTypeDef>>(
8572                     &spec->u)}) {
8573           const parser::DerivedTypeStmt &dtStmt{
8574               std::get<parser::Statement<parser::DerivedTypeStmt>>(
8575                   dtDef->value().t)
8576                   .statement};
8577           const parser::Name &name{std::get<parser::Name>(dtStmt.t)};
8578           if (implicitDerivedTypes.find(name.source) !=
8579                   implicitDerivedTypes.end() &&
8580               !FindInScope(name)) {
8581             DerivedTypeDetails details;
8582             details.set_isForwardReferenced(true);
8583             Resolve(name, MakeSymbol(name, std::move(details)));
8584             implicitDerivedTypes.erase(name.source);
8585           }
8586         }
8587       }
8588     }
8589   }
8590 }
8591 
8592 bool ResolveNamesVisitor::Pre(const parser::SpecificationPart &x) {
8593   const auto &[accDecls, ompDecls, compilerDirectives, useStmts, importStmts,
8594       implicitPart, decls] = x.t;
8595   auto flagRestorer{common::ScopedSet(inSpecificationPart_, true)};
8596   auto stateRestorer{
8597       common::ScopedSet(specPartState_, SpecificationPartState{})};
8598   Walk(accDecls);
8599   Walk(ompDecls);
8600   Walk(compilerDirectives);
8601   for (const auto &useStmt : useStmts) {
8602     CollectUseRenames(useStmt.statement.value());
8603   }
8604   Walk(useStmts);
8605   UseCUDABuiltinNames();
8606   ClearUseRenames();
8607   ClearUseOnly();
8608   ClearModuleUses();
8609   Walk(importStmts);
8610   HandleDerivedTypesInImplicitStmts(implicitPart, decls);
8611   Walk(implicitPart);
8612   for (const auto &decl : decls) {
8613     if (const auto *spec{
8614             std::get_if<parser::SpecificationConstruct>(&decl.u)}) {
8615       PreSpecificationConstruct(*spec);
8616     }
8617   }
8618   Walk(decls);
8619   FinishSpecificationPart(decls);
8620   return false;
8621 }
8622 
8623 void ResolveNamesVisitor::UseCUDABuiltinNames() {
8624   if (FindCUDADeviceContext(&currScope())) {
8625     for (const auto &[name, symbol] : context().GetCUDABuiltinsScope()) {
8626       if (!FindInScope(name)) {
8627         auto &localSymbol{MakeSymbol(name)};
8628         localSymbol.set_details(UseDetails{name, *symbol});
8629         localSymbol.flags() = symbol->flags();
8630       }
8631     }
8632   }
8633 }
8634 
8635 // Initial processing on specification constructs, before visiting them.
8636 void ResolveNamesVisitor::PreSpecificationConstruct(
8637     const parser::SpecificationConstruct &spec) {
8638   common::visit(
8639       common::visitors{
8640           [&](const parser::Statement<Indirection<parser::GenericStmt>> &y) {
8641             CreateGeneric(std::get<parser::GenericSpec>(y.statement.value().t));
8642           },
8643           [&](const Indirection<parser::InterfaceBlock> &y) {
8644             const auto &stmt{std::get<parser::Statement<parser::InterfaceStmt>>(
8645                 y.value().t)};
8646             if (const auto *spec{parser::Unwrap<parser::GenericSpec>(stmt)}) {
8647               CreateGeneric(*spec);
8648             }
8649           },
8650           [&](const parser::Statement<parser::OtherSpecificationStmt> &y) {
8651             common::visit(
8652                 common::visitors{
8653                     [&](const common::Indirection<parser::CommonStmt> &z) {
8654                       CreateCommonBlockSymbols(z.value());
8655                     },
8656                     [&](const common::Indirection<parser::TargetStmt> &z) {
8657                       CreateObjectSymbols(z.value().v, Attr::TARGET);
8658                     },
8659                     [](const auto &) {},
8660                 },
8661                 y.statement.u);
8662           },
8663           [](const auto &) {},
8664       },
8665       spec.u);
8666 }
8667 
8668 void ResolveNamesVisitor::CreateCommonBlockSymbols(
8669     const parser::CommonStmt &commonStmt) {
8670   for (const parser::CommonStmt::Block &block : commonStmt.blocks) {
8671     const auto &[name, objects] = block.t;
8672     Symbol &commonBlock{MakeCommonBlockSymbol(name)};
8673     for (const auto &object : objects) {
8674       Symbol &obj{DeclareObjectEntity(std::get<parser::Name>(object.t))};
8675       if (auto *details{obj.detailsIf<ObjectEntityDetails>()}) {
8676         details->set_commonBlock(commonBlock);
8677         commonBlock.get<CommonBlockDetails>().add_object(obj);
8678       }
8679     }
8680   }
8681 }
8682 
8683 void ResolveNamesVisitor::CreateObjectSymbols(
8684     const std::list<parser::ObjectDecl> &decls, Attr attr) {
8685   for (const parser::ObjectDecl &decl : decls) {
8686     SetImplicitAttr(DeclareEntity<ObjectEntityDetails>(
8687                         std::get<parser::ObjectName>(decl.t), Attrs{}),
8688         attr);
8689   }
8690 }
8691 
8692 void ResolveNamesVisitor::CreateGeneric(const parser::GenericSpec &x) {
8693   auto info{GenericSpecInfo{x}};
8694   SourceName symbolName{info.symbolName()};
8695   if (IsLogicalConstant(context(), symbolName)) {
8696     Say(symbolName,
8697         "Logical constant '%s' may not be used as a defined operator"_err_en_US);
8698     return;
8699   }
8700   GenericDetails genericDetails;
8701   Symbol *existing{nullptr};
8702   // Check all variants of names, e.g. "operator(.ne.)" for "operator(/=)"
8703   for (const std::string &n : GetAllNames(context(), symbolName)) {
8704     existing = currScope().FindSymbol(SourceName{n});
8705     if (existing) {
8706       break;
8707     }
8708   }
8709   if (existing) {
8710     Symbol &ultimate{existing->GetUltimate()};
8711     if (auto *existingGeneric{ultimate.detailsIf<GenericDetails>()}) {
8712       if (&existing->owner() == &currScope()) {
8713         if (const auto *existingUse{existing->detailsIf<UseDetails>()}) {
8714           // Create a local copy of a use associated generic so that
8715           // it can be locally extended without corrupting the original.
8716           genericDetails.CopyFrom(*existingGeneric);
8717           if (existingGeneric->specific()) {
8718             genericDetails.set_specific(*existingGeneric->specific());
8719           }
8720           AddGenericUse(
8721               genericDetails, existing->name(), existingUse->symbol());
8722         } else if (existing == &ultimate) {
8723           // Extending an extant generic in the same scope
8724           info.Resolve(existing);
8725           return;
8726         } else {
8727           // Host association of a generic is handled elsewhere
8728           CHECK(existing->has<HostAssocDetails>());
8729         }
8730       } else {
8731         // Create a new generic for this scope.
8732       }
8733     } else if (ultimate.has<SubprogramDetails>() ||
8734         ultimate.has<SubprogramNameDetails>()) {
8735       genericDetails.set_specific(*existing);
8736     } else if (ultimate.has<ProcEntityDetails>()) {
8737       if (existing->name() != symbolName ||
8738           !ultimate.attrs().test(Attr::INTRINSIC)) {
8739         genericDetails.set_specific(*existing);
8740       }
8741     } else if (ultimate.has<DerivedTypeDetails>()) {
8742       genericDetails.set_derivedType(*existing);
8743     } else if (&existing->owner() == &currScope()) {
8744       SayAlreadyDeclared(symbolName, *existing);
8745       return;
8746     }
8747     if (&existing->owner() == &currScope()) {
8748       EraseSymbol(*existing);
8749     }
8750   }
8751   info.Resolve(&MakeSymbol(symbolName, Attrs{}, std::move(genericDetails)));
8752 }
8753 
8754 void ResolveNamesVisitor::FinishSpecificationPart(
8755     const std::list<parser::DeclarationConstruct> &decls) {
8756   misparsedStmtFuncFound_ = false;
8757   funcResultStack().CompleteFunctionResultType();
8758   CheckImports();
8759   for (auto &pair : currScope()) {
8760     auto &symbol{*pair.second};
8761     if (inInterfaceBlock()) {
8762       ConvertToObjectEntity(symbol);
8763     }
8764     if (NeedsExplicitType(symbol)) {
8765       ApplyImplicitRules(symbol);
8766     }
8767     if (IsDummy(symbol) && isImplicitNoneType() &&
8768         symbol.test(Symbol::Flag::Implicit) && !context().HasError(symbol)) {
8769       Say(symbol.name(),
8770           "No explicit type declared for dummy argument '%s'"_err_en_US);
8771       context().SetError(symbol);
8772     }
8773     if (symbol.has<GenericDetails>()) {
8774       CheckGenericProcedures(symbol);
8775     }
8776     if (!symbol.has<HostAssocDetails>()) {
8777       CheckPossibleBadForwardRef(symbol);
8778     }
8779     // Propagate BIND(C) attribute to procedure entities from their interfaces,
8780     // but not the NAME=, even if it is empty (which would be a reasonable
8781     // and useful behavior, actually).  This interpretation is not at all
8782     // clearly described in the standard, but matches the behavior of several
8783     // other compilers.
8784     if (auto *proc{symbol.detailsIf<ProcEntityDetails>()}; proc &&
8785         !proc->isDummy() && !IsPointer(symbol) &&
8786         !symbol.attrs().test(Attr::BIND_C)) {
8787       if (const Symbol * iface{proc->procInterface()};
8788           iface && IsBindCProcedure(*iface)) {
8789         SetImplicitAttr(symbol, Attr::BIND_C);
8790         SetBindNameOn(symbol);
8791       }
8792     }
8793   }
8794   currScope().InstantiateDerivedTypes();
8795   for (const auto &decl : decls) {
8796     if (const auto *statement{std::get_if<
8797             parser::Statement<common::Indirection<parser::StmtFunctionStmt>>>(
8798             &decl.u)}) {
8799       messageHandler().set_currStmtSource(statement->source);
8800       AnalyzeStmtFunctionStmt(statement->statement.value());
8801     }
8802   }
8803   // TODO: what about instantiations in BLOCK?
8804   CheckSaveStmts();
8805   CheckCommonBlocks();
8806   if (!inInterfaceBlock()) {
8807     // TODO: warn for the case where the EQUIVALENCE statement is in a
8808     // procedure declaration in an interface block
8809     CheckEquivalenceSets();
8810   }
8811 }
8812 
8813 // Analyze the bodies of statement functions now that the symbols in this
8814 // specification part have been fully declared and implicitly typed.
8815 // (Statement function references are not allowed in specification
8816 // expressions, so it's safe to defer processing their definitions.)
8817 void ResolveNamesVisitor::AnalyzeStmtFunctionStmt(
8818     const parser::StmtFunctionStmt &stmtFunc) {
8819   const auto &name{std::get<parser::Name>(stmtFunc.t)};
8820   Symbol *symbol{name.symbol};
8821   auto *details{symbol ? symbol->detailsIf<SubprogramDetails>() : nullptr};
8822   if (!details || !symbol->scope() ||
8823       &symbol->scope()->parent() != &currScope() || details->isInterface() ||
8824       details->isDummy() || details->entryScope() ||
8825       details->moduleInterface() || symbol->test(Symbol::Flag::Subroutine)) {
8826     return; // error recovery
8827   }
8828   // Resolve the symbols on the RHS of the statement function.
8829   PushScope(*symbol->scope());
8830   const auto &parsedExpr{std::get<parser::Scalar<parser::Expr>>(stmtFunc.t)};
8831   Walk(parsedExpr);
8832   PopScope();
8833   if (auto expr{AnalyzeExpr(context(), stmtFunc)}) {
8834     if (auto type{evaluate::DynamicType::From(*symbol)}) {
8835       if (auto converted{evaluate::ConvertToType(*type, std::move(*expr))}) {
8836         details->set_stmtFunction(std::move(*converted));
8837       } else {
8838         Say(name.source,
8839             "Defining expression of statement function '%s' cannot be converted to its result type %s"_err_en_US,
8840             name.source, type->AsFortran());
8841       }
8842     } else {
8843       details->set_stmtFunction(std::move(*expr));
8844     }
8845   }
8846   if (!details->stmtFunction()) {
8847     context().SetError(*symbol);
8848   }
8849 }
8850 
8851 void ResolveNamesVisitor::CheckImports() {
8852   auto &scope{currScope()};
8853   switch (scope.GetImportKind()) {
8854   case common::ImportKind::None:
8855     break;
8856   case common::ImportKind::All:
8857     // C8102: all entities in host must not be hidden
8858     for (const auto &pair : scope.parent()) {
8859       auto &name{pair.first};
8860       std::optional<SourceName> scopeName{scope.GetName()};
8861       if (!scopeName || name != *scopeName) {
8862         CheckImport(prevImportStmt_.value(), name);
8863       }
8864     }
8865     break;
8866   case common::ImportKind::Default:
8867   case common::ImportKind::Only:
8868     // C8102: entities named in IMPORT must not be hidden
8869     for (auto &name : scope.importNames()) {
8870       CheckImport(name, name);
8871     }
8872     break;
8873   }
8874 }
8875 
8876 void ResolveNamesVisitor::CheckImport(
8877     const SourceName &location, const SourceName &name) {
8878   if (auto *symbol{FindInScope(name)}) {
8879     const Symbol &ultimate{symbol->GetUltimate()};
8880     if (&ultimate.owner() == &currScope()) {
8881       Say(location, "'%s' from host is not accessible"_err_en_US, name)
8882           .Attach(symbol->name(), "'%s' is hidden by this entity"_because_en_US,
8883               symbol->name());
8884     }
8885   }
8886 }
8887 
8888 bool ResolveNamesVisitor::Pre(const parser::ImplicitStmt &x) {
8889   return CheckNotInBlock("IMPLICIT") && // C1107
8890       ImplicitRulesVisitor::Pre(x);
8891 }
8892 
8893 void ResolveNamesVisitor::Post(const parser::PointerObject &x) {
8894   common::visit(common::visitors{
8895                     [&](const parser::Name &x) { ResolveName(x); },
8896                     [&](const parser::StructureComponent &x) {
8897                       ResolveStructureComponent(x);
8898                     },
8899                 },
8900       x.u);
8901 }
8902 void ResolveNamesVisitor::Post(const parser::AllocateObject &x) {
8903   common::visit(common::visitors{
8904                     [&](const parser::Name &x) { ResolveName(x); },
8905                     [&](const parser::StructureComponent &x) {
8906                       ResolveStructureComponent(x);
8907                     },
8908                 },
8909       x.u);
8910 }
8911 
8912 bool ResolveNamesVisitor::Pre(const parser::PointerAssignmentStmt &x) {
8913   const auto &dataRef{std::get<parser::DataRef>(x.t)};
8914   const auto &bounds{std::get<parser::PointerAssignmentStmt::Bounds>(x.t)};
8915   const auto &expr{std::get<parser::Expr>(x.t)};
8916   ResolveDataRef(dataRef);
8917   Symbol *ptrSymbol{parser::GetLastName(dataRef).symbol};
8918   Walk(bounds);
8919   // Resolve unrestricted specific intrinsic procedures as in "p => cos".
8920   if (const parser::Name * name{parser::Unwrap<parser::Name>(expr)}) {
8921     if (NameIsKnownOrIntrinsic(*name)) {
8922       if (Symbol * symbol{name->symbol}) {
8923         if (IsProcedurePointer(ptrSymbol) &&
8924             !ptrSymbol->test(Symbol::Flag::Function) &&
8925             !ptrSymbol->test(Symbol::Flag::Subroutine)) {
8926           if (symbol->test(Symbol::Flag::Function)) {
8927             ApplyImplicitRules(*ptrSymbol);
8928           }
8929         }
8930         // If the name is known because it is an object entity from a host
8931         // procedure, create a host associated symbol.
8932         if (symbol->GetUltimate().has<ObjectEntityDetails>() &&
8933             IsUplevelReference(*symbol)) {
8934           MakeHostAssocSymbol(*name, *symbol);
8935         }
8936       }
8937       return false;
8938     }
8939     // Can also reference a global external procedure here
8940     if (auto it{context().globalScope().find(name->source)};
8941         it != context().globalScope().end()) {
8942       Symbol &global{*it->second};
8943       if (IsProcedure(global)) {
8944         Resolve(*name, global);
8945         return false;
8946       }
8947     }
8948     if (IsProcedurePointer(parser::GetLastName(dataRef).symbol) &&
8949         !FindSymbol(*name)) {
8950       // Unknown target of procedure pointer must be an external procedure
8951       Symbol &symbol{MakeSymbol(
8952           context().globalScope(), name->source, Attrs{Attr::EXTERNAL})};
8953       symbol.implicitAttrs().set(Attr::EXTERNAL);
8954       Resolve(*name, symbol);
8955       ConvertToProcEntity(symbol, name->source);
8956       return false;
8957     }
8958   }
8959   Walk(expr);
8960   return false;
8961 }
8962 void ResolveNamesVisitor::Post(const parser::Designator &x) {
8963   ResolveDesignator(x);
8964 }
8965 void ResolveNamesVisitor::Post(const parser::SubstringInquiry &x) {
8966   Walk(std::get<parser::SubstringRange>(x.v.t).t);
8967   ResolveDataRef(std::get<parser::DataRef>(x.v.t));
8968 }
8969 
8970 void ResolveNamesVisitor::Post(const parser::ProcComponentRef &x) {
8971   ResolveStructureComponent(x.v.thing);
8972 }
8973 void ResolveNamesVisitor::Post(const parser::TypeGuardStmt &x) {
8974   DeclTypeSpecVisitor::Post(x);
8975   ConstructVisitor::Post(x);
8976 }
8977 bool ResolveNamesVisitor::Pre(const parser::StmtFunctionStmt &x) {
8978   if (HandleStmtFunction(x)) {
8979     return false;
8980   } else {
8981     // This is an array element or pointer-valued function assignment:
8982     // resolve the names of indices/arguments
8983     const auto &names{std::get<std::list<parser::Name>>(x.t)};
8984     for (auto &name : names) {
8985       ResolveName(name);
8986     }
8987     return true;
8988   }
8989 }
8990 
8991 bool ResolveNamesVisitor::Pre(const parser::DefinedOpName &x) {
8992   const parser::Name &name{x.v};
8993   if (FindSymbol(name)) {
8994     // OK
8995   } else if (IsLogicalConstant(context(), name.source)) {
8996     Say(name,
8997         "Logical constant '%s' may not be used as a defined operator"_err_en_US);
8998   } else {
8999     // Resolved later in expression semantics
9000     MakePlaceholder(name, MiscDetails::Kind::TypeBoundDefinedOp);
9001   }
9002   return false;
9003 }
9004 
9005 void ResolveNamesVisitor::Post(const parser::AssignStmt &x) {
9006   if (auto *name{ResolveName(std::get<parser::Name>(x.t))}) {
9007     CheckEntryDummyUse(name->source, name->symbol);
9008     ConvertToObjectEntity(DEREF(name->symbol));
9009   }
9010 }
9011 void ResolveNamesVisitor::Post(const parser::AssignedGotoStmt &x) {
9012   if (auto *name{ResolveName(std::get<parser::Name>(x.t))}) {
9013     CheckEntryDummyUse(name->source, name->symbol);
9014     ConvertToObjectEntity(DEREF(name->symbol));
9015   }
9016 }
9017 
9018 void ResolveNamesVisitor::Post(const parser::CompilerDirective &x) {
9019   if (std::holds_alternative<parser::CompilerDirective::VectorAlways>(x.u)) {
9020     return;
9021   }
9022   if (const auto *tkr{
9023           std::get_if<std::list<parser::CompilerDirective::IgnoreTKR>>(&x.u)}) {
9024     if (currScope().IsTopLevel() ||
9025         GetProgramUnitContaining(currScope()).kind() !=
9026             Scope::Kind::Subprogram) {
9027       Say(x.source,
9028           "!DIR$ IGNORE_TKR directive must appear in a subroutine or function"_err_en_US);
9029       return;
9030     }
9031     if (!inSpecificationPart_) {
9032       Say(x.source,
9033           "!DIR$ IGNORE_TKR directive must appear in the specification part"_err_en_US);
9034       return;
9035     }
9036     if (tkr->empty()) {
9037       Symbol *symbol{currScope().symbol()};
9038       if (SubprogramDetails *
9039           subp{symbol ? symbol->detailsIf<SubprogramDetails>() : nullptr}) {
9040         subp->set_defaultIgnoreTKR(true);
9041       }
9042     } else {
9043       for (const parser::CompilerDirective::IgnoreTKR &item : *tkr) {
9044         common::IgnoreTKRSet set;
9045         if (const auto &maybeList{
9046                 std::get<std::optional<std::list<const char *>>>(item.t)}) {
9047           for (const char *p : *maybeList) {
9048             if (p) {
9049               switch (*p) {
9050               case 't':
9051                 set.set(common::IgnoreTKR::Type);
9052                 break;
9053               case 'k':
9054                 set.set(common::IgnoreTKR::Kind);
9055                 break;
9056               case 'r':
9057                 set.set(common::IgnoreTKR::Rank);
9058                 break;
9059               case 'd':
9060                 set.set(common::IgnoreTKR::Device);
9061                 break;
9062               case 'm':
9063                 set.set(common::IgnoreTKR::Managed);
9064                 break;
9065               case 'c':
9066                 set.set(common::IgnoreTKR::Contiguous);
9067                 break;
9068               case 'a':
9069                 set = common::ignoreTKRAll;
9070                 break;
9071               default:
9072                 Say(x.source,
9073                     "'%c' is not a valid letter for !DIR$ IGNORE_TKR directive"_err_en_US,
9074                     *p);
9075                 set = common::ignoreTKRAll;
9076                 break;
9077               }
9078             }
9079           }
9080           if (set.empty()) {
9081             Say(x.source,
9082                 "!DIR$ IGNORE_TKR directive may not have an empty parenthesized list of letters"_err_en_US);
9083           }
9084         } else { // no (list)
9085           set = common::ignoreTKRAll;
9086           ;
9087         }
9088         const auto &name{std::get<parser::Name>(item.t)};
9089         Symbol *symbol{FindSymbol(name)};
9090         if (!symbol) {
9091           symbol = &MakeSymbol(name, Attrs{}, ObjectEntityDetails{});
9092         }
9093         if (symbol->owner() != currScope()) {
9094           SayWithDecl(
9095               name, *symbol, "'%s' must be local to this subprogram"_err_en_US);
9096         } else {
9097           ConvertToObjectEntity(*symbol);
9098           if (auto *object{symbol->detailsIf<ObjectEntityDetails>()}) {
9099             object->set_ignoreTKR(set);
9100           } else {
9101             SayWithDecl(name, *symbol, "'%s' must be an object"_err_en_US);
9102           }
9103         }
9104       }
9105     }
9106   } else if (context().ShouldWarn(common::UsageWarning::IgnoredDirective)) {
9107     Say(x.source, "Unrecognized compiler directive was ignored"_warn_en_US)
9108         .set_usageWarning(common::UsageWarning::IgnoredDirective);
9109   }
9110 }
9111 
9112 bool ResolveNamesVisitor::Pre(const parser::ProgramUnit &x) {
9113   if (std::holds_alternative<common::Indirection<parser::CompilerDirective>>(
9114           x.u)) {
9115     // TODO: global directives
9116     return true;
9117   }
9118   if (std::holds_alternative<
9119           common::Indirection<parser::OpenACCRoutineConstruct>>(x.u)) {
9120     ResolveAccParts(context(), x, &topScope_);
9121     return false;
9122   }
9123   auto root{ProgramTree::Build(x, context())};
9124   SetScope(topScope_);
9125   ResolveSpecificationParts(root);
9126   FinishSpecificationParts(root);
9127   ResolveExecutionParts(root);
9128   FinishExecutionParts(root);
9129   ResolveAccParts(context(), x, /*topScope=*/nullptr);
9130   ResolveOmpParts(context(), x);
9131   return false;
9132 }
9133 
9134 template <typename A> std::set<SourceName> GetUses(const A &x) {
9135   std::set<SourceName> uses;
9136   if constexpr (!std::is_same_v<A, parser::CompilerDirective> &&
9137       !std::is_same_v<A, parser::OpenACCRoutineConstruct>) {
9138     const auto &spec{std::get<parser::SpecificationPart>(x.t)};
9139     const auto &unitUses{std::get<
9140         std::list<parser::Statement<common::Indirection<parser::UseStmt>>>>(
9141         spec.t)};
9142     for (const auto &u : unitUses) {
9143       uses.insert(u.statement.value().moduleName.source);
9144     }
9145   }
9146   return uses;
9147 }
9148 
9149 bool ResolveNamesVisitor::Pre(const parser::Program &x) {
9150   std::map<SourceName, const parser::ProgramUnit *> modules;
9151   std::set<SourceName> uses;
9152   bool disordered{false};
9153   for (const auto &progUnit : x.v) {
9154     if (const auto *indMod{
9155             std::get_if<common::Indirection<parser::Module>>(&progUnit.u)}) {
9156       const parser::Module &mod{indMod->value()};
9157       const auto &moduleStmt{
9158           std::get<parser::Statement<parser::ModuleStmt>>(mod.t)};
9159       const SourceName &name{moduleStmt.statement.v.source};
9160       if (auto iter{modules.find(name)}; iter != modules.end()) {
9161         Say(name,
9162             "Module '%s' appears multiple times in a compilation unit"_err_en_US)
9163             .Attach(iter->first, "First definition of module"_en_US);
9164         return true;
9165       }
9166       modules.emplace(name, &progUnit);
9167       if (auto iter{uses.find(name)}; iter != uses.end()) {
9168         if (context().ShouldWarn(common::LanguageFeature::MiscUseExtensions)) {
9169           Say(name,
9170               "A USE statement referencing module '%s' appears earlier in this compilation unit"_port_en_US,
9171               name)
9172               .Attach(*iter, "First USE of module"_en_US);
9173         }
9174         disordered = true;
9175       }
9176     }
9177     for (SourceName used : common::visit(
9178              [](const auto &indUnit) { return GetUses(indUnit.value()); },
9179              progUnit.u)) {
9180       uses.insert(used);
9181     }
9182   }
9183   if (!disordered) {
9184     return true;
9185   }
9186   // Process modules in topological order
9187   std::vector<const parser::ProgramUnit *> moduleOrder;
9188   while (!modules.empty()) {
9189     bool ok;
9190     for (const auto &pair : modules) {
9191       const SourceName &name{pair.first};
9192       const parser::ProgramUnit &progUnit{*pair.second};
9193       const parser::Module &m{
9194           std::get<common::Indirection<parser::Module>>(progUnit.u).value()};
9195       ok = true;
9196       for (const SourceName &use : GetUses(m)) {
9197         if (modules.find(use) != modules.end()) {
9198           ok = false;
9199           break;
9200         }
9201       }
9202       if (ok) {
9203         moduleOrder.push_back(&progUnit);
9204         modules.erase(name);
9205         break;
9206       }
9207     }
9208     if (!ok) {
9209       Message *msg{nullptr};
9210       for (const auto &pair : modules) {
9211         if (msg) {
9212           msg->Attach(pair.first, "Module in a cycle"_en_US);
9213         } else {
9214           msg = &Say(pair.first,
9215               "Some modules in this compilation unit form one or more cycles of dependence"_err_en_US);
9216         }
9217       }
9218       return false;
9219     }
9220   }
9221   // Modules can be ordered.  Process them first, and then all of the other
9222   // program units.
9223   for (const parser::ProgramUnit *progUnit : moduleOrder) {
9224     Walk(*progUnit);
9225   }
9226   for (const auto &progUnit : x.v) {
9227     if (!std::get_if<common::Indirection<parser::Module>>(&progUnit.u)) {
9228       Walk(progUnit);
9229     }
9230   }
9231   return false;
9232 }
9233 
9234 // References to procedures need to record that their symbols are known
9235 // to be procedures, so that they don't get converted to objects by default.
9236 class ExecutionPartCallSkimmer : public ExecutionPartSkimmerBase {
9237 public:
9238   explicit ExecutionPartCallSkimmer(ResolveNamesVisitor &resolver)
9239       : resolver_{resolver} {}
9240 
9241   void Walk(const parser::ExecutionPart &exec) {
9242     parser::Walk(exec, *this);
9243     EndWalk();
9244   }
9245 
9246   using ExecutionPartSkimmerBase::Post;
9247   using ExecutionPartSkimmerBase::Pre;
9248 
9249   void Post(const parser::FunctionReference &fr) {
9250     NoteCall(Symbol::Flag::Function, fr.v, false);
9251   }
9252   void Post(const parser::CallStmt &cs) {
9253     NoteCall(Symbol::Flag::Subroutine, cs.call, cs.chevrons.has_value());
9254   }
9255 
9256 private:
9257   void NoteCall(
9258       Symbol::Flag flag, const parser::Call &call, bool hasCUDAChevrons) {
9259     auto &designator{std::get<parser::ProcedureDesignator>(call.t)};
9260     if (const auto *name{std::get_if<parser::Name>(&designator.u)}) {
9261       if (!IsHidden(name->source)) {
9262         resolver_.NoteExecutablePartCall(flag, name->source, hasCUDAChevrons);
9263       }
9264     }
9265   }
9266 
9267   ResolveNamesVisitor &resolver_;
9268 };
9269 
9270 // Build the scope tree and resolve names in the specification parts of this
9271 // node and its children
9272 void ResolveNamesVisitor::ResolveSpecificationParts(ProgramTree &node) {
9273   if (node.isSpecificationPartResolved()) {
9274     return; // been here already
9275   }
9276   node.set_isSpecificationPartResolved();
9277   if (!BeginScopeForNode(node)) {
9278     return; // an error prevented scope from being created
9279   }
9280   Scope &scope{currScope()};
9281   node.set_scope(scope);
9282   AddSubpNames(node);
9283   common::visit(
9284       [&](const auto *x) {
9285         if (x) {
9286           Walk(*x);
9287         }
9288       },
9289       node.stmt());
9290   Walk(node.spec());
9291   // If this is a function, convert result to an object. This is to prevent the
9292   // result from being converted later to a function symbol if it is called
9293   // inside the function.
9294   // If the result is function pointer, then ConvertToObjectEntity will not
9295   // convert the result to an object, and calling the symbol inside the function
9296   // will result in calls to the result pointer.
9297   // A function cannot be called recursively if RESULT was not used to define a
9298   // distinct result name (15.6.2.2 point 4.).
9299   if (Symbol * symbol{scope.symbol()}) {
9300     if (auto *details{symbol->detailsIf<SubprogramDetails>()}) {
9301       if (details->isFunction()) {
9302         ConvertToObjectEntity(const_cast<Symbol &>(details->result()));
9303       }
9304     }
9305   }
9306   if (node.IsModule()) {
9307     ApplyDefaultAccess();
9308   }
9309   for (auto &child : node.children()) {
9310     ResolveSpecificationParts(child);
9311   }
9312   if (node.exec()) {
9313     ExecutionPartCallSkimmer{*this}.Walk(*node.exec());
9314     HandleImpliedAsynchronousInScope(node.exec()->v);
9315   }
9316   EndScopeForNode(node);
9317   // Ensure that every object entity has a type.
9318   bool inModule{node.GetKind() == ProgramTree::Kind::Module ||
9319       node.GetKind() == ProgramTree::Kind::Submodule};
9320   for (auto &pair : *node.scope()) {
9321     Symbol &symbol{*pair.second};
9322     if (inModule && symbol.attrs().test(Attr::EXTERNAL) && !IsPointer(symbol) &&
9323         !symbol.test(Symbol::Flag::Function) &&
9324         !symbol.test(Symbol::Flag::Subroutine)) {
9325       // in a module, external proc without return type is subroutine
9326       symbol.set(
9327           symbol.GetType() ? Symbol::Flag::Function : Symbol::Flag::Subroutine);
9328     }
9329     ApplyImplicitRules(symbol);
9330   }
9331 }
9332 
9333 // Add SubprogramNameDetails symbols for module and internal subprograms and
9334 // their ENTRY statements.
9335 void ResolveNamesVisitor::AddSubpNames(ProgramTree &node) {
9336   auto kind{
9337       node.IsModule() ? SubprogramKind::Module : SubprogramKind::Internal};
9338   for (auto &child : node.children()) {
9339     auto &symbol{MakeSymbol(child.name(), SubprogramNameDetails{kind, child})};
9340     if (child.HasModulePrefix()) {
9341       SetExplicitAttr(symbol, Attr::MODULE);
9342     }
9343     if (child.bindingSpec()) {
9344       SetExplicitAttr(symbol, Attr::BIND_C);
9345     }
9346     auto childKind{child.GetKind()};
9347     if (childKind == ProgramTree::Kind::Function) {
9348       symbol.set(Symbol::Flag::Function);
9349     } else if (childKind == ProgramTree::Kind::Subroutine) {
9350       symbol.set(Symbol::Flag::Subroutine);
9351     } else {
9352       continue; // make ENTRY symbols only where valid
9353     }
9354     for (const auto &entryStmt : child.entryStmts()) {
9355       SubprogramNameDetails details{kind, child};
9356       auto &symbol{
9357           MakeSymbol(std::get<parser::Name>(entryStmt->t), std::move(details))};
9358       symbol.set(child.GetSubpFlag());
9359       if (child.HasModulePrefix()) {
9360         SetExplicitAttr(symbol, Attr::MODULE);
9361       }
9362       if (child.bindingSpec()) {
9363         SetExplicitAttr(symbol, Attr::BIND_C);
9364       }
9365     }
9366   }
9367   for (const auto &generic : node.genericSpecs()) {
9368     if (const auto *name{std::get_if<parser::Name>(&generic->u)}) {
9369       if (currScope().find(name->source) != currScope().end()) {
9370         // If this scope has both a generic interface and a contained
9371         // subprogram with the same name, create the generic's symbol
9372         // now so that any other generics of the same name that are pulled
9373         // into scope later via USE association will properly merge instead
9374         // of raising a bogus error due a conflict with the subprogram.
9375         CreateGeneric(*generic);
9376       }
9377     }
9378   }
9379 }
9380 
9381 // Push a new scope for this node or return false on error.
9382 bool ResolveNamesVisitor::BeginScopeForNode(const ProgramTree &node) {
9383   switch (node.GetKind()) {
9384     SWITCH_COVERS_ALL_CASES
9385   case ProgramTree::Kind::Program:
9386     PushScope(Scope::Kind::MainProgram,
9387         &MakeSymbol(node.name(), MainProgramDetails{}));
9388     return true;
9389   case ProgramTree::Kind::Function:
9390   case ProgramTree::Kind::Subroutine:
9391     return BeginSubprogram(node.name(), node.GetSubpFlag(),
9392         node.HasModulePrefix(), node.bindingSpec(), &node.entryStmts());
9393   case ProgramTree::Kind::MpSubprogram:
9394     return BeginMpSubprogram(node.name());
9395   case ProgramTree::Kind::Module:
9396     BeginModule(node.name(), false);
9397     return true;
9398   case ProgramTree::Kind::Submodule:
9399     return BeginSubmodule(node.name(), node.GetParentId());
9400   case ProgramTree::Kind::BlockData:
9401     PushBlockDataScope(node.name());
9402     return true;
9403   }
9404 }
9405 
9406 void ResolveNamesVisitor::EndScopeForNode(const ProgramTree &node) {
9407   std::optional<parser::CharBlock> stmtSource;
9408   const std::optional<parser::LanguageBindingSpec> *binding{nullptr};
9409   common::visit(
9410       common::visitors{
9411           [&](const parser::Statement<parser::FunctionStmt> *stmt) {
9412             if (stmt) {
9413               stmtSource = stmt->source;
9414               if (const auto &maybeSuffix{
9415                       std::get<std::optional<parser::Suffix>>(
9416                           stmt->statement.t)}) {
9417                 binding = &maybeSuffix->binding;
9418               }
9419             }
9420           },
9421           [&](const parser::Statement<parser::SubroutineStmt> *stmt) {
9422             if (stmt) {
9423               stmtSource = stmt->source;
9424               binding = &std::get<std::optional<parser::LanguageBindingSpec>>(
9425                   stmt->statement.t);
9426             }
9427           },
9428           [](const auto *) {},
9429       },
9430       node.stmt());
9431   EndSubprogram(stmtSource, binding, &node.entryStmts());
9432 }
9433 
9434 // Some analyses and checks, such as the processing of initializers of
9435 // pointers, are deferred until all of the pertinent specification parts
9436 // have been visited.  This deferred processing enables the use of forward
9437 // references in these circumstances.
9438 // Data statement objects with implicit derived types are finally
9439 // resolved here.
9440 class DeferredCheckVisitor {
9441 public:
9442   explicit DeferredCheckVisitor(ResolveNamesVisitor &resolver)
9443       : resolver_{resolver} {}
9444 
9445   template <typename A> void Walk(const A &x) { parser::Walk(x, *this); }
9446 
9447   template <typename A> bool Pre(const A &) { return true; }
9448   template <typename A> void Post(const A &) {}
9449 
9450   void Post(const parser::DerivedTypeStmt &x) {
9451     const auto &name{std::get<parser::Name>(x.t)};
9452     if (Symbol * symbol{name.symbol}) {
9453       if (Scope * scope{symbol->scope()}) {
9454         if (scope->IsDerivedType()) {
9455           CHECK(outerScope_ == nullptr);
9456           outerScope_ = &resolver_.currScope();
9457           resolver_.SetScope(*scope);
9458         }
9459       }
9460     }
9461   }
9462   void Post(const parser::EndTypeStmt &) {
9463     if (outerScope_) {
9464       resolver_.SetScope(*outerScope_);
9465       outerScope_ = nullptr;
9466     }
9467   }
9468 
9469   void Post(const parser::ProcInterface &pi) {
9470     if (const auto *name{std::get_if<parser::Name>(&pi.u)}) {
9471       resolver_.CheckExplicitInterface(*name);
9472     }
9473   }
9474   bool Pre(const parser::EntityDecl &decl) {
9475     Init(std::get<parser::Name>(decl.t),
9476         std::get<std::optional<parser::Initialization>>(decl.t));
9477     return false;
9478   }
9479   bool Pre(const parser::ComponentDecl &decl) {
9480     Init(std::get<parser::Name>(decl.t),
9481         std::get<std::optional<parser::Initialization>>(decl.t));
9482     return false;
9483   }
9484   bool Pre(const parser::ProcDecl &decl) {
9485     if (const auto &init{
9486             std::get<std::optional<parser::ProcPointerInit>>(decl.t)}) {
9487       resolver_.PointerInitialization(std::get<parser::Name>(decl.t), *init);
9488     }
9489     return false;
9490   }
9491   void Post(const parser::TypeBoundProcedureStmt::WithInterface &tbps) {
9492     resolver_.CheckExplicitInterface(tbps.interfaceName);
9493   }
9494   void Post(const parser::TypeBoundProcedureStmt::WithoutInterface &tbps) {
9495     if (outerScope_) {
9496       resolver_.CheckBindings(tbps);
9497     }
9498   }
9499   bool Pre(const parser::DataStmtObject &) {
9500     ++dataStmtObjectNesting_;
9501     return true;
9502   }
9503   void Post(const parser::DataStmtObject &) { --dataStmtObjectNesting_; }
9504   void Post(const parser::Designator &x) {
9505     if (dataStmtObjectNesting_ > 0) {
9506       resolver_.ResolveDesignator(x);
9507     }
9508   }
9509 
9510 private:
9511   void Init(const parser::Name &name,
9512       const std::optional<parser::Initialization> &init) {
9513     if (init) {
9514       if (const auto *target{
9515               std::get_if<parser::InitialDataTarget>(&init->u)}) {
9516         resolver_.PointerInitialization(name, *target);
9517       } else if (const auto *expr{
9518                      std::get_if<parser::ConstantExpr>(&init->u)}) {
9519         if (name.symbol) {
9520           if (const auto *object{name.symbol->detailsIf<ObjectEntityDetails>()};
9521               !object || !object->init()) {
9522             resolver_.NonPointerInitialization(name, *expr);
9523           }
9524         }
9525       }
9526     }
9527   }
9528 
9529   ResolveNamesVisitor &resolver_;
9530   Scope *outerScope_{nullptr};
9531   int dataStmtObjectNesting_{0};
9532 };
9533 
9534 // Perform checks and completions that need to happen after all of
9535 // the specification parts but before any of the execution parts.
9536 void ResolveNamesVisitor::FinishSpecificationParts(const ProgramTree &node) {
9537   if (!node.scope()) {
9538     return; // error occurred creating scope
9539   }
9540   auto flagRestorer{common::ScopedSet(inSpecificationPart_, true)};
9541   SetScope(*node.scope());
9542   // The initializers of pointers and non-PARAMETER objects, the default
9543   // initializers of components, and non-deferred type-bound procedure
9544   // bindings have not yet been traversed.
9545   // We do that now, when any forward references that appeared
9546   // in those initializers will resolve to the right symbols without
9547   // incurring spurious errors with IMPLICIT NONE or forward references
9548   // to nested subprograms.
9549   DeferredCheckVisitor{*this}.Walk(node.spec());
9550   for (Scope &childScope : currScope().children()) {
9551     if (childScope.IsParameterizedDerivedTypeInstantiation()) {
9552       FinishDerivedTypeInstantiation(childScope);
9553     }
9554   }
9555   for (const auto &child : node.children()) {
9556     FinishSpecificationParts(child);
9557   }
9558 }
9559 
9560 void ResolveNamesVisitor::FinishExecutionParts(const ProgramTree &node) {
9561   if (node.scope()) {
9562     SetScope(*node.scope());
9563     if (node.exec()) {
9564       DeferredCheckVisitor{*this}.Walk(*node.exec());
9565     }
9566     for (const auto &child : node.children()) {
9567       FinishExecutionParts(child);
9568     }
9569   }
9570 }
9571 
9572 // Duplicate and fold component object pointer default initializer designators
9573 // using the actual type parameter values of each particular instantiation.
9574 // Validation is done later in declaration checking.
9575 void ResolveNamesVisitor::FinishDerivedTypeInstantiation(Scope &scope) {
9576   CHECK(scope.IsDerivedType() && !scope.symbol());
9577   if (DerivedTypeSpec * spec{scope.derivedTypeSpec()}) {
9578     spec->Instantiate(currScope());
9579     const Symbol &origTypeSymbol{spec->typeSymbol()};
9580     if (const Scope * origTypeScope{origTypeSymbol.scope()}) {
9581       CHECK(origTypeScope->IsDerivedType() &&
9582           origTypeScope->symbol() == &origTypeSymbol);
9583       auto &foldingContext{GetFoldingContext()};
9584       auto restorer{foldingContext.WithPDTInstance(*spec)};
9585       for (auto &pair : scope) {
9586         Symbol &comp{*pair.second};
9587         const Symbol &origComp{DEREF(FindInScope(*origTypeScope, comp.name()))};
9588         if (IsPointer(comp)) {
9589           if (auto *details{comp.detailsIf<ObjectEntityDetails>()}) {
9590             auto origDetails{origComp.get<ObjectEntityDetails>()};
9591             if (const MaybeExpr & init{origDetails.init()}) {
9592               SomeExpr newInit{*init};
9593               MaybeExpr folded{FoldExpr(std::move(newInit))};
9594               details->set_init(std::move(folded));
9595             }
9596           }
9597         }
9598       }
9599     }
9600   }
9601 }
9602 
9603 // Resolve names in the execution part of this node and its children
9604 void ResolveNamesVisitor::ResolveExecutionParts(const ProgramTree &node) {
9605   if (!node.scope()) {
9606     return; // error occurred creating scope
9607   }
9608   SetScope(*node.scope());
9609   if (const auto *exec{node.exec()}) {
9610     Walk(*exec);
9611   }
9612   FinishNamelists();
9613   if (node.IsModule()) {
9614     // A second final pass to catch new symbols added from implicitly
9615     // typed names in NAMELIST groups or the specification parts of
9616     // module subprograms.
9617     ApplyDefaultAccess();
9618   }
9619   PopScope(); // converts unclassified entities into objects
9620   for (const auto &child : node.children()) {
9621     ResolveExecutionParts(child);
9622   }
9623 }
9624 
9625 void ResolveNamesVisitor::Post(const parser::Program &x) {
9626   // ensure that all temps were deallocated
9627   CHECK(!attrs_);
9628   CHECK(!cudaDataAttr_);
9629   CHECK(!GetDeclTypeSpec());
9630   // Top-level resolution to propagate information across program units after
9631   // each of them has been resolved separately.
9632   ResolveOmpTopLevelParts(context(), x);
9633 }
9634 
9635 // A singleton instance of the scope -> IMPLICIT rules mapping is
9636 // shared by all instances of ResolveNamesVisitor and accessed by this
9637 // pointer when the visitors (other than the top-level original) are
9638 // constructed.
9639 static ImplicitRulesMap *sharedImplicitRulesMap{nullptr};
9640 
9641 bool ResolveNames(
9642     SemanticsContext &context, const parser::Program &program, Scope &top) {
9643   ImplicitRulesMap implicitRulesMap;
9644   auto restorer{common::ScopedSet(sharedImplicitRulesMap, &implicitRulesMap)};
9645   ResolveNamesVisitor{context, implicitRulesMap, top}.Walk(program);
9646   return !context.AnyFatalError();
9647 }
9648 
9649 // Processes a module (but not internal) function when it is referenced
9650 // in a specification expression in a sibling procedure.
9651 void ResolveSpecificationParts(
9652     SemanticsContext &context, const Symbol &subprogram) {
9653   auto originalLocation{context.location()};
9654   ImplicitRulesMap implicitRulesMap;
9655   bool localImplicitRulesMap{false};
9656   if (!sharedImplicitRulesMap) {
9657     sharedImplicitRulesMap = &implicitRulesMap;
9658     localImplicitRulesMap = true;
9659   }
9660   ResolveNamesVisitor visitor{
9661       context, *sharedImplicitRulesMap, context.globalScope()};
9662   const auto &details{subprogram.get<SubprogramNameDetails>()};
9663   ProgramTree &node{details.node()};
9664   const Scope &moduleScope{subprogram.owner()};
9665   if (localImplicitRulesMap) {
9666     visitor.BeginScope(const_cast<Scope &>(moduleScope));
9667   } else {
9668     visitor.SetScope(const_cast<Scope &>(moduleScope));
9669   }
9670   visitor.ResolveSpecificationParts(node);
9671   context.set_location(std::move(originalLocation));
9672   if (localImplicitRulesMap) {
9673     sharedImplicitRulesMap = nullptr;
9674   }
9675 }
9676 
9677 } // namespace Fortran::semantics
9678