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 "mod-file.h"
11 #include "pointer-assignment.h"
12 #include "program-tree.h"
13 #include "resolve-directives.h"
14 #include "resolve-names-utils.h"
15 #include "rewrite-parse-tree.h"
16 #include "flang/Common/Fortran.h"
17 #include "flang/Common/default-kinds.h"
18 #include "flang/Common/indirection.h"
19 #include "flang/Common/restorer.h"
20 #include "flang/Common/visit.h"
21 #include "flang/Evaluate/characteristics.h"
22 #include "flang/Evaluate/check-expression.h"
23 #include "flang/Evaluate/common.h"
24 #include "flang/Evaluate/fold-designator.h"
25 #include "flang/Evaluate/fold.h"
26 #include "flang/Evaluate/intrinsics.h"
27 #include "flang/Evaluate/tools.h"
28 #include "flang/Evaluate/type.h"
29 #include "flang/Parser/parse-tree-visitor.h"
30 #include "flang/Parser/parse-tree.h"
31 #include "flang/Parser/tools.h"
32 #include "flang/Semantics/attr.h"
33 #include "flang/Semantics/expression.h"
34 #include "flang/Semantics/scope.h"
35 #include "flang/Semantics/semantics.h"
36 #include "flang/Semantics/symbol.h"
37 #include "flang/Semantics/tools.h"
38 #include "flang/Semantics/type.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <list>
41 #include <map>
42 #include <set>
43 #include <stack>
44 
45 namespace Fortran::semantics {
46 
47 using namespace parser::literals;
48 
49 template <typename T> using Indirection = common::Indirection<T>;
50 using Message = parser::Message;
51 using Messages = parser::Messages;
52 using MessageFixedText = parser::MessageFixedText;
53 using MessageFormattedText = parser::MessageFormattedText;
54 
55 class ResolveNamesVisitor;
56 class ScopeHandler;
57 
58 // ImplicitRules maps initial character of identifier to the DeclTypeSpec
59 // representing the implicit type; std::nullopt if none.
60 // It also records the presence of IMPLICIT NONE statements.
61 // When inheritFromParent is set, defaults come from the parent rules.
62 class ImplicitRules {
63 public:
64   ImplicitRules(SemanticsContext &context, ImplicitRules *parent)
65       : parent_{parent}, context_{context} {
66     inheritFromParent_ = parent != nullptr;
67   }
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   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 //   |       + InterfaceVisitor      |  |
140 //   |       +-+ SubprogramVisitor ==|==+
141 //   + ArraySpecVisitor              |  |
142 //     + DeclarationVisitor <--------+  |
143 //       + ConstructVisitor             |
144 //         + ResolveNamesVisitor <------+
145 
146 class BaseVisitor {
147 public:
148   BaseVisitor() { DIE("BaseVisitor: default-constructed"); }
149   BaseVisitor(
150       SemanticsContext &c, ResolveNamesVisitor &v, ImplicitRulesMap &rules)
151       : implicitRulesMap_{&rules}, this_{&v}, context_{&c}, messageHandler_{c} {
152   }
153   template <typename T> void Walk(const T &);
154 
155   MessageHandler &messageHandler() { return messageHandler_; }
156   const std::optional<SourceName> &currStmtSource() {
157     return context_->location();
158   }
159   SemanticsContext &context() const { return *context_; }
160   evaluate::FoldingContext &GetFoldingContext() const {
161     return context_->foldingContext();
162   }
163   bool IsIntrinsic(
164       const SourceName &name, std::optional<Symbol::Flag> flag) const {
165     if (!flag) {
166       return context_->intrinsics().IsIntrinsic(name.ToString());
167     } else if (flag == Symbol::Flag::Function) {
168       return context_->intrinsics().IsIntrinsicFunction(name.ToString());
169     } else if (flag == Symbol::Flag::Subroutine) {
170       return context_->intrinsics().IsIntrinsicSubroutine(name.ToString());
171     } else {
172       DIE("expected Subroutine or Function flag");
173     }
174   }
175 
176   // Make a placeholder symbol for a Name that otherwise wouldn't have one.
177   // It is not in any scope and always has MiscDetails.
178   void MakePlaceholder(const parser::Name &, MiscDetails::Kind);
179 
180   template <typename T> common::IfNoLvalue<T, T> FoldExpr(T &&expr) {
181     return evaluate::Fold(GetFoldingContext(), std::move(expr));
182   }
183 
184   template <typename T> MaybeExpr EvaluateExpr(const T &expr) {
185     return FoldExpr(AnalyzeExpr(*context_, expr));
186   }
187 
188   template <typename T>
189   MaybeExpr EvaluateNonPointerInitializer(
190       const Symbol &symbol, const T &expr, parser::CharBlock source) {
191     if (!context().HasError(symbol)) {
192       if (auto maybeExpr{AnalyzeExpr(*context_, expr)}) {
193         auto restorer{GetFoldingContext().messages().SetLocation(source)};
194         return evaluate::NonPointerInitializationExpr(
195             symbol, std::move(*maybeExpr), GetFoldingContext());
196       }
197     }
198     return std::nullopt;
199   }
200 
201   template <typename T> MaybeIntExpr EvaluateIntExpr(const T &expr) {
202     return semantics::EvaluateIntExpr(*context_, expr);
203   }
204 
205   template <typename T>
206   MaybeSubscriptIntExpr EvaluateSubscriptIntExpr(const T &expr) {
207     if (MaybeIntExpr maybeIntExpr{EvaluateIntExpr(expr)}) {
208       return FoldExpr(evaluate::ConvertToType<evaluate::SubscriptInteger>(
209           std::move(*maybeIntExpr)));
210     } else {
211       return std::nullopt;
212     }
213   }
214 
215   template <typename... A> Message &Say(A &&...args) {
216     return messageHandler_.Say(std::forward<A>(args)...);
217   }
218   template <typename... A>
219   Message &Say(
220       const parser::Name &name, MessageFixedText &&text, const A &...args) {
221     return messageHandler_.Say(name.source, std::move(text), args...);
222   }
223 
224 protected:
225   ImplicitRulesMap *implicitRulesMap_{nullptr};
226 
227 private:
228   ResolveNamesVisitor *this_;
229   SemanticsContext *context_;
230   MessageHandler messageHandler_;
231 };
232 
233 // Provide Post methods to collect attributes into a member variable.
234 class AttrsVisitor : public virtual BaseVisitor {
235 public:
236   bool BeginAttrs(); // always returns true
237   Attrs GetAttrs();
238   Attrs EndAttrs();
239   bool SetPassNameOn(Symbol &);
240   void SetBindNameOn(Symbol &);
241   void Post(const parser::LanguageBindingSpec &);
242   bool Pre(const parser::IntentSpec &);
243   bool Pre(const parser::Pass &);
244 
245   bool CheckAndSet(Attr);
246 
247 // Simple case: encountering CLASSNAME causes ATTRNAME to be set.
248 #define HANDLE_ATTR_CLASS(CLASSNAME, ATTRNAME) \
249   bool Pre(const parser::CLASSNAME &) { \
250     CheckAndSet(Attr::ATTRNAME); \
251     return false; \
252   }
253   HANDLE_ATTR_CLASS(PrefixSpec::Elemental, ELEMENTAL)
254   HANDLE_ATTR_CLASS(PrefixSpec::Impure, IMPURE)
255   HANDLE_ATTR_CLASS(PrefixSpec::Module, MODULE)
256   HANDLE_ATTR_CLASS(PrefixSpec::Non_Recursive, NON_RECURSIVE)
257   HANDLE_ATTR_CLASS(PrefixSpec::Pure, PURE)
258   HANDLE_ATTR_CLASS(PrefixSpec::Recursive, RECURSIVE)
259   HANDLE_ATTR_CLASS(TypeAttrSpec::BindC, BIND_C)
260   HANDLE_ATTR_CLASS(BindAttr::Deferred, DEFERRED)
261   HANDLE_ATTR_CLASS(BindAttr::Non_Overridable, NON_OVERRIDABLE)
262   HANDLE_ATTR_CLASS(Abstract, ABSTRACT)
263   HANDLE_ATTR_CLASS(Allocatable, ALLOCATABLE)
264   HANDLE_ATTR_CLASS(Asynchronous, ASYNCHRONOUS)
265   HANDLE_ATTR_CLASS(Contiguous, CONTIGUOUS)
266   HANDLE_ATTR_CLASS(External, EXTERNAL)
267   HANDLE_ATTR_CLASS(Intrinsic, INTRINSIC)
268   HANDLE_ATTR_CLASS(NoPass, NOPASS)
269   HANDLE_ATTR_CLASS(Optional, OPTIONAL)
270   HANDLE_ATTR_CLASS(Parameter, PARAMETER)
271   HANDLE_ATTR_CLASS(Pointer, POINTER)
272   HANDLE_ATTR_CLASS(Protected, PROTECTED)
273   HANDLE_ATTR_CLASS(Save, SAVE)
274   HANDLE_ATTR_CLASS(Target, TARGET)
275   HANDLE_ATTR_CLASS(Value, VALUE)
276   HANDLE_ATTR_CLASS(Volatile, VOLATILE)
277 #undef HANDLE_ATTR_CLASS
278 
279 protected:
280   std::optional<Attrs> attrs_;
281 
282   Attr AccessSpecToAttr(const parser::AccessSpec &x) {
283     switch (x.v) {
284     case parser::AccessSpec::Kind::Public:
285       return Attr::PUBLIC;
286     case parser::AccessSpec::Kind::Private:
287       return Attr::PRIVATE;
288     }
289     llvm_unreachable("Switch covers all cases"); // suppress g++ warning
290   }
291   Attr IntentSpecToAttr(const parser::IntentSpec &x) {
292     switch (x.v) {
293     case parser::IntentSpec::Intent::In:
294       return Attr::INTENT_IN;
295     case parser::IntentSpec::Intent::Out:
296       return Attr::INTENT_OUT;
297     case parser::IntentSpec::Intent::InOut:
298       return Attr::INTENT_INOUT;
299     }
300     llvm_unreachable("Switch covers all cases"); // suppress g++ warning
301   }
302 
303 private:
304   bool IsDuplicateAttr(Attr);
305   bool HaveAttrConflict(Attr, Attr, Attr);
306   bool IsConflictingAttr(Attr);
307 
308   MaybeExpr bindName_; // from BIND(C, NAME="...")
309   std::optional<SourceName> passName_; // from PASS(...)
310 };
311 
312 // Find and create types from declaration-type-spec nodes.
313 class DeclTypeSpecVisitor : public AttrsVisitor {
314 public:
315   using AttrsVisitor::Post;
316   using AttrsVisitor::Pre;
317   void Post(const parser::IntrinsicTypeSpec::DoublePrecision &);
318   void Post(const parser::IntrinsicTypeSpec::DoubleComplex &);
319   void Post(const parser::DeclarationTypeSpec::ClassStar &);
320   void Post(const parser::DeclarationTypeSpec::TypeStar &);
321   bool Pre(const parser::TypeGuardStmt &);
322   void Post(const parser::TypeGuardStmt &);
323   void Post(const parser::TypeSpec &);
324 
325   // Walk the parse tree of a type spec and return the DeclTypeSpec for it.
326   template <typename T>
327   const DeclTypeSpec *ProcessTypeSpec(const T &x, bool allowForward = false) {
328     auto restorer{common::ScopedSet(state_, State{})};
329     set_allowForwardReferenceToDerivedType(allowForward);
330     BeginDeclTypeSpec();
331     Walk(x);
332     const auto *type{GetDeclTypeSpec()};
333     EndDeclTypeSpec();
334     return type;
335   }
336 
337 protected:
338   struct State {
339     bool expectDeclTypeSpec{false}; // should see decl-type-spec only when true
340     const DeclTypeSpec *declTypeSpec{nullptr};
341     struct {
342       DerivedTypeSpec *type{nullptr};
343       DeclTypeSpec::Category category{DeclTypeSpec::TypeDerived};
344     } derived;
345     bool allowForwardReferenceToDerivedType{false};
346   };
347 
348   bool allowForwardReferenceToDerivedType() const {
349     return state_.allowForwardReferenceToDerivedType;
350   }
351   void set_allowForwardReferenceToDerivedType(bool yes) {
352     state_.allowForwardReferenceToDerivedType = yes;
353   }
354 
355   const DeclTypeSpec *GetDeclTypeSpec();
356   void BeginDeclTypeSpec();
357   void EndDeclTypeSpec();
358   void SetDeclTypeSpec(const DeclTypeSpec &);
359   void SetDeclTypeSpecCategory(DeclTypeSpec::Category);
360   DeclTypeSpec::Category GetDeclTypeSpecCategory() const {
361     return state_.derived.category;
362   }
363   KindExpr GetKindParamExpr(
364       TypeCategory, const std::optional<parser::KindSelector> &);
365   void CheckForAbstractType(const Symbol &typeSymbol);
366 
367 private:
368   State state_;
369 
370   void MakeNumericType(TypeCategory, int kind);
371 };
372 
373 // Visit ImplicitStmt and related parse tree nodes and updates implicit rules.
374 class ImplicitRulesVisitor : public DeclTypeSpecVisitor {
375 public:
376   using DeclTypeSpecVisitor::Post;
377   using DeclTypeSpecVisitor::Pre;
378   using ImplicitNoneNameSpec = parser::ImplicitStmt::ImplicitNoneNameSpec;
379 
380   void Post(const parser::ParameterStmt &);
381   bool Pre(const parser::ImplicitStmt &);
382   bool Pre(const parser::LetterSpec &);
383   bool Pre(const parser::ImplicitSpec &);
384   void Post(const parser::ImplicitSpec &);
385 
386   const DeclTypeSpec *GetType(
387       SourceName name, bool respectImplicitNoneType = true) {
388     return implicitRules_->GetType(name, respectImplicitNoneType);
389   }
390   bool isImplicitNoneType() const {
391     return implicitRules_->isImplicitNoneType();
392   }
393   bool isImplicitNoneType(const Scope &scope) const {
394     return implicitRulesMap_->at(&scope).isImplicitNoneType();
395   }
396   bool isImplicitNoneExternal() const {
397     return implicitRules_->isImplicitNoneExternal();
398   }
399   void set_inheritFromParent(bool x) {
400     implicitRules_->set_inheritFromParent(x);
401   }
402 
403 protected:
404   void BeginScope(const Scope &);
405   void SetScope(const Scope &);
406 
407 private:
408   // implicit rules in effect for current scope
409   ImplicitRules *implicitRules_{nullptr};
410   std::optional<SourceName> prevImplicit_;
411   std::optional<SourceName> prevImplicitNone_;
412   std::optional<SourceName> prevImplicitNoneType_;
413   std::optional<SourceName> prevParameterStmt_;
414 
415   bool HandleImplicitNone(const std::list<ImplicitNoneNameSpec> &nameSpecs);
416 };
417 
418 // Track array specifications. They can occur in AttrSpec, EntityDecl,
419 // ObjectDecl, DimensionStmt, CommonBlockObject, or BasedPointerStmt.
420 // 1. INTEGER, DIMENSION(10) :: x
421 // 2. INTEGER :: x(10)
422 // 3. ALLOCATABLE :: x(:)
423 // 4. DIMENSION :: x(10)
424 // 5. COMMON x(10)
425 // 6. BasedPointerStmt
426 class ArraySpecVisitor : public virtual BaseVisitor {
427 public:
428   void Post(const parser::ArraySpec &);
429   void Post(const parser::ComponentArraySpec &);
430   void Post(const parser::CoarraySpec &);
431   void Post(const parser::AttrSpec &) { PostAttrSpec(); }
432   void Post(const parser::ComponentAttrSpec &) { PostAttrSpec(); }
433 
434 protected:
435   const ArraySpec &arraySpec();
436   void set_arraySpec(const ArraySpec arraySpec) { arraySpec_ = arraySpec; }
437   const ArraySpec &coarraySpec();
438   void BeginArraySpec();
439   void EndArraySpec();
440   void ClearArraySpec() { arraySpec_.clear(); }
441   void ClearCoarraySpec() { coarraySpec_.clear(); }
442 
443 private:
444   // arraySpec_/coarraySpec_ are populated from any ArraySpec/CoarraySpec
445   ArraySpec arraySpec_;
446   ArraySpec coarraySpec_;
447   // When an ArraySpec is under an AttrSpec or ComponentAttrSpec, it is moved
448   // into attrArraySpec_
449   ArraySpec attrArraySpec_;
450   ArraySpec attrCoarraySpec_;
451 
452   void PostAttrSpec();
453 };
454 
455 // Manages a stack of function result information.  We defer the processing
456 // of a type specification that appears in the prefix of a FUNCTION statement
457 // until the function result variable appears in the specification part
458 // or the end of the specification part.  This allows for forward references
459 // in the type specification to resolve to local names.
460 class FuncResultStack {
461 public:
462   explicit FuncResultStack(ScopeHandler &scopeHandler)
463       : scopeHandler_{scopeHandler} {}
464   ~FuncResultStack();
465 
466   struct FuncInfo {
467     explicit FuncInfo(const Scope &s) : scope{s} {}
468     const Scope &scope;
469     // Parse tree of the type specification in the FUNCTION prefix
470     const parser::DeclarationTypeSpec *parsedType{nullptr};
471     // Name of the function RESULT in the FUNCTION suffix, if any
472     const parser::Name *resultName{nullptr};
473     // Result symbol
474     Symbol *resultSymbol{nullptr};
475     std::optional<SourceName> source;
476     bool inFunctionStmt{false}; // true between Pre/Post of FunctionStmt
477   };
478 
479   // Completes the definition of the top function's result.
480   void CompleteFunctionResultType();
481   // Completes the definition of a symbol if it is the top function's result.
482   void CompleteTypeIfFunctionResult(Symbol &);
483 
484   FuncInfo *Top() { return stack_.empty() ? nullptr : &stack_.back(); }
485   FuncInfo &Push(const Scope &scope) { return stack_.emplace_back(scope); }
486   void Pop();
487 
488 private:
489   ScopeHandler &scopeHandler_;
490   std::vector<FuncInfo> stack_;
491 };
492 
493 // Manage a stack of Scopes
494 class ScopeHandler : public ImplicitRulesVisitor {
495 public:
496   using ImplicitRulesVisitor::Post;
497   using ImplicitRulesVisitor::Pre;
498 
499   Scope &currScope() { return DEREF(currScope_); }
500   // The enclosing host procedure if current scope is in an internal procedure
501   Scope *GetHostProcedure();
502   // The innermost enclosing program unit scope, ignoring BLOCK and other
503   // construct scopes.
504   Scope &InclusiveScope();
505   // The enclosing scope, skipping derived types.
506   Scope &NonDerivedTypeScope();
507 
508   // Create a new scope and push it on the scope stack.
509   void PushScope(Scope::Kind kind, Symbol *symbol);
510   void PushScope(Scope &scope);
511   void PopScope();
512   void SetScope(Scope &);
513 
514   template <typename T> bool Pre(const parser::Statement<T> &x) {
515     messageHandler().set_currStmtSource(x.source);
516     currScope_->AddSourceRange(x.source);
517     return true;
518   }
519   template <typename T> void Post(const parser::Statement<T> &) {
520     messageHandler().set_currStmtSource(std::nullopt);
521   }
522 
523   // Special messages: already declared; referencing symbol's declaration;
524   // about a type; two names & locations
525   void SayAlreadyDeclared(const parser::Name &, Symbol &);
526   void SayAlreadyDeclared(const SourceName &, Symbol &);
527   void SayAlreadyDeclared(const SourceName &, const SourceName &);
528   void SayWithReason(
529       const parser::Name &, Symbol &, MessageFixedText &&, Message &&);
530   void SayWithDecl(const parser::Name &, Symbol &, MessageFixedText &&);
531   void SayLocalMustBeVariable(const parser::Name &, Symbol &);
532   void SayDerivedType(const SourceName &, MessageFixedText &&, const Scope &);
533   void Say2(const SourceName &, MessageFixedText &&, const SourceName &,
534       MessageFixedText &&);
535   void Say2(
536       const SourceName &, MessageFixedText &&, Symbol &, MessageFixedText &&);
537   void Say2(
538       const parser::Name &, MessageFixedText &&, Symbol &, MessageFixedText &&);
539 
540   // Search for symbol by name in current, parent derived type, and
541   // containing scopes
542   Symbol *FindSymbol(const parser::Name &);
543   Symbol *FindSymbol(const Scope &, const parser::Name &);
544   // Search for name only in scope, not in enclosing scopes.
545   Symbol *FindInScope(const Scope &, const parser::Name &);
546   Symbol *FindInScope(const Scope &, const SourceName &);
547   template <typename T> Symbol *FindInScope(const T &name) {
548     return FindInScope(currScope(), name);
549   }
550   // Search for name in a derived type scope and its parents.
551   Symbol *FindInTypeOrParents(const Scope &, const parser::Name &);
552   Symbol *FindInTypeOrParents(const parser::Name &);
553   void EraseSymbol(const parser::Name &);
554   void EraseSymbol(const Symbol &symbol) { currScope().erase(symbol.name()); }
555   // Make a new symbol with the name and attrs of an existing one
556   Symbol &CopySymbol(const SourceName &, const Symbol &);
557 
558   // Make symbols in the current or named scope
559   Symbol &MakeSymbol(Scope &, const SourceName &, Attrs);
560   Symbol &MakeSymbol(const SourceName &, Attrs = Attrs{});
561   Symbol &MakeSymbol(const parser::Name &, Attrs = Attrs{});
562   Symbol &MakeHostAssocSymbol(const parser::Name &, const Symbol &);
563 
564   template <typename D>
565   common::IfNoLvalue<Symbol &, D> MakeSymbol(
566       const parser::Name &name, D &&details) {
567     return MakeSymbol(name, Attrs{}, std::move(details));
568   }
569 
570   template <typename D>
571   common::IfNoLvalue<Symbol &, D> MakeSymbol(
572       const parser::Name &name, const Attrs &attrs, D &&details) {
573     return Resolve(name, MakeSymbol(name.source, attrs, std::move(details)));
574   }
575 
576   template <typename D>
577   common::IfNoLvalue<Symbol &, D> MakeSymbol(
578       const SourceName &name, const Attrs &attrs, D &&details) {
579     // Note: don't use FindSymbol here. If this is a derived type scope,
580     // we want to detect whether the name is already declared as a component.
581     auto *symbol{FindInScope(name)};
582     if (!symbol) {
583       symbol = &MakeSymbol(name, attrs);
584       symbol->set_details(std::move(details));
585       return *symbol;
586     }
587     if constexpr (std::is_same_v<DerivedTypeDetails, D>) {
588       if (auto *d{symbol->detailsIf<GenericDetails>()}) {
589         if (!d->specific()) {
590           // derived type with same name as a generic
591           auto *derivedType{d->derivedType()};
592           if (!derivedType) {
593             derivedType =
594                 &currScope().MakeSymbol(name, attrs, std::move(details));
595             d->set_derivedType(*derivedType);
596           } else if (derivedType->CanReplaceDetails(details)) {
597             // was forward-referenced
598             derivedType->attrs() |= attrs;
599             derivedType->set_details(std::move(details));
600           } else {
601             SayAlreadyDeclared(name, *derivedType);
602           }
603           return *derivedType;
604         }
605       }
606     }
607     if (symbol->CanReplaceDetails(details)) {
608       // update the existing symbol
609       symbol->attrs() |= attrs;
610       if constexpr (std::is_same_v<SubprogramDetails, D>) {
611         // Dummy argument defined by explicit interface
612         details.set_isDummy(IsDummy(*symbol));
613       }
614       symbol->set_details(std::move(details));
615       return *symbol;
616     } else if constexpr (std::is_same_v<UnknownDetails, D>) {
617       symbol->attrs() |= attrs;
618       return *symbol;
619     } else {
620       if (!CheckPossibleBadForwardRef(*symbol)) {
621         if (name.empty() && symbol->name().empty()) {
622           // report the error elsewhere
623           return *symbol;
624         }
625         SayAlreadyDeclared(name, *symbol);
626       }
627       // replace the old symbol with a new one with correct details
628       EraseSymbol(*symbol);
629       auto &result{MakeSymbol(name, attrs, std::move(details))};
630       context().SetError(result);
631       return result;
632     }
633   }
634 
635   void MakeExternal(Symbol &);
636 
637 protected:
638   FuncResultStack &funcResultStack() { return funcResultStack_; }
639 
640   // Apply the implicit type rules to this symbol.
641   void ApplyImplicitRules(Symbol &, bool allowForwardReference = false);
642   bool ImplicitlyTypeForwardRef(Symbol &);
643   void AcquireIntrinsicProcedureFlags(Symbol &);
644   const DeclTypeSpec *GetImplicitType(
645       Symbol &, bool respectImplicitNoneType = true);
646   bool ConvertToObjectEntity(Symbol &);
647   bool ConvertToProcEntity(Symbol &);
648 
649   const DeclTypeSpec &MakeNumericType(
650       TypeCategory, const std::optional<parser::KindSelector> &);
651   const DeclTypeSpec &MakeLogicalType(
652       const std::optional<parser::KindSelector> &);
653   void NotePossibleBadForwardRef(const parser::Name &);
654   std::optional<SourceName> HadForwardRef(const Symbol &) const;
655   bool CheckPossibleBadForwardRef(const Symbol &);
656 
657   bool inSpecificationPart_{false};
658   bool inEquivalenceStmt_{false};
659 
660   // Some information is collected from a specification part for deferred
661   // processing in DeclarationPartVisitor functions (e.g., CheckSaveStmts())
662   // that are called by ResolveNamesVisitor::FinishSpecificationPart().  Since
663   // specification parts can nest (e.g., INTERFACE bodies), the collected
664   // information that is not contained in the scope needs to be packaged
665   // and restorable.
666   struct SpecificationPartState {
667     std::set<SourceName> forwardRefs;
668     // Collect equivalence sets and process at end of specification part
669     std::vector<const std::list<parser::EquivalenceObject> *> equivalenceSets;
670     // Names of all common block objects in the scope
671     std::set<SourceName> commonBlockObjects;
672     // Info about about SAVE statements and attributes in current scope
673     struct {
674       std::optional<SourceName> saveAll; // "SAVE" without entity list
675       std::set<SourceName> entities; // names of entities with save attr
676       std::set<SourceName> commons; // names of common blocks with save attr
677     } saveInfo;
678   } specPartState_;
679 
680   // Some declaration processing can and should be deferred to
681   // ResolveExecutionParts() to avoid prematurely creating implicitly-typed
682   // local symbols that should be host associations.
683   struct DeferredDeclarationState {
684     // The content of each namelist group
685     std::list<const parser::NamelistStmt::Group *> namelistGroups;
686   };
687   DeferredDeclarationState *GetDeferredDeclarationState(bool add = false) {
688     if (!add && deferred_.find(&currScope()) == deferred_.end()) {
689       return nullptr;
690     } else {
691       return &deferred_.emplace(&currScope(), DeferredDeclarationState{})
692                   .first->second;
693     }
694   }
695 
696 private:
697   Scope *currScope_{nullptr};
698   FuncResultStack funcResultStack_{*this};
699   std::map<Scope *, DeferredDeclarationState> deferred_;
700 };
701 
702 class ModuleVisitor : public virtual ScopeHandler {
703 public:
704   bool Pre(const parser::AccessStmt &);
705   bool Pre(const parser::Only &);
706   bool Pre(const parser::Rename::Names &);
707   bool Pre(const parser::Rename::Operators &);
708   bool Pre(const parser::UseStmt &);
709   void Post(const parser::UseStmt &);
710 
711   void BeginModule(const parser::Name &, bool isSubmodule);
712   bool BeginSubmodule(const parser::Name &, const parser::ParentIdentifier &);
713   void ApplyDefaultAccess();
714   Symbol &AddGenericUse(GenericDetails &, const SourceName &, const Symbol &);
715   void AddAndCheckExplicitIntrinsicUse(SourceName, bool isIntrinsic);
716   void ClearUseRenames() { useRenames_.clear(); }
717   void ClearUseOnly() { useOnly_.clear(); }
718   void ClearExplicitIntrinsicUses() {
719     explicitIntrinsicUses_.clear();
720     explicitNonIntrinsicUses_.clear();
721   }
722 
723 private:
724   // The default access spec for this module.
725   Attr defaultAccess_{Attr::PUBLIC};
726   // The location of the last AccessStmt without access-ids, if any.
727   std::optional<SourceName> prevAccessStmt_;
728   // The scope of the module during a UseStmt
729   Scope *useModuleScope_{nullptr};
730   // Names that have appeared in a rename clause of a USE statement
731   std::set<std::pair<SourceName, Scope *>> useRenames_;
732   // Names that have appeared in an ONLY clause of a USE statement
733   std::set<std::pair<SourceName, Scope *>> useOnly_;
734   // Module names that have appeared in USE statements with explicit
735   // INTRINSIC or NON_INTRINSIC keywords
736   std::set<SourceName> explicitIntrinsicUses_;
737   std::set<SourceName> explicitNonIntrinsicUses_;
738 
739   Symbol &SetAccess(const SourceName &, Attr attr, Symbol * = nullptr);
740   // A rename in a USE statement: local => use
741   struct SymbolRename {
742     Symbol *local{nullptr};
743     Symbol *use{nullptr};
744   };
745   // Record a use from useModuleScope_ of use Name/Symbol as local Name/Symbol
746   SymbolRename AddUse(const SourceName &localName, const SourceName &useName);
747   SymbolRename AddUse(const SourceName &, const SourceName &, Symbol *);
748   void DoAddUse(
749       SourceName, SourceName, Symbol &localSymbol, const Symbol &useSymbol);
750   void AddUse(const GenericSpecInfo &);
751   // If appropriate, erase a previously USE-associated symbol
752   void EraseRenamedSymbol(const Symbol &);
753   // Record a name appearing in a USE rename clause
754   void AddUseRename(const SourceName &name) {
755     useRenames_.emplace(std::make_pair(name, useModuleScope_));
756   }
757   bool IsUseRenamed(const SourceName &name) const {
758     return useRenames_.find({name, useModuleScope_}) != useRenames_.end();
759   }
760   // Record a name appearing in a USE ONLY clause
761   void AddUseOnly(const SourceName &name) {
762     useOnly_.emplace(std::make_pair(name, useModuleScope_));
763   }
764   bool IsUseOnly(const SourceName &name) const {
765     return useOnly_.find({name, useModuleScope_}) != useOnly_.end();
766   }
767   Scope *FindModule(const parser::Name &, std::optional<bool> isIntrinsic,
768       Scope *ancestor = nullptr);
769 };
770 
771 class InterfaceVisitor : public virtual ScopeHandler {
772 public:
773   bool Pre(const parser::InterfaceStmt &);
774   void Post(const parser::InterfaceStmt &);
775   void Post(const parser::EndInterfaceStmt &);
776   bool Pre(const parser::GenericSpec &);
777   bool Pre(const parser::ProcedureStmt &);
778   bool Pre(const parser::GenericStmt &);
779   void Post(const parser::GenericStmt &);
780 
781   bool inInterfaceBlock() const;
782   bool isGeneric() const;
783   bool isAbstract() const;
784 
785 protected:
786   Symbol &GetGenericSymbol() { return DEREF(genericInfo_.top().symbol); }
787   // Add to generic the symbol for the subprogram with the same name
788   void CheckGenericProcedures(Symbol &);
789 
790 private:
791   // A new GenericInfo is pushed for each interface block and generic stmt
792   struct GenericInfo {
793     GenericInfo(bool isInterface, bool isAbstract = false)
794         : isInterface{isInterface}, isAbstract{isAbstract} {}
795     bool isInterface; // in interface block
796     bool isAbstract; // in abstract interface block
797     Symbol *symbol{nullptr}; // the generic symbol being defined
798   };
799   std::stack<GenericInfo> genericInfo_;
800   const GenericInfo &GetGenericInfo() const { return genericInfo_.top(); }
801   void SetGenericSymbol(Symbol &symbol) { genericInfo_.top().symbol = &symbol; }
802 
803   using ProcedureKind = parser::ProcedureStmt::Kind;
804   // mapping of generic to its specific proc names and kinds
805   std::multimap<Symbol *, std::pair<const parser::Name *, ProcedureKind>>
806       specificProcs_;
807 
808   void AddSpecificProcs(const std::list<parser::Name> &, ProcedureKind);
809   void ResolveSpecificsInGeneric(Symbol &generic);
810 };
811 
812 class SubprogramVisitor : public virtual ScopeHandler, public InterfaceVisitor {
813 public:
814   bool HandleStmtFunction(const parser::StmtFunctionStmt &);
815   bool Pre(const parser::SubroutineStmt &);
816   bool Pre(const parser::FunctionStmt &);
817   void Post(const parser::FunctionStmt &);
818   bool Pre(const parser::EntryStmt &);
819   void Post(const parser::EntryStmt &);
820   bool Pre(const parser::InterfaceBody::Subroutine &);
821   void Post(const parser::InterfaceBody::Subroutine &);
822   bool Pre(const parser::InterfaceBody::Function &);
823   void Post(const parser::InterfaceBody::Function &);
824   bool Pre(const parser::Suffix &);
825   bool Pre(const parser::PrefixSpec &);
826 
827   bool BeginSubprogram(const parser::Name &, Symbol::Flag,
828       bool hasModulePrefix = false,
829       const parser::LanguageBindingSpec * = nullptr,
830       const ProgramTree::EntryStmtList * = nullptr);
831   bool BeginMpSubprogram(const parser::Name &);
832   void PushBlockDataScope(const parser::Name &);
833   void EndSubprogram(std::optional<parser::CharBlock> stmtSource = std::nullopt,
834       const std::optional<parser::LanguageBindingSpec> * = nullptr);
835 
836 protected:
837   // Set when we see a stmt function that is really an array element assignment
838   bool badStmtFuncFound_{false};
839 
840 private:
841   // Edits an existing symbol created for earlier calls to a subprogram or ENTRY
842   // so that it can be replaced by a later definition.
843   bool HandlePreviousCalls(const parser::Name &, Symbol &, Symbol::Flag);
844   void CheckExtantProc(const parser::Name &, Symbol::Flag);
845   // Create a subprogram symbol in the current scope and push a new scope.
846   Symbol &PushSubprogramScope(const parser::Name &, Symbol::Flag,
847       const parser::LanguageBindingSpec * = nullptr);
848   Symbol *GetSpecificFromGeneric(const parser::Name &);
849   SubprogramDetails &PostSubprogramStmt(const parser::Name &);
850   void CreateEntry(const parser::EntryStmt &stmt, Symbol &subprogram);
851   void PostEntryStmt(const parser::EntryStmt &stmt);
852 };
853 
854 class DeclarationVisitor : public ArraySpecVisitor,
855                            public virtual ScopeHandler {
856 public:
857   using ArraySpecVisitor::Post;
858   using ScopeHandler::Post;
859   using ScopeHandler::Pre;
860 
861   bool Pre(const parser::Initialization &);
862   void Post(const parser::EntityDecl &);
863   void Post(const parser::ObjectDecl &);
864   void Post(const parser::PointerDecl &);
865   bool Pre(const parser::BindStmt &) { return BeginAttrs(); }
866   void Post(const parser::BindStmt &) { EndAttrs(); }
867   bool Pre(const parser::BindEntity &);
868   bool Pre(const parser::OldParameterStmt &);
869   bool Pre(const parser::NamedConstantDef &);
870   bool Pre(const parser::NamedConstant &);
871   void Post(const parser::EnumDef &);
872   bool Pre(const parser::Enumerator &);
873   bool Pre(const parser::AccessSpec &);
874   bool Pre(const parser::AsynchronousStmt &);
875   bool Pre(const parser::ContiguousStmt &);
876   bool Pre(const parser::ExternalStmt &);
877   bool Pre(const parser::IntentStmt &);
878   bool Pre(const parser::IntrinsicStmt &);
879   bool Pre(const parser::OptionalStmt &);
880   bool Pre(const parser::ProtectedStmt &);
881   bool Pre(const parser::ValueStmt &);
882   bool Pre(const parser::VolatileStmt &);
883   bool Pre(const parser::AllocatableStmt &) {
884     objectDeclAttr_ = Attr::ALLOCATABLE;
885     return true;
886   }
887   void Post(const parser::AllocatableStmt &) { objectDeclAttr_ = std::nullopt; }
888   bool Pre(const parser::TargetStmt &) {
889     objectDeclAttr_ = Attr::TARGET;
890     return true;
891   }
892   void Post(const parser::TargetStmt &) { objectDeclAttr_ = std::nullopt; }
893   void Post(const parser::DimensionStmt::Declaration &);
894   void Post(const parser::CodimensionDecl &);
895   bool Pre(const parser::TypeDeclarationStmt &) { return BeginDecl(); }
896   void Post(const parser::TypeDeclarationStmt &);
897   void Post(const parser::IntegerTypeSpec &);
898   void Post(const parser::IntrinsicTypeSpec::Real &);
899   void Post(const parser::IntrinsicTypeSpec::Complex &);
900   void Post(const parser::IntrinsicTypeSpec::Logical &);
901   void Post(const parser::IntrinsicTypeSpec::Character &);
902   void Post(const parser::CharSelector::LengthAndKind &);
903   void Post(const parser::CharLength &);
904   void Post(const parser::LengthSelector &);
905   bool Pre(const parser::KindParam &);
906   bool Pre(const parser::DeclarationTypeSpec::Type &);
907   void Post(const parser::DeclarationTypeSpec::Type &);
908   bool Pre(const parser::DeclarationTypeSpec::Class &);
909   void Post(const parser::DeclarationTypeSpec::Class &);
910   void Post(const parser::DeclarationTypeSpec::Record &);
911   void Post(const parser::DerivedTypeSpec &);
912   bool Pre(const parser::DerivedTypeDef &);
913   bool Pre(const parser::DerivedTypeStmt &);
914   void Post(const parser::DerivedTypeStmt &);
915   bool Pre(const parser::TypeParamDefStmt &) { return BeginDecl(); }
916   void Post(const parser::TypeParamDefStmt &);
917   bool Pre(const parser::TypeAttrSpec::Extends &);
918   bool Pre(const parser::PrivateStmt &);
919   bool Pre(const parser::SequenceStmt &);
920   bool Pre(const parser::ComponentDefStmt &) { return BeginDecl(); }
921   void Post(const parser::ComponentDefStmt &) { EndDecl(); }
922   void Post(const parser::ComponentDecl &);
923   void Post(const parser::FillDecl &);
924   bool Pre(const parser::ProcedureDeclarationStmt &);
925   void Post(const parser::ProcedureDeclarationStmt &);
926   bool Pre(const parser::DataComponentDefStmt &); // returns false
927   bool Pre(const parser::ProcComponentDefStmt &);
928   void Post(const parser::ProcComponentDefStmt &);
929   bool Pre(const parser::ProcPointerInit &);
930   void Post(const parser::ProcInterface &);
931   void Post(const parser::ProcDecl &);
932   bool Pre(const parser::TypeBoundProcedurePart &);
933   void Post(const parser::TypeBoundProcedurePart &);
934   void Post(const parser::ContainsStmt &);
935   bool Pre(const parser::TypeBoundProcBinding &) { return BeginAttrs(); }
936   void Post(const parser::TypeBoundProcBinding &) { EndAttrs(); }
937   void Post(const parser::TypeBoundProcedureStmt::WithoutInterface &);
938   void Post(const parser::TypeBoundProcedureStmt::WithInterface &);
939   void Post(const parser::FinalProcedureStmt &);
940   bool Pre(const parser::TypeBoundGenericStmt &);
941   bool Pre(const parser::StructureDef &); // returns false
942   bool Pre(const parser::Union::UnionStmt &);
943   bool Pre(const parser::StructureField &);
944   void Post(const parser::StructureField &);
945   bool Pre(const parser::AllocateStmt &);
946   void Post(const parser::AllocateStmt &);
947   bool Pre(const parser::StructureConstructor &);
948   bool Pre(const parser::NamelistStmt::Group &);
949   bool Pre(const parser::IoControlSpec &);
950   bool Pre(const parser::CommonStmt::Block &);
951   bool Pre(const parser::CommonBlockObject &);
952   void Post(const parser::CommonBlockObject &);
953   bool Pre(const parser::EquivalenceStmt &);
954   bool Pre(const parser::SaveStmt &);
955   bool Pre(const parser::BasedPointerStmt &);
956 
957   void PointerInitialization(
958       const parser::Name &, const parser::InitialDataTarget &);
959   void PointerInitialization(
960       const parser::Name &, const parser::ProcPointerInit &);
961   void NonPointerInitialization(
962       const parser::Name &, const parser::ConstantExpr &);
963   void CheckExplicitInterface(const parser::Name &);
964   void CheckBindings(const parser::TypeBoundProcedureStmt::WithoutInterface &);
965 
966   const parser::Name *ResolveDesignator(const parser::Designator &);
967 
968 protected:
969   bool BeginDecl();
970   void EndDecl();
971   Symbol &DeclareObjectEntity(const parser::Name &, Attrs = Attrs{});
972   // Make sure that there's an entity in an enclosing scope called Name
973   Symbol &FindOrDeclareEnclosingEntity(const parser::Name &);
974   // Declare a LOCAL/LOCAL_INIT entity. If there isn't a type specified
975   // it comes from the entity in the containing scope, or implicit rules.
976   // Return pointer to the new symbol, or nullptr on error.
977   Symbol *DeclareLocalEntity(const parser::Name &);
978   // Declare a statement entity (i.e., an implied DO loop index for
979   // a DATA statement or an array constructor).  If there isn't an explict
980   // type specified, implicit rules apply. Return pointer to the new symbol,
981   // or nullptr on error.
982   Symbol *DeclareStatementEntity(const parser::DoVariable &,
983       const std::optional<parser::IntegerTypeSpec> &);
984   Symbol &MakeCommonBlockSymbol(const parser::Name &);
985   Symbol &MakeCommonBlockSymbol(const std::optional<parser::Name> &);
986   bool CheckUseError(const parser::Name &);
987   void CheckAccessibility(const SourceName &, bool, Symbol &);
988   void CheckCommonBlocks();
989   void CheckSaveStmts();
990   void CheckEquivalenceSets();
991   bool CheckNotInBlock(const char *);
992   bool NameIsKnownOrIntrinsic(const parser::Name &);
993   void FinishNamelists();
994 
995   // Each of these returns a pointer to a resolved Name (i.e. with symbol)
996   // or nullptr in case of error.
997   const parser::Name *ResolveStructureComponent(
998       const parser::StructureComponent &);
999   const parser::Name *ResolveDataRef(const parser::DataRef &);
1000   const parser::Name *ResolveName(const parser::Name &);
1001   bool PassesSharedLocalityChecks(const parser::Name &name, Symbol &symbol);
1002   Symbol *NoteInterfaceName(const parser::Name &);
1003   bool IsUplevelReference(const Symbol &);
1004 
1005   std::optional<SourceName> BeginCheckOnIndexUseInOwnBounds(
1006       const parser::DoVariable &name) {
1007     std::optional<SourceName> result{checkIndexUseInOwnBounds_};
1008     checkIndexUseInOwnBounds_ = name.thing.thing.source;
1009     return result;
1010   }
1011   void EndCheckOnIndexUseInOwnBounds(const std::optional<SourceName> &restore) {
1012     checkIndexUseInOwnBounds_ = restore;
1013   }
1014 
1015 private:
1016   // The attribute corresponding to the statement containing an ObjectDecl
1017   std::optional<Attr> objectDeclAttr_;
1018   // Info about current character type while walking DeclTypeSpec.
1019   // Also captures any "*length" specifier on an individual declaration.
1020   struct {
1021     std::optional<ParamValue> length;
1022     std::optional<KindExpr> kind;
1023   } charInfo_;
1024   // Info about current derived type or STRUCTURE while walking
1025   // DerivedTypeDef / StructureDef
1026   struct {
1027     const parser::Name *extends{nullptr}; // EXTENDS(name)
1028     bool privateComps{false}; // components are private by default
1029     bool privateBindings{false}; // bindings are private by default
1030     bool sawContains{false}; // currently processing bindings
1031     bool sequence{false}; // is a sequence type
1032     const Symbol *type{nullptr}; // derived type being defined
1033     bool isStructure{false}; // is a DEC STRUCTURE
1034   } derivedTypeInfo_;
1035   // In a ProcedureDeclarationStmt or ProcComponentDefStmt, this is
1036   // the interface name, if any.
1037   const parser::Name *interfaceName_{nullptr};
1038   // Map type-bound generic to binding names of its specific bindings
1039   std::multimap<Symbol *, const parser::Name *> genericBindings_;
1040   // Info about current ENUM
1041   struct EnumeratorState {
1042     // Enum value must hold inside a C_INT (7.6.2).
1043     std::optional<int> value{0};
1044   } enumerationState_;
1045   // Set for OldParameterStmt processing
1046   bool inOldStyleParameterStmt_{false};
1047   // Set when walking DATA & array constructor implied DO loop bounds
1048   // to warn about use of the implied DO intex therein.
1049   std::optional<SourceName> checkIndexUseInOwnBounds_;
1050   bool hasBindCName_{false};
1051 
1052   bool HandleAttributeStmt(Attr, const std::list<parser::Name> &);
1053   Symbol &HandleAttributeStmt(Attr, const parser::Name &);
1054   Symbol &DeclareUnknownEntity(const parser::Name &, Attrs);
1055   Symbol &DeclareProcEntity(const parser::Name &, Attrs, const ProcInterface &);
1056   void SetType(const parser::Name &, const DeclTypeSpec &);
1057   std::optional<DerivedTypeSpec> ResolveDerivedType(const parser::Name &);
1058   std::optional<DerivedTypeSpec> ResolveExtendsType(
1059       const parser::Name &, const parser::Name *);
1060   Symbol *MakeTypeSymbol(const SourceName &, Details &&);
1061   Symbol *MakeTypeSymbol(const parser::Name &, Details &&);
1062   bool OkToAddComponent(const parser::Name &, const Symbol * = nullptr);
1063   ParamValue GetParamValue(
1064       const parser::TypeParamValue &, common::TypeParamAttr attr);
1065   void CheckCommonBlockDerivedType(const SourceName &, const Symbol &);
1066   std::optional<MessageFixedText> CheckSaveAttr(const Symbol &);
1067   Attrs HandleSaveName(const SourceName &, Attrs);
1068   void AddSaveName(std::set<SourceName> &, const SourceName &);
1069   void SetSaveAttr(Symbol &);
1070   bool HandleUnrestrictedSpecificIntrinsicFunction(const parser::Name &);
1071   const parser::Name *FindComponent(const parser::Name *, const parser::Name &);
1072   void Initialization(const parser::Name &, const parser::Initialization &,
1073       bool inComponentDecl);
1074   bool PassesLocalityChecks(const parser::Name &name, Symbol &symbol);
1075   bool CheckForHostAssociatedImplicit(const parser::Name &);
1076 
1077   // Declare an object or procedure entity.
1078   // T is one of: EntityDetails, ObjectEntityDetails, ProcEntityDetails
1079   template <typename T>
1080   Symbol &DeclareEntity(const parser::Name &name, Attrs attrs) {
1081     Symbol &symbol{MakeSymbol(name, attrs)};
1082     if (context().HasError(symbol) || symbol.has<T>()) {
1083       return symbol; // OK or error already reported
1084     } else if (symbol.has<UnknownDetails>()) {
1085       symbol.set_details(T{});
1086       return symbol;
1087     } else if (auto *details{symbol.detailsIf<EntityDetails>()}) {
1088       symbol.set_details(T{std::move(*details)});
1089       return symbol;
1090     } else if (std::is_same_v<EntityDetails, T> &&
1091         (symbol.has<ObjectEntityDetails>() ||
1092             symbol.has<ProcEntityDetails>())) {
1093       return symbol; // OK
1094     } else if (auto *details{symbol.detailsIf<UseDetails>()}) {
1095       Say(name.source,
1096           "'%s' is use-associated from module '%s' and cannot be re-declared"_err_en_US,
1097           name.source, GetUsedModule(*details).name());
1098     } else if (auto *details{symbol.detailsIf<SubprogramNameDetails>()}) {
1099       if (details->kind() == SubprogramKind::Module) {
1100         Say2(name,
1101             "Declaration of '%s' conflicts with its use as module procedure"_err_en_US,
1102             symbol, "Module procedure definition"_en_US);
1103       } else if (details->kind() == SubprogramKind::Internal) {
1104         Say2(name,
1105             "Declaration of '%s' conflicts with its use as internal procedure"_err_en_US,
1106             symbol, "Internal procedure definition"_en_US);
1107       } else {
1108         DIE("unexpected kind");
1109       }
1110     } else if (std::is_same_v<ObjectEntityDetails, T> &&
1111         symbol.has<ProcEntityDetails>()) {
1112       SayWithDecl(
1113           name, symbol, "'%s' is already declared as a procedure"_err_en_US);
1114     } else if (std::is_same_v<ProcEntityDetails, T> &&
1115         symbol.has<ObjectEntityDetails>()) {
1116       if (InCommonBlock(symbol)) {
1117         SayWithDecl(name, symbol,
1118             "'%s' may not be a procedure as it is in a COMMON block"_err_en_US);
1119       } else {
1120         SayWithDecl(
1121             name, symbol, "'%s' is already declared as an object"_err_en_US);
1122       }
1123     } else if (!CheckPossibleBadForwardRef(symbol)) {
1124       SayAlreadyDeclared(name, symbol);
1125     }
1126     context().SetError(symbol);
1127     return symbol;
1128   }
1129   bool HasCycle(const Symbol &, const ProcInterface &);
1130 };
1131 
1132 // Resolve construct entities and statement entities.
1133 // Check that construct names don't conflict with other names.
1134 class ConstructVisitor : public virtual DeclarationVisitor {
1135 public:
1136   bool Pre(const parser::ConcurrentHeader &);
1137   bool Pre(const parser::LocalitySpec::Local &);
1138   bool Pre(const parser::LocalitySpec::LocalInit &);
1139   bool Pre(const parser::LocalitySpec::Shared &);
1140   bool Pre(const parser::AcSpec &);
1141   bool Pre(const parser::AcImpliedDo &);
1142   bool Pre(const parser::DataImpliedDo &);
1143   bool Pre(const parser::DataIDoObject &);
1144   bool Pre(const parser::DataStmtObject &);
1145   bool Pre(const parser::DataStmtValue &);
1146   bool Pre(const parser::DoConstruct &);
1147   void Post(const parser::DoConstruct &);
1148   bool Pre(const parser::ForallConstruct &);
1149   void Post(const parser::ForallConstruct &);
1150   bool Pre(const parser::ForallStmt &);
1151   void Post(const parser::ForallStmt &);
1152   bool Pre(const parser::BlockStmt &);
1153   bool Pre(const parser::EndBlockStmt &);
1154   void Post(const parser::Selector &);
1155   void Post(const parser::AssociateStmt &);
1156   void Post(const parser::EndAssociateStmt &);
1157   bool Pre(const parser::Association &);
1158   void Post(const parser::SelectTypeStmt &);
1159   void Post(const parser::SelectRankStmt &);
1160   bool Pre(const parser::SelectTypeConstruct &);
1161   void Post(const parser::SelectTypeConstruct &);
1162   bool Pre(const parser::SelectTypeConstruct::TypeCase &);
1163   void Post(const parser::SelectTypeConstruct::TypeCase &);
1164   // Creates Block scopes with neither symbol name nor symbol details.
1165   bool Pre(const parser::SelectRankConstruct::RankCase &);
1166   void Post(const parser::SelectRankConstruct::RankCase &);
1167   void Post(const parser::TypeGuardStmt::Guard &);
1168   void Post(const parser::SelectRankCaseStmt::Rank &);
1169   bool Pre(const parser::ChangeTeamStmt &);
1170   void Post(const parser::EndChangeTeamStmt &);
1171   void Post(const parser::CoarrayAssociation &);
1172 
1173   // Definitions of construct names
1174   bool Pre(const parser::WhereConstructStmt &x) { return CheckDef(x.t); }
1175   bool Pre(const parser::ForallConstructStmt &x) { return CheckDef(x.t); }
1176   bool Pre(const parser::CriticalStmt &x) { return CheckDef(x.t); }
1177   bool Pre(const parser::LabelDoStmt &) {
1178     return false; // error recovery
1179   }
1180   bool Pre(const parser::NonLabelDoStmt &x) { return CheckDef(x.t); }
1181   bool Pre(const parser::IfThenStmt &x) { return CheckDef(x.t); }
1182   bool Pre(const parser::SelectCaseStmt &x) { return CheckDef(x.t); }
1183   bool Pre(const parser::SelectRankConstruct &);
1184   void Post(const parser::SelectRankConstruct &);
1185   bool Pre(const parser::SelectRankStmt &x) {
1186     return CheckDef(std::get<0>(x.t));
1187   }
1188   bool Pre(const parser::SelectTypeStmt &x) {
1189     return CheckDef(std::get<0>(x.t));
1190   }
1191 
1192   // References to construct names
1193   void Post(const parser::MaskedElsewhereStmt &x) { CheckRef(x.t); }
1194   void Post(const parser::ElsewhereStmt &x) { CheckRef(x.v); }
1195   void Post(const parser::EndWhereStmt &x) { CheckRef(x.v); }
1196   void Post(const parser::EndForallStmt &x) { CheckRef(x.v); }
1197   void Post(const parser::EndCriticalStmt &x) { CheckRef(x.v); }
1198   void Post(const parser::EndDoStmt &x) { CheckRef(x.v); }
1199   void Post(const parser::ElseIfStmt &x) { CheckRef(x.t); }
1200   void Post(const parser::ElseStmt &x) { CheckRef(x.v); }
1201   void Post(const parser::EndIfStmt &x) { CheckRef(x.v); }
1202   void Post(const parser::CaseStmt &x) { CheckRef(x.t); }
1203   void Post(const parser::EndSelectStmt &x) { CheckRef(x.v); }
1204   void Post(const parser::SelectRankCaseStmt &x) { CheckRef(x.t); }
1205   void Post(const parser::TypeGuardStmt &x) { CheckRef(x.t); }
1206   void Post(const parser::CycleStmt &x) { CheckRef(x.v); }
1207   void Post(const parser::ExitStmt &x) { CheckRef(x.v); }
1208 
1209 private:
1210   // R1105 selector -> expr | variable
1211   // expr is set in either case unless there were errors
1212   struct Selector {
1213     Selector() {}
1214     Selector(const SourceName &source, MaybeExpr &&expr)
1215         : source{source}, expr{std::move(expr)} {}
1216     operator bool() const { return expr.has_value(); }
1217     parser::CharBlock source;
1218     MaybeExpr expr;
1219   };
1220   // association -> [associate-name =>] selector
1221   struct Association {
1222     const parser::Name *name{nullptr};
1223     Selector selector;
1224   };
1225   std::vector<Association> associationStack_;
1226   Association *currentAssociation_{nullptr};
1227 
1228   template <typename T> bool CheckDef(const T &t) {
1229     return CheckDef(std::get<std::optional<parser::Name>>(t));
1230   }
1231   template <typename T> void CheckRef(const T &t) {
1232     CheckRef(std::get<std::optional<parser::Name>>(t));
1233   }
1234   bool CheckDef(const std::optional<parser::Name> &);
1235   void CheckRef(const std::optional<parser::Name> &);
1236   const DeclTypeSpec &ToDeclTypeSpec(evaluate::DynamicType &&);
1237   const DeclTypeSpec &ToDeclTypeSpec(
1238       evaluate::DynamicType &&, MaybeSubscriptIntExpr &&length);
1239   Symbol *MakeAssocEntity();
1240   void SetTypeFromAssociation(Symbol &);
1241   void SetAttrsFromAssociation(Symbol &);
1242   Selector ResolveSelector(const parser::Selector &);
1243   void ResolveIndexName(const parser::ConcurrentControl &control);
1244   void SetCurrentAssociation(std::size_t n);
1245   Association &GetCurrentAssociation();
1246   void PushAssociation();
1247   void PopAssociation(std::size_t count = 1);
1248 };
1249 
1250 // Create scopes for OpenACC constructs
1251 class AccVisitor : public virtual DeclarationVisitor {
1252 public:
1253   void AddAccSourceRange(const parser::CharBlock &);
1254 
1255   static bool NeedsScope(const parser::OpenACCBlockConstruct &);
1256 
1257   bool Pre(const parser::OpenACCBlockConstruct &);
1258   void Post(const parser::OpenACCBlockConstruct &);
1259   bool Pre(const parser::AccBeginBlockDirective &x) {
1260     AddAccSourceRange(x.source);
1261     return true;
1262   }
1263   void Post(const parser::AccBeginBlockDirective &) {
1264     messageHandler().set_currStmtSource(std::nullopt);
1265   }
1266   bool Pre(const parser::AccEndBlockDirective &x) {
1267     AddAccSourceRange(x.source);
1268     return true;
1269   }
1270   void Post(const parser::AccEndBlockDirective &) {
1271     messageHandler().set_currStmtSource(std::nullopt);
1272   }
1273   bool Pre(const parser::AccBeginLoopDirective &x) {
1274     AddAccSourceRange(x.source);
1275     return true;
1276   }
1277   void Post(const parser::AccBeginLoopDirective &x) {
1278     messageHandler().set_currStmtSource(std::nullopt);
1279   }
1280 };
1281 
1282 bool AccVisitor::NeedsScope(const parser::OpenACCBlockConstruct &x) {
1283   const auto &beginBlockDir{std::get<parser::AccBeginBlockDirective>(x.t)};
1284   const auto &beginDir{std::get<parser::AccBlockDirective>(beginBlockDir.t)};
1285   switch (beginDir.v) {
1286   case llvm::acc::Directive::ACCD_data:
1287   case llvm::acc::Directive::ACCD_host_data:
1288   case llvm::acc::Directive::ACCD_kernels:
1289   case llvm::acc::Directive::ACCD_parallel:
1290   case llvm::acc::Directive::ACCD_serial:
1291     return true;
1292   default:
1293     return false;
1294   }
1295 }
1296 
1297 void AccVisitor::AddAccSourceRange(const parser::CharBlock &source) {
1298   messageHandler().set_currStmtSource(source);
1299   currScope().AddSourceRange(source);
1300 }
1301 
1302 bool AccVisitor::Pre(const parser::OpenACCBlockConstruct &x) {
1303   if (NeedsScope(x)) {
1304     PushScope(Scope::Kind::Block, nullptr);
1305   }
1306   return true;
1307 }
1308 
1309 void AccVisitor::Post(const parser::OpenACCBlockConstruct &x) {
1310   if (NeedsScope(x)) {
1311     PopScope();
1312   }
1313 }
1314 
1315 // Create scopes for OpenMP constructs
1316 class OmpVisitor : public virtual DeclarationVisitor {
1317 public:
1318   void AddOmpSourceRange(const parser::CharBlock &);
1319 
1320   static bool NeedsScope(const parser::OpenMPBlockConstruct &);
1321 
1322   bool Pre(const parser::OpenMPBlockConstruct &);
1323   void Post(const parser::OpenMPBlockConstruct &);
1324   bool Pre(const parser::OmpBeginBlockDirective &x) {
1325     AddOmpSourceRange(x.source);
1326     return true;
1327   }
1328   void Post(const parser::OmpBeginBlockDirective &) {
1329     messageHandler().set_currStmtSource(std::nullopt);
1330   }
1331   bool Pre(const parser::OmpEndBlockDirective &x) {
1332     AddOmpSourceRange(x.source);
1333     return true;
1334   }
1335   void Post(const parser::OmpEndBlockDirective &) {
1336     messageHandler().set_currStmtSource(std::nullopt);
1337   }
1338 
1339   bool Pre(const parser::OpenMPLoopConstruct &) {
1340     PushScope(Scope::Kind::Block, nullptr);
1341     return true;
1342   }
1343   void Post(const parser::OpenMPLoopConstruct &) { PopScope(); }
1344   bool Pre(const parser::OmpBeginLoopDirective &x) {
1345     AddOmpSourceRange(x.source);
1346     return true;
1347   }
1348   void Post(const parser::OmpBeginLoopDirective &) {
1349     messageHandler().set_currStmtSource(std::nullopt);
1350   }
1351   bool Pre(const parser::OmpEndLoopDirective &x) {
1352     AddOmpSourceRange(x.source);
1353     return true;
1354   }
1355   void Post(const parser::OmpEndLoopDirective &) {
1356     messageHandler().set_currStmtSource(std::nullopt);
1357   }
1358 
1359   bool Pre(const parser::OpenMPSectionsConstruct &) {
1360     PushScope(Scope::Kind::Block, nullptr);
1361     return true;
1362   }
1363   void Post(const parser::OpenMPSectionsConstruct &) { PopScope(); }
1364   bool Pre(const parser::OmpBeginSectionsDirective &x) {
1365     AddOmpSourceRange(x.source);
1366     return true;
1367   }
1368   void Post(const parser::OmpBeginSectionsDirective &) {
1369     messageHandler().set_currStmtSource(std::nullopt);
1370   }
1371   bool Pre(const parser::OmpEndSectionsDirective &x) {
1372     AddOmpSourceRange(x.source);
1373     return true;
1374   }
1375   void Post(const parser::OmpEndSectionsDirective &) {
1376     messageHandler().set_currStmtSource(std::nullopt);
1377   }
1378 };
1379 
1380 bool OmpVisitor::NeedsScope(const parser::OpenMPBlockConstruct &x) {
1381   const auto &beginBlockDir{std::get<parser::OmpBeginBlockDirective>(x.t)};
1382   const auto &beginDir{std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
1383   switch (beginDir.v) {
1384   case llvm::omp::Directive::OMPD_target_data:
1385   case llvm::omp::Directive::OMPD_master:
1386   case llvm::omp::Directive::OMPD_ordered:
1387   case llvm::omp::Directive::OMPD_taskgroup:
1388     return false;
1389   default:
1390     return true;
1391   }
1392 }
1393 
1394 void OmpVisitor::AddOmpSourceRange(const parser::CharBlock &source) {
1395   messageHandler().set_currStmtSource(source);
1396   currScope().AddSourceRange(source);
1397 }
1398 
1399 bool OmpVisitor::Pre(const parser::OpenMPBlockConstruct &x) {
1400   if (NeedsScope(x)) {
1401     PushScope(Scope::Kind::Block, nullptr);
1402   }
1403   return true;
1404 }
1405 
1406 void OmpVisitor::Post(const parser::OpenMPBlockConstruct &x) {
1407   if (NeedsScope(x)) {
1408     PopScope();
1409   }
1410 }
1411 
1412 // Walk the parse tree and resolve names to symbols.
1413 class ResolveNamesVisitor : public virtual ScopeHandler,
1414                             public ModuleVisitor,
1415                             public SubprogramVisitor,
1416                             public ConstructVisitor,
1417                             public OmpVisitor,
1418                             public AccVisitor {
1419 public:
1420   using AccVisitor::Post;
1421   using AccVisitor::Pre;
1422   using ArraySpecVisitor::Post;
1423   using ConstructVisitor::Post;
1424   using ConstructVisitor::Pre;
1425   using DeclarationVisitor::Post;
1426   using DeclarationVisitor::Pre;
1427   using ImplicitRulesVisitor::Post;
1428   using ImplicitRulesVisitor::Pre;
1429   using InterfaceVisitor::Post;
1430   using InterfaceVisitor::Pre;
1431   using ModuleVisitor::Post;
1432   using ModuleVisitor::Pre;
1433   using OmpVisitor::Post;
1434   using OmpVisitor::Pre;
1435   using ScopeHandler::Post;
1436   using ScopeHandler::Pre;
1437   using SubprogramVisitor::Post;
1438   using SubprogramVisitor::Pre;
1439 
1440   ResolveNamesVisitor(
1441       SemanticsContext &context, ImplicitRulesMap &rules, Scope &top)
1442       : BaseVisitor{context, *this, rules}, topScope_{top} {
1443     PushScope(top);
1444   }
1445 
1446   Scope &topScope() const { return topScope_; }
1447 
1448   // Default action for a parse tree node is to visit children.
1449   template <typename T> bool Pre(const T &) { return true; }
1450   template <typename T> void Post(const T &) {}
1451 
1452   bool Pre(const parser::SpecificationPart &);
1453   void Post(const parser::Program &);
1454   bool Pre(const parser::ImplicitStmt &);
1455   void Post(const parser::PointerObject &);
1456   void Post(const parser::AllocateObject &);
1457   bool Pre(const parser::PointerAssignmentStmt &);
1458   void Post(const parser::Designator &);
1459   template <typename A, typename B>
1460   void Post(const parser::LoopBounds<A, B> &x) {
1461     ResolveName(*parser::Unwrap<parser::Name>(x.name));
1462   }
1463   void Post(const parser::ProcComponentRef &);
1464   bool Pre(const parser::FunctionReference &);
1465   bool Pre(const parser::CallStmt &);
1466   bool Pre(const parser::ImportStmt &);
1467   void Post(const parser::TypeGuardStmt &);
1468   bool Pre(const parser::StmtFunctionStmt &);
1469   bool Pre(const parser::DefinedOpName &);
1470   bool Pre(const parser::ProgramUnit &);
1471   void Post(const parser::AssignStmt &);
1472   void Post(const parser::AssignedGotoStmt &);
1473 
1474   // These nodes should never be reached: they are handled in ProgramUnit
1475   bool Pre(const parser::MainProgram &) {
1476     llvm_unreachable("This node is handled in ProgramUnit");
1477   }
1478   bool Pre(const parser::FunctionSubprogram &) {
1479     llvm_unreachable("This node is handled in ProgramUnit");
1480   }
1481   bool Pre(const parser::SubroutineSubprogram &) {
1482     llvm_unreachable("This node is handled in ProgramUnit");
1483   }
1484   bool Pre(const parser::SeparateModuleSubprogram &) {
1485     llvm_unreachable("This node is handled in ProgramUnit");
1486   }
1487   bool Pre(const parser::Module &) {
1488     llvm_unreachable("This node is handled in ProgramUnit");
1489   }
1490   bool Pre(const parser::Submodule &) {
1491     llvm_unreachable("This node is handled in ProgramUnit");
1492   }
1493   bool Pre(const parser::BlockData &) {
1494     llvm_unreachable("This node is handled in ProgramUnit");
1495   }
1496 
1497   void NoteExecutablePartCall(Symbol::Flag, const parser::Call &);
1498 
1499   friend void ResolveSpecificationParts(SemanticsContext &, const Symbol &);
1500 
1501 private:
1502   // Kind of procedure we are expecting to see in a ProcedureDesignator
1503   std::optional<Symbol::Flag> expectedProcFlag_;
1504   std::optional<SourceName> prevImportStmt_;
1505   Scope &topScope_;
1506 
1507   void PreSpecificationConstruct(const parser::SpecificationConstruct &);
1508   void CreateCommonBlockSymbols(const parser::CommonStmt &);
1509   void CreateGeneric(const parser::GenericSpec &);
1510   void FinishSpecificationPart(const std::list<parser::DeclarationConstruct> &);
1511   void AnalyzeStmtFunctionStmt(const parser::StmtFunctionStmt &);
1512   void CheckImports();
1513   void CheckImport(const SourceName &, const SourceName &);
1514   void HandleCall(Symbol::Flag, const parser::Call &);
1515   void HandleProcedureName(Symbol::Flag, const parser::Name &);
1516   bool CheckImplicitNoneExternal(const SourceName &, const Symbol &);
1517   bool SetProcFlag(const parser::Name &, Symbol &, Symbol::Flag);
1518   void ResolveSpecificationParts(ProgramTree &);
1519   void AddSubpNames(ProgramTree &);
1520   bool BeginScopeForNode(const ProgramTree &);
1521   void EndScopeForNode(const ProgramTree &);
1522   void FinishSpecificationParts(const ProgramTree &);
1523   void FinishDerivedTypeInstantiation(Scope &);
1524   void ResolveExecutionParts(const ProgramTree &);
1525 };
1526 
1527 // ImplicitRules implementation
1528 
1529 bool ImplicitRules::isImplicitNoneType() const {
1530   if (isImplicitNoneType_) {
1531     return true;
1532   } else if (map_.empty() && inheritFromParent_) {
1533     return parent_->isImplicitNoneType();
1534   } else {
1535     return false; // default if not specified
1536   }
1537 }
1538 
1539 bool ImplicitRules::isImplicitNoneExternal() const {
1540   if (isImplicitNoneExternal_) {
1541     return true;
1542   } else if (inheritFromParent_) {
1543     return parent_->isImplicitNoneExternal();
1544   } else {
1545     return false; // default if not specified
1546   }
1547 }
1548 
1549 const DeclTypeSpec *ImplicitRules::GetType(
1550     SourceName name, bool respectImplicitNoneType) const {
1551   char ch{name.begin()[0]};
1552   if (isImplicitNoneType_ && respectImplicitNoneType) {
1553     return nullptr;
1554   } else if (auto it{map_.find(ch)}; it != map_.end()) {
1555     return &*it->second;
1556   } else if (inheritFromParent_) {
1557     return parent_->GetType(name, respectImplicitNoneType);
1558   } else if (ch >= 'i' && ch <= 'n') {
1559     return &context_.MakeNumericType(TypeCategory::Integer);
1560   } else if (ch >= 'a' && ch <= 'z') {
1561     return &context_.MakeNumericType(TypeCategory::Real);
1562   } else {
1563     return nullptr;
1564   }
1565 }
1566 
1567 void ImplicitRules::SetTypeMapping(const DeclTypeSpec &type,
1568     parser::Location fromLetter, parser::Location toLetter) {
1569   for (char ch = *fromLetter; ch; ch = ImplicitRules::Incr(ch)) {
1570     auto res{map_.emplace(ch, type)};
1571     if (!res.second) {
1572       context_.Say(parser::CharBlock{fromLetter},
1573           "More than one implicit type specified for '%c'"_err_en_US, ch);
1574     }
1575     if (ch == *toLetter) {
1576       break;
1577     }
1578   }
1579 }
1580 
1581 // Return the next char after ch in a way that works for ASCII or EBCDIC.
1582 // Return '\0' for the char after 'z'.
1583 char ImplicitRules::Incr(char ch) {
1584   switch (ch) {
1585   case 'i':
1586     return 'j';
1587   case 'r':
1588     return 's';
1589   case 'z':
1590     return '\0';
1591   default:
1592     return ch + 1;
1593   }
1594 }
1595 
1596 llvm::raw_ostream &operator<<(
1597     llvm::raw_ostream &o, const ImplicitRules &implicitRules) {
1598   o << "ImplicitRules:\n";
1599   for (char ch = 'a'; ch; ch = ImplicitRules::Incr(ch)) {
1600     ShowImplicitRule(o, implicitRules, ch);
1601   }
1602   ShowImplicitRule(o, implicitRules, '_');
1603   ShowImplicitRule(o, implicitRules, '$');
1604   ShowImplicitRule(o, implicitRules, '@');
1605   return o;
1606 }
1607 void ShowImplicitRule(
1608     llvm::raw_ostream &o, const ImplicitRules &implicitRules, char ch) {
1609   auto it{implicitRules.map_.find(ch)};
1610   if (it != implicitRules.map_.end()) {
1611     o << "  " << ch << ": " << *it->second << '\n';
1612   }
1613 }
1614 
1615 template <typename T> void BaseVisitor::Walk(const T &x) {
1616   parser::Walk(x, *this_);
1617 }
1618 
1619 void BaseVisitor::MakePlaceholder(
1620     const parser::Name &name, MiscDetails::Kind kind) {
1621   if (!name.symbol) {
1622     name.symbol = &context_->globalScope().MakeSymbol(
1623         name.source, Attrs{}, MiscDetails{kind});
1624   }
1625 }
1626 
1627 // AttrsVisitor implementation
1628 
1629 bool AttrsVisitor::BeginAttrs() {
1630   CHECK(!attrs_);
1631   attrs_ = std::make_optional<Attrs>();
1632   return true;
1633 }
1634 Attrs AttrsVisitor::GetAttrs() {
1635   CHECK(attrs_);
1636   return *attrs_;
1637 }
1638 Attrs AttrsVisitor::EndAttrs() {
1639   Attrs result{GetAttrs()};
1640   attrs_.reset();
1641   passName_ = std::nullopt;
1642   bindName_.reset();
1643   return result;
1644 }
1645 
1646 bool AttrsVisitor::SetPassNameOn(Symbol &symbol) {
1647   if (!passName_) {
1648     return false;
1649   }
1650   common::visit(common::visitors{
1651                     [&](ProcEntityDetails &x) { x.set_passName(*passName_); },
1652                     [&](ProcBindingDetails &x) { x.set_passName(*passName_); },
1653                     [](auto &) { common::die("unexpected pass name"); },
1654                 },
1655       symbol.details());
1656   return true;
1657 }
1658 
1659 void AttrsVisitor::SetBindNameOn(Symbol &symbol) {
1660   if (!attrs_ || !attrs_->test(Attr::BIND_C)) {
1661     return;
1662   }
1663   std::optional<std::string> label{
1664       evaluate::GetScalarConstantValue<evaluate::Ascii>(bindName_)};
1665   if (ClassifyProcedure(symbol) == ProcedureDefinitionClass::Internal) {
1666     if (label) { // C1552: no NAME= allowed even if null
1667       Say(symbol.name(),
1668           "An internal procedure may not have a BIND(C,NAME=) binding label"_err_en_US);
1669     }
1670     return;
1671   }
1672   // 18.9.2(2): discard leading and trailing blanks
1673   if (label) {
1674     auto first{label->find_first_not_of(" ")};
1675     if (first == std::string::npos) {
1676       // Empty NAME= means no binding at all (18.10.2p2)
1677       return;
1678     }
1679     auto last{label->find_last_not_of(" ")};
1680     label = label->substr(first, last - first + 1);
1681   } else {
1682     label = parser::ToLowerCaseLetters(symbol.name().ToString());
1683   }
1684   // Check if a symbol has two Bind names.
1685   std::string oldBindName;
1686   if (symbol.GetBindName()) {
1687     oldBindName = *symbol.GetBindName();
1688   }
1689   symbol.SetBindName(std::move(*label));
1690   if (!oldBindName.empty()) {
1691     if (const std::string * newBindName{symbol.GetBindName()}) {
1692       if (oldBindName.compare(*newBindName) != 0) {
1693         Say(symbol.name(), "The entity '%s' has multiple BIND names"_err_en_US);
1694       }
1695     }
1696   }
1697 }
1698 
1699 void AttrsVisitor::Post(const parser::LanguageBindingSpec &x) {
1700   CHECK(attrs_);
1701   if (CheckAndSet(Attr::BIND_C)) {
1702     if (x.v) {
1703       bindName_ = EvaluateExpr(*x.v);
1704     }
1705   }
1706 }
1707 bool AttrsVisitor::Pre(const parser::IntentSpec &x) {
1708   CHECK(attrs_);
1709   CheckAndSet(IntentSpecToAttr(x));
1710   return false;
1711 }
1712 bool AttrsVisitor::Pre(const parser::Pass &x) {
1713   if (CheckAndSet(Attr::PASS)) {
1714     if (x.v) {
1715       passName_ = x.v->source;
1716       MakePlaceholder(*x.v, MiscDetails::Kind::PassName);
1717     }
1718   }
1719   return false;
1720 }
1721 
1722 // C730, C743, C755, C778, C1543 say no attribute or prefix repetitions
1723 bool AttrsVisitor::IsDuplicateAttr(Attr attrName) {
1724   if (attrs_->test(attrName)) {
1725     Say(currStmtSource().value(),
1726         "Attribute '%s' cannot be used more than once"_warn_en_US,
1727         AttrToString(attrName));
1728     return true;
1729   }
1730   return false;
1731 }
1732 
1733 // See if attrName violates a constraint cause by a conflict.  attr1 and attr2
1734 // name attributes that cannot be used on the same declaration
1735 bool AttrsVisitor::HaveAttrConflict(Attr attrName, Attr attr1, Attr attr2) {
1736   if ((attrName == attr1 && attrs_->test(attr2)) ||
1737       (attrName == attr2 && attrs_->test(attr1))) {
1738     Say(currStmtSource().value(),
1739         "Attributes '%s' and '%s' conflict with each other"_err_en_US,
1740         AttrToString(attr1), AttrToString(attr2));
1741     return true;
1742   }
1743   return false;
1744 }
1745 // C759, C1543
1746 bool AttrsVisitor::IsConflictingAttr(Attr attrName) {
1747   return HaveAttrConflict(attrName, Attr::INTENT_IN, Attr::INTENT_INOUT) ||
1748       HaveAttrConflict(attrName, Attr::INTENT_IN, Attr::INTENT_OUT) ||
1749       HaveAttrConflict(attrName, Attr::INTENT_INOUT, Attr::INTENT_OUT) ||
1750       HaveAttrConflict(attrName, Attr::PASS, Attr::NOPASS) || // C781
1751       HaveAttrConflict(attrName, Attr::PURE, Attr::IMPURE) ||
1752       HaveAttrConflict(attrName, Attr::PUBLIC, Attr::PRIVATE) ||
1753       HaveAttrConflict(attrName, Attr::RECURSIVE, Attr::NON_RECURSIVE);
1754 }
1755 bool AttrsVisitor::CheckAndSet(Attr attrName) {
1756   CHECK(attrs_);
1757   if (IsConflictingAttr(attrName) || IsDuplicateAttr(attrName)) {
1758     return false;
1759   }
1760   attrs_->set(attrName);
1761   return true;
1762 }
1763 
1764 // DeclTypeSpecVisitor implementation
1765 
1766 const DeclTypeSpec *DeclTypeSpecVisitor::GetDeclTypeSpec() {
1767   return state_.declTypeSpec;
1768 }
1769 
1770 void DeclTypeSpecVisitor::BeginDeclTypeSpec() {
1771   CHECK(!state_.expectDeclTypeSpec);
1772   CHECK(!state_.declTypeSpec);
1773   state_.expectDeclTypeSpec = true;
1774 }
1775 void DeclTypeSpecVisitor::EndDeclTypeSpec() {
1776   CHECK(state_.expectDeclTypeSpec);
1777   state_ = {};
1778 }
1779 
1780 void DeclTypeSpecVisitor::SetDeclTypeSpecCategory(
1781     DeclTypeSpec::Category category) {
1782   CHECK(state_.expectDeclTypeSpec);
1783   state_.derived.category = category;
1784 }
1785 
1786 bool DeclTypeSpecVisitor::Pre(const parser::TypeGuardStmt &) {
1787   BeginDeclTypeSpec();
1788   return true;
1789 }
1790 void DeclTypeSpecVisitor::Post(const parser::TypeGuardStmt &) {
1791   EndDeclTypeSpec();
1792 }
1793 
1794 void DeclTypeSpecVisitor::Post(const parser::TypeSpec &typeSpec) {
1795   // Record the resolved DeclTypeSpec in the parse tree for use by
1796   // expression semantics if the DeclTypeSpec is a valid TypeSpec.
1797   // The grammar ensures that it's an intrinsic or derived type spec,
1798   // not TYPE(*) or CLASS(*) or CLASS(T).
1799   if (const DeclTypeSpec * spec{state_.declTypeSpec}) {
1800     switch (spec->category()) {
1801     case DeclTypeSpec::Numeric:
1802     case DeclTypeSpec::Logical:
1803     case DeclTypeSpec::Character:
1804       typeSpec.declTypeSpec = spec;
1805       break;
1806     case DeclTypeSpec::TypeDerived:
1807       if (const DerivedTypeSpec * derived{spec->AsDerived()}) {
1808         CheckForAbstractType(derived->typeSymbol()); // C703
1809         typeSpec.declTypeSpec = spec;
1810       }
1811       break;
1812     default:
1813       CRASH_NO_CASE;
1814     }
1815   }
1816 }
1817 
1818 void DeclTypeSpecVisitor::Post(
1819     const parser::IntrinsicTypeSpec::DoublePrecision &) {
1820   MakeNumericType(TypeCategory::Real, context().doublePrecisionKind());
1821 }
1822 void DeclTypeSpecVisitor::Post(
1823     const parser::IntrinsicTypeSpec::DoubleComplex &) {
1824   MakeNumericType(TypeCategory::Complex, context().doublePrecisionKind());
1825 }
1826 void DeclTypeSpecVisitor::MakeNumericType(TypeCategory category, int kind) {
1827   SetDeclTypeSpec(context().MakeNumericType(category, kind));
1828 }
1829 
1830 void DeclTypeSpecVisitor::CheckForAbstractType(const Symbol &typeSymbol) {
1831   if (typeSymbol.attrs().test(Attr::ABSTRACT)) {
1832     Say("ABSTRACT derived type may not be used here"_err_en_US);
1833   }
1834 }
1835 
1836 void DeclTypeSpecVisitor::Post(const parser::DeclarationTypeSpec::ClassStar &) {
1837   SetDeclTypeSpec(context().globalScope().MakeClassStarType());
1838 }
1839 void DeclTypeSpecVisitor::Post(const parser::DeclarationTypeSpec::TypeStar &) {
1840   SetDeclTypeSpec(context().globalScope().MakeTypeStarType());
1841 }
1842 
1843 // Check that we're expecting to see a DeclTypeSpec (and haven't seen one yet)
1844 // and save it in state_.declTypeSpec.
1845 void DeclTypeSpecVisitor::SetDeclTypeSpec(const DeclTypeSpec &declTypeSpec) {
1846   CHECK(state_.expectDeclTypeSpec);
1847   CHECK(!state_.declTypeSpec);
1848   state_.declTypeSpec = &declTypeSpec;
1849 }
1850 
1851 KindExpr DeclTypeSpecVisitor::GetKindParamExpr(
1852     TypeCategory category, const std::optional<parser::KindSelector> &kind) {
1853   return AnalyzeKindSelector(context(), category, kind);
1854 }
1855 
1856 // MessageHandler implementation
1857 
1858 Message &MessageHandler::Say(MessageFixedText &&msg) {
1859   return context_->Say(currStmtSource().value(), std::move(msg));
1860 }
1861 Message &MessageHandler::Say(MessageFormattedText &&msg) {
1862   return context_->Say(currStmtSource().value(), std::move(msg));
1863 }
1864 Message &MessageHandler::Say(const SourceName &name, MessageFixedText &&msg) {
1865   return Say(name, std::move(msg), name);
1866 }
1867 
1868 // ImplicitRulesVisitor implementation
1869 
1870 void ImplicitRulesVisitor::Post(const parser::ParameterStmt &) {
1871   prevParameterStmt_ = currStmtSource();
1872 }
1873 
1874 bool ImplicitRulesVisitor::Pre(const parser::ImplicitStmt &x) {
1875   bool result{
1876       common::visit(common::visitors{
1877                         [&](const std::list<ImplicitNoneNameSpec> &y) {
1878                           return HandleImplicitNone(y);
1879                         },
1880                         [&](const std::list<parser::ImplicitSpec> &) {
1881                           if (prevImplicitNoneType_) {
1882                             Say("IMPLICIT statement after IMPLICIT NONE or "
1883                                 "IMPLICIT NONE(TYPE) statement"_err_en_US);
1884                             return false;
1885                           }
1886                           implicitRules_->set_isImplicitNoneType(false);
1887                           return true;
1888                         },
1889                     },
1890           x.u)};
1891   prevImplicit_ = currStmtSource();
1892   return result;
1893 }
1894 
1895 bool ImplicitRulesVisitor::Pre(const parser::LetterSpec &x) {
1896   auto loLoc{std::get<parser::Location>(x.t)};
1897   auto hiLoc{loLoc};
1898   if (auto hiLocOpt{std::get<std::optional<parser::Location>>(x.t)}) {
1899     hiLoc = *hiLocOpt;
1900     if (*hiLoc < *loLoc) {
1901       Say(hiLoc, "'%s' does not follow '%s' alphabetically"_err_en_US,
1902           std::string(hiLoc, 1), std::string(loLoc, 1));
1903       return false;
1904     }
1905   }
1906   implicitRules_->SetTypeMapping(*GetDeclTypeSpec(), loLoc, hiLoc);
1907   return false;
1908 }
1909 
1910 bool ImplicitRulesVisitor::Pre(const parser::ImplicitSpec &) {
1911   BeginDeclTypeSpec();
1912   set_allowForwardReferenceToDerivedType(true);
1913   return true;
1914 }
1915 
1916 void ImplicitRulesVisitor::Post(const parser::ImplicitSpec &) {
1917   EndDeclTypeSpec();
1918 }
1919 
1920 void ImplicitRulesVisitor::SetScope(const Scope &scope) {
1921   implicitRules_ = &DEREF(implicitRulesMap_).at(&scope);
1922   prevImplicit_ = std::nullopt;
1923   prevImplicitNone_ = std::nullopt;
1924   prevImplicitNoneType_ = std::nullopt;
1925   prevParameterStmt_ = std::nullopt;
1926 }
1927 void ImplicitRulesVisitor::BeginScope(const Scope &scope) {
1928   // find or create implicit rules for this scope
1929   DEREF(implicitRulesMap_).try_emplace(&scope, context(), implicitRules_);
1930   SetScope(scope);
1931 }
1932 
1933 // TODO: for all of these errors, reference previous statement too
1934 bool ImplicitRulesVisitor::HandleImplicitNone(
1935     const std::list<ImplicitNoneNameSpec> &nameSpecs) {
1936   if (prevImplicitNone_) {
1937     Say("More than one IMPLICIT NONE statement"_err_en_US);
1938     Say(*prevImplicitNone_, "Previous IMPLICIT NONE statement"_en_US);
1939     return false;
1940   }
1941   if (prevParameterStmt_) {
1942     Say("IMPLICIT NONE statement after PARAMETER statement"_err_en_US);
1943     return false;
1944   }
1945   prevImplicitNone_ = currStmtSource();
1946   bool implicitNoneTypeNever{
1947       context().IsEnabled(common::LanguageFeature::ImplicitNoneTypeNever)};
1948   if (nameSpecs.empty()) {
1949     if (!implicitNoneTypeNever) {
1950       prevImplicitNoneType_ = currStmtSource();
1951       implicitRules_->set_isImplicitNoneType(true);
1952       if (prevImplicit_) {
1953         Say("IMPLICIT NONE statement after IMPLICIT statement"_err_en_US);
1954         return false;
1955       }
1956     }
1957   } else {
1958     int sawType{0};
1959     int sawExternal{0};
1960     for (const auto noneSpec : nameSpecs) {
1961       switch (noneSpec) {
1962       case ImplicitNoneNameSpec::External:
1963         implicitRules_->set_isImplicitNoneExternal(true);
1964         ++sawExternal;
1965         break;
1966       case ImplicitNoneNameSpec::Type:
1967         if (!implicitNoneTypeNever) {
1968           prevImplicitNoneType_ = currStmtSource();
1969           implicitRules_->set_isImplicitNoneType(true);
1970           if (prevImplicit_) {
1971             Say("IMPLICIT NONE(TYPE) after IMPLICIT statement"_err_en_US);
1972             return false;
1973           }
1974           ++sawType;
1975         }
1976         break;
1977       }
1978     }
1979     if (sawType > 1) {
1980       Say("TYPE specified more than once in IMPLICIT NONE statement"_err_en_US);
1981       return false;
1982     }
1983     if (sawExternal > 1) {
1984       Say("EXTERNAL specified more than once in IMPLICIT NONE statement"_err_en_US);
1985       return false;
1986     }
1987   }
1988   return true;
1989 }
1990 
1991 // ArraySpecVisitor implementation
1992 
1993 void ArraySpecVisitor::Post(const parser::ArraySpec &x) {
1994   CHECK(arraySpec_.empty());
1995   arraySpec_ = AnalyzeArraySpec(context(), x);
1996 }
1997 void ArraySpecVisitor::Post(const parser::ComponentArraySpec &x) {
1998   CHECK(arraySpec_.empty());
1999   arraySpec_ = AnalyzeArraySpec(context(), x);
2000 }
2001 void ArraySpecVisitor::Post(const parser::CoarraySpec &x) {
2002   CHECK(coarraySpec_.empty());
2003   coarraySpec_ = AnalyzeCoarraySpec(context(), x);
2004 }
2005 
2006 const ArraySpec &ArraySpecVisitor::arraySpec() {
2007   return !arraySpec_.empty() ? arraySpec_ : attrArraySpec_;
2008 }
2009 const ArraySpec &ArraySpecVisitor::coarraySpec() {
2010   return !coarraySpec_.empty() ? coarraySpec_ : attrCoarraySpec_;
2011 }
2012 void ArraySpecVisitor::BeginArraySpec() {
2013   CHECK(arraySpec_.empty());
2014   CHECK(coarraySpec_.empty());
2015   CHECK(attrArraySpec_.empty());
2016   CHECK(attrCoarraySpec_.empty());
2017 }
2018 void ArraySpecVisitor::EndArraySpec() {
2019   CHECK(arraySpec_.empty());
2020   CHECK(coarraySpec_.empty());
2021   attrArraySpec_.clear();
2022   attrCoarraySpec_.clear();
2023 }
2024 void ArraySpecVisitor::PostAttrSpec() {
2025   // Save dimension/codimension from attrs so we can process array/coarray-spec
2026   // on the entity-decl
2027   if (!arraySpec_.empty()) {
2028     if (attrArraySpec_.empty()) {
2029       attrArraySpec_ = arraySpec_;
2030       arraySpec_.clear();
2031     } else {
2032       Say(currStmtSource().value(),
2033           "Attribute 'DIMENSION' cannot be used more than once"_err_en_US);
2034     }
2035   }
2036   if (!coarraySpec_.empty()) {
2037     if (attrCoarraySpec_.empty()) {
2038       attrCoarraySpec_ = coarraySpec_;
2039       coarraySpec_.clear();
2040     } else {
2041       Say(currStmtSource().value(),
2042           "Attribute 'CODIMENSION' cannot be used more than once"_err_en_US);
2043     }
2044   }
2045 }
2046 
2047 // FuncResultStack implementation
2048 
2049 FuncResultStack::~FuncResultStack() { CHECK(stack_.empty()); }
2050 
2051 void FuncResultStack::CompleteFunctionResultType() {
2052   // If the function has a type in the prefix, process it now.
2053   FuncInfo *info{Top()};
2054   if (info && &info->scope == &scopeHandler_.currScope()) {
2055     if (info->parsedType) {
2056       scopeHandler_.messageHandler().set_currStmtSource(info->source);
2057       if (const auto *type{
2058               scopeHandler_.ProcessTypeSpec(*info->parsedType, true)}) {
2059         if (!scopeHandler_.context().HasError(info->resultSymbol)) {
2060           info->resultSymbol->SetType(*type);
2061         }
2062       }
2063       info->parsedType = nullptr;
2064     }
2065   }
2066 }
2067 
2068 // Called from ConvertTo{Object/Proc}Entity to cope with any appearance
2069 // of the function result in a specification expression.
2070 void FuncResultStack::CompleteTypeIfFunctionResult(Symbol &symbol) {
2071   if (FuncInfo * info{Top()}) {
2072     if (info->resultSymbol == &symbol) {
2073       CompleteFunctionResultType();
2074     }
2075   }
2076 }
2077 
2078 void FuncResultStack::Pop() {
2079   if (!stack_.empty() && &stack_.back().scope == &scopeHandler_.currScope()) {
2080     stack_.pop_back();
2081   }
2082 }
2083 
2084 // ScopeHandler implementation
2085 
2086 void ScopeHandler::SayAlreadyDeclared(const parser::Name &name, Symbol &prev) {
2087   SayAlreadyDeclared(name.source, prev);
2088 }
2089 void ScopeHandler::SayAlreadyDeclared(const SourceName &name, Symbol &prev) {
2090   if (context().HasError(prev)) {
2091     // don't report another error about prev
2092   } else {
2093     if (const auto *details{prev.detailsIf<UseDetails>()}) {
2094       Say(name, "'%s' is already declared in this scoping unit"_err_en_US)
2095           .Attach(details->location(),
2096               "It is use-associated with '%s' in module '%s'"_en_US,
2097               details->symbol().name(), GetUsedModule(*details).name());
2098     } else {
2099       SayAlreadyDeclared(name, prev.name());
2100     }
2101     context().SetError(prev);
2102   }
2103 }
2104 void ScopeHandler::SayAlreadyDeclared(
2105     const SourceName &name1, const SourceName &name2) {
2106   if (name1.begin() < name2.begin()) {
2107     SayAlreadyDeclared(name2, name1);
2108   } else {
2109     Say(name1, "'%s' is already declared in this scoping unit"_err_en_US)
2110         .Attach(name2, "Previous declaration of '%s'"_en_US, name2);
2111   }
2112 }
2113 
2114 void ScopeHandler::SayWithReason(const parser::Name &name, Symbol &symbol,
2115     MessageFixedText &&msg1, Message &&msg2) {
2116   Say(name, std::move(msg1), symbol.name()).Attach(std::move(msg2));
2117   context().SetError(symbol, msg1.isFatal());
2118 }
2119 
2120 void ScopeHandler::SayWithDecl(
2121     const parser::Name &name, Symbol &symbol, MessageFixedText &&msg) {
2122   Say(name, std::move(msg), symbol.name())
2123       .Attach(Message{name.source,
2124           symbol.test(Symbol::Flag::Implicit)
2125               ? "Implicit declaration of '%s'"_en_US
2126               : "Declaration of '%s'"_en_US,
2127           name.source});
2128   context().SetError(symbol, msg.isFatal());
2129 }
2130 
2131 void ScopeHandler::SayLocalMustBeVariable(
2132     const parser::Name &name, Symbol &symbol) {
2133   SayWithDecl(name, symbol,
2134       "The name '%s' must be a variable to appear"
2135       " in a locality-spec"_err_en_US);
2136 }
2137 
2138 void ScopeHandler::SayDerivedType(
2139     const SourceName &name, MessageFixedText &&msg, const Scope &type) {
2140   const Symbol &typeSymbol{DEREF(type.GetSymbol())};
2141   Say(name, std::move(msg), name, typeSymbol.name())
2142       .Attach(typeSymbol.name(), "Declaration of derived type '%s'"_en_US,
2143           typeSymbol.name());
2144 }
2145 void ScopeHandler::Say2(const SourceName &name1, MessageFixedText &&msg1,
2146     const SourceName &name2, MessageFixedText &&msg2) {
2147   Say(name1, std::move(msg1)).Attach(name2, std::move(msg2), name2);
2148 }
2149 void ScopeHandler::Say2(const SourceName &name, MessageFixedText &&msg1,
2150     Symbol &symbol, MessageFixedText &&msg2) {
2151   Say2(name, std::move(msg1), symbol.name(), std::move(msg2));
2152   context().SetError(symbol, msg1.isFatal());
2153 }
2154 void ScopeHandler::Say2(const parser::Name &name, MessageFixedText &&msg1,
2155     Symbol &symbol, MessageFixedText &&msg2) {
2156   Say2(name.source, std::move(msg1), symbol.name(), std::move(msg2));
2157   context().SetError(symbol, msg1.isFatal());
2158 }
2159 
2160 // This is essentially GetProgramUnitContaining(), but it can return
2161 // a mutable Scope &, it ignores statement functions, and it fails
2162 // gracefully for error recovery (returning the original Scope).
2163 template <typename T> static T &GetInclusiveScope(T &scope) {
2164   for (T *s{&scope}; !s->IsGlobal(); s = &s->parent()) {
2165     switch (s->kind()) {
2166     case Scope::Kind::Module:
2167     case Scope::Kind::MainProgram:
2168     case Scope::Kind::Subprogram:
2169     case Scope::Kind::BlockData:
2170       if (!s->IsStmtFunction()) {
2171         return *s;
2172       }
2173       break;
2174     default:;
2175     }
2176   }
2177   return scope;
2178 }
2179 
2180 Scope &ScopeHandler::InclusiveScope() { return GetInclusiveScope(currScope()); }
2181 
2182 Scope *ScopeHandler::GetHostProcedure() {
2183   Scope &parent{InclusiveScope().parent()};
2184   switch (parent.kind()) {
2185   case Scope::Kind::Subprogram:
2186     return &parent;
2187   case Scope::Kind::MainProgram:
2188     return &parent;
2189   default:
2190     return nullptr;
2191   }
2192 }
2193 
2194 Scope &ScopeHandler::NonDerivedTypeScope() {
2195   return currScope_->IsDerivedType() ? currScope_->parent() : *currScope_;
2196 }
2197 
2198 void ScopeHandler::PushScope(Scope::Kind kind, Symbol *symbol) {
2199   PushScope(currScope().MakeScope(kind, symbol));
2200 }
2201 void ScopeHandler::PushScope(Scope &scope) {
2202   currScope_ = &scope;
2203   auto kind{currScope_->kind()};
2204   if (kind != Scope::Kind::Block) {
2205     BeginScope(scope);
2206   }
2207   // The name of a module or submodule cannot be "used" in its scope,
2208   // as we read 19.3.1(2), so we allow the name to be used as a local
2209   // identifier in the module or submodule too.  Same with programs
2210   // (14.1(3)) and BLOCK DATA.
2211   if (!currScope_->IsDerivedType() && kind != Scope::Kind::Module &&
2212       kind != Scope::Kind::MainProgram && kind != Scope::Kind::BlockData) {
2213     if (auto *symbol{scope.symbol()}) {
2214       // Create a dummy symbol so we can't create another one with the same
2215       // name. It might already be there if we previously pushed the scope.
2216       SourceName name{symbol->name()};
2217       if (!FindInScope(scope, name)) {
2218         auto &newSymbol{MakeSymbol(name)};
2219         if (kind == Scope::Kind::Subprogram) {
2220           // Allow for recursive references.  If this symbol is a function
2221           // without an explicit RESULT(), this new symbol will be discarded
2222           // and replaced with an object of the same name.
2223           newSymbol.set_details(HostAssocDetails{*symbol});
2224         } else {
2225           newSymbol.set_details(MiscDetails{MiscDetails::Kind::ScopeName});
2226         }
2227       }
2228     }
2229   }
2230 }
2231 void ScopeHandler::PopScope() {
2232   // Entities that are not yet classified as objects or procedures are now
2233   // assumed to be objects.
2234   // TODO: Statement functions
2235   for (auto &pair : currScope()) {
2236     ConvertToObjectEntity(*pair.second);
2237   }
2238   funcResultStack_.Pop();
2239   // If popping back into a global scope, pop back to the main global scope.
2240   SetScope(currScope_->parent().IsGlobal() ? context().globalScope()
2241                                            : currScope_->parent());
2242 }
2243 void ScopeHandler::SetScope(Scope &scope) {
2244   currScope_ = &scope;
2245   ImplicitRulesVisitor::SetScope(InclusiveScope());
2246 }
2247 
2248 Symbol *ScopeHandler::FindSymbol(const parser::Name &name) {
2249   return FindSymbol(currScope(), name);
2250 }
2251 Symbol *ScopeHandler::FindSymbol(const Scope &scope, const parser::Name &name) {
2252   if (scope.IsDerivedType()) {
2253     if (Symbol * symbol{scope.FindComponent(name.source)}) {
2254       if (!symbol->has<ProcBindingDetails>() &&
2255           !symbol->test(Symbol::Flag::ParentComp)) {
2256         return Resolve(name, symbol);
2257       }
2258     }
2259     return FindSymbol(scope.parent(), name);
2260   } else {
2261     // In EQUIVALENCE statements only resolve names in the local scope, see
2262     // 19.5.1.4, paragraph 2, item (10)
2263     return Resolve(name,
2264         inEquivalenceStmt_ ? FindInScope(scope, name)
2265                            : scope.FindSymbol(name.source));
2266   }
2267 }
2268 
2269 Symbol &ScopeHandler::MakeSymbol(
2270     Scope &scope, const SourceName &name, Attrs attrs) {
2271   if (Symbol * symbol{FindInScope(scope, name)}) {
2272     symbol->attrs() |= attrs;
2273     return *symbol;
2274   } else {
2275     const auto pair{scope.try_emplace(name, attrs, UnknownDetails{})};
2276     CHECK(pair.second); // name was not found, so must be able to add
2277     return *pair.first->second;
2278   }
2279 }
2280 Symbol &ScopeHandler::MakeSymbol(const SourceName &name, Attrs attrs) {
2281   return MakeSymbol(currScope(), name, attrs);
2282 }
2283 Symbol &ScopeHandler::MakeSymbol(const parser::Name &name, Attrs attrs) {
2284   return Resolve(name, MakeSymbol(name.source, attrs));
2285 }
2286 Symbol &ScopeHandler::MakeHostAssocSymbol(
2287     const parser::Name &name, const Symbol &hostSymbol) {
2288   Symbol &symbol{*NonDerivedTypeScope()
2289                       .try_emplace(name.source, HostAssocDetails{hostSymbol})
2290                       .first->second};
2291   name.symbol = &symbol;
2292   symbol.attrs() = hostSymbol.attrs(); // TODO: except PRIVATE, PUBLIC?
2293   symbol.flags() = hostSymbol.flags();
2294   return symbol;
2295 }
2296 Symbol &ScopeHandler::CopySymbol(const SourceName &name, const Symbol &symbol) {
2297   CHECK(!FindInScope(name));
2298   return MakeSymbol(currScope(), name, symbol.attrs());
2299 }
2300 
2301 // Look for name only in scope, not in enclosing scopes.
2302 Symbol *ScopeHandler::FindInScope(
2303     const Scope &scope, const parser::Name &name) {
2304   return Resolve(name, FindInScope(scope, name.source));
2305 }
2306 Symbol *ScopeHandler::FindInScope(const Scope &scope, const SourceName &name) {
2307   // all variants of names, e.g. "operator(.ne.)" for "operator(/=)"
2308   for (const std::string &n : GetAllNames(context(), name)) {
2309     auto it{scope.find(SourceName{n})};
2310     if (it != scope.end()) {
2311       return &*it->second;
2312     }
2313   }
2314   return nullptr;
2315 }
2316 
2317 // Find a component or type parameter by name in a derived type or its parents.
2318 Symbol *ScopeHandler::FindInTypeOrParents(
2319     const Scope &scope, const parser::Name &name) {
2320   return Resolve(name, scope.FindComponent(name.source));
2321 }
2322 Symbol *ScopeHandler::FindInTypeOrParents(const parser::Name &name) {
2323   return FindInTypeOrParents(currScope(), name);
2324 }
2325 
2326 void ScopeHandler::EraseSymbol(const parser::Name &name) {
2327   currScope().erase(name.source);
2328   name.symbol = nullptr;
2329 }
2330 
2331 static bool NeedsType(const Symbol &symbol) {
2332   return !symbol.GetType() &&
2333       common::visit(common::visitors{
2334                         [](const EntityDetails &) { return true; },
2335                         [](const ObjectEntityDetails &) { return true; },
2336                         [](const AssocEntityDetails &) { return true; },
2337                         [&](const ProcEntityDetails &p) {
2338                           return symbol.test(Symbol::Flag::Function) &&
2339                               !symbol.attrs().test(Attr::INTRINSIC) &&
2340                               !p.interface().type() && !p.interface().symbol();
2341                         },
2342                         [](const auto &) { return false; },
2343                     },
2344           symbol.details());
2345 }
2346 
2347 void ScopeHandler::ApplyImplicitRules(
2348     Symbol &symbol, bool allowForwardReference) {
2349   funcResultStack_.CompleteTypeIfFunctionResult(symbol);
2350   if (context().HasError(symbol) || !NeedsType(symbol)) {
2351     return;
2352   }
2353   if (const DeclTypeSpec * type{GetImplicitType(symbol)}) {
2354     symbol.set(Symbol::Flag::Implicit);
2355     symbol.SetType(*type);
2356     return;
2357   }
2358   if (symbol.has<ProcEntityDetails>() && !symbol.attrs().test(Attr::EXTERNAL)) {
2359     std::optional<Symbol::Flag> functionOrSubroutineFlag;
2360     if (symbol.test(Symbol::Flag::Function)) {
2361       functionOrSubroutineFlag = Symbol::Flag::Function;
2362     } else if (symbol.test(Symbol::Flag::Subroutine)) {
2363       functionOrSubroutineFlag = Symbol::Flag::Subroutine;
2364     }
2365     if (IsIntrinsic(symbol.name(), functionOrSubroutineFlag)) {
2366       // type will be determined in expression semantics
2367       AcquireIntrinsicProcedureFlags(symbol);
2368       return;
2369     }
2370   }
2371   if (allowForwardReference && ImplicitlyTypeForwardRef(symbol)) {
2372     return;
2373   }
2374   if (!context().HasError(symbol)) {
2375     Say(symbol.name(), "No explicit type declared for '%s'"_err_en_US);
2376     context().SetError(symbol);
2377   }
2378 }
2379 
2380 // Extension: Allow forward references to scalar integer dummy arguments
2381 // to appear in specification expressions under IMPLICIT NONE(TYPE) when
2382 // what would otherwise have been their implicit type is default INTEGER.
2383 bool ScopeHandler::ImplicitlyTypeForwardRef(Symbol &symbol) {
2384   if (!inSpecificationPart_ || context().HasError(symbol) || !IsDummy(symbol) ||
2385       symbol.Rank() != 0 ||
2386       !context().languageFeatures().IsEnabled(
2387           common::LanguageFeature::ForwardRefDummyImplicitNone)) {
2388     return false;
2389   }
2390   const DeclTypeSpec *type{
2391       GetImplicitType(symbol, false /*ignore IMPLICIT NONE*/)};
2392   if (!type || !type->IsNumeric(TypeCategory::Integer)) {
2393     return false;
2394   }
2395   auto kind{evaluate::ToInt64(type->numericTypeSpec().kind())};
2396   if (!kind || *kind != context().GetDefaultKind(TypeCategory::Integer)) {
2397     return false;
2398   }
2399   if (!ConvertToObjectEntity(symbol)) {
2400     return false;
2401   }
2402   // TODO: check no INTENT(OUT)?
2403   if (context().languageFeatures().ShouldWarn(
2404           common::LanguageFeature::ForwardRefDummyImplicitNone)) {
2405     Say(symbol.name(),
2406         "Dummy argument '%s' was used without being explicitly typed"_warn_en_US,
2407         symbol.name());
2408   }
2409   symbol.set(Symbol::Flag::Implicit);
2410   symbol.SetType(*type);
2411   return true;
2412 }
2413 
2414 // Ensure that the symbol for an intrinsic procedure is marked with
2415 // the INTRINSIC attribute.  Also set PURE &/or ELEMENTAL as
2416 // appropriate.
2417 void ScopeHandler::AcquireIntrinsicProcedureFlags(Symbol &symbol) {
2418   symbol.attrs().set(Attr::INTRINSIC);
2419   switch (context().intrinsics().GetIntrinsicClass(symbol.name().ToString())) {
2420   case evaluate::IntrinsicClass::elementalFunction:
2421   case evaluate::IntrinsicClass::elementalSubroutine:
2422     symbol.attrs().set(Attr::ELEMENTAL);
2423     symbol.attrs().set(Attr::PURE);
2424     break;
2425   case evaluate::IntrinsicClass::impureSubroutine:
2426     break;
2427   default:
2428     symbol.attrs().set(Attr::PURE);
2429   }
2430 }
2431 
2432 const DeclTypeSpec *ScopeHandler::GetImplicitType(
2433     Symbol &symbol, bool respectImplicitNoneType) {
2434   const Scope *scope{&symbol.owner()};
2435   if (scope->IsGlobal()) {
2436     scope = &currScope();
2437   }
2438   scope = &GetInclusiveScope(*scope);
2439   const auto *type{implicitRulesMap_->at(scope).GetType(
2440       symbol.name(), respectImplicitNoneType)};
2441   if (type) {
2442     if (const DerivedTypeSpec * derived{type->AsDerived()}) {
2443       // Resolve any forward-referenced derived type; a quick no-op else.
2444       auto &instantiatable{*const_cast<DerivedTypeSpec *>(derived)};
2445       instantiatable.Instantiate(currScope());
2446     }
2447   }
2448   return type;
2449 }
2450 
2451 // Convert symbol to be a ObjectEntity or return false if it can't be.
2452 bool ScopeHandler::ConvertToObjectEntity(Symbol &symbol) {
2453   if (symbol.has<ObjectEntityDetails>()) {
2454     // nothing to do
2455   } else if (symbol.has<UnknownDetails>()) {
2456     symbol.set_details(ObjectEntityDetails{});
2457   } else if (auto *details{symbol.detailsIf<EntityDetails>()}) {
2458     funcResultStack_.CompleteTypeIfFunctionResult(symbol);
2459     symbol.set_details(ObjectEntityDetails{std::move(*details)});
2460   } else if (auto *useDetails{symbol.detailsIf<UseDetails>()}) {
2461     return useDetails->symbol().has<ObjectEntityDetails>();
2462   } else if (auto *hostDetails{symbol.detailsIf<HostAssocDetails>()}) {
2463     return hostDetails->symbol().has<ObjectEntityDetails>();
2464   } else {
2465     return false;
2466   }
2467   return true;
2468 }
2469 // Convert symbol to be a ProcEntity or return false if it can't be.
2470 bool ScopeHandler::ConvertToProcEntity(Symbol &symbol) {
2471   if (symbol.has<ProcEntityDetails>()) {
2472     // nothing to do
2473   } else if (symbol.has<UnknownDetails>()) {
2474     symbol.set_details(ProcEntityDetails{});
2475   } else if (auto *details{symbol.detailsIf<EntityDetails>()}) {
2476     if (IsFunctionResult(symbol) &&
2477         !(IsPointer(symbol) && symbol.attrs().test(Attr::EXTERNAL))) {
2478       // Don't turn function result into a procedure pointer unless both
2479       // POUNTER and EXTERNAL
2480       return false;
2481     }
2482     funcResultStack_.CompleteTypeIfFunctionResult(symbol);
2483     symbol.set_details(ProcEntityDetails{std::move(*details)});
2484     if (symbol.GetType() && !symbol.test(Symbol::Flag::Implicit)) {
2485       CHECK(!symbol.test(Symbol::Flag::Subroutine));
2486       symbol.set(Symbol::Flag::Function);
2487     }
2488   } else if (auto *useDetails{symbol.detailsIf<UseDetails>()}) {
2489     return useDetails->symbol().has<ProcEntityDetails>();
2490   } else if (auto *hostDetails{symbol.detailsIf<HostAssocDetails>()}) {
2491     return hostDetails->symbol().has<ProcEntityDetails>();
2492   } else {
2493     return false;
2494   }
2495   return true;
2496 }
2497 
2498 const DeclTypeSpec &ScopeHandler::MakeNumericType(
2499     TypeCategory category, const std::optional<parser::KindSelector> &kind) {
2500   KindExpr value{GetKindParamExpr(category, kind)};
2501   if (auto known{evaluate::ToInt64(value)}) {
2502     return context().MakeNumericType(category, static_cast<int>(*known));
2503   } else {
2504     return currScope_->MakeNumericType(category, std::move(value));
2505   }
2506 }
2507 
2508 const DeclTypeSpec &ScopeHandler::MakeLogicalType(
2509     const std::optional<parser::KindSelector> &kind) {
2510   KindExpr value{GetKindParamExpr(TypeCategory::Logical, kind)};
2511   if (auto known{evaluate::ToInt64(value)}) {
2512     return context().MakeLogicalType(static_cast<int>(*known));
2513   } else {
2514     return currScope_->MakeLogicalType(std::move(value));
2515   }
2516 }
2517 
2518 void ScopeHandler::NotePossibleBadForwardRef(const parser::Name &name) {
2519   if (inSpecificationPart_ && name.symbol) {
2520     auto kind{currScope().kind()};
2521     if ((kind == Scope::Kind::Subprogram && !currScope().IsStmtFunction()) ||
2522         kind == Scope::Kind::Block) {
2523       bool isHostAssociated{&name.symbol->owner() == &currScope()
2524               ? name.symbol->has<HostAssocDetails>()
2525               : name.symbol->owner().Contains(currScope())};
2526       if (isHostAssociated) {
2527         specPartState_.forwardRefs.insert(name.source);
2528       }
2529     }
2530   }
2531 }
2532 
2533 std::optional<SourceName> ScopeHandler::HadForwardRef(
2534     const Symbol &symbol) const {
2535   auto iter{specPartState_.forwardRefs.find(symbol.name())};
2536   if (iter != specPartState_.forwardRefs.end()) {
2537     return *iter;
2538   }
2539   return std::nullopt;
2540 }
2541 
2542 bool ScopeHandler::CheckPossibleBadForwardRef(const Symbol &symbol) {
2543   if (!context().HasError(symbol)) {
2544     if (auto fwdRef{HadForwardRef(symbol)}) {
2545       const Symbol *outer{symbol.owner().FindSymbol(symbol.name())};
2546       if (outer && symbol.has<UseDetails>() &&
2547           &symbol.GetUltimate() == &outer->GetUltimate()) {
2548         // e.g. IMPORT of host's USE association
2549         return false;
2550       }
2551       Say(*fwdRef,
2552           "Forward reference to '%s' is not allowed in the same specification part"_err_en_US,
2553           *fwdRef)
2554           .Attach(symbol.name(), "Later declaration of '%s'"_en_US, *fwdRef);
2555       context().SetError(symbol);
2556       return true;
2557     }
2558     if (IsDummy(symbol) && isImplicitNoneType() &&
2559         symbol.test(Symbol::Flag::Implicit) && !context().HasError(symbol)) {
2560       // Dummy was implicitly typed despite IMPLICIT NONE(TYPE) in
2561       // ApplyImplicitRules() due to use in a specification expression,
2562       // and no explicit type declaration appeared later.
2563       Say(symbol.name(),
2564           "No explicit type declared for dummy argument '%s'"_err_en_US);
2565       context().SetError(symbol);
2566       return true;
2567     }
2568   }
2569   return false;
2570 }
2571 
2572 void ScopeHandler::MakeExternal(Symbol &symbol) {
2573   if (!symbol.attrs().test(Attr::EXTERNAL)) {
2574     symbol.attrs().set(Attr::EXTERNAL);
2575     if (symbol.attrs().test(Attr::INTRINSIC)) { // C840
2576       Say(symbol.name(),
2577           "Symbol '%s' cannot have both EXTERNAL and INTRINSIC attributes"_err_en_US,
2578           symbol.name());
2579     }
2580   }
2581 }
2582 
2583 // ModuleVisitor implementation
2584 
2585 bool ModuleVisitor::Pre(const parser::Only &x) {
2586   common::visit(common::visitors{
2587                     [&](const Indirection<parser::GenericSpec> &generic) {
2588                       GenericSpecInfo genericSpecInfo{generic.value()};
2589                       AddUseOnly(genericSpecInfo.symbolName());
2590                       AddUse(genericSpecInfo);
2591                     },
2592                     [&](const parser::Name &name) {
2593                       AddUseOnly(name.source);
2594                       Resolve(name, AddUse(name.source, name.source).use);
2595                     },
2596                     [&](const parser::Rename &rename) { Walk(rename); },
2597                 },
2598       x.u);
2599   return false;
2600 }
2601 
2602 bool ModuleVisitor::Pre(const parser::Rename::Names &x) {
2603   const auto &localName{std::get<0>(x.t)};
2604   const auto &useName{std::get<1>(x.t)};
2605   AddUseRename(useName.source);
2606   SymbolRename rename{AddUse(localName.source, useName.source)};
2607   if (rename.use) {
2608     EraseRenamedSymbol(*rename.use);
2609   }
2610   Resolve(useName, rename.use);
2611   Resolve(localName, rename.local);
2612   return false;
2613 }
2614 bool ModuleVisitor::Pre(const parser::Rename::Operators &x) {
2615   const parser::DefinedOpName &local{std::get<0>(x.t)};
2616   const parser::DefinedOpName &use{std::get<1>(x.t)};
2617   GenericSpecInfo localInfo{local};
2618   GenericSpecInfo useInfo{use};
2619   if (IsIntrinsicOperator(context(), local.v.source)) {
2620     Say(local.v,
2621         "Intrinsic operator '%s' may not be used as a defined operator"_err_en_US);
2622   } else if (IsLogicalConstant(context(), local.v.source)) {
2623     Say(local.v,
2624         "Logical constant '%s' may not be used as a defined operator"_err_en_US);
2625   } else {
2626     SymbolRename rename{AddUse(localInfo.symbolName(), useInfo.symbolName())};
2627     if (rename.use) {
2628       EraseRenamedSymbol(*rename.use);
2629     }
2630     useInfo.Resolve(rename.use);
2631     localInfo.Resolve(rename.local);
2632   }
2633   return false;
2634 }
2635 
2636 // Set useModuleScope_ to the Scope of the module being used.
2637 bool ModuleVisitor::Pre(const parser::UseStmt &x) {
2638   std::optional<bool> isIntrinsic;
2639   if (x.nature) {
2640     isIntrinsic = *x.nature == parser::UseStmt::ModuleNature::Intrinsic;
2641     AddAndCheckExplicitIntrinsicUse(x.moduleName.source, *isIntrinsic);
2642   } else if (currScope().IsModule() && currScope().symbol() &&
2643       currScope().symbol()->attrs().test(Attr::INTRINSIC)) {
2644     // Intrinsic modules USE only other intrinsic modules
2645     isIntrinsic = true;
2646   }
2647   useModuleScope_ = FindModule(x.moduleName, isIntrinsic);
2648   if (!useModuleScope_) {
2649     return false;
2650   }
2651   // use the name from this source file
2652   useModuleScope_->symbol()->ReplaceName(x.moduleName.source);
2653   return true;
2654 }
2655 
2656 void ModuleVisitor::Post(const parser::UseStmt &x) {
2657   if (const auto *list{std::get_if<std::list<parser::Rename>>(&x.u)}) {
2658     // Not a use-only: collect the names that were used in renames,
2659     // then add a use for each public name that was not renamed.
2660     std::set<SourceName> useNames;
2661     for (const auto &rename : *list) {
2662       common::visit(common::visitors{
2663                         [&](const parser::Rename::Names &names) {
2664                           useNames.insert(std::get<1>(names.t).source);
2665                         },
2666                         [&](const parser::Rename::Operators &ops) {
2667                           useNames.insert(std::get<1>(ops.t).v.source);
2668                         },
2669                     },
2670           rename.u);
2671     }
2672     for (const auto &[name, symbol] : *useModuleScope_) {
2673       if (symbol->attrs().test(Attr::PUBLIC) && !IsUseRenamed(symbol->name()) &&
2674           (!symbol->attrs().test(Attr::INTRINSIC) ||
2675               symbol->has<UseDetails>()) &&
2676           !symbol->has<MiscDetails>() && useNames.count(name) == 0) {
2677         SourceName location{x.moduleName.source};
2678         if (auto *localSymbol{FindInScope(name)}) {
2679           DoAddUse(location, localSymbol->name(), *localSymbol, *symbol);
2680         } else {
2681           DoAddUse(location, location, CopySymbol(name, *symbol), *symbol);
2682         }
2683       }
2684     }
2685   }
2686   useModuleScope_ = nullptr;
2687 }
2688 
2689 ModuleVisitor::SymbolRename ModuleVisitor::AddUse(
2690     const SourceName &localName, const SourceName &useName) {
2691   return AddUse(localName, useName, FindInScope(*useModuleScope_, useName));
2692 }
2693 
2694 ModuleVisitor::SymbolRename ModuleVisitor::AddUse(
2695     const SourceName &localName, const SourceName &useName, Symbol *useSymbol) {
2696   if (!useModuleScope_) {
2697     return {}; // error occurred finding module
2698   }
2699   if (!useSymbol) {
2700     Say(useName, "'%s' not found in module '%s'"_err_en_US, MakeOpName(useName),
2701         useModuleScope_->GetName().value());
2702     return {};
2703   }
2704   if (useSymbol->attrs().test(Attr::PRIVATE) &&
2705       !FindModuleFileContaining(currScope())) {
2706     // Privacy is not enforced in module files so that generic interfaces
2707     // can be resolved to private specific procedures in specification
2708     // expressions.
2709     Say(useName, "'%s' is PRIVATE in '%s'"_err_en_US, MakeOpName(useName),
2710         useModuleScope_->GetName().value());
2711     return {};
2712   }
2713   auto &localSymbol{MakeSymbol(localName)};
2714   DoAddUse(useName, localName, localSymbol, *useSymbol);
2715   return {&localSymbol, useSymbol};
2716 }
2717 
2718 // symbol must be either a Use or a Generic formed by merging two uses.
2719 // Convert it to a UseError with this additional location.
2720 static bool ConvertToUseError(
2721     Symbol &symbol, const SourceName &location, const Scope &module) {
2722   const auto *useDetails{symbol.detailsIf<UseDetails>()};
2723   if (!useDetails) {
2724     if (auto *genericDetails{symbol.detailsIf<GenericDetails>()}) {
2725       if (!genericDetails->uses().empty()) {
2726         useDetails = &genericDetails->uses().at(0)->get<UseDetails>();
2727       }
2728     }
2729   }
2730   if (useDetails) {
2731     symbol.set_details(
2732         UseErrorDetails{*useDetails}.add_occurrence(location, module));
2733     return true;
2734   } else {
2735     return false;
2736   }
2737 }
2738 
2739 // If a symbol has previously been USE-associated and did not appear in a USE
2740 // ONLY clause, erase it from the current scope.  This is needed when a name
2741 // appears in a USE rename clause.
2742 void ModuleVisitor::EraseRenamedSymbol(const Symbol &useSymbol) {
2743   const SourceName &name{useSymbol.name()};
2744   if (const Symbol * symbol{FindInScope(name)}) {
2745     if (auto *useDetails{symbol->detailsIf<UseDetails>()}) {
2746       const Symbol &moduleSymbol{useDetails->symbol()};
2747       if (moduleSymbol.name() == name &&
2748           moduleSymbol.owner() == useSymbol.owner() && IsUseRenamed(name) &&
2749           !IsUseOnly(name)) {
2750         EraseSymbol(*symbol);
2751       }
2752     }
2753   }
2754 }
2755 
2756 void ModuleVisitor::DoAddUse(SourceName location, SourceName localName,
2757     Symbol &localSymbol, const Symbol &useSymbol) {
2758   if (localName != useSymbol.name()) {
2759     EraseRenamedSymbol(useSymbol);
2760   }
2761   if (auto *details{localSymbol.detailsIf<UseErrorDetails>()}) {
2762     details->add_occurrence(location, *useModuleScope_);
2763     return;
2764   }
2765 
2766   if (localSymbol.has<UnknownDetails>()) {
2767     localSymbol.set_details(UseDetails{localName, useSymbol});
2768     localSymbol.attrs() =
2769         useSymbol.attrs() & ~Attrs{Attr::PUBLIC, Attr::PRIVATE};
2770     localSymbol.flags() = useSymbol.flags();
2771     return;
2772   }
2773 
2774   Symbol &localUltimate{localSymbol.GetUltimate()};
2775   const Symbol &useUltimate{useSymbol.GetUltimate()};
2776   if (&localUltimate == &useUltimate) {
2777     // use-associating the same symbol again -- ok
2778     return;
2779   }
2780 
2781   auto checkAmbiguousDerivedType{[this, location, localName](
2782                                      const Symbol *t1, const Symbol *t2) {
2783     if (!t1 || !t2) {
2784       return true;
2785     } else {
2786       t1 = &t1->GetUltimate();
2787       t2 = &t2->GetUltimate();
2788       if (&t1 != &t2) {
2789         Say(location,
2790             "Generic interface '%s' has ambiguous derived types from modules '%s' and '%s'"_err_en_US,
2791             localName, t1->owner().GetName().value(),
2792             t2->owner().GetName().value());
2793         return false;
2794       }
2795     }
2796   }};
2797 
2798   auto *localGeneric{localUltimate.detailsIf<GenericDetails>()};
2799   const auto *useGeneric{useUltimate.detailsIf<GenericDetails>()};
2800   auto combine{false};
2801   if (localGeneric) {
2802     if (useGeneric) {
2803       if (!checkAmbiguousDerivedType(
2804               localGeneric->derivedType(), useGeneric->derivedType())) {
2805         return;
2806       }
2807       combine = true;
2808     } else if (useUltimate.has<DerivedTypeDetails>()) {
2809       if (checkAmbiguousDerivedType(
2810               &useUltimate, localGeneric->derivedType())) {
2811         combine = true;
2812       } else {
2813         return;
2814       }
2815     } else if (&useUltimate == &BypassGeneric(localUltimate)) {
2816       return; // nothing to do; used subprogram is local's specific
2817     }
2818   } else if (useGeneric) {
2819     if (localUltimate.has<DerivedTypeDetails>()) {
2820       if (checkAmbiguousDerivedType(
2821               &localUltimate, useGeneric->derivedType())) {
2822         combine = true;
2823       } else {
2824         return;
2825       }
2826     } else if (&localUltimate == &BypassGeneric(useUltimate).GetUltimate()) {
2827       // Local is the specific of the used generic; replace it.
2828       EraseSymbol(localSymbol);
2829       Symbol &newSymbol{MakeSymbol(localName,
2830           useUltimate.attrs() & ~Attrs{Attr::PUBLIC, Attr::PRIVATE},
2831           UseDetails{localName, useUltimate})};
2832       newSymbol.flags() = useSymbol.flags();
2833       return;
2834     }
2835   }
2836   if (!combine) {
2837     if (!ConvertToUseError(localSymbol, location, *useModuleScope_)) {
2838       Say(location,
2839           "Cannot use-associate '%s'; it is already declared in this scope"_err_en_US,
2840           localName)
2841           .Attach(localSymbol.name(), "Previous declaration of '%s'"_en_US,
2842               localName);
2843     }
2844     return;
2845   }
2846 
2847   // Two items are being use-associated from different modules
2848   // to the same local name.  At least one of them must be a generic,
2849   // and the other one can be a generic or a derived type.
2850   // (It could also have been the specific of the generic, but those
2851   // cases are handled above without needing to make a local copy of the
2852   // generic.)
2853 
2854   if (localGeneric) {
2855     if (localSymbol.has<UseDetails>()) {
2856       // Create a local copy of a previously use-associated generic so that
2857       // it can be locally extended without corrupting the original.
2858       GenericDetails generic;
2859       generic.CopyFrom(*localGeneric);
2860       EraseSymbol(localSymbol);
2861       Symbol &newSymbol{MakeSymbol(
2862           localSymbol.name(), localSymbol.attrs(), std::move(generic))};
2863       newSymbol.flags() = localSymbol.flags();
2864       localGeneric = &newSymbol.get<GenericDetails>();
2865       localGeneric->AddUse(localSymbol);
2866     }
2867     if (useGeneric) {
2868       // Combine two use-associated generics
2869       localSymbol.attrs() =
2870           useSymbol.attrs() & ~Attrs{Attr::PUBLIC, Attr::PRIVATE};
2871       localSymbol.flags() = useSymbol.flags();
2872       AddGenericUse(*localGeneric, localName, useUltimate);
2873       localGeneric->CopyFrom(*useGeneric);
2874     } else {
2875       CHECK(useUltimate.has<DerivedTypeDetails>());
2876       localGeneric->set_derivedType(
2877           AddGenericUse(*localGeneric, localName, useUltimate));
2878     }
2879   } else {
2880     CHECK(useGeneric && localUltimate.has<DerivedTypeDetails>());
2881     CHECK(localSymbol.has<UseDetails>());
2882     // Create a local copy of the use-associated generic, then extend it
2883     // with the local derived type.
2884     GenericDetails generic;
2885     generic.CopyFrom(*useGeneric);
2886     EraseSymbol(localSymbol);
2887     Symbol &newSymbol{MakeSymbol(localName,
2888         useUltimate.attrs() & ~Attrs{Attr::PUBLIC, Attr::PRIVATE},
2889         std::move(generic))};
2890     newSymbol.flags() = useUltimate.flags();
2891     auto &newUseGeneric{newSymbol.get<GenericDetails>()};
2892     AddGenericUse(newUseGeneric, localName, useUltimate);
2893     newUseGeneric.AddUse(localSymbol);
2894     newUseGeneric.set_derivedType(localSymbol);
2895   }
2896 }
2897 
2898 void ModuleVisitor::AddUse(const GenericSpecInfo &info) {
2899   if (useModuleScope_) {
2900     const auto &name{info.symbolName()};
2901     auto rename{AddUse(name, name, FindInScope(*useModuleScope_, name))};
2902     info.Resolve(rename.use);
2903   }
2904 }
2905 
2906 // Create a UseDetails symbol for this USE and add it to generic
2907 Symbol &ModuleVisitor::AddGenericUse(
2908     GenericDetails &generic, const SourceName &name, const Symbol &useSymbol) {
2909   Symbol &newSymbol{
2910       currScope().MakeSymbol(name, {}, UseDetails{name, useSymbol})};
2911   generic.AddUse(newSymbol);
2912   return newSymbol;
2913 }
2914 
2915 // Enforce C1406
2916 void ModuleVisitor::AddAndCheckExplicitIntrinsicUse(
2917     SourceName name, bool isIntrinsic) {
2918   if (isIntrinsic) {
2919     if (auto iter{explicitNonIntrinsicUses_.find(name)};
2920         iter != explicitNonIntrinsicUses_.end()) {
2921       Say(name,
2922           "Cannot USE,INTRINSIC module '%s' in the same scope as USE,NON_INTRINSIC"_err_en_US,
2923           name)
2924           .Attach(*iter, "Previous USE of '%s'"_en_US, *iter);
2925     }
2926     explicitIntrinsicUses_.insert(name);
2927   } else {
2928     if (auto iter{explicitIntrinsicUses_.find(name)};
2929         iter != explicitIntrinsicUses_.end()) {
2930       Say(name,
2931           "Cannot USE,NON_INTRINSIC module '%s' in the same scope as USE,INTRINSIC"_err_en_US,
2932           name)
2933           .Attach(*iter, "Previous USE of '%s'"_en_US, *iter);
2934     }
2935     explicitNonIntrinsicUses_.insert(name);
2936   }
2937 }
2938 
2939 bool ModuleVisitor::BeginSubmodule(
2940     const parser::Name &name, const parser::ParentIdentifier &parentId) {
2941   const auto &ancestorName{std::get<parser::Name>(parentId.t)};
2942   Scope *parentScope{nullptr};
2943   Scope *ancestor{FindModule(ancestorName, false /*not intrinsic*/)};
2944   if (ancestor) {
2945     if (const auto &parentName{
2946             std::get<std::optional<parser::Name>>(parentId.t)}) {
2947       parentScope = FindModule(*parentName, false /*not intrinsic*/, ancestor);
2948     } else {
2949       parentScope = ancestor;
2950     }
2951   }
2952   if (parentScope) {
2953     PushScope(*parentScope);
2954   } else {
2955     // Error recovery: there's no ancestor scope, so create a dummy one to
2956     // hold the submodule's scope.
2957     SourceName dummyName{context().GetTempName(currScope())};
2958     Symbol &dummySymbol{MakeSymbol(dummyName, Attrs{}, ModuleDetails{false})};
2959     PushScope(Scope::Kind::Module, &dummySymbol);
2960     parentScope = &currScope();
2961   }
2962   BeginModule(name, true);
2963   if (ancestor && !ancestor->AddSubmodule(name.source, currScope())) {
2964     Say(name, "Module '%s' already has a submodule named '%s'"_err_en_US,
2965         ancestorName.source, name.source);
2966   }
2967   return true;
2968 }
2969 
2970 void ModuleVisitor::BeginModule(const parser::Name &name, bool isSubmodule) {
2971   auto &symbol{MakeSymbol(name, ModuleDetails{isSubmodule})};
2972   auto &details{symbol.get<ModuleDetails>()};
2973   PushScope(Scope::Kind::Module, &symbol);
2974   details.set_scope(&currScope());
2975   defaultAccess_ = Attr::PUBLIC;
2976   prevAccessStmt_ = std::nullopt;
2977 }
2978 
2979 // Find a module or submodule by name and return its scope.
2980 // If ancestor is present, look for a submodule of that ancestor module.
2981 // May have to read a .mod file to find it.
2982 // If an error occurs, report it and return nullptr.
2983 Scope *ModuleVisitor::FindModule(const parser::Name &name,
2984     std::optional<bool> isIntrinsic, Scope *ancestor) {
2985   ModFileReader reader{context()};
2986   Scope *scope{reader.Read(name.source, isIntrinsic, ancestor)};
2987   if (!scope) {
2988     return nullptr;
2989   }
2990   if (DoesScopeContain(scope, currScope())) { // 14.2.2(1)
2991     Say(name, "Module '%s' cannot USE itself"_err_en_US);
2992   }
2993   Resolve(name, scope->symbol());
2994   return scope;
2995 }
2996 
2997 void ModuleVisitor::ApplyDefaultAccess() {
2998   for (auto &pair : currScope()) {
2999     Symbol &symbol = *pair.second;
3000     if (!symbol.attrs().HasAny({Attr::PUBLIC, Attr::PRIVATE})) {
3001       symbol.attrs().set(defaultAccess_);
3002     }
3003   }
3004 }
3005 
3006 // InterfaceVistor implementation
3007 
3008 bool InterfaceVisitor::Pre(const parser::InterfaceStmt &x) {
3009   bool isAbstract{std::holds_alternative<parser::Abstract>(x.u)};
3010   genericInfo_.emplace(/*isInterface*/ true, isAbstract);
3011   return BeginAttrs();
3012 }
3013 
3014 void InterfaceVisitor::Post(const parser::InterfaceStmt &) { EndAttrs(); }
3015 
3016 void InterfaceVisitor::Post(const parser::EndInterfaceStmt &) {
3017   genericInfo_.pop();
3018 }
3019 
3020 // Create a symbol in genericSymbol_ for this GenericSpec.
3021 bool InterfaceVisitor::Pre(const parser::GenericSpec &x) {
3022   if (auto *symbol{FindInScope(GenericSpecInfo{x}.symbolName())}) {
3023     SetGenericSymbol(*symbol);
3024   }
3025   return false;
3026 }
3027 
3028 bool InterfaceVisitor::Pre(const parser::ProcedureStmt &x) {
3029   if (!isGeneric()) {
3030     Say("A PROCEDURE statement is only allowed in a generic interface block"_err_en_US);
3031     return false;
3032   }
3033   auto kind{std::get<parser::ProcedureStmt::Kind>(x.t)};
3034   const auto &names{std::get<std::list<parser::Name>>(x.t)};
3035   AddSpecificProcs(names, kind);
3036   return false;
3037 }
3038 
3039 bool InterfaceVisitor::Pre(const parser::GenericStmt &) {
3040   genericInfo_.emplace(/*isInterface*/ false);
3041   return true;
3042 }
3043 void InterfaceVisitor::Post(const parser::GenericStmt &x) {
3044   if (auto &accessSpec{std::get<std::optional<parser::AccessSpec>>(x.t)}) {
3045     GetGenericInfo().symbol->attrs().set(AccessSpecToAttr(*accessSpec));
3046   }
3047   const auto &names{std::get<std::list<parser::Name>>(x.t)};
3048   AddSpecificProcs(names, ProcedureKind::Procedure);
3049   genericInfo_.pop();
3050 }
3051 
3052 bool InterfaceVisitor::inInterfaceBlock() const {
3053   return !genericInfo_.empty() && GetGenericInfo().isInterface;
3054 }
3055 bool InterfaceVisitor::isGeneric() const {
3056   return !genericInfo_.empty() && GetGenericInfo().symbol;
3057 }
3058 bool InterfaceVisitor::isAbstract() const {
3059   return !genericInfo_.empty() && GetGenericInfo().isAbstract;
3060 }
3061 
3062 void InterfaceVisitor::AddSpecificProcs(
3063     const std::list<parser::Name> &names, ProcedureKind kind) {
3064   for (const auto &name : names) {
3065     specificProcs_.emplace(
3066         GetGenericInfo().symbol, std::make_pair(&name, kind));
3067   }
3068 }
3069 
3070 // By now we should have seen all specific procedures referenced by name in
3071 // this generic interface. Resolve those names to symbols.
3072 void InterfaceVisitor::ResolveSpecificsInGeneric(Symbol &generic) {
3073   auto &details{generic.get<GenericDetails>()};
3074   UnorderedSymbolSet symbolsSeen;
3075   for (const Symbol &symbol : details.specificProcs()) {
3076     symbolsSeen.insert(symbol.GetUltimate());
3077   }
3078   auto range{specificProcs_.equal_range(&generic)};
3079   for (auto it{range.first}; it != range.second; ++it) {
3080     const parser::Name *name{it->second.first};
3081     auto kind{it->second.second};
3082     const auto *symbol{FindSymbol(*name)};
3083     if (!symbol) {
3084       Say(*name, "Procedure '%s' not found"_err_en_US);
3085       continue;
3086     }
3087     const Symbol &specific{BypassGeneric(*symbol)};
3088     const Symbol &ultimate{specific.GetUltimate()};
3089     if (!ultimate.has<SubprogramDetails>() &&
3090         !ultimate.has<SubprogramNameDetails>()) {
3091       Say(*name, "'%s' is not a subprogram"_err_en_US);
3092       continue;
3093     }
3094     if (kind == ProcedureKind::ModuleProcedure) {
3095       if (const auto *nd{ultimate.detailsIf<SubprogramNameDetails>()}) {
3096         if (nd->kind() != SubprogramKind::Module) {
3097           Say(*name, "'%s' is not a module procedure"_err_en_US);
3098         }
3099       } else {
3100         // USE-associated procedure
3101         const auto *sd{ultimate.detailsIf<SubprogramDetails>()};
3102         CHECK(sd);
3103         if (ultimate.owner().kind() != Scope::Kind::Module ||
3104             sd->isInterface()) {
3105           Say(*name, "'%s' is not a module procedure"_err_en_US);
3106         }
3107       }
3108     }
3109     if (symbolsSeen.insert(ultimate).second /*true if added*/) {
3110       // When a specific procedure is a USE association, that association
3111       // is saved in the generic's specifics, not its ultimate symbol,
3112       // so that module file output of interfaces can distinguish them.
3113       details.AddSpecificProc(specific, name->source);
3114     } else if (&specific == &ultimate) {
3115       Say(name->source,
3116           "Procedure '%s' is already specified in generic '%s'"_err_en_US,
3117           name->source, MakeOpName(generic.name()));
3118     } else {
3119       Say(name->source,
3120           "Procedure '%s' from module '%s' is already specified in generic '%s'"_err_en_US,
3121           ultimate.name(), ultimate.owner().GetName().value(),
3122           MakeOpName(generic.name()));
3123     }
3124   }
3125   specificProcs_.erase(range.first, range.second);
3126 }
3127 
3128 // Check that the specific procedures are all functions or all subroutines.
3129 // If there is a derived type with the same name they must be functions.
3130 // Set the corresponding flag on generic.
3131 void InterfaceVisitor::CheckGenericProcedures(Symbol &generic) {
3132   ResolveSpecificsInGeneric(generic);
3133   auto &details{generic.get<GenericDetails>()};
3134   if (auto *proc{details.CheckSpecific()}) {
3135     auto msg{
3136         "'%s' may not be the name of both a generic interface and a"
3137         " procedure unless it is a specific procedure of the generic"_err_en_US};
3138     if (proc->name().begin() > generic.name().begin()) {
3139       Say(proc->name(), std::move(msg));
3140     } else {
3141       Say(generic.name(), std::move(msg));
3142     }
3143   }
3144   auto &specifics{details.specificProcs()};
3145   if (specifics.empty()) {
3146     if (details.derivedType()) {
3147       generic.set(Symbol::Flag::Function);
3148     }
3149     return;
3150   }
3151   const Symbol &firstSpecific{specifics.front()};
3152   bool isFunction{firstSpecific.test(Symbol::Flag::Function)};
3153   for (const Symbol &specific : specifics) {
3154     if (isFunction != specific.test(Symbol::Flag::Function)) { // C1514
3155       auto &msg{Say(generic.name(),
3156           "Generic interface '%s' has both a function and a subroutine"_err_en_US)};
3157       if (isFunction) {
3158         msg.Attach(firstSpecific.name(), "Function declaration"_en_US);
3159         msg.Attach(specific.name(), "Subroutine declaration"_en_US);
3160       } else {
3161         msg.Attach(firstSpecific.name(), "Subroutine declaration"_en_US);
3162         msg.Attach(specific.name(), "Function declaration"_en_US);
3163       }
3164     }
3165   }
3166   if (!isFunction && details.derivedType()) {
3167     SayDerivedType(generic.name(),
3168         "Generic interface '%s' may only contain functions due to derived type"
3169         " with same name"_err_en_US,
3170         *details.derivedType()->scope());
3171   }
3172   generic.set(isFunction ? Symbol::Flag::Function : Symbol::Flag::Subroutine);
3173 }
3174 
3175 // SubprogramVisitor implementation
3176 
3177 // Return false if it is actually an assignment statement.
3178 bool SubprogramVisitor::HandleStmtFunction(const parser::StmtFunctionStmt &x) {
3179   const auto &name{std::get<parser::Name>(x.t)};
3180   const DeclTypeSpec *resultType{nullptr};
3181   // Look up name: provides return type or tells us if it's an array
3182   if (auto *symbol{FindSymbol(name)}) {
3183     auto *details{symbol->detailsIf<EntityDetails>()};
3184     if (!details) {
3185       badStmtFuncFound_ = true;
3186       return false;
3187     }
3188     // TODO: check that attrs are compatible with stmt func
3189     resultType = details->type();
3190     symbol->details() = UnknownDetails{}; // will be replaced below
3191   }
3192   if (badStmtFuncFound_) {
3193     Say(name, "'%s' has not been declared as an array"_err_en_US);
3194     return true;
3195   }
3196   auto &symbol{PushSubprogramScope(name, Symbol::Flag::Function)};
3197   symbol.set(Symbol::Flag::StmtFunction);
3198   EraseSymbol(symbol); // removes symbol added by PushSubprogramScope
3199   auto &details{symbol.get<SubprogramDetails>()};
3200   for (const auto &dummyName : std::get<std::list<parser::Name>>(x.t)) {
3201     ObjectEntityDetails dummyDetails{true};
3202     if (auto *dummySymbol{FindInScope(currScope().parent(), dummyName)}) {
3203       if (auto *d{dummySymbol->detailsIf<EntityDetails>()}) {
3204         if (d->type()) {
3205           dummyDetails.set_type(*d->type());
3206         }
3207       }
3208     }
3209     Symbol &dummy{MakeSymbol(dummyName, std::move(dummyDetails))};
3210     ApplyImplicitRules(dummy);
3211     details.add_dummyArg(dummy);
3212   }
3213   ObjectEntityDetails resultDetails;
3214   if (resultType) {
3215     resultDetails.set_type(*resultType);
3216   }
3217   resultDetails.set_funcResult(true);
3218   Symbol &result{MakeSymbol(name, std::move(resultDetails))};
3219   ApplyImplicitRules(result);
3220   details.set_result(result);
3221   const auto &parsedExpr{std::get<parser::Scalar<parser::Expr>>(x.t)};
3222   Walk(parsedExpr);
3223   // The analysis of the expression that constitutes the body of the
3224   // statement function is deferred to FinishSpecificationPart() so that
3225   // all declarations and implicit typing are complete.
3226   PopScope();
3227   return true;
3228 }
3229 
3230 bool SubprogramVisitor::Pre(const parser::Suffix &suffix) {
3231   if (suffix.resultName) {
3232     if (IsFunction(currScope())) {
3233       if (FuncResultStack::FuncInfo * info{funcResultStack().Top()}) {
3234         if (info->inFunctionStmt) {
3235           info->resultName = &suffix.resultName.value();
3236         } else {
3237           // will check the result name in Post(EntryStmt)
3238         }
3239       }
3240     } else {
3241       Message &msg{Say(*suffix.resultName,
3242           "RESULT(%s) may appear only in a function"_err_en_US)};
3243       if (const Symbol * subprogram{InclusiveScope().symbol()}) {
3244         msg.Attach(subprogram->name(), "Containing subprogram"_en_US);
3245       }
3246     }
3247   }
3248   // LanguageBindingSpec deferred to Post(EntryStmt) or, for FunctionStmt,
3249   // all the way to EndSubprogram().
3250   return false;
3251 }
3252 
3253 bool SubprogramVisitor::Pre(const parser::PrefixSpec &x) {
3254   // Save this to process after UseStmt and ImplicitPart
3255   if (const auto *parsedType{std::get_if<parser::DeclarationTypeSpec>(&x.u)}) {
3256     FuncResultStack::FuncInfo &info{DEREF(funcResultStack().Top())};
3257     if (info.parsedType) { // C1543
3258       Say(currStmtSource().value(),
3259           "FUNCTION prefix cannot specify the type more than once"_err_en_US);
3260       return false;
3261     } else {
3262       info.parsedType = parsedType;
3263       info.source = currStmtSource();
3264       return false;
3265     }
3266   } else {
3267     return true;
3268   }
3269 }
3270 
3271 bool SubprogramVisitor::Pre(const parser::InterfaceBody::Subroutine &x) {
3272   const auto &name{std::get<parser::Name>(
3273       std::get<parser::Statement<parser::SubroutineStmt>>(x.t).statement.t)};
3274   return BeginSubprogram(name, Symbol::Flag::Subroutine);
3275 }
3276 void SubprogramVisitor::Post(const parser::InterfaceBody::Subroutine &x) {
3277   const auto &stmt{std::get<parser::Statement<parser::SubroutineStmt>>(x.t)};
3278   EndSubprogram(stmt.source,
3279       &std::get<std::optional<parser::LanguageBindingSpec>>(stmt.statement.t));
3280 }
3281 bool SubprogramVisitor::Pre(const parser::InterfaceBody::Function &x) {
3282   const auto &name{std::get<parser::Name>(
3283       std::get<parser::Statement<parser::FunctionStmt>>(x.t).statement.t)};
3284   return BeginSubprogram(name, Symbol::Flag::Function);
3285 }
3286 void SubprogramVisitor::Post(const parser::InterfaceBody::Function &x) {
3287   const auto &stmt{std::get<parser::Statement<parser::FunctionStmt>>(x.t)};
3288   const auto &maybeSuffix{
3289       std::get<std::optional<parser::Suffix>>(stmt.statement.t)};
3290   EndSubprogram(stmt.source, maybeSuffix ? &maybeSuffix->binding : nullptr);
3291 }
3292 
3293 bool SubprogramVisitor::Pre(const parser::SubroutineStmt &stmt) {
3294   BeginAttrs();
3295   Walk(std::get<std::list<parser::PrefixSpec>>(stmt.t));
3296   Walk(std::get<parser::Name>(stmt.t));
3297   Walk(std::get<std::list<parser::DummyArg>>(stmt.t));
3298   // Don't traverse the LanguageBindingSpec now; it's deferred to EndSubprogram.
3299   const auto &name{std::get<parser::Name>(stmt.t)};
3300   auto &details{PostSubprogramStmt(name)};
3301   for (const auto &dummyArg : std::get<std::list<parser::DummyArg>>(stmt.t)) {
3302     if (const auto *dummyName{std::get_if<parser::Name>(&dummyArg.u)}) {
3303       Symbol &dummy{MakeSymbol(*dummyName, EntityDetails{true})};
3304       details.add_dummyArg(dummy);
3305     } else {
3306       details.add_alternateReturn();
3307     }
3308   }
3309   return false;
3310 }
3311 bool SubprogramVisitor::Pre(const parser::FunctionStmt &) {
3312   FuncResultStack::FuncInfo &info{DEREF(funcResultStack().Top())};
3313   CHECK(!info.inFunctionStmt);
3314   info.inFunctionStmt = true;
3315   return BeginAttrs();
3316 }
3317 bool SubprogramVisitor::Pre(const parser::EntryStmt &) { return BeginAttrs(); }
3318 
3319 void SubprogramVisitor::Post(const parser::FunctionStmt &stmt) {
3320   const auto &name{std::get<parser::Name>(stmt.t)};
3321   auto &details{PostSubprogramStmt(name)};
3322   for (const auto &dummyName : std::get<std::list<parser::Name>>(stmt.t)) {
3323     Symbol &dummy{MakeSymbol(dummyName, EntityDetails{true})};
3324     details.add_dummyArg(dummy);
3325   }
3326   const parser::Name *funcResultName;
3327   FuncResultStack::FuncInfo &info{DEREF(funcResultStack().Top())};
3328   CHECK(info.inFunctionStmt);
3329   info.inFunctionStmt = false;
3330   bool distinctResultName{
3331       info.resultName && info.resultName->source != name.source};
3332   if (distinctResultName) {
3333     // Note that RESULT is ignored if it has the same name as the function.
3334     // The symbol created by PushScope() is retained as a place-holder
3335     // for error detection.
3336     funcResultName = info.resultName;
3337   } else {
3338     EraseSymbol(name); // was added by PushScope()
3339     funcResultName = &name;
3340   }
3341   if (details.isFunction()) {
3342     CHECK(context().HasError(currScope().symbol()));
3343   } else {
3344     // RESULT(x) can be the same explicitly-named RESULT(x) as an ENTRY
3345     // statement.
3346     Symbol *result{nullptr};
3347     if (distinctResultName) {
3348       if (auto iter{currScope().find(funcResultName->source)};
3349           iter != currScope().end()) {
3350         Symbol &entryResult{*iter->second};
3351         if (IsFunctionResult(entryResult)) {
3352           result = &entryResult;
3353         }
3354       }
3355     }
3356     if (result) {
3357       Resolve(*funcResultName, *result);
3358     } else {
3359       // add function result to function scope
3360       EntityDetails funcResultDetails;
3361       funcResultDetails.set_funcResult(true);
3362       result = &MakeSymbol(*funcResultName, std::move(funcResultDetails));
3363     }
3364     info.resultSymbol = result;
3365     details.set_result(*result);
3366   }
3367   // C1560.
3368   if (info.resultName && !distinctResultName) {
3369     Say(info.resultName->source,
3370         "The function name should not appear in RESULT, references to '%s' "
3371         "inside the function will be considered as references to the "
3372         "result only"_warn_en_US,
3373         name.source);
3374     // RESULT name was ignored above, the only side effect from doing so will be
3375     // the inability to make recursive calls. The related parser::Name is still
3376     // resolved to the created function result symbol because every parser::Name
3377     // should be resolved to avoid internal errors.
3378     Resolve(*info.resultName, info.resultSymbol);
3379   }
3380   name.symbol = currScope().symbol(); // must not be function result symbol
3381   // Clear the RESULT() name now in case an ENTRY statement in the implicit-part
3382   // has a RESULT() suffix.
3383   info.resultName = nullptr;
3384 }
3385 
3386 SubprogramDetails &SubprogramVisitor::PostSubprogramStmt(
3387     const parser::Name &name) {
3388   Symbol &symbol{*currScope().symbol()};
3389   symbol.attrs() |= EndAttrs();
3390   if (symbol.attrs().test(Attr::MODULE)) {
3391     symbol.attrs().set(Attr::EXTERNAL, false);
3392   }
3393   return symbol.get<SubprogramDetails>();
3394 }
3395 
3396 void SubprogramVisitor::Post(const parser::EntryStmt &stmt) {
3397   if (const auto &suffix{std::get<std::optional<parser::Suffix>>(stmt.t)}) {
3398     Walk(suffix->binding);
3399   }
3400   PostEntryStmt(stmt);
3401   EndAttrs();
3402 }
3403 
3404 void SubprogramVisitor::CreateEntry(
3405     const parser::EntryStmt &stmt, Symbol &subprogram) {
3406   const auto &entryName{std::get<parser::Name>(stmt.t)};
3407   Scope &outer{currScope().parent()};
3408   Symbol::Flag subpFlag{subprogram.test(Symbol::Flag::Function)
3409           ? Symbol::Flag::Function
3410           : Symbol::Flag::Subroutine};
3411   Attrs attrs;
3412   if (Symbol * extant{FindSymbol(outer, entryName)}) {
3413     if (!HandlePreviousCalls(entryName, *extant, subpFlag)) {
3414       if (outer.IsTopLevel()) {
3415         Say2(entryName,
3416             "'%s' is already defined as a global identifier"_err_en_US, *extant,
3417             "Previous definition of '%s'"_en_US);
3418       } else {
3419         SayAlreadyDeclared(entryName, *extant);
3420       }
3421       return;
3422     }
3423     attrs = extant->attrs();
3424   }
3425   const auto &suffix{std::get<std::optional<parser::Suffix>>(stmt.t)};
3426   bool badResultName{false};
3427   std::optional<SourceName> distinctResultName;
3428   if (suffix && suffix->resultName &&
3429       suffix->resultName->source != entryName.source) {
3430     distinctResultName = suffix->resultName->source;
3431     const parser::Name &resultName{*suffix->resultName};
3432     if (resultName.source == subprogram.name()) { // C1574
3433       Say2(resultName.source,
3434           "RESULT(%s) may not have the same name as the function"_err_en_US,
3435           subprogram, "Containing function"_en_US);
3436       badResultName = true;
3437     } else if (const Symbol * extant{FindSymbol(outer, resultName)}) { // C1574
3438       if (const auto *details{extant->detailsIf<SubprogramDetails>()}) {
3439         if (details->entryScope() == &currScope()) {
3440           Say2(resultName.source,
3441               "RESULT(%s) may not have the same name as an ENTRY in the function"_err_en_US,
3442               extant->name(), "Conflicting ENTRY"_en_US);
3443           badResultName = true;
3444         }
3445       }
3446     }
3447   }
3448   if (outer.IsModule() && !attrs.test(Attr::PRIVATE)) {
3449     attrs.set(Attr::PUBLIC);
3450   }
3451   Symbol *entrySymbol{FindInScope(outer, entryName.source)};
3452   if (entrySymbol) {
3453     if (auto *generic{entrySymbol->detailsIf<GenericDetails>()}) {
3454       if (auto *specific{generic->specific()}) {
3455         // Forward reference to ENTRY from a generic interface
3456         entrySymbol = specific;
3457         entrySymbol->attrs() |= attrs;
3458       }
3459     }
3460   } else {
3461     entrySymbol = &MakeSymbol(outer, entryName.source, attrs);
3462   }
3463   SubprogramDetails entryDetails;
3464   entryDetails.set_entryScope(currScope());
3465   entrySymbol->set(subpFlag);
3466   if (subpFlag == Symbol::Flag::Function) {
3467     Symbol *result{nullptr};
3468     EntityDetails resultDetails;
3469     resultDetails.set_funcResult(true);
3470     if (distinctResultName) {
3471       if (!badResultName) {
3472         // RESULT(x) can be the same explicitly-named RESULT(x) as
3473         // the enclosing function or another ENTRY.
3474         if (auto iter{currScope().find(suffix->resultName->source)};
3475             iter != currScope().end()) {
3476           result = &*iter->second;
3477         }
3478         if (!result) {
3479           result = &MakeSymbol(
3480               *distinctResultName, Attrs{}, std::move(resultDetails));
3481         }
3482         Resolve(*suffix->resultName, *result);
3483       }
3484     } else {
3485       result = &MakeSymbol(entryName.source, Attrs{}, std::move(resultDetails));
3486     }
3487     if (result) {
3488       entryDetails.set_result(*result);
3489     }
3490   }
3491   if (subpFlag == Symbol::Flag::Subroutine ||
3492       (distinctResultName && !badResultName)) {
3493     Symbol &assoc{MakeSymbol(entryName.source)};
3494     assoc.set_details(HostAssocDetails{*entrySymbol});
3495     assoc.set(Symbol::Flag::Subroutine);
3496   }
3497   Resolve(entryName, *entrySymbol);
3498   Details details{std::move(entryDetails)};
3499   entrySymbol->set_details(std::move(entryDetails));
3500 }
3501 
3502 void SubprogramVisitor::PostEntryStmt(const parser::EntryStmt &stmt) {
3503   // The entry symbol should have already been created and resolved
3504   // in CreateEntry(), called by BeginSubprogram(), with one exception (below).
3505   const auto &name{std::get<parser::Name>(stmt.t)};
3506   Scope &inclusiveScope{InclusiveScope()};
3507   if (!name.symbol) {
3508     if (inclusiveScope.kind() != Scope::Kind::Subprogram) {
3509       Say(name.source,
3510           "ENTRY '%s' may appear only in a subroutine or function"_err_en_US,
3511           name.source);
3512     } else if (FindSeparateModuleSubprogramInterface(inclusiveScope.symbol())) {
3513       Say(name.source,
3514           "ENTRY '%s' may not appear in a separate module procedure"_err_en_US,
3515           name.source);
3516     } else {
3517       // C1571 - entry is nested, so was not put into the program tree; error
3518       // is emitted from MiscChecker in semantics.cpp.
3519     }
3520     return;
3521   }
3522   Symbol &entrySymbol{*name.symbol};
3523   if (context().HasError(entrySymbol)) {
3524     return;
3525   }
3526   if (!entrySymbol.has<SubprogramDetails>()) {
3527     SayAlreadyDeclared(name, entrySymbol);
3528     return;
3529   }
3530   SubprogramDetails &entryDetails{entrySymbol.get<SubprogramDetails>()};
3531   CHECK(entryDetails.entryScope() == &inclusiveScope);
3532   entrySymbol.attrs() |= GetAttrs();
3533   SetBindNameOn(entrySymbol);
3534   for (const auto &dummyArg : std::get<std::list<parser::DummyArg>>(stmt.t)) {
3535     if (const auto *dummyName{std::get_if<parser::Name>(&dummyArg.u)}) {
3536       Symbol *dummy{FindSymbol(*dummyName)};
3537       if (dummy) {
3538         common::visit(
3539             common::visitors{[](EntityDetails &x) { x.set_isDummy(); },
3540                 [](ObjectEntityDetails &x) { x.set_isDummy(); },
3541                 [](ProcEntityDetails &x) { x.set_isDummy(); },
3542                 [](SubprogramDetails &x) { x.set_isDummy(); },
3543                 [&](const auto &) {
3544                   Say2(dummyName->source,
3545                       "ENTRY dummy argument '%s' is previously declared as an item that may not be used as a dummy argument"_err_en_US,
3546                       dummy->name(), "Previous declaration of '%s'"_en_US);
3547                 }},
3548             dummy->details());
3549       } else {
3550         dummy = &MakeSymbol(*dummyName, EntityDetails{true});
3551         if (!inSpecificationPart_) {
3552           ApplyImplicitRules(*dummy);
3553         }
3554       }
3555       entryDetails.add_dummyArg(*dummy);
3556     } else {
3557       if (entrySymbol.test(Symbol::Flag::Function)) { // C1573
3558         Say(name,
3559             "ENTRY in a function may not have an alternate return dummy argument"_err_en_US);
3560         break;
3561       }
3562       entryDetails.add_alternateReturn();
3563     }
3564   }
3565 }
3566 
3567 // A subprogram declared with MODULE PROCEDURE
3568 bool SubprogramVisitor::BeginMpSubprogram(const parser::Name &name) {
3569   auto *symbol{FindSymbol(name)};
3570   if (symbol && symbol->has<SubprogramNameDetails>()) {
3571     symbol = FindSymbol(currScope().parent(), name);
3572   }
3573   if (!IsSeparateModuleProcedureInterface(symbol)) {
3574     Say(name, "'%s' was not declared a separate module procedure"_err_en_US);
3575     return false;
3576   }
3577   if (symbol->owner() == currScope() && symbol->scope()) {
3578     // This is a MODULE PROCEDURE whose interface appears in its host.
3579     // Convert the module procedure's interface into a subprogram.
3580     SetScope(DEREF(symbol->scope()));
3581     symbol->get<SubprogramDetails>().set_isInterface(false);
3582   } else {
3583     // Copy the interface into a new subprogram scope.
3584     Symbol &newSymbol{MakeSymbol(name, SubprogramDetails{})};
3585     PushScope(Scope::Kind::Subprogram, &newSymbol);
3586     const auto &details{symbol->get<SubprogramDetails>()};
3587     auto &newDetails{newSymbol.get<SubprogramDetails>()};
3588     newDetails.set_moduleInterface(*symbol);
3589     for (const Symbol *dummyArg : details.dummyArgs()) {
3590       if (!dummyArg) {
3591         newDetails.add_alternateReturn();
3592       } else if (Symbol * copy{currScope().CopySymbol(*dummyArg)}) {
3593         newDetails.add_dummyArg(*copy);
3594       }
3595     }
3596     if (details.isFunction()) {
3597       currScope().erase(symbol->name());
3598       newDetails.set_result(*currScope().CopySymbol(details.result()));
3599     }
3600   }
3601   return true;
3602 }
3603 
3604 // A subprogram or interface declared with SUBROUTINE or FUNCTION
3605 bool SubprogramVisitor::BeginSubprogram(const parser::Name &name,
3606     Symbol::Flag subpFlag, bool hasModulePrefix,
3607     const parser::LanguageBindingSpec *bindingSpec,
3608     const ProgramTree::EntryStmtList *entryStmts) {
3609   if (hasModulePrefix && currScope().IsGlobal()) { // C1547
3610     Say(name,
3611         "'%s' is a MODULE procedure which must be declared within a "
3612         "MODULE or SUBMODULE"_err_en_US);
3613     return false;
3614   }
3615   Symbol *moduleInterface{nullptr};
3616   if (hasModulePrefix && !inInterfaceBlock()) {
3617     moduleInterface = FindSymbol(currScope(), name);
3618     if (IsSeparateModuleProcedureInterface(moduleInterface)) {
3619       // Subprogram is MODULE FUNCTION or MODULE SUBROUTINE with an interface
3620       // previously defined in the same scope.
3621       currScope().erase(moduleInterface->name());
3622     } else {
3623       moduleInterface = nullptr;
3624     }
3625     if (!moduleInterface) {
3626       moduleInterface = FindSymbol(currScope().parent(), name);
3627       if (!IsSeparateModuleProcedureInterface(moduleInterface)) {
3628         Say(name,
3629             "'%s' was not declared a separate module procedure"_err_en_US);
3630         return false;
3631       }
3632     }
3633   }
3634   Symbol &newSymbol{PushSubprogramScope(name, subpFlag, bindingSpec)};
3635   if (moduleInterface) {
3636     newSymbol.get<SubprogramDetails>().set_moduleInterface(*moduleInterface);
3637     if (moduleInterface->attrs().test(Attr::PRIVATE)) {
3638       newSymbol.attrs().set(Attr::PRIVATE);
3639     } else if (moduleInterface->attrs().test(Attr::PUBLIC)) {
3640       newSymbol.attrs().set(Attr::PUBLIC);
3641     }
3642   }
3643   if (entryStmts) {
3644     for (const auto &ref : *entryStmts) {
3645       CreateEntry(*ref, newSymbol);
3646     }
3647   }
3648   return true;
3649 }
3650 
3651 void SubprogramVisitor::EndSubprogram(
3652     std::optional<parser::CharBlock> stmtSource,
3653     const std::optional<parser::LanguageBindingSpec> *binding) {
3654   if (binding && *binding && currScope().symbol()) {
3655     // Finally process the BIND(C,NAME=name) now that symbols in the name
3656     // expression will resolve local names.
3657     auto flagRestorer{common::ScopedSet(inSpecificationPart_, false)};
3658     auto originalStmtSource{messageHandler().currStmtSource()};
3659     messageHandler().set_currStmtSource(stmtSource);
3660     BeginAttrs();
3661     Walk(**binding);
3662     SetBindNameOn(*currScope().symbol());
3663     currScope().symbol()->attrs() |= EndAttrs();
3664     messageHandler().set_currStmtSource(originalStmtSource);
3665   }
3666   PopScope();
3667 }
3668 
3669 bool SubprogramVisitor::HandlePreviousCalls(
3670     const parser::Name &name, Symbol &symbol, Symbol::Flag subpFlag) {
3671   // If the extant symbol is a generic, check its homonymous specific
3672   // procedure instead if it has one.
3673   if (auto *generic{symbol.detailsIf<GenericDetails>()}) {
3674     return generic->specific() &&
3675         HandlePreviousCalls(name, *generic->specific(), subpFlag);
3676   } else if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}; proc &&
3677              !proc->isDummy() &&
3678              !symbol.attrs().HasAny(Attrs{Attr::INTRINSIC, Attr::POINTER})) {
3679     // There's a symbol created for previous calls to this subprogram or
3680     // ENTRY's name.  We have to replace that symbol in situ to avoid the
3681     // obligation to rewrite symbol pointers in the parse tree.
3682     if (!symbol.test(subpFlag)) {
3683       Say2(name,
3684           subpFlag == Symbol::Flag::Function
3685               ? "'%s' was previously called as a subroutine"_err_en_US
3686               : "'%s' was previously called as a function"_err_en_US,
3687           symbol, "Previous call of '%s'"_en_US);
3688     }
3689     EntityDetails entity;
3690     if (proc->type()) {
3691       entity.set_type(*proc->type());
3692     }
3693     symbol.details() = std::move(entity);
3694     return true;
3695   } else {
3696     return symbol.has<UnknownDetails>() || symbol.has<SubprogramNameDetails>();
3697   }
3698 }
3699 
3700 void SubprogramVisitor::CheckExtantProc(
3701     const parser::Name &name, Symbol::Flag subpFlag) {
3702   if (auto *prev{FindSymbol(name)}) {
3703     if (IsDummy(*prev)) {
3704     } else if (auto *entity{prev->detailsIf<EntityDetails>()};
3705                IsPointer(*prev) && !entity->type()) {
3706       // POINTER attribute set before interface
3707     } else if (inInterfaceBlock() && currScope() != prev->owner()) {
3708       // Procedures in an INTERFACE block do not resolve to symbols
3709       // in scopes between the global scope and the current scope.
3710     } else if (!HandlePreviousCalls(name, *prev, subpFlag)) {
3711       SayAlreadyDeclared(name, *prev);
3712     }
3713   }
3714 }
3715 
3716 Symbol &SubprogramVisitor::PushSubprogramScope(const parser::Name &name,
3717     Symbol::Flag subpFlag, const parser::LanguageBindingSpec *bindingSpec) {
3718   Symbol *symbol{GetSpecificFromGeneric(name)};
3719   if (!symbol) {
3720     if (bindingSpec && currScope().IsGlobal() && bindingSpec->v) {
3721       // Create this new top-level subprogram with a binding label
3722       // in a new global scope, so that its symbol's name won't clash
3723       // with another symbol that has a distinct binding label.
3724       PushScope(Scope::Kind::Global,
3725           &MakeSymbol(context().GetTempName(currScope()), Attrs{},
3726               MiscDetails{MiscDetails::Kind::ScopeName}));
3727     }
3728     CheckExtantProc(name, subpFlag);
3729     symbol = &MakeSymbol(name, SubprogramDetails{});
3730   }
3731   symbol->ReplaceName(name.source);
3732   symbol->set(subpFlag);
3733   PushScope(Scope::Kind::Subprogram, symbol);
3734   if (subpFlag == Symbol::Flag::Function) {
3735     funcResultStack().Push(currScope());
3736   }
3737   if (inInterfaceBlock()) {
3738     auto &details{symbol->get<SubprogramDetails>()};
3739     details.set_isInterface();
3740     if (isAbstract()) {
3741       symbol->attrs().set(Attr::ABSTRACT);
3742     } else {
3743       MakeExternal(*symbol);
3744     }
3745     if (isGeneric()) {
3746       Symbol &genericSymbol{GetGenericSymbol()};
3747       if (genericSymbol.has<GenericDetails>()) {
3748         genericSymbol.get<GenericDetails>().AddSpecificProc(
3749             *symbol, name.source);
3750       } else {
3751         CHECK(context().HasError(genericSymbol));
3752       }
3753     }
3754     set_inheritFromParent(false);
3755   }
3756   FindSymbol(name)->set(subpFlag); // PushScope() created symbol
3757   return *symbol;
3758 }
3759 
3760 void SubprogramVisitor::PushBlockDataScope(const parser::Name &name) {
3761   if (auto *prev{FindSymbol(name)}) {
3762     if (prev->attrs().test(Attr::EXTERNAL) && prev->has<ProcEntityDetails>()) {
3763       if (prev->test(Symbol::Flag::Subroutine) ||
3764           prev->test(Symbol::Flag::Function)) {
3765         Say2(name, "BLOCK DATA '%s' has been called"_err_en_US, *prev,
3766             "Previous call of '%s'"_en_US);
3767       }
3768       EraseSymbol(name);
3769     }
3770   }
3771   if (name.source.empty()) {
3772     // Don't let unnamed BLOCK DATA conflict with unnamed PROGRAM
3773     PushScope(Scope::Kind::BlockData, nullptr);
3774   } else {
3775     PushScope(Scope::Kind::BlockData, &MakeSymbol(name, SubprogramDetails{}));
3776   }
3777 }
3778 
3779 // If name is a generic, return specific subprogram with the same name.
3780 Symbol *SubprogramVisitor::GetSpecificFromGeneric(const parser::Name &name) {
3781   // Search for the name but don't resolve it
3782   if (auto *symbol{currScope().FindSymbol(name.source)}) {
3783     if (auto *details{symbol->detailsIf<GenericDetails>()}) {
3784       // found generic, want subprogram
3785       auto *specific{details->specific()};
3786       if (!specific) {
3787         specific =
3788             &currScope().MakeSymbol(name.source, Attrs{}, SubprogramDetails{});
3789         if (details->derivedType()) {
3790           // A specific procedure with the same name as a derived type
3791           SayAlreadyDeclared(name, *details->derivedType());
3792         } else {
3793           details->set_specific(Resolve(name, *specific));
3794         }
3795       } else if (isGeneric()) {
3796         SayAlreadyDeclared(name, *specific);
3797       }
3798       if (!specific->has<SubprogramDetails>()) {
3799         specific->set_details(SubprogramDetails{});
3800       }
3801       return specific;
3802     }
3803   }
3804   return nullptr;
3805 }
3806 
3807 // DeclarationVisitor implementation
3808 
3809 bool DeclarationVisitor::BeginDecl() {
3810   BeginDeclTypeSpec();
3811   BeginArraySpec();
3812   return BeginAttrs();
3813 }
3814 void DeclarationVisitor::EndDecl() {
3815   EndDeclTypeSpec();
3816   EndArraySpec();
3817   EndAttrs();
3818 }
3819 
3820 bool DeclarationVisitor::CheckUseError(const parser::Name &name) {
3821   const auto *details{
3822       name.symbol ? name.symbol->detailsIf<UseErrorDetails>() : nullptr};
3823   if (!details) {
3824     return false;
3825   }
3826   Message &msg{Say(name, "Reference to '%s' is ambiguous"_err_en_US)};
3827   for (const auto &[location, module] : details->occurrences()) {
3828     msg.Attach(location, "'%s' was use-associated from module '%s'"_en_US,
3829         name.source, module->GetName().value());
3830   }
3831   context().SetError(*name.symbol);
3832   return true;
3833 }
3834 
3835 // Report error if accessibility of symbol doesn't match isPrivate.
3836 void DeclarationVisitor::CheckAccessibility(
3837     const SourceName &name, bool isPrivate, Symbol &symbol) {
3838   if (symbol.attrs().test(Attr::PRIVATE) != isPrivate) {
3839     Say2(name,
3840         "'%s' does not have the same accessibility as its previous declaration"_err_en_US,
3841         symbol, "Previous declaration of '%s'"_en_US);
3842   }
3843 }
3844 
3845 void DeclarationVisitor::Post(const parser::TypeDeclarationStmt &) {
3846   if (!GetAttrs().HasAny({Attr::POINTER, Attr::ALLOCATABLE})) { // C702
3847     if (const auto *typeSpec{GetDeclTypeSpec()}) {
3848       if (typeSpec->category() == DeclTypeSpec::Character) {
3849         if (typeSpec->characterTypeSpec().length().isDeferred()) {
3850           Say("The type parameter LEN cannot be deferred without"
3851               " the POINTER or ALLOCATABLE attribute"_err_en_US);
3852         }
3853       } else if (const DerivedTypeSpec * derivedSpec{typeSpec->AsDerived()}) {
3854         for (const auto &pair : derivedSpec->parameters()) {
3855           if (pair.second.isDeferred()) {
3856             Say(currStmtSource().value(),
3857                 "The value of type parameter '%s' cannot be deferred"
3858                 " without the POINTER or ALLOCATABLE attribute"_err_en_US,
3859                 pair.first);
3860           }
3861         }
3862       }
3863     }
3864   }
3865   EndDecl();
3866 }
3867 
3868 void DeclarationVisitor::Post(const parser::DimensionStmt::Declaration &x) {
3869   DeclareObjectEntity(std::get<parser::Name>(x.t));
3870 }
3871 void DeclarationVisitor::Post(const parser::CodimensionDecl &x) {
3872   DeclareObjectEntity(std::get<parser::Name>(x.t));
3873 }
3874 
3875 bool DeclarationVisitor::Pre(const parser::Initialization &) {
3876   // Defer inspection of initializers to Initialization() so that the
3877   // symbol being initialized will be available within the initialization
3878   // expression.
3879   return false;
3880 }
3881 
3882 void DeclarationVisitor::Post(const parser::EntityDecl &x) {
3883   const auto &name{std::get<parser::ObjectName>(x.t)};
3884   Attrs attrs{attrs_ ? HandleSaveName(name.source, *attrs_) : Attrs{}};
3885   Symbol &symbol{DeclareUnknownEntity(name, attrs)};
3886   symbol.ReplaceName(name.source);
3887   if (const auto &init{std::get<std::optional<parser::Initialization>>(x.t)}) {
3888     if (ConvertToObjectEntity(symbol)) {
3889       Initialization(name, *init, false);
3890     }
3891   } else if (attrs.test(Attr::PARAMETER)) { // C882, C883
3892     Say(name, "Missing initialization for parameter '%s'"_err_en_US);
3893   }
3894 }
3895 
3896 void DeclarationVisitor::Post(const parser::PointerDecl &x) {
3897   const auto &name{std::get<parser::Name>(x.t)};
3898   if (const auto &deferredShapeSpecs{
3899           std::get<std::optional<parser::DeferredShapeSpecList>>(x.t)}) {
3900     CHECK(arraySpec().empty());
3901     BeginArraySpec();
3902     set_arraySpec(AnalyzeDeferredShapeSpecList(context(), *deferredShapeSpecs));
3903     Symbol &symbol{DeclareObjectEntity(name, Attrs{Attr::POINTER})};
3904     symbol.ReplaceName(name.source);
3905     EndArraySpec();
3906   } else {
3907     HandleAttributeStmt(Attr::POINTER, std::get<parser::Name>(x.t));
3908   }
3909 }
3910 
3911 bool DeclarationVisitor::Pre(const parser::BindEntity &x) {
3912   auto kind{std::get<parser::BindEntity::Kind>(x.t)};
3913   auto &name{std::get<parser::Name>(x.t)};
3914   Symbol *symbol;
3915   if (kind == parser::BindEntity::Kind::Object) {
3916     symbol = &HandleAttributeStmt(Attr::BIND_C, name);
3917   } else {
3918     symbol = &MakeCommonBlockSymbol(name);
3919     symbol->attrs().set(Attr::BIND_C);
3920   }
3921   // 8.6.4(1)
3922   // Some entities such as named constant or module name need to checked
3923   // elsewhere. This is to skip the ICE caused by setting Bind name for non-name
3924   // things such as data type and also checks for procedures.
3925   if (symbol->has<CommonBlockDetails>() || symbol->has<ObjectEntityDetails>() ||
3926       symbol->has<EntityDetails>()) {
3927     SetBindNameOn(*symbol);
3928   } else {
3929     Say(name,
3930         "Only variable and named common block can be in BIND statement"_err_en_US);
3931   }
3932   return false;
3933 }
3934 bool DeclarationVisitor::Pre(const parser::OldParameterStmt &x) {
3935   inOldStyleParameterStmt_ = true;
3936   Walk(x.v);
3937   inOldStyleParameterStmt_ = false;
3938   return false;
3939 }
3940 bool DeclarationVisitor::Pre(const parser::NamedConstantDef &x) {
3941   auto &name{std::get<parser::NamedConstant>(x.t).v};
3942   auto &symbol{HandleAttributeStmt(Attr::PARAMETER, name)};
3943   if (!ConvertToObjectEntity(symbol) ||
3944       symbol.test(Symbol::Flag::CrayPointer) ||
3945       symbol.test(Symbol::Flag::CrayPointee)) {
3946     SayWithDecl(
3947         name, symbol, "PARAMETER attribute not allowed on '%s'"_err_en_US);
3948     return false;
3949   }
3950   const auto &expr{std::get<parser::ConstantExpr>(x.t)};
3951   auto &details{symbol.get<ObjectEntityDetails>()};
3952   if (inOldStyleParameterStmt_) {
3953     // non-standard extension PARAMETER statement (no parentheses)
3954     Walk(expr);
3955     auto folded{EvaluateExpr(expr)};
3956     if (details.type()) {
3957       SayWithDecl(name, symbol,
3958           "Alternative style PARAMETER '%s' must not already have an explicit type"_err_en_US);
3959     } else if (folded) {
3960       auto at{expr.thing.value().source};
3961       if (evaluate::IsActuallyConstant(*folded)) {
3962         if (const auto *type{currScope().GetType(*folded)}) {
3963           if (type->IsPolymorphic()) {
3964             Say(at, "The expression must not be polymorphic"_err_en_US);
3965           } else if (auto shape{ToArraySpec(
3966                          GetFoldingContext(), evaluate::GetShape(*folded))}) {
3967             // The type of the named constant is assumed from the expression.
3968             details.set_type(*type);
3969             details.set_init(std::move(*folded));
3970             details.set_shape(std::move(*shape));
3971           } else {
3972             Say(at, "The expression must have constant shape"_err_en_US);
3973           }
3974         } else {
3975           Say(at, "The expression must have a known type"_err_en_US);
3976         }
3977       } else {
3978         Say(at, "The expression must be a constant of known type"_err_en_US);
3979       }
3980     }
3981   } else {
3982     // standard-conforming PARAMETER statement (with parentheses)
3983     ApplyImplicitRules(symbol);
3984     Walk(expr);
3985     if (auto converted{EvaluateNonPointerInitializer(
3986             symbol, expr, expr.thing.value().source)}) {
3987       details.set_init(std::move(*converted));
3988     }
3989   }
3990   return false;
3991 }
3992 bool DeclarationVisitor::Pre(const parser::NamedConstant &x) {
3993   const parser::Name &name{x.v};
3994   if (!FindSymbol(name)) {
3995     Say(name, "Named constant '%s' not found"_err_en_US);
3996   } else {
3997     CheckUseError(name);
3998   }
3999   return false;
4000 }
4001 
4002 bool DeclarationVisitor::Pre(const parser::Enumerator &enumerator) {
4003   const parser::Name &name{std::get<parser::NamedConstant>(enumerator.t).v};
4004   Symbol *symbol{FindSymbol(name)};
4005   if (symbol && !symbol->has<UnknownDetails>()) {
4006     // Contrary to named constants appearing in a PARAMETER statement,
4007     // enumerator names should not have their type, dimension or any other
4008     // attributes defined before they are declared in the enumerator statement,
4009     // with the exception of accessibility.
4010     // This is not explicitly forbidden by the standard, but they are scalars
4011     // which type is left for the compiler to chose, so do not let users try to
4012     // tamper with that.
4013     SayAlreadyDeclared(name, *symbol);
4014     symbol = nullptr;
4015   } else {
4016     // Enumerators are treated as PARAMETER (section 7.6 paragraph (4))
4017     symbol = &MakeSymbol(name, Attrs{Attr::PARAMETER}, ObjectEntityDetails{});
4018     symbol->SetType(context().MakeNumericType(
4019         TypeCategory::Integer, evaluate::CInteger::kind));
4020   }
4021 
4022   if (auto &init{std::get<std::optional<parser::ScalarIntConstantExpr>>(
4023           enumerator.t)}) {
4024     Walk(*init); // Resolve names in expression before evaluation.
4025     if (auto value{EvaluateInt64(context(), *init)}) {
4026       // Cast all init expressions to C_INT so that they can then be
4027       // safely incremented (see 7.6 Note 2).
4028       enumerationState_.value = static_cast<int>(*value);
4029     } else {
4030       Say(name,
4031           "Enumerator value could not be computed "
4032           "from the given expression"_err_en_US);
4033       // Prevent resolution of next enumerators value
4034       enumerationState_.value = std::nullopt;
4035     }
4036   }
4037 
4038   if (symbol) {
4039     if (enumerationState_.value) {
4040       symbol->get<ObjectEntityDetails>().set_init(SomeExpr{
4041           evaluate::Expr<evaluate::CInteger>{*enumerationState_.value}});
4042     } else {
4043       context().SetError(*symbol);
4044     }
4045   }
4046 
4047   if (enumerationState_.value) {
4048     (*enumerationState_.value)++;
4049   }
4050   return false;
4051 }
4052 
4053 void DeclarationVisitor::Post(const parser::EnumDef &) {
4054   enumerationState_ = EnumeratorState{};
4055 }
4056 
4057 bool DeclarationVisitor::Pre(const parser::AccessSpec &x) {
4058   Attr attr{AccessSpecToAttr(x)};
4059   if (!NonDerivedTypeScope().IsModule()) { // C817
4060     Say(currStmtSource().value(),
4061         "%s attribute may only appear in the specification part of a module"_err_en_US,
4062         EnumToString(attr));
4063   }
4064   CheckAndSet(attr);
4065   return false;
4066 }
4067 
4068 bool DeclarationVisitor::Pre(const parser::AsynchronousStmt &x) {
4069   return HandleAttributeStmt(Attr::ASYNCHRONOUS, x.v);
4070 }
4071 bool DeclarationVisitor::Pre(const parser::ContiguousStmt &x) {
4072   return HandleAttributeStmt(Attr::CONTIGUOUS, x.v);
4073 }
4074 bool DeclarationVisitor::Pre(const parser::ExternalStmt &x) {
4075   HandleAttributeStmt(Attr::EXTERNAL, x.v);
4076   for (const auto &name : x.v) {
4077     auto *symbol{FindSymbol(name)};
4078     if (!ConvertToProcEntity(DEREF(symbol))) {
4079       SayWithDecl(
4080           name, *symbol, "EXTERNAL attribute not allowed on '%s'"_err_en_US);
4081     } else if (symbol->attrs().test(Attr::INTRINSIC)) { // C840
4082       Say(symbol->name(),
4083           "Symbol '%s' cannot have both INTRINSIC and EXTERNAL attributes"_err_en_US,
4084           symbol->name());
4085     }
4086   }
4087   return false;
4088 }
4089 bool DeclarationVisitor::Pre(const parser::IntentStmt &x) {
4090   auto &intentSpec{std::get<parser::IntentSpec>(x.t)};
4091   auto &names{std::get<std::list<parser::Name>>(x.t)};
4092   return CheckNotInBlock("INTENT") && // C1107
4093       HandleAttributeStmt(IntentSpecToAttr(intentSpec), names);
4094 }
4095 bool DeclarationVisitor::Pre(const parser::IntrinsicStmt &x) {
4096   HandleAttributeStmt(Attr::INTRINSIC, x.v);
4097   for (const auto &name : x.v) {
4098     if (!IsIntrinsic(name.source, std::nullopt)) {
4099       Say(name.source, "'%s' is not a known intrinsic procedure"_err_en_US);
4100     }
4101     auto &symbol{DEREF(FindSymbol(name))};
4102     if (symbol.has<GenericDetails>()) {
4103       // Generic interface is extending intrinsic; ok
4104     } else if (!ConvertToProcEntity(symbol)) {
4105       SayWithDecl(
4106           name, symbol, "INTRINSIC attribute not allowed on '%s'"_err_en_US);
4107     } else if (symbol.attrs().test(Attr::EXTERNAL)) { // C840
4108       Say(symbol.name(),
4109           "Symbol '%s' cannot have both EXTERNAL and INTRINSIC attributes"_err_en_US,
4110           symbol.name());
4111     } else if (symbol.GetType()) {
4112       // These warnings are worded so that they should make sense in either
4113       // order.
4114       Say(symbol.name(),
4115           "Explicit type declaration ignored for intrinsic function '%s'"_warn_en_US,
4116           symbol.name())
4117           .Attach(name.source,
4118               "INTRINSIC statement for explicitly-typed '%s'"_en_US,
4119               name.source);
4120     }
4121   }
4122   return false;
4123 }
4124 bool DeclarationVisitor::Pre(const parser::OptionalStmt &x) {
4125   return CheckNotInBlock("OPTIONAL") && // C1107
4126       HandleAttributeStmt(Attr::OPTIONAL, x.v);
4127 }
4128 bool DeclarationVisitor::Pre(const parser::ProtectedStmt &x) {
4129   return HandleAttributeStmt(Attr::PROTECTED, x.v);
4130 }
4131 bool DeclarationVisitor::Pre(const parser::ValueStmt &x) {
4132   return CheckNotInBlock("VALUE") && // C1107
4133       HandleAttributeStmt(Attr::VALUE, x.v);
4134 }
4135 bool DeclarationVisitor::Pre(const parser::VolatileStmt &x) {
4136   return HandleAttributeStmt(Attr::VOLATILE, x.v);
4137 }
4138 // Handle a statement that sets an attribute on a list of names.
4139 bool DeclarationVisitor::HandleAttributeStmt(
4140     Attr attr, const std::list<parser::Name> &names) {
4141   for (const auto &name : names) {
4142     HandleAttributeStmt(attr, name);
4143   }
4144   return false;
4145 }
4146 Symbol &DeclarationVisitor::HandleAttributeStmt(
4147     Attr attr, const parser::Name &name) {
4148   auto *symbol{FindInScope(name)};
4149   if (attr == Attr::ASYNCHRONOUS || attr == Attr::VOLATILE) {
4150     // these can be set on a symbol that is host-assoc or use-assoc
4151     if (!symbol &&
4152         (currScope().kind() == Scope::Kind::Subprogram ||
4153             currScope().kind() == Scope::Kind::Block)) {
4154       if (auto *hostSymbol{FindSymbol(name)}) {
4155         symbol = &MakeHostAssocSymbol(name, *hostSymbol);
4156       }
4157     }
4158   } else if (symbol && symbol->has<UseDetails>()) {
4159     Say(currStmtSource().value(),
4160         "Cannot change %s attribute on use-associated '%s'"_err_en_US,
4161         EnumToString(attr), name.source);
4162     return *symbol;
4163   }
4164   if (!symbol) {
4165     symbol = &MakeSymbol(name, EntityDetails{});
4166   }
4167   symbol->attrs().set(attr);
4168   symbol->attrs() = HandleSaveName(name.source, symbol->attrs());
4169   return *symbol;
4170 }
4171 // C1107
4172 bool DeclarationVisitor::CheckNotInBlock(const char *stmt) {
4173   if (currScope().kind() == Scope::Kind::Block) {
4174     Say(MessageFormattedText{
4175         "%s statement is not allowed in a BLOCK construct"_err_en_US, stmt});
4176     return false;
4177   } else {
4178     return true;
4179   }
4180 }
4181 
4182 void DeclarationVisitor::Post(const parser::ObjectDecl &x) {
4183   CHECK(objectDeclAttr_);
4184   const auto &name{std::get<parser::ObjectName>(x.t)};
4185   DeclareObjectEntity(name, Attrs{*objectDeclAttr_});
4186 }
4187 
4188 // Declare an entity not yet known to be an object or proc.
4189 Symbol &DeclarationVisitor::DeclareUnknownEntity(
4190     const parser::Name &name, Attrs attrs) {
4191   if (!arraySpec().empty() || !coarraySpec().empty()) {
4192     return DeclareObjectEntity(name, attrs);
4193   } else {
4194     Symbol &symbol{DeclareEntity<EntityDetails>(name, attrs)};
4195     if (auto *type{GetDeclTypeSpec()}) {
4196       SetType(name, *type);
4197     }
4198     charInfo_.length.reset();
4199     if (symbol.attrs().test(Attr::EXTERNAL)) {
4200       ConvertToProcEntity(symbol);
4201     }
4202     SetBindNameOn(symbol);
4203     return symbol;
4204   }
4205 }
4206 
4207 bool DeclarationVisitor::HasCycle(
4208     const Symbol &procSymbol, const ProcInterface &interface) {
4209   SourceOrderedSymbolSet procsInCycle;
4210   procsInCycle.insert(procSymbol);
4211   const ProcInterface *thisInterface{&interface};
4212   bool haveInterface{true};
4213   while (haveInterface) {
4214     haveInterface = false;
4215     if (const Symbol * interfaceSymbol{thisInterface->symbol()}) {
4216       if (procsInCycle.count(*interfaceSymbol) > 0) {
4217         for (const auto &procInCycle : procsInCycle) {
4218           Say(procInCycle->name(),
4219               "The interface for procedure '%s' is recursively "
4220               "defined"_err_en_US,
4221               procInCycle->name());
4222           context().SetError(*procInCycle);
4223         }
4224         return true;
4225       } else if (const auto *procDetails{
4226                      interfaceSymbol->detailsIf<ProcEntityDetails>()}) {
4227         haveInterface = true;
4228         thisInterface = &procDetails->interface();
4229         procsInCycle.insert(*interfaceSymbol);
4230       }
4231     }
4232   }
4233   return false;
4234 }
4235 
4236 Symbol &DeclarationVisitor::DeclareProcEntity(
4237     const parser::Name &name, Attrs attrs, const ProcInterface &interface) {
4238   Symbol &symbol{DeclareEntity<ProcEntityDetails>(name, attrs)};
4239   if (auto *details{symbol.detailsIf<ProcEntityDetails>()}) {
4240     if (details->IsInterfaceSet()) {
4241       SayWithDecl(name, symbol,
4242           "The interface for procedure '%s' has already been "
4243           "declared"_err_en_US);
4244       context().SetError(symbol);
4245     } else if (HasCycle(symbol, interface)) {
4246       return symbol;
4247     } else if (interface.type()) {
4248       symbol.set(Symbol::Flag::Function);
4249     } else if (interface.symbol()) {
4250       if (interface.symbol()->test(Symbol::Flag::Function)) {
4251         symbol.set(Symbol::Flag::Function);
4252       } else if (interface.symbol()->test(Symbol::Flag::Subroutine)) {
4253         symbol.set(Symbol::Flag::Subroutine);
4254       }
4255     }
4256     details->set_interface(interface);
4257     SetBindNameOn(symbol);
4258     SetPassNameOn(symbol);
4259   }
4260   return symbol;
4261 }
4262 
4263 Symbol &DeclarationVisitor::DeclareObjectEntity(
4264     const parser::Name &name, Attrs attrs) {
4265   Symbol &symbol{DeclareEntity<ObjectEntityDetails>(name, attrs)};
4266   if (auto *details{symbol.detailsIf<ObjectEntityDetails>()}) {
4267     if (auto *type{GetDeclTypeSpec()}) {
4268       SetType(name, *type);
4269     }
4270     if (!arraySpec().empty()) {
4271       if (details->IsArray()) {
4272         if (!context().HasError(symbol)) {
4273           Say(name,
4274               "The dimensions of '%s' have already been declared"_err_en_US);
4275           context().SetError(symbol);
4276         }
4277       } else {
4278         details->set_shape(arraySpec());
4279       }
4280     }
4281     if (!coarraySpec().empty()) {
4282       if (details->IsCoarray()) {
4283         if (!context().HasError(symbol)) {
4284           Say(name,
4285               "The codimensions of '%s' have already been declared"_err_en_US);
4286           context().SetError(symbol);
4287         }
4288       } else {
4289         details->set_coshape(coarraySpec());
4290       }
4291     }
4292     SetBindNameOn(symbol);
4293   }
4294   ClearArraySpec();
4295   ClearCoarraySpec();
4296   charInfo_.length.reset();
4297   return symbol;
4298 }
4299 
4300 void DeclarationVisitor::Post(const parser::IntegerTypeSpec &x) {
4301   SetDeclTypeSpec(MakeNumericType(TypeCategory::Integer, x.v));
4302 }
4303 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Real &x) {
4304   SetDeclTypeSpec(MakeNumericType(TypeCategory::Real, x.kind));
4305 }
4306 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Complex &x) {
4307   SetDeclTypeSpec(MakeNumericType(TypeCategory::Complex, x.kind));
4308 }
4309 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Logical &x) {
4310   SetDeclTypeSpec(MakeLogicalType(x.kind));
4311 }
4312 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Character &) {
4313   if (!charInfo_.length) {
4314     charInfo_.length = ParamValue{1, common::TypeParamAttr::Len};
4315   }
4316   if (!charInfo_.kind) {
4317     charInfo_.kind =
4318         KindExpr{context().GetDefaultKind(TypeCategory::Character)};
4319   }
4320   SetDeclTypeSpec(currScope().MakeCharacterType(
4321       std::move(*charInfo_.length), std::move(*charInfo_.kind)));
4322   charInfo_ = {};
4323 }
4324 void DeclarationVisitor::Post(const parser::CharSelector::LengthAndKind &x) {
4325   charInfo_.kind = EvaluateSubscriptIntExpr(x.kind);
4326   std::optional<std::int64_t> intKind{ToInt64(charInfo_.kind)};
4327   if (intKind &&
4328       !context().targetCharacteristics().IsTypeEnabled(
4329           TypeCategory::Character, *intKind)) { // C715, C719
4330     Say(currStmtSource().value(),
4331         "KIND value (%jd) not valid for CHARACTER"_err_en_US, *intKind);
4332     charInfo_.kind = std::nullopt; // prevent further errors
4333   }
4334   if (x.length) {
4335     charInfo_.length = GetParamValue(*x.length, common::TypeParamAttr::Len);
4336   }
4337 }
4338 void DeclarationVisitor::Post(const parser::CharLength &x) {
4339   if (const auto *length{std::get_if<std::uint64_t>(&x.u)}) {
4340     charInfo_.length = ParamValue{
4341         static_cast<ConstantSubscript>(*length), common::TypeParamAttr::Len};
4342   } else {
4343     charInfo_.length = GetParamValue(
4344         std::get<parser::TypeParamValue>(x.u), common::TypeParamAttr::Len);
4345   }
4346 }
4347 void DeclarationVisitor::Post(const parser::LengthSelector &x) {
4348   if (const auto *param{std::get_if<parser::TypeParamValue>(&x.u)}) {
4349     charInfo_.length = GetParamValue(*param, common::TypeParamAttr::Len);
4350   }
4351 }
4352 
4353 bool DeclarationVisitor::Pre(const parser::KindParam &x) {
4354   if (const auto *kind{std::get_if<
4355           parser::Scalar<parser::Integer<parser::Constant<parser::Name>>>>(
4356           &x.u)}) {
4357     const parser::Name &name{kind->thing.thing.thing};
4358     if (!FindSymbol(name)) {
4359       Say(name, "Parameter '%s' not found"_err_en_US);
4360     }
4361   }
4362   return false;
4363 }
4364 
4365 bool DeclarationVisitor::Pre(const parser::DeclarationTypeSpec::Type &) {
4366   CHECK(GetDeclTypeSpecCategory() == DeclTypeSpec::Category::TypeDerived);
4367   return true;
4368 }
4369 
4370 void DeclarationVisitor::Post(const parser::DeclarationTypeSpec::Type &type) {
4371   const parser::Name &derivedName{std::get<parser::Name>(type.derived.t)};
4372   if (const Symbol * derivedSymbol{derivedName.symbol}) {
4373     CheckForAbstractType(*derivedSymbol); // C706
4374   }
4375 }
4376 
4377 bool DeclarationVisitor::Pre(const parser::DeclarationTypeSpec::Class &) {
4378   SetDeclTypeSpecCategory(DeclTypeSpec::Category::ClassDerived);
4379   return true;
4380 }
4381 
4382 void DeclarationVisitor::Post(
4383     const parser::DeclarationTypeSpec::Class &parsedClass) {
4384   const auto &typeName{std::get<parser::Name>(parsedClass.derived.t)};
4385   if (auto spec{ResolveDerivedType(typeName)};
4386       spec && !IsExtensibleType(&*spec)) { // C705
4387     SayWithDecl(typeName, *typeName.symbol,
4388         "Non-extensible derived type '%s' may not be used with CLASS"
4389         " keyword"_err_en_US);
4390   }
4391 }
4392 
4393 void DeclarationVisitor::Post(const parser::DerivedTypeSpec &x) {
4394   const auto &typeName{std::get<parser::Name>(x.t)};
4395   auto spec{ResolveDerivedType(typeName)};
4396   if (!spec) {
4397     return;
4398   }
4399   bool seenAnyName{false};
4400   for (const auto &typeParamSpec :
4401       std::get<std::list<parser::TypeParamSpec>>(x.t)) {
4402     const auto &optKeyword{
4403         std::get<std::optional<parser::Keyword>>(typeParamSpec.t)};
4404     std::optional<SourceName> name;
4405     if (optKeyword) {
4406       seenAnyName = true;
4407       name = optKeyword->v.source;
4408     } else if (seenAnyName) {
4409       Say(typeName.source, "Type parameter value must have a name"_err_en_US);
4410       continue;
4411     }
4412     const auto &value{std::get<parser::TypeParamValue>(typeParamSpec.t)};
4413     // The expressions in a derived type specifier whose values define
4414     // non-defaulted type parameters are evaluated (folded) in the enclosing
4415     // scope.  The KIND/LEN distinction is resolved later in
4416     // DerivedTypeSpec::CookParameters().
4417     ParamValue param{GetParamValue(value, common::TypeParamAttr::Kind)};
4418     if (!param.isExplicit() || param.GetExplicit()) {
4419       spec->AddRawParamValue(optKeyword, std::move(param));
4420     }
4421   }
4422 
4423   // The DerivedTypeSpec *spec is used initially as a search key.
4424   // If it turns out to have the same name and actual parameter
4425   // value expressions as another DerivedTypeSpec in the current
4426   // scope does, then we'll use that extant spec; otherwise, when this
4427   // spec is distinct from all derived types previously instantiated
4428   // in the current scope, this spec will be moved into that collection.
4429   const auto &dtDetails{spec->typeSymbol().get<DerivedTypeDetails>()};
4430   auto category{GetDeclTypeSpecCategory()};
4431   if (dtDetails.isForwardReferenced()) {
4432     DeclTypeSpec &type{currScope().MakeDerivedType(category, std::move(*spec))};
4433     SetDeclTypeSpec(type);
4434     return;
4435   }
4436   // Normalize parameters to produce a better search key.
4437   spec->CookParameters(GetFoldingContext());
4438   if (!spec->MightBeParameterized()) {
4439     spec->EvaluateParameters(context());
4440   }
4441   if (const DeclTypeSpec *
4442       extant{currScope().FindInstantiatedDerivedType(*spec, category)}) {
4443     // This derived type and parameter expressions (if any) are already present
4444     // in this scope.
4445     SetDeclTypeSpec(*extant);
4446   } else {
4447     DeclTypeSpec &type{currScope().MakeDerivedType(category, std::move(*spec))};
4448     DerivedTypeSpec &derived{type.derivedTypeSpec()};
4449     if (derived.MightBeParameterized() &&
4450         currScope().IsParameterizedDerivedType()) {
4451       // Defer instantiation; use the derived type's definition's scope.
4452       derived.set_scope(DEREF(spec->typeSymbol().scope()));
4453     } else if (&currScope() == spec->typeSymbol().scope()) {
4454       // Direct recursive use of a type in the definition of one of its
4455       // components: defer instantiation
4456     } else {
4457       auto restorer{
4458           GetFoldingContext().messages().SetLocation(currStmtSource().value())};
4459       derived.Instantiate(currScope());
4460     }
4461     SetDeclTypeSpec(type);
4462   }
4463   // Capture the DerivedTypeSpec in the parse tree for use in building
4464   // structure constructor expressions.
4465   x.derivedTypeSpec = &GetDeclTypeSpec()->derivedTypeSpec();
4466 }
4467 
4468 void DeclarationVisitor::Post(const parser::DeclarationTypeSpec::Record &rec) {
4469   const auto &typeName{rec.v};
4470   if (auto spec{ResolveDerivedType(typeName)}) {
4471     spec->CookParameters(GetFoldingContext());
4472     spec->EvaluateParameters(context());
4473     if (const DeclTypeSpec *
4474         extant{currScope().FindInstantiatedDerivedType(
4475             *spec, DeclTypeSpec::TypeDerived)}) {
4476       SetDeclTypeSpec(*extant);
4477     } else {
4478       Say(typeName.source, "%s is not a known STRUCTURE"_err_en_US,
4479           typeName.source);
4480     }
4481   }
4482 }
4483 
4484 // The descendents of DerivedTypeDef in the parse tree are visited directly
4485 // in this Pre() routine so that recursive use of the derived type can be
4486 // supported in the components.
4487 bool DeclarationVisitor::Pre(const parser::DerivedTypeDef &x) {
4488   auto &stmt{std::get<parser::Statement<parser::DerivedTypeStmt>>(x.t)};
4489   Walk(stmt);
4490   Walk(std::get<std::list<parser::Statement<parser::TypeParamDefStmt>>>(x.t));
4491   auto &scope{currScope()};
4492   CHECK(scope.symbol());
4493   CHECK(scope.symbol()->scope() == &scope);
4494   auto &details{scope.symbol()->get<DerivedTypeDetails>()};
4495   details.set_isForwardReferenced(false);
4496   std::set<SourceName> paramNames;
4497   for (auto &paramName : std::get<std::list<parser::Name>>(stmt.statement.t)) {
4498     details.add_paramName(paramName.source);
4499     auto *symbol{FindInScope(scope, paramName)};
4500     if (!symbol) {
4501       Say(paramName,
4502           "No definition found for type parameter '%s'"_err_en_US); // C742
4503       // No symbol for a type param.  Create one and mark it as containing an
4504       // error to improve subsequent semantic processing
4505       BeginAttrs();
4506       Symbol *typeParam{MakeTypeSymbol(
4507           paramName, TypeParamDetails{common::TypeParamAttr::Len})};
4508       context().SetError(*typeParam);
4509       EndAttrs();
4510     } else if (!symbol->has<TypeParamDetails>()) {
4511       Say2(paramName, "'%s' is not defined as a type parameter"_err_en_US,
4512           *symbol, "Definition of '%s'"_en_US); // C741
4513     }
4514     if (!paramNames.insert(paramName.source).second) {
4515       Say(paramName,
4516           "Duplicate type parameter name: '%s'"_err_en_US); // C731
4517     }
4518   }
4519   for (const auto &[name, symbol] : currScope()) {
4520     if (symbol->has<TypeParamDetails>() && !paramNames.count(name)) {
4521       SayDerivedType(name,
4522           "'%s' is not a type parameter of this derived type"_err_en_US,
4523           currScope()); // C741
4524     }
4525   }
4526   Walk(std::get<std::list<parser::Statement<parser::PrivateOrSequence>>>(x.t));
4527   const auto &componentDefs{
4528       std::get<std::list<parser::Statement<parser::ComponentDefStmt>>>(x.t)};
4529   Walk(componentDefs);
4530   if (derivedTypeInfo_.sequence) {
4531     details.set_sequence(true);
4532     if (componentDefs.empty()) { // C740
4533       Say(stmt.source,
4534           "A sequence type must have at least one component"_err_en_US);
4535     }
4536     if (!details.paramNames().empty()) { // C740
4537       Say(stmt.source,
4538           "A sequence type may not have type parameters"_err_en_US);
4539     }
4540     if (derivedTypeInfo_.extends) { // C735
4541       Say(stmt.source,
4542           "A sequence type may not have the EXTENDS attribute"_err_en_US);
4543     }
4544   }
4545   Walk(std::get<std::optional<parser::TypeBoundProcedurePart>>(x.t));
4546   Walk(std::get<parser::Statement<parser::EndTypeStmt>>(x.t));
4547   derivedTypeInfo_ = {};
4548   PopScope();
4549   return false;
4550 }
4551 
4552 bool DeclarationVisitor::Pre(const parser::DerivedTypeStmt &) {
4553   return BeginAttrs();
4554 }
4555 void DeclarationVisitor::Post(const parser::DerivedTypeStmt &x) {
4556   auto &name{std::get<parser::Name>(x.t)};
4557   // Resolve the EXTENDS() clause before creating the derived
4558   // type's symbol to foil attempts to recursively extend a type.
4559   auto *extendsName{derivedTypeInfo_.extends};
4560   std::optional<DerivedTypeSpec> extendsType{
4561       ResolveExtendsType(name, extendsName)};
4562   auto &symbol{MakeSymbol(name, GetAttrs(), DerivedTypeDetails{})};
4563   symbol.ReplaceName(name.source);
4564   derivedTypeInfo_.type = &symbol;
4565   PushScope(Scope::Kind::DerivedType, &symbol);
4566   if (extendsType) {
4567     // Declare the "parent component"; private if the type is.
4568     // Any symbol stored in the EXTENDS() clause is temporarily
4569     // hidden so that a new symbol can be created for the parent
4570     // component without producing spurious errors about already
4571     // existing.
4572     const Symbol &extendsSymbol{extendsType->typeSymbol()};
4573     auto restorer{common::ScopedSet(extendsName->symbol, nullptr)};
4574     if (OkToAddComponent(*extendsName, &extendsSymbol)) {
4575       auto &comp{DeclareEntity<ObjectEntityDetails>(*extendsName, Attrs{})};
4576       comp.attrs().set(
4577           Attr::PRIVATE, extendsSymbol.attrs().test(Attr::PRIVATE));
4578       comp.set(Symbol::Flag::ParentComp);
4579       DeclTypeSpec &type{currScope().MakeDerivedType(
4580           DeclTypeSpec::TypeDerived, std::move(*extendsType))};
4581       type.derivedTypeSpec().set_scope(*extendsSymbol.scope());
4582       comp.SetType(type);
4583       DerivedTypeDetails &details{symbol.get<DerivedTypeDetails>()};
4584       details.add_component(comp);
4585     }
4586   }
4587   EndAttrs();
4588 }
4589 
4590 void DeclarationVisitor::Post(const parser::TypeParamDefStmt &x) {
4591   auto *type{GetDeclTypeSpec()};
4592   auto attr{std::get<common::TypeParamAttr>(x.t)};
4593   for (auto &decl : std::get<std::list<parser::TypeParamDecl>>(x.t)) {
4594     auto &name{std::get<parser::Name>(decl.t)};
4595     if (Symbol * symbol{MakeTypeSymbol(name, TypeParamDetails{attr})}) {
4596       SetType(name, *type);
4597       if (auto &init{
4598               std::get<std::optional<parser::ScalarIntConstantExpr>>(decl.t)}) {
4599         if (auto maybeExpr{EvaluateNonPointerInitializer(
4600                 *symbol, *init, init->thing.thing.thing.value().source)}) {
4601           if (auto *intExpr{std::get_if<SomeIntExpr>(&maybeExpr->u)}) {
4602             symbol->get<TypeParamDetails>().set_init(std::move(*intExpr));
4603           }
4604         }
4605       }
4606     }
4607   }
4608   EndDecl();
4609 }
4610 bool DeclarationVisitor::Pre(const parser::TypeAttrSpec::Extends &x) {
4611   if (derivedTypeInfo_.extends) {
4612     Say(currStmtSource().value(),
4613         "Attribute 'EXTENDS' cannot be used more than once"_err_en_US);
4614   } else {
4615     derivedTypeInfo_.extends = &x.v;
4616   }
4617   return false;
4618 }
4619 
4620 bool DeclarationVisitor::Pre(const parser::PrivateStmt &) {
4621   if (!currScope().parent().IsModule()) {
4622     Say("PRIVATE is only allowed in a derived type that is"
4623         " in a module"_err_en_US); // C766
4624   } else if (derivedTypeInfo_.sawContains) {
4625     derivedTypeInfo_.privateBindings = true;
4626   } else if (!derivedTypeInfo_.privateComps) {
4627     derivedTypeInfo_.privateComps = true;
4628   } else {
4629     Say("PRIVATE may not appear more than once in"
4630         " derived type components"_warn_en_US); // C738
4631   }
4632   return false;
4633 }
4634 bool DeclarationVisitor::Pre(const parser::SequenceStmt &) {
4635   if (derivedTypeInfo_.sequence) {
4636     Say("SEQUENCE may not appear more than once in"
4637         " derived type components"_warn_en_US); // C738
4638   }
4639   derivedTypeInfo_.sequence = true;
4640   return false;
4641 }
4642 void DeclarationVisitor::Post(const parser::ComponentDecl &x) {
4643   const auto &name{std::get<parser::Name>(x.t)};
4644   auto attrs{GetAttrs()};
4645   if (derivedTypeInfo_.privateComps &&
4646       !attrs.HasAny({Attr::PUBLIC, Attr::PRIVATE})) {
4647     attrs.set(Attr::PRIVATE);
4648   }
4649   if (const auto *declType{GetDeclTypeSpec()}) {
4650     if (const auto *derived{declType->AsDerived()}) {
4651       if (!attrs.HasAny({Attr::POINTER, Attr::ALLOCATABLE})) {
4652         if (derivedTypeInfo_.type == &derived->typeSymbol()) { // C744
4653           Say("Recursive use of the derived type requires "
4654               "POINTER or ALLOCATABLE"_err_en_US);
4655         }
4656       }
4657       // TODO: This would be more appropriate in CheckDerivedType()
4658       if (auto it{FindCoarrayUltimateComponent(*derived)}) { // C748
4659         std::string ultimateName{it.BuildResultDesignatorName()};
4660         // Strip off the leading "%"
4661         if (ultimateName.length() > 1) {
4662           ultimateName.erase(0, 1);
4663           if (attrs.HasAny({Attr::POINTER, Attr::ALLOCATABLE})) {
4664             evaluate::AttachDeclaration(
4665                 Say(name.source,
4666                     "A component with a POINTER or ALLOCATABLE attribute may "
4667                     "not "
4668                     "be of a type with a coarray ultimate component (named "
4669                     "'%s')"_err_en_US,
4670                     ultimateName),
4671                 derived->typeSymbol());
4672           }
4673           if (!arraySpec().empty() || !coarraySpec().empty()) {
4674             evaluate::AttachDeclaration(
4675                 Say(name.source,
4676                     "An array or coarray component may not be of a type with a "
4677                     "coarray ultimate component (named '%s')"_err_en_US,
4678                     ultimateName),
4679                 derived->typeSymbol());
4680           }
4681         }
4682       }
4683     }
4684   }
4685   if (OkToAddComponent(name)) {
4686     auto &symbol{DeclareObjectEntity(name, attrs)};
4687     if (symbol.has<ObjectEntityDetails>()) {
4688       if (auto &init{std::get<std::optional<parser::Initialization>>(x.t)}) {
4689         Initialization(name, *init, true);
4690       }
4691     }
4692     currScope().symbol()->get<DerivedTypeDetails>().add_component(symbol);
4693   }
4694   ClearArraySpec();
4695   ClearCoarraySpec();
4696 }
4697 void DeclarationVisitor::Post(const parser::FillDecl &x) {
4698   // Replace "%FILL" with a distinct generated name
4699   const auto &name{std::get<parser::Name>(x.t)};
4700   const_cast<SourceName &>(name.source) = context().GetTempName(currScope());
4701   if (OkToAddComponent(name)) {
4702     auto &symbol{DeclareObjectEntity(name, GetAttrs())};
4703     currScope().symbol()->get<DerivedTypeDetails>().add_component(symbol);
4704   }
4705   ClearArraySpec();
4706 }
4707 bool DeclarationVisitor::Pre(const parser::ProcedureDeclarationStmt &x) {
4708   CHECK(!interfaceName_);
4709   const auto &procAttrSpec{std::get<std::list<parser::ProcAttrSpec>>(x.t)};
4710   for (const parser::ProcAttrSpec &procAttr : procAttrSpec) {
4711     if (auto *bindC{std::get_if<parser::LanguageBindingSpec>(&procAttr.u)}) {
4712       if (bindC->v.has_value()) {
4713         hasBindCName_ = true;
4714         break;
4715       }
4716     }
4717   }
4718   return BeginDecl();
4719 }
4720 void DeclarationVisitor::Post(const parser::ProcedureDeclarationStmt &) {
4721   interfaceName_ = nullptr;
4722   hasBindCName_ = false;
4723   EndDecl();
4724 }
4725 bool DeclarationVisitor::Pre(const parser::DataComponentDefStmt &x) {
4726   // Overrides parse tree traversal so as to handle attributes first,
4727   // so POINTER & ALLOCATABLE enable forward references to derived types.
4728   Walk(std::get<std::list<parser::ComponentAttrSpec>>(x.t));
4729   set_allowForwardReferenceToDerivedType(
4730       GetAttrs().HasAny({Attr::POINTER, Attr::ALLOCATABLE}));
4731   Walk(std::get<parser::DeclarationTypeSpec>(x.t));
4732   set_allowForwardReferenceToDerivedType(false);
4733   if (derivedTypeInfo_.sequence) { // C740
4734     if (const auto *declType{GetDeclTypeSpec()}) {
4735       if (!declType->AsIntrinsic() && !declType->IsSequenceType()) {
4736         if (GetAttrs().test(Attr::POINTER) &&
4737             context().IsEnabled(common::LanguageFeature::PointerInSeqType)) {
4738           if (context().ShouldWarn(common::LanguageFeature::PointerInSeqType)) {
4739             Say("A sequence type data component that is a pointer to a non-sequence type is not standard"_port_en_US);
4740           }
4741         } else {
4742           Say("A sequence type data component must either be of an intrinsic type or a derived sequence type"_err_en_US);
4743         }
4744       }
4745     }
4746   }
4747   Walk(std::get<std::list<parser::ComponentOrFill>>(x.t));
4748   return false;
4749 }
4750 bool DeclarationVisitor::Pre(const parser::ProcComponentDefStmt &) {
4751   CHECK(!interfaceName_);
4752   return true;
4753 }
4754 void DeclarationVisitor::Post(const parser::ProcComponentDefStmt &) {
4755   interfaceName_ = nullptr;
4756 }
4757 bool DeclarationVisitor::Pre(const parser::ProcPointerInit &x) {
4758   if (auto *name{std::get_if<parser::Name>(&x.u)}) {
4759     return !NameIsKnownOrIntrinsic(*name);
4760   }
4761   return true;
4762 }
4763 void DeclarationVisitor::Post(const parser::ProcInterface &x) {
4764   if (auto *name{std::get_if<parser::Name>(&x.u)}) {
4765     interfaceName_ = name;
4766     NoteInterfaceName(*name);
4767   }
4768 }
4769 void DeclarationVisitor::Post(const parser::ProcDecl &x) {
4770   const auto &name{std::get<parser::Name>(x.t)};
4771   ProcInterface interface;
4772   if (interfaceName_) {
4773     interface.set_symbol(*interfaceName_->symbol);
4774   } else if (auto *type{GetDeclTypeSpec()}) {
4775     interface.set_type(*type);
4776   }
4777   auto attrs{HandleSaveName(name.source, GetAttrs())};
4778   DerivedTypeDetails *dtDetails{nullptr};
4779   if (Symbol * symbol{currScope().symbol()}) {
4780     dtDetails = symbol->detailsIf<DerivedTypeDetails>();
4781   }
4782   if (!dtDetails) {
4783     attrs.set(Attr::EXTERNAL);
4784   }
4785   Symbol &symbol{DeclareProcEntity(name, attrs, interface)};
4786   symbol.ReplaceName(name.source);
4787   if (dtDetails) {
4788     dtDetails->add_component(symbol);
4789   }
4790   if (hasBindCName_ && (IsPointer(symbol) || IsDummy(symbol))) {
4791     Say(symbol.name(),
4792         "BIND(C) procedure with NAME= specified can neither have POINTER attribute nor be a dummy procedure"_err_en_US);
4793   }
4794 }
4795 
4796 bool DeclarationVisitor::Pre(const parser::TypeBoundProcedurePart &) {
4797   derivedTypeInfo_.sawContains = true;
4798   return true;
4799 }
4800 
4801 // Resolve binding names from type-bound generics, saved in genericBindings_.
4802 void DeclarationVisitor::Post(const parser::TypeBoundProcedurePart &) {
4803   // track specifics seen for the current generic to detect duplicates:
4804   const Symbol *currGeneric{nullptr};
4805   std::set<SourceName> specifics;
4806   for (const auto &[generic, bindingName] : genericBindings_) {
4807     if (generic != currGeneric) {
4808       currGeneric = generic;
4809       specifics.clear();
4810     }
4811     auto [it, inserted]{specifics.insert(bindingName->source)};
4812     if (!inserted) {
4813       Say(*bindingName, // C773
4814           "Binding name '%s' was already specified for generic '%s'"_err_en_US,
4815           bindingName->source, generic->name())
4816           .Attach(*it, "Previous specification of '%s'"_en_US, *it);
4817       continue;
4818     }
4819     auto *symbol{FindInTypeOrParents(*bindingName)};
4820     if (!symbol) {
4821       Say(*bindingName, // C772
4822           "Binding name '%s' not found in this derived type"_err_en_US);
4823     } else if (!symbol->has<ProcBindingDetails>()) {
4824       SayWithDecl(*bindingName, *symbol, // C772
4825           "'%s' is not the name of a specific binding of this type"_err_en_US);
4826     } else {
4827       generic->get<GenericDetails>().AddSpecificProc(
4828           *symbol, bindingName->source);
4829     }
4830   }
4831   genericBindings_.clear();
4832 }
4833 
4834 void DeclarationVisitor::Post(const parser::ContainsStmt &) {
4835   if (derivedTypeInfo_.sequence) {
4836     Say("A sequence type may not have a CONTAINS statement"_err_en_US); // C740
4837   }
4838 }
4839 
4840 void DeclarationVisitor::Post(
4841     const parser::TypeBoundProcedureStmt::WithoutInterface &x) {
4842   if (GetAttrs().test(Attr::DEFERRED)) { // C783
4843     Say("DEFERRED is only allowed when an interface-name is provided"_err_en_US);
4844   }
4845   for (auto &declaration : x.declarations) {
4846     auto &bindingName{std::get<parser::Name>(declaration.t)};
4847     auto &optName{std::get<std::optional<parser::Name>>(declaration.t)};
4848     const parser::Name &procedureName{optName ? *optName : bindingName};
4849     Symbol *procedure{FindSymbol(procedureName)};
4850     if (!procedure) {
4851       procedure = NoteInterfaceName(procedureName);
4852     }
4853     if (auto *s{MakeTypeSymbol(bindingName, ProcBindingDetails{*procedure})}) {
4854       SetPassNameOn(*s);
4855       if (GetAttrs().test(Attr::DEFERRED)) {
4856         context().SetError(*s);
4857       }
4858     }
4859   }
4860 }
4861 
4862 void DeclarationVisitor::CheckBindings(
4863     const parser::TypeBoundProcedureStmt::WithoutInterface &tbps) {
4864   CHECK(currScope().IsDerivedType());
4865   for (auto &declaration : tbps.declarations) {
4866     auto &bindingName{std::get<parser::Name>(declaration.t)};
4867     if (Symbol * binding{FindInScope(bindingName)}) {
4868       if (auto *details{binding->detailsIf<ProcBindingDetails>()}) {
4869         const Symbol *procedure{FindSubprogram(details->symbol())};
4870         if (!CanBeTypeBoundProc(procedure)) {
4871           if (details->symbol().name() != binding->name()) {
4872             Say(binding->name(),
4873                 "The binding of '%s' ('%s') must be either an accessible "
4874                 "module procedure or an external procedure with "
4875                 "an explicit interface"_err_en_US,
4876                 binding->name(), details->symbol().name());
4877           } else {
4878             Say(binding->name(),
4879                 "'%s' must be either an accessible module procedure "
4880                 "or an external procedure with an explicit interface"_err_en_US,
4881                 binding->name());
4882           }
4883           context().SetError(*binding);
4884         }
4885       }
4886     }
4887   }
4888 }
4889 
4890 void DeclarationVisitor::Post(
4891     const parser::TypeBoundProcedureStmt::WithInterface &x) {
4892   if (!GetAttrs().test(Attr::DEFERRED)) { // C783
4893     Say("DEFERRED is required when an interface-name is provided"_err_en_US);
4894   }
4895   if (Symbol * interface{NoteInterfaceName(x.interfaceName)}) {
4896     for (auto &bindingName : x.bindingNames) {
4897       if (auto *s{
4898               MakeTypeSymbol(bindingName, ProcBindingDetails{*interface})}) {
4899         SetPassNameOn(*s);
4900         if (!GetAttrs().test(Attr::DEFERRED)) {
4901           context().SetError(*s);
4902         }
4903       }
4904     }
4905   }
4906 }
4907 
4908 void DeclarationVisitor::Post(const parser::FinalProcedureStmt &x) {
4909   if (currScope().IsDerivedType() && currScope().symbol()) {
4910     if (auto *details{currScope().symbol()->detailsIf<DerivedTypeDetails>()}) {
4911       for (const auto &subrName : x.v) {
4912         if (const auto *name{ResolveName(subrName)}) {
4913           auto pair{
4914               details->finals().emplace(name->source, DEREF(name->symbol))};
4915           if (!pair.second) { // C787
4916             Say(name->source,
4917                 "FINAL subroutine '%s' already appeared in this derived type"_err_en_US,
4918                 name->source)
4919                 .Attach(pair.first->first,
4920                     "earlier appearance of this FINAL subroutine"_en_US);
4921           }
4922         }
4923       }
4924     }
4925   }
4926 }
4927 
4928 bool DeclarationVisitor::Pre(const parser::TypeBoundGenericStmt &x) {
4929   const auto &accessSpec{std::get<std::optional<parser::AccessSpec>>(x.t)};
4930   const auto &genericSpec{std::get<Indirection<parser::GenericSpec>>(x.t)};
4931   const auto &bindingNames{std::get<std::list<parser::Name>>(x.t)};
4932   auto info{GenericSpecInfo{genericSpec.value()}};
4933   SourceName symbolName{info.symbolName()};
4934   bool isPrivate{accessSpec ? accessSpec->v == parser::AccessSpec::Kind::Private
4935                             : derivedTypeInfo_.privateBindings};
4936   auto *genericSymbol{FindInScope(symbolName)};
4937   if (genericSymbol) {
4938     if (!genericSymbol->has<GenericDetails>()) {
4939       genericSymbol = nullptr; // MakeTypeSymbol will report the error below
4940     }
4941   } else {
4942     // look in parent types:
4943     Symbol *inheritedSymbol{nullptr};
4944     for (const auto &name : GetAllNames(context(), symbolName)) {
4945       inheritedSymbol = currScope().FindComponent(SourceName{name});
4946       if (inheritedSymbol) {
4947         break;
4948       }
4949     }
4950     if (inheritedSymbol && inheritedSymbol->has<GenericDetails>()) {
4951       CheckAccessibility(symbolName, isPrivate, *inheritedSymbol); // C771
4952     }
4953   }
4954   if (genericSymbol) {
4955     CheckAccessibility(symbolName, isPrivate, *genericSymbol); // C771
4956   } else {
4957     genericSymbol = MakeTypeSymbol(symbolName, GenericDetails{});
4958     if (!genericSymbol) {
4959       return false;
4960     }
4961     if (isPrivate) {
4962       genericSymbol->attrs().set(Attr::PRIVATE);
4963     }
4964   }
4965   for (const parser::Name &bindingName : bindingNames) {
4966     genericBindings_.emplace(genericSymbol, &bindingName);
4967   }
4968   info.Resolve(genericSymbol);
4969   return false;
4970 }
4971 
4972 // DEC STRUCTUREs are handled thus to allow for nested definitions.
4973 bool DeclarationVisitor::Pre(const parser::StructureDef &def) {
4974   const auto &structureStatement{
4975       std::get<parser::Statement<parser::StructureStmt>>(def.t)};
4976   auto saveDerivedTypeInfo{derivedTypeInfo_};
4977   derivedTypeInfo_ = {};
4978   derivedTypeInfo_.isStructure = true;
4979   derivedTypeInfo_.sequence = true;
4980   Scope *previousStructure{nullptr};
4981   if (saveDerivedTypeInfo.isStructure) {
4982     previousStructure = &currScope();
4983     PopScope();
4984   }
4985   const parser::StructureStmt &structStmt{structureStatement.statement};
4986   const auto &name{std::get<std::optional<parser::Name>>(structStmt.t)};
4987   if (!name) {
4988     // Construct a distinct generated name for an anonymous structure
4989     auto &mutableName{const_cast<std::optional<parser::Name> &>(name)};
4990     mutableName.emplace(
4991         parser::Name{context().GetTempName(currScope()), nullptr});
4992   }
4993   auto &symbol{MakeSymbol(*name, DerivedTypeDetails{})};
4994   symbol.ReplaceName(name->source);
4995   symbol.get<DerivedTypeDetails>().set_sequence(true);
4996   symbol.get<DerivedTypeDetails>().set_isDECStructure(true);
4997   derivedTypeInfo_.type = &symbol;
4998   PushScope(Scope::Kind::DerivedType, &symbol);
4999   const auto &fields{std::get<std::list<parser::StructureField>>(def.t)};
5000   Walk(fields);
5001   PopScope();
5002   // Complete the definition
5003   DerivedTypeSpec derivedTypeSpec{symbol.name(), symbol};
5004   derivedTypeSpec.set_scope(DEREF(symbol.scope()));
5005   derivedTypeSpec.CookParameters(GetFoldingContext());
5006   derivedTypeSpec.EvaluateParameters(context());
5007   DeclTypeSpec &type{currScope().MakeDerivedType(
5008       DeclTypeSpec::TypeDerived, std::move(derivedTypeSpec))};
5009   type.derivedTypeSpec().Instantiate(currScope());
5010   // Restore previous structure definition context, if any
5011   derivedTypeInfo_ = saveDerivedTypeInfo;
5012   if (previousStructure) {
5013     PushScope(*previousStructure);
5014   }
5015   // Handle any entity declarations on the STRUCTURE statement
5016   const auto &decls{std::get<std::list<parser::EntityDecl>>(structStmt.t)};
5017   if (!decls.empty()) {
5018     BeginDecl();
5019     SetDeclTypeSpec(type);
5020     Walk(decls);
5021     EndDecl();
5022   }
5023   return false;
5024 }
5025 
5026 bool DeclarationVisitor::Pre(const parser::Union::UnionStmt &) {
5027   Say("support for UNION"_todo_en_US); // TODO
5028   return true;
5029 }
5030 
5031 bool DeclarationVisitor::Pre(const parser::StructureField &x) {
5032   if (std::holds_alternative<parser::Statement<parser::DataComponentDefStmt>>(
5033           x.u)) {
5034     BeginDecl();
5035   }
5036   return true;
5037 }
5038 
5039 void DeclarationVisitor::Post(const parser::StructureField &x) {
5040   if (std::holds_alternative<parser::Statement<parser::DataComponentDefStmt>>(
5041           x.u)) {
5042     EndDecl();
5043   }
5044 }
5045 
5046 bool DeclarationVisitor::Pre(const parser::AllocateStmt &) {
5047   BeginDeclTypeSpec();
5048   return true;
5049 }
5050 void DeclarationVisitor::Post(const parser::AllocateStmt &) {
5051   EndDeclTypeSpec();
5052 }
5053 
5054 bool DeclarationVisitor::Pre(const parser::StructureConstructor &x) {
5055   auto &parsedType{std::get<parser::DerivedTypeSpec>(x.t)};
5056   const DeclTypeSpec *type{ProcessTypeSpec(parsedType)};
5057   if (!type) {
5058     return false;
5059   }
5060   const DerivedTypeSpec *spec{type->AsDerived()};
5061   const Scope *typeScope{spec ? spec->scope() : nullptr};
5062   if (!typeScope) {
5063     return false;
5064   }
5065 
5066   // N.B C7102 is implicitly enforced by having inaccessible types not
5067   // being found in resolution.
5068   // More constraints are enforced in expression.cpp so that they
5069   // can apply to structure constructors that have been converted
5070   // from misparsed function references.
5071   for (const auto &component :
5072       std::get<std::list<parser::ComponentSpec>>(x.t)) {
5073     // Visit the component spec expression, but not the keyword, since
5074     // we need to resolve its symbol in the scope of the derived type.
5075     Walk(std::get<parser::ComponentDataSource>(component.t));
5076     if (const auto &kw{std::get<std::optional<parser::Keyword>>(component.t)}) {
5077       FindInTypeOrParents(*typeScope, kw->v);
5078     }
5079   }
5080   return false;
5081 }
5082 
5083 bool DeclarationVisitor::Pre(const parser::BasedPointerStmt &x) {
5084   for (const parser::BasedPointer &bp : x.v) {
5085     const parser::ObjectName &pointerName{std::get<0>(bp.t)};
5086     const parser::ObjectName &pointeeName{std::get<1>(bp.t)};
5087     auto *pointer{FindSymbol(pointerName)};
5088     if (!pointer) {
5089       pointer = &MakeSymbol(pointerName, ObjectEntityDetails{});
5090     } else if (!ConvertToObjectEntity(*pointer) || IsNamedConstant(*pointer)) {
5091       SayWithDecl(pointerName, *pointer, "'%s' is not a variable"_err_en_US);
5092     } else if (pointer->Rank() > 0) {
5093       SayWithDecl(pointerName, *pointer,
5094           "Cray pointer '%s' must be a scalar"_err_en_US);
5095     } else if (pointer->test(Symbol::Flag::CrayPointee)) {
5096       Say(pointerName,
5097           "'%s' cannot be a Cray pointer as it is already a Cray pointee"_err_en_US);
5098     }
5099     pointer->set(Symbol::Flag::CrayPointer);
5100     const DeclTypeSpec &pointerType{MakeNumericType(TypeCategory::Integer,
5101         context().defaultKinds().subscriptIntegerKind())};
5102     const auto *type{pointer->GetType()};
5103     if (!type) {
5104       pointer->SetType(pointerType);
5105     } else if (*type != pointerType) {
5106       Say(pointerName.source, "Cray pointer '%s' must have type %s"_err_en_US,
5107           pointerName.source, pointerType.AsFortran());
5108     }
5109     if (ResolveName(pointeeName)) {
5110       Symbol &pointee{*pointeeName.symbol};
5111       if (pointee.has<UseDetails>()) {
5112         Say(pointeeName,
5113             "'%s' cannot be a Cray pointee as it is use-associated"_err_en_US);
5114         continue;
5115       } else if (!ConvertToObjectEntity(pointee) || IsNamedConstant(pointee)) {
5116         Say(pointeeName, "'%s' is not a variable"_err_en_US);
5117         continue;
5118       } else if (pointee.test(Symbol::Flag::CrayPointer)) {
5119         Say(pointeeName,
5120             "'%s' cannot be a Cray pointee as it is already a Cray pointer"_err_en_US);
5121       } else if (pointee.test(Symbol::Flag::CrayPointee)) {
5122         Say(pointeeName,
5123             "'%s' was already declared as a Cray pointee"_err_en_US);
5124       } else {
5125         pointee.set(Symbol::Flag::CrayPointee);
5126       }
5127       if (const auto *pointeeType{pointee.GetType()}) {
5128         if (const auto *derived{pointeeType->AsDerived()}) {
5129           if (!derived->typeSymbol().get<DerivedTypeDetails>().sequence()) {
5130             Say(pointeeName,
5131                 "Type of Cray pointee '%s' is a non-sequence derived type"_err_en_US);
5132           }
5133         }
5134       }
5135       // process the pointee array-spec, if present
5136       BeginArraySpec();
5137       Walk(std::get<std::optional<parser::ArraySpec>>(bp.t));
5138       const auto &spec{arraySpec()};
5139       if (!spec.empty()) {
5140         auto &details{pointee.get<ObjectEntityDetails>()};
5141         if (details.shape().empty()) {
5142           details.set_shape(spec);
5143         } else {
5144           SayWithDecl(pointeeName, pointee,
5145               "Array spec was already declared for '%s'"_err_en_US);
5146         }
5147       }
5148       ClearArraySpec();
5149       currScope().add_crayPointer(pointeeName.source, *pointer);
5150     }
5151   }
5152   return false;
5153 }
5154 
5155 bool DeclarationVisitor::Pre(const parser::NamelistStmt::Group &x) {
5156   if (!CheckNotInBlock("NAMELIST")) { // C1107
5157     return false;
5158   }
5159   const auto &groupName{std::get<parser::Name>(x.t)};
5160   auto *groupSymbol{FindInScope(groupName)};
5161   if (!groupSymbol || !groupSymbol->has<NamelistDetails>()) {
5162     groupSymbol = &MakeSymbol(groupName, NamelistDetails{});
5163     groupSymbol->ReplaceName(groupName.source);
5164   }
5165   // Name resolution of group items is deferred to FinishNamelists()
5166   // so that host association is handled correctly.
5167   GetDeferredDeclarationState(true)->namelistGroups.emplace_back(&x);
5168   return false;
5169 }
5170 
5171 void DeclarationVisitor::FinishNamelists() {
5172   if (auto *deferred{GetDeferredDeclarationState()}) {
5173     for (const parser::NamelistStmt::Group *group : deferred->namelistGroups) {
5174       if (auto *groupSymbol{FindInScope(std::get<parser::Name>(group->t))}) {
5175         if (auto *details{groupSymbol->detailsIf<NamelistDetails>()}) {
5176           for (const auto &name : std::get<std::list<parser::Name>>(group->t)) {
5177             auto *symbol{FindSymbol(name)};
5178             if (!symbol) {
5179               symbol = &MakeSymbol(name, ObjectEntityDetails{});
5180               ApplyImplicitRules(*symbol);
5181             } else if (!ConvertToObjectEntity(*symbol)) {
5182               SayWithDecl(name, *symbol, "'%s' is not a variable"_err_en_US);
5183             }
5184             symbol->GetUltimate().set(Symbol::Flag::InNamelist);
5185             details->add_object(*symbol);
5186           }
5187         }
5188       }
5189     }
5190     deferred->namelistGroups.clear();
5191   }
5192 }
5193 
5194 bool DeclarationVisitor::Pre(const parser::IoControlSpec &x) {
5195   if (const auto *name{std::get_if<parser::Name>(&x.u)}) {
5196     auto *symbol{FindSymbol(*name)};
5197     if (!symbol) {
5198       Say(*name, "Namelist group '%s' not found"_err_en_US);
5199     } else if (!symbol->GetUltimate().has<NamelistDetails>()) {
5200       SayWithDecl(
5201           *name, *symbol, "'%s' is not the name of a namelist group"_err_en_US);
5202     }
5203   }
5204   return true;
5205 }
5206 
5207 bool DeclarationVisitor::Pre(const parser::CommonStmt::Block &x) {
5208   CheckNotInBlock("COMMON"); // C1107
5209   return true;
5210 }
5211 
5212 bool DeclarationVisitor::Pre(const parser::CommonBlockObject &) {
5213   BeginArraySpec();
5214   return true;
5215 }
5216 
5217 void DeclarationVisitor::Post(const parser::CommonBlockObject &x) {
5218   const auto &name{std::get<parser::Name>(x.t)};
5219   DeclareObjectEntity(name);
5220   auto pair{specPartState_.commonBlockObjects.insert(name.source)};
5221   if (!pair.second) {
5222     const SourceName &prev{*pair.first};
5223     Say2(name.source, "'%s' is already in a COMMON block"_err_en_US, prev,
5224         "Previous occurrence of '%s' in a COMMON block"_en_US);
5225   }
5226 }
5227 
5228 bool DeclarationVisitor::Pre(const parser::EquivalenceStmt &x) {
5229   // save equivalence sets to be processed after specification part
5230   if (CheckNotInBlock("EQUIVALENCE")) { // C1107
5231     for (const std::list<parser::EquivalenceObject> &set : x.v) {
5232       specPartState_.equivalenceSets.push_back(&set);
5233     }
5234   }
5235   return false; // don't implicitly declare names yet
5236 }
5237 
5238 void DeclarationVisitor::CheckEquivalenceSets() {
5239   EquivalenceSets equivSets{context()};
5240   inEquivalenceStmt_ = true;
5241   for (const auto *set : specPartState_.equivalenceSets) {
5242     const auto &source{set->front().v.value().source};
5243     if (set->size() <= 1) { // R871
5244       Say(source, "Equivalence set must have more than one object"_err_en_US);
5245     }
5246     for (const parser::EquivalenceObject &object : *set) {
5247       const auto &designator{object.v.value()};
5248       // The designator was not resolved when it was encountered so do it now.
5249       // AnalyzeExpr causes array sections to be changed to substrings as needed
5250       Walk(designator);
5251       if (AnalyzeExpr(context(), designator)) {
5252         equivSets.AddToSet(designator);
5253       }
5254     }
5255     equivSets.FinishSet(source);
5256   }
5257   inEquivalenceStmt_ = false;
5258   for (auto &set : equivSets.sets()) {
5259     if (!set.empty()) {
5260       currScope().add_equivalenceSet(std::move(set));
5261     }
5262   }
5263   specPartState_.equivalenceSets.clear();
5264 }
5265 
5266 bool DeclarationVisitor::Pre(const parser::SaveStmt &x) {
5267   if (x.v.empty()) {
5268     specPartState_.saveInfo.saveAll = currStmtSource();
5269     currScope().set_hasSAVE();
5270   } else {
5271     for (const parser::SavedEntity &y : x.v) {
5272       auto kind{std::get<parser::SavedEntity::Kind>(y.t)};
5273       const auto &name{std::get<parser::Name>(y.t)};
5274       if (kind == parser::SavedEntity::Kind::Common) {
5275         MakeCommonBlockSymbol(name);
5276         AddSaveName(specPartState_.saveInfo.commons, name.source);
5277       } else {
5278         HandleAttributeStmt(Attr::SAVE, name);
5279       }
5280     }
5281   }
5282   return false;
5283 }
5284 
5285 void DeclarationVisitor::CheckSaveStmts() {
5286   for (const SourceName &name : specPartState_.saveInfo.entities) {
5287     auto *symbol{FindInScope(name)};
5288     if (!symbol) {
5289       // error was reported
5290     } else if (specPartState_.saveInfo.saveAll) {
5291       // C889 - note that pgi, ifort, xlf do not enforce this constraint
5292       Say2(name,
5293           "Explicit SAVE of '%s' is redundant due to global SAVE statement"_warn_en_US,
5294           *specPartState_.saveInfo.saveAll, "Global SAVE statement"_en_US);
5295     } else if (auto msg{CheckSaveAttr(*symbol)}) {
5296       Say(name, std::move(*msg));
5297       context().SetError(*symbol);
5298     } else {
5299       SetSaveAttr(*symbol);
5300     }
5301   }
5302   for (const SourceName &name : specPartState_.saveInfo.commons) {
5303     if (auto *symbol{currScope().FindCommonBlock(name)}) {
5304       auto &objects{symbol->get<CommonBlockDetails>().objects()};
5305       if (objects.empty()) {
5306         if (currScope().kind() != Scope::Kind::Block) {
5307           Say(name,
5308               "'%s' appears as a COMMON block in a SAVE statement but not in"
5309               " a COMMON statement"_err_en_US);
5310         } else { // C1108
5311           Say(name,
5312               "SAVE statement in BLOCK construct may not contain a"
5313               " common block name '%s'"_err_en_US);
5314         }
5315       } else {
5316         for (auto &object : symbol->get<CommonBlockDetails>().objects()) {
5317           SetSaveAttr(*object);
5318         }
5319       }
5320     }
5321   }
5322   if (specPartState_.saveInfo.saveAll) {
5323     // Apply SAVE attribute to applicable symbols
5324     for (auto pair : currScope()) {
5325       auto &symbol{*pair.second};
5326       if (!CheckSaveAttr(symbol)) {
5327         SetSaveAttr(symbol);
5328       }
5329     }
5330   }
5331   specPartState_.saveInfo = {};
5332 }
5333 
5334 // If SAVE attribute can't be set on symbol, return error message.
5335 std::optional<MessageFixedText> DeclarationVisitor::CheckSaveAttr(
5336     const Symbol &symbol) {
5337   if (IsDummy(symbol)) {
5338     return "SAVE attribute may not be applied to dummy argument '%s'"_err_en_US;
5339   } else if (symbol.IsFuncResult()) {
5340     return "SAVE attribute may not be applied to function result '%s'"_err_en_US;
5341   } else if (symbol.has<ProcEntityDetails>() &&
5342       !symbol.attrs().test(Attr::POINTER)) {
5343     return "Procedure '%s' with SAVE attribute must also have POINTER attribute"_err_en_US;
5344   } else if (IsAutomatic(symbol)) {
5345     return "SAVE attribute may not be applied to automatic data object '%s'"_err_en_US;
5346   } else {
5347     return std::nullopt;
5348   }
5349 }
5350 
5351 // Record SAVEd names in specPartState_.saveInfo.entities.
5352 Attrs DeclarationVisitor::HandleSaveName(const SourceName &name, Attrs attrs) {
5353   if (attrs.test(Attr::SAVE)) {
5354     AddSaveName(specPartState_.saveInfo.entities, name);
5355   }
5356   return attrs;
5357 }
5358 
5359 // Record a name in a set of those to be saved.
5360 void DeclarationVisitor::AddSaveName(
5361     std::set<SourceName> &set, const SourceName &name) {
5362   auto pair{set.insert(name)};
5363   if (!pair.second) {
5364     Say2(name, "SAVE attribute was already specified on '%s'"_warn_en_US,
5365         *pair.first, "Previous specification of SAVE attribute"_en_US);
5366   }
5367 }
5368 
5369 // Set the SAVE attribute on symbol unless it is implicitly saved anyway.
5370 void DeclarationVisitor::SetSaveAttr(Symbol &symbol) {
5371   if (!IsSaved(symbol)) {
5372     symbol.attrs().set(Attr::SAVE);
5373   }
5374 }
5375 
5376 // Check types of common block objects, now that they are known.
5377 void DeclarationVisitor::CheckCommonBlocks() {
5378   // check for empty common blocks
5379   for (const auto &pair : currScope().commonBlocks()) {
5380     const auto &symbol{*pair.second};
5381     if (symbol.get<CommonBlockDetails>().objects().empty() &&
5382         symbol.attrs().test(Attr::BIND_C)) {
5383       Say(symbol.name(),
5384           "'%s' appears as a COMMON block in a BIND statement but not in"
5385           " a COMMON statement"_err_en_US);
5386     }
5387   }
5388   // check objects in common blocks
5389   for (const auto &name : specPartState_.commonBlockObjects) {
5390     const auto *symbol{currScope().FindSymbol(name)};
5391     if (!symbol) {
5392       continue;
5393     }
5394     const auto &attrs{symbol->attrs()};
5395     if (attrs.test(Attr::ALLOCATABLE)) {
5396       Say(name,
5397           "ALLOCATABLE object '%s' may not appear in a COMMON block"_err_en_US);
5398     } else if (attrs.test(Attr::BIND_C)) {
5399       Say(name,
5400           "Variable '%s' with BIND attribute may not appear in a COMMON block"_err_en_US);
5401     } else if (IsNamedConstant(*symbol)) {
5402       Say(name,
5403           "A named constant '%s' may not appear in a COMMON block"_err_en_US);
5404     } else if (IsDummy(*symbol)) {
5405       Say(name,
5406           "Dummy argument '%s' may not appear in a COMMON block"_err_en_US);
5407     } else if (symbol->IsFuncResult()) {
5408       Say(name,
5409           "Function result '%s' may not appear in a COMMON block"_err_en_US);
5410     } else if (const DeclTypeSpec * type{symbol->GetType()}) {
5411       if (type->category() == DeclTypeSpec::ClassStar) {
5412         Say(name,
5413             "Unlimited polymorphic pointer '%s' may not appear in a COMMON block"_err_en_US);
5414       } else if (const auto *derived{type->AsDerived()}) {
5415         auto &typeSymbol{derived->typeSymbol()};
5416         if (!typeSymbol.attrs().test(Attr::BIND_C) &&
5417             !typeSymbol.get<DerivedTypeDetails>().sequence()) {
5418           Say(name,
5419               "Derived type '%s' in COMMON block must have the BIND or"
5420               " SEQUENCE attribute"_err_en_US);
5421         }
5422         CheckCommonBlockDerivedType(name, typeSymbol);
5423       }
5424     }
5425   }
5426   specPartState_.commonBlockObjects = {};
5427 }
5428 
5429 Symbol &DeclarationVisitor::MakeCommonBlockSymbol(const parser::Name &name) {
5430   return Resolve(name, currScope().MakeCommonBlock(name.source));
5431 }
5432 Symbol &DeclarationVisitor::MakeCommonBlockSymbol(
5433     const std::optional<parser::Name> &name) {
5434   if (name) {
5435     return MakeCommonBlockSymbol(*name);
5436   } else {
5437     return MakeCommonBlockSymbol(parser::Name{});
5438   }
5439 }
5440 
5441 bool DeclarationVisitor::NameIsKnownOrIntrinsic(const parser::Name &name) {
5442   return FindSymbol(name) || HandleUnrestrictedSpecificIntrinsicFunction(name);
5443 }
5444 
5445 // Check if this derived type can be in a COMMON block.
5446 void DeclarationVisitor::CheckCommonBlockDerivedType(
5447     const SourceName &name, const Symbol &typeSymbol) {
5448   if (const auto *scope{typeSymbol.scope()}) {
5449     for (const auto &pair : *scope) {
5450       const Symbol &component{*pair.second};
5451       if (component.attrs().test(Attr::ALLOCATABLE)) {
5452         Say2(name,
5453             "Derived type variable '%s' may not appear in a COMMON block"
5454             " due to ALLOCATABLE component"_err_en_US,
5455             component.name(), "Component with ALLOCATABLE attribute"_en_US);
5456         return;
5457       }
5458       const auto *details{component.detailsIf<ObjectEntityDetails>()};
5459       if (component.test(Symbol::Flag::InDataStmt) ||
5460           (details && details->init())) {
5461         Say2(name,
5462             "Derived type variable '%s' may not appear in a COMMON block due to component with default initialization"_err_en_US,
5463             component.name(), "Component with default initialization"_en_US);
5464         return;
5465       }
5466       if (details) {
5467         if (const auto *type{details->type()}) {
5468           if (const auto *derived{type->AsDerived()}) {
5469             CheckCommonBlockDerivedType(name, derived->typeSymbol());
5470           }
5471         }
5472       }
5473     }
5474   }
5475 }
5476 
5477 bool DeclarationVisitor::HandleUnrestrictedSpecificIntrinsicFunction(
5478     const parser::Name &name) {
5479   if (auto interface{context().intrinsics().IsSpecificIntrinsicFunction(
5480           name.source.ToString())}) {
5481     // Unrestricted specific intrinsic function names (e.g., "cos")
5482     // are acceptable as procedure interfaces.  The presence of the
5483     // INTRINSIC flag will cause this symbol to have a complete interface
5484     // recreated for it later on demand, but capturing its result type here
5485     // will make GetType() return a correct result without having to
5486     // probe the intrinsics table again.
5487     Symbol &symbol{
5488         MakeSymbol(InclusiveScope(), name.source, Attrs{Attr::INTRINSIC})};
5489     CHECK(interface->functionResult.has_value());
5490     evaluate::DynamicType dyType{
5491         DEREF(interface->functionResult->GetTypeAndShape()).type()};
5492     CHECK(common::IsNumericTypeCategory(dyType.category()));
5493     const DeclTypeSpec &typeSpec{
5494         MakeNumericType(dyType.category(), dyType.kind())};
5495     ProcEntityDetails details;
5496     ProcInterface procInterface;
5497     procInterface.set_type(typeSpec);
5498     details.set_interface(procInterface);
5499     symbol.set_details(std::move(details));
5500     symbol.set(Symbol::Flag::Function);
5501     if (interface->IsElemental()) {
5502       symbol.attrs().set(Attr::ELEMENTAL);
5503     }
5504     if (interface->IsPure()) {
5505       symbol.attrs().set(Attr::PURE);
5506     }
5507     Resolve(name, symbol);
5508     return true;
5509   } else {
5510     return false;
5511   }
5512 }
5513 
5514 // Checks for all locality-specs: LOCAL, LOCAL_INIT, and SHARED
5515 bool DeclarationVisitor::PassesSharedLocalityChecks(
5516     const parser::Name &name, Symbol &symbol) {
5517   if (!IsVariableName(symbol)) {
5518     SayLocalMustBeVariable(name, symbol); // C1124
5519     return false;
5520   }
5521   if (symbol.owner() == currScope()) { // C1125 and C1126
5522     SayAlreadyDeclared(name, symbol);
5523     return false;
5524   }
5525   return true;
5526 }
5527 
5528 // Checks for locality-specs LOCAL and LOCAL_INIT
5529 bool DeclarationVisitor::PassesLocalityChecks(
5530     const parser::Name &name, Symbol &symbol) {
5531   if (IsAllocatable(symbol)) { // C1128
5532     SayWithDecl(name, symbol,
5533         "ALLOCATABLE variable '%s' not allowed in a locality-spec"_err_en_US);
5534     return false;
5535   }
5536   if (IsOptional(symbol)) { // C1128
5537     SayWithDecl(name, symbol,
5538         "OPTIONAL argument '%s' not allowed in a locality-spec"_err_en_US);
5539     return false;
5540   }
5541   if (IsIntentIn(symbol)) { // C1128
5542     SayWithDecl(name, symbol,
5543         "INTENT IN argument '%s' not allowed in a locality-spec"_err_en_US);
5544     return false;
5545   }
5546   if (IsFinalizable(symbol)) { // C1128
5547     SayWithDecl(name, symbol,
5548         "Finalizable variable '%s' not allowed in a locality-spec"_err_en_US);
5549     return false;
5550   }
5551   if (evaluate::IsCoarray(symbol)) { // C1128
5552     SayWithDecl(
5553         name, symbol, "Coarray '%s' not allowed in a locality-spec"_err_en_US);
5554     return false;
5555   }
5556   if (const DeclTypeSpec * type{symbol.GetType()}) {
5557     if (type->IsPolymorphic() && IsDummy(symbol) &&
5558         !IsPointer(symbol)) { // C1128
5559       SayWithDecl(name, symbol,
5560           "Nonpointer polymorphic argument '%s' not allowed in a "
5561           "locality-spec"_err_en_US);
5562       return false;
5563     }
5564   }
5565   if (IsAssumedSizeArray(symbol)) { // C1128
5566     SayWithDecl(name, symbol,
5567         "Assumed size array '%s' not allowed in a locality-spec"_err_en_US);
5568     return false;
5569   }
5570   if (std::optional<Message> msg{WhyNotModifiable(symbol, currScope())}) {
5571     SayWithReason(name, symbol,
5572         "'%s' may not appear in a locality-spec because it is not "
5573         "definable"_err_en_US,
5574         std::move(*msg));
5575     return false;
5576   }
5577   return PassesSharedLocalityChecks(name, symbol);
5578 }
5579 
5580 Symbol &DeclarationVisitor::FindOrDeclareEnclosingEntity(
5581     const parser::Name &name) {
5582   Symbol *prev{FindSymbol(name)};
5583   if (!prev) {
5584     // Declare the name as an object in the enclosing scope so that
5585     // the name can't be repurposed there later as something else.
5586     prev = &MakeSymbol(InclusiveScope(), name.source, Attrs{});
5587     ConvertToObjectEntity(*prev);
5588     ApplyImplicitRules(*prev);
5589   }
5590   return *prev;
5591 }
5592 
5593 Symbol *DeclarationVisitor::DeclareLocalEntity(const parser::Name &name) {
5594   Symbol &prev{FindOrDeclareEnclosingEntity(name)};
5595   if (!PassesLocalityChecks(name, prev)) {
5596     return nullptr;
5597   }
5598   return &MakeHostAssocSymbol(name, prev);
5599 }
5600 
5601 Symbol *DeclarationVisitor::DeclareStatementEntity(
5602     const parser::DoVariable &doVar,
5603     const std::optional<parser::IntegerTypeSpec> &type) {
5604   const parser::Name &name{doVar.thing.thing};
5605   const DeclTypeSpec *declTypeSpec{nullptr};
5606   if (auto *prev{FindSymbol(name)}) {
5607     if (prev->owner() == currScope()) {
5608       SayAlreadyDeclared(name, *prev);
5609       return nullptr;
5610     }
5611     name.symbol = nullptr;
5612     declTypeSpec = prev->GetType();
5613   }
5614   Symbol &symbol{DeclareEntity<ObjectEntityDetails>(name, {})};
5615   if (!symbol.has<ObjectEntityDetails>()) {
5616     return nullptr; // error was reported in DeclareEntity
5617   }
5618   if (type) {
5619     declTypeSpec = ProcessTypeSpec(*type);
5620   }
5621   if (declTypeSpec) {
5622     // Subtlety: Don't let a "*length" specifier (if any is pending) affect the
5623     // declaration of this implied DO loop control variable.
5624     auto restorer{
5625         common::ScopedSet(charInfo_.length, std::optional<ParamValue>{})};
5626     SetType(name, *declTypeSpec);
5627   } else {
5628     ApplyImplicitRules(symbol);
5629   }
5630   Symbol *result{Resolve(name, &symbol)};
5631   AnalyzeExpr(context(), doVar); // enforce INTEGER type
5632   return result;
5633 }
5634 
5635 // Set the type of an entity or report an error.
5636 void DeclarationVisitor::SetType(
5637     const parser::Name &name, const DeclTypeSpec &type) {
5638   CHECK(name.symbol);
5639   auto &symbol{*name.symbol};
5640   if (charInfo_.length) { // Declaration has "*length" (R723)
5641     auto length{std::move(*charInfo_.length)};
5642     charInfo_.length.reset();
5643     if (type.category() == DeclTypeSpec::Character) {
5644       auto kind{type.characterTypeSpec().kind()};
5645       // Recurse with correct type.
5646       SetType(name,
5647           currScope().MakeCharacterType(std::move(length), std::move(kind)));
5648       return;
5649     } else { // C753
5650       Say(name,
5651           "A length specifier cannot be used to declare the non-character entity '%s'"_err_en_US);
5652     }
5653   }
5654   auto *prevType{symbol.GetType()};
5655   if (!prevType) {
5656     symbol.SetType(type);
5657   } else if (symbol.has<UseDetails>()) {
5658     // error recovery case, redeclaration of use-associated name
5659   } else if (HadForwardRef(symbol)) {
5660     // error recovery after use of host-associated name
5661   } else if (!symbol.test(Symbol::Flag::Implicit)) {
5662     SayWithDecl(
5663         name, symbol, "The type of '%s' has already been declared"_err_en_US);
5664     context().SetError(symbol);
5665   } else if (type != *prevType) {
5666     SayWithDecl(name, symbol,
5667         "The type of '%s' has already been implicitly declared"_err_en_US);
5668     context().SetError(symbol);
5669   } else {
5670     symbol.set(Symbol::Flag::Implicit, false);
5671   }
5672 }
5673 
5674 std::optional<DerivedTypeSpec> DeclarationVisitor::ResolveDerivedType(
5675     const parser::Name &name) {
5676   Scope &outer{NonDerivedTypeScope()};
5677   Symbol *symbol{FindSymbol(outer, name)};
5678   Symbol *ultimate{symbol ? &symbol->GetUltimate() : nullptr};
5679   auto *generic{ultimate ? ultimate->detailsIf<GenericDetails>() : nullptr};
5680   if (generic) {
5681     if (Symbol * genDT{generic->derivedType()}) {
5682       symbol = genDT;
5683       generic = nullptr;
5684     }
5685   }
5686   if (!symbol || symbol->has<UnknownDetails>() ||
5687       (generic && &ultimate->owner() == &outer)) {
5688     if (allowForwardReferenceToDerivedType()) {
5689       if (!symbol) {
5690         symbol = &MakeSymbol(outer, name.source, Attrs{});
5691         Resolve(name, *symbol);
5692       } else if (generic) {
5693         // forward ref to type with later homonymous generic
5694         symbol = &outer.MakeSymbol(name.source, Attrs{}, UnknownDetails{});
5695         generic->set_derivedType(*symbol);
5696         name.symbol = symbol;
5697       }
5698       DerivedTypeDetails details;
5699       details.set_isForwardReferenced(true);
5700       symbol->set_details(std::move(details));
5701     } else { // C732
5702       Say(name, "Derived type '%s' not found"_err_en_US);
5703       return std::nullopt;
5704     }
5705   }
5706   if (CheckUseError(name)) {
5707     return std::nullopt;
5708   }
5709   symbol = &symbol->GetUltimate();
5710   if (symbol->has<DerivedTypeDetails>()) {
5711     return DerivedTypeSpec{name.source, *symbol};
5712   } else {
5713     Say(name, "'%s' is not a derived type"_err_en_US);
5714     return std::nullopt;
5715   }
5716 }
5717 
5718 std::optional<DerivedTypeSpec> DeclarationVisitor::ResolveExtendsType(
5719     const parser::Name &typeName, const parser::Name *extendsName) {
5720   if (!extendsName) {
5721     return std::nullopt;
5722   } else if (typeName.source == extendsName->source) {
5723     Say(extendsName->source,
5724         "Derived type '%s' cannot extend itself"_err_en_US);
5725     return std::nullopt;
5726   } else {
5727     return ResolveDerivedType(*extendsName);
5728   }
5729 }
5730 
5731 Symbol *DeclarationVisitor::NoteInterfaceName(const parser::Name &name) {
5732   // The symbol is checked later by CheckExplicitInterface() and
5733   // CheckBindings().  It can be a forward reference.
5734   if (!NameIsKnownOrIntrinsic(name)) {
5735     Symbol &symbol{MakeSymbol(InclusiveScope(), name.source, Attrs{})};
5736     Resolve(name, symbol);
5737   }
5738   return name.symbol;
5739 }
5740 
5741 void DeclarationVisitor::CheckExplicitInterface(const parser::Name &name) {
5742   if (const Symbol * symbol{name.symbol}) {
5743     if (!context().HasError(*symbol) && !symbol->HasExplicitInterface()) {
5744       Say(name,
5745           "'%s' must be an abstract interface or a procedure with "
5746           "an explicit interface"_err_en_US,
5747           symbol->name());
5748     }
5749   }
5750 }
5751 
5752 // Create a symbol for a type parameter, component, or procedure binding in
5753 // the current derived type scope. Return false on error.
5754 Symbol *DeclarationVisitor::MakeTypeSymbol(
5755     const parser::Name &name, Details &&details) {
5756   return Resolve(name, MakeTypeSymbol(name.source, std::move(details)));
5757 }
5758 Symbol *DeclarationVisitor::MakeTypeSymbol(
5759     const SourceName &name, Details &&details) {
5760   Scope &derivedType{currScope()};
5761   CHECK(derivedType.IsDerivedType());
5762   if (auto *symbol{FindInScope(derivedType, name)}) { // C742
5763     Say2(name,
5764         "Type parameter, component, or procedure binding '%s'"
5765         " already defined in this type"_err_en_US,
5766         *symbol, "Previous definition of '%s'"_en_US);
5767     return nullptr;
5768   } else {
5769     auto attrs{GetAttrs()};
5770     // Apply binding-private-stmt if present and this is a procedure binding
5771     if (derivedTypeInfo_.privateBindings &&
5772         !attrs.HasAny({Attr::PUBLIC, Attr::PRIVATE}) &&
5773         std::holds_alternative<ProcBindingDetails>(details)) {
5774       attrs.set(Attr::PRIVATE);
5775     }
5776     Symbol &result{MakeSymbol(name, attrs, std::move(details))};
5777     if (result.has<TypeParamDetails>()) {
5778       derivedType.symbol()->get<DerivedTypeDetails>().add_paramDecl(result);
5779     }
5780     return &result;
5781   }
5782 }
5783 
5784 // Return true if it is ok to declare this component in the current scope.
5785 // Otherwise, emit an error and return false.
5786 bool DeclarationVisitor::OkToAddComponent(
5787     const parser::Name &name, const Symbol *extends) {
5788   for (const Scope *scope{&currScope()}; scope;) {
5789     CHECK(scope->IsDerivedType());
5790     if (auto *prev{FindInScope(*scope, name)}) {
5791       if (!context().HasError(*prev)) {
5792         parser::MessageFixedText msg;
5793         if (extends) {
5794           msg = "Type cannot be extended as it has a component named"
5795                 " '%s'"_err_en_US;
5796         } else if (prev->test(Symbol::Flag::ParentComp)) {
5797           msg = "'%s' is a parent type of this type and so cannot be"
5798                 " a component"_err_en_US;
5799         } else if (scope != &currScope()) {
5800           msg = "Component '%s' is already declared in a parent of this"
5801                 " derived type"_err_en_US;
5802         } else {
5803           msg = "Component '%s' is already declared in this"
5804                 " derived type"_err_en_US;
5805         }
5806         Say2(name, std::move(msg), *prev, "Previous declaration of '%s'"_en_US);
5807       }
5808       return false;
5809     }
5810     if (scope == &currScope() && extends) {
5811       // The parent component has not yet been added to the scope.
5812       scope = extends->scope();
5813     } else {
5814       scope = scope->GetDerivedTypeParent();
5815     }
5816   }
5817   return true;
5818 }
5819 
5820 ParamValue DeclarationVisitor::GetParamValue(
5821     const parser::TypeParamValue &x, common::TypeParamAttr attr) {
5822   return common::visit(
5823       common::visitors{
5824           [=](const parser::ScalarIntExpr &x) { // C704
5825             return ParamValue{EvaluateIntExpr(x), attr};
5826           },
5827           [=](const parser::Star &) { return ParamValue::Assumed(attr); },
5828           [=](const parser::TypeParamValue::Deferred &) {
5829             return ParamValue::Deferred(attr);
5830           },
5831       },
5832       x.u);
5833 }
5834 
5835 // ConstructVisitor implementation
5836 
5837 void ConstructVisitor::ResolveIndexName(
5838     const parser::ConcurrentControl &control) {
5839   const parser::Name &name{std::get<parser::Name>(control.t)};
5840   auto *prev{FindSymbol(name)};
5841   if (prev) {
5842     if (prev->owner().kind() == Scope::Kind::Forall ||
5843         prev->owner() == currScope()) {
5844       SayAlreadyDeclared(name, *prev);
5845       return;
5846     }
5847     name.symbol = nullptr;
5848   }
5849   auto &symbol{DeclareObjectEntity(name)};
5850   if (symbol.GetType()) {
5851     // type came from explicit type-spec
5852   } else if (!prev) {
5853     ApplyImplicitRules(symbol);
5854   } else {
5855     const Symbol &prevRoot{ResolveAssociations(*prev)};
5856     // prev could be host- use- or construct-associated with another symbol
5857     if (!prevRoot.has<ObjectEntityDetails>() &&
5858         !prevRoot.has<EntityDetails>()) {
5859       Say2(name, "Index name '%s' conflicts with existing identifier"_err_en_US,
5860           *prev, "Previous declaration of '%s'"_en_US);
5861       context().SetError(symbol);
5862       return;
5863     } else {
5864       if (const auto *type{prevRoot.GetType()}) {
5865         symbol.SetType(*type);
5866       }
5867       if (prevRoot.IsObjectArray()) {
5868         SayWithDecl(name, *prev, "Index variable '%s' is not scalar"_err_en_US);
5869         return;
5870       }
5871     }
5872   }
5873   EvaluateExpr(parser::Scalar{parser::Integer{common::Clone(name)}});
5874 }
5875 
5876 // We need to make sure that all of the index-names get declared before the
5877 // expressions in the loop control are evaluated so that references to the
5878 // index-names in the expressions are correctly detected.
5879 bool ConstructVisitor::Pre(const parser::ConcurrentHeader &header) {
5880   BeginDeclTypeSpec();
5881   Walk(std::get<std::optional<parser::IntegerTypeSpec>>(header.t));
5882   const auto &controls{
5883       std::get<std::list<parser::ConcurrentControl>>(header.t)};
5884   for (const auto &control : controls) {
5885     ResolveIndexName(control);
5886   }
5887   Walk(controls);
5888   Walk(std::get<std::optional<parser::ScalarLogicalExpr>>(header.t));
5889   EndDeclTypeSpec();
5890   return false;
5891 }
5892 
5893 bool ConstructVisitor::Pre(const parser::LocalitySpec::Local &x) {
5894   for (auto &name : x.v) {
5895     if (auto *symbol{DeclareLocalEntity(name)}) {
5896       symbol->set(Symbol::Flag::LocalityLocal);
5897     }
5898   }
5899   return false;
5900 }
5901 
5902 bool ConstructVisitor::Pre(const parser::LocalitySpec::LocalInit &x) {
5903   for (auto &name : x.v) {
5904     if (auto *symbol{DeclareLocalEntity(name)}) {
5905       symbol->set(Symbol::Flag::LocalityLocalInit);
5906     }
5907   }
5908   return false;
5909 }
5910 
5911 bool ConstructVisitor::Pre(const parser::LocalitySpec::Shared &x) {
5912   for (const auto &name : x.v) {
5913     if (!FindSymbol(name)) {
5914       Say(name,
5915           "Variable '%s' with SHARED locality implicitly declared"_warn_en_US);
5916     }
5917     Symbol &prev{FindOrDeclareEnclosingEntity(name)};
5918     if (PassesSharedLocalityChecks(name, prev)) {
5919       MakeHostAssocSymbol(name, prev).set(Symbol::Flag::LocalityShared);
5920     }
5921   }
5922   return false;
5923 }
5924 
5925 bool ConstructVisitor::Pre(const parser::AcSpec &x) {
5926   ProcessTypeSpec(x.type);
5927   Walk(x.values);
5928   return false;
5929 }
5930 
5931 // Section 19.4, paragraph 5 says that each ac-do-variable has the scope of the
5932 // enclosing ac-implied-do
5933 bool ConstructVisitor::Pre(const parser::AcImpliedDo &x) {
5934   auto &values{std::get<std::list<parser::AcValue>>(x.t)};
5935   auto &control{std::get<parser::AcImpliedDoControl>(x.t)};
5936   auto &type{std::get<std::optional<parser::IntegerTypeSpec>>(control.t)};
5937   auto &bounds{std::get<parser::AcImpliedDoControl::Bounds>(control.t)};
5938   // F'2018 has the scope of the implied DO variable covering the entire
5939   // implied DO production (19.4(5)), which seems wrong in cases where the name
5940   // of the implied DO variable appears in one of the bound expressions. Thus
5941   // this extension, which shrinks the scope of the variable to exclude the
5942   // expressions in the bounds.
5943   auto restore{BeginCheckOnIndexUseInOwnBounds(bounds.name)};
5944   Walk(bounds.lower);
5945   Walk(bounds.upper);
5946   Walk(bounds.step);
5947   EndCheckOnIndexUseInOwnBounds(restore);
5948   PushScope(Scope::Kind::ImpliedDos, nullptr);
5949   DeclareStatementEntity(bounds.name, type);
5950   Walk(values);
5951   PopScope();
5952   return false;
5953 }
5954 
5955 bool ConstructVisitor::Pre(const parser::DataImpliedDo &x) {
5956   auto &objects{std::get<std::list<parser::DataIDoObject>>(x.t)};
5957   auto &type{std::get<std::optional<parser::IntegerTypeSpec>>(x.t)};
5958   auto &bounds{std::get<parser::DataImpliedDo::Bounds>(x.t)};
5959   // See comment in Pre(AcImpliedDo) above.
5960   auto restore{BeginCheckOnIndexUseInOwnBounds(bounds.name)};
5961   Walk(bounds.lower);
5962   Walk(bounds.upper);
5963   Walk(bounds.step);
5964   EndCheckOnIndexUseInOwnBounds(restore);
5965   bool pushScope{currScope().kind() != Scope::Kind::ImpliedDos};
5966   if (pushScope) {
5967     PushScope(Scope::Kind::ImpliedDos, nullptr);
5968   }
5969   DeclareStatementEntity(bounds.name, type);
5970   Walk(objects);
5971   if (pushScope) {
5972     PopScope();
5973   }
5974   return false;
5975 }
5976 
5977 // Sets InDataStmt flag on a variable (or misidentified function) in a DATA
5978 // statement so that the predicate IsInitialized() will be true
5979 // during semantic analysis before the symbol's initializer is constructed.
5980 bool ConstructVisitor::Pre(const parser::DataIDoObject &x) {
5981   common::visit(
5982       common::visitors{
5983           [&](const parser::Scalar<Indirection<parser::Designator>> &y) {
5984             Walk(y.thing.value());
5985             const parser::Name &first{parser::GetFirstName(y.thing.value())};
5986             if (first.symbol) {
5987               first.symbol->set(Symbol::Flag::InDataStmt);
5988             }
5989           },
5990           [&](const Indirection<parser::DataImpliedDo> &y) { Walk(y.value()); },
5991       },
5992       x.u);
5993   return false;
5994 }
5995 
5996 bool ConstructVisitor::Pre(const parser::DataStmtObject &x) {
5997   // Subtle: DATA statements may appear in both the specification and
5998   // execution parts, but should be treated as if in the execution part
5999   // for purposes of implicit variable declaration vs. host association.
6000   // When a name first appears as an object in a DATA statement, it should
6001   // be implicitly declared locally as if it had been assigned.
6002   auto flagRestorer{common::ScopedSet(inSpecificationPart_, false)};
6003   common::visit(common::visitors{
6004                     [&](const Indirection<parser::Variable> &y) {
6005                       Walk(y.value());
6006                       const parser::Name &first{
6007                           parser::GetFirstName(y.value())};
6008                       if (first.symbol) {
6009                         first.symbol->set(Symbol::Flag::InDataStmt);
6010                       }
6011                     },
6012                     [&](const parser::DataImpliedDo &y) {
6013                       PushScope(Scope::Kind::ImpliedDos, nullptr);
6014                       Walk(y);
6015                       PopScope();
6016                     },
6017                 },
6018       x.u);
6019   return false;
6020 }
6021 
6022 bool ConstructVisitor::Pre(const parser::DataStmtValue &x) {
6023   const auto &data{std::get<parser::DataStmtConstant>(x.t)};
6024   auto &mutableData{const_cast<parser::DataStmtConstant &>(data)};
6025   if (auto *elem{parser::Unwrap<parser::ArrayElement>(mutableData)}) {
6026     if (const auto *name{std::get_if<parser::Name>(&elem->base.u)}) {
6027       if (const Symbol * symbol{FindSymbol(*name)}) {
6028         const Symbol &ultimate{symbol->GetUltimate()};
6029         if (ultimate.has<DerivedTypeDetails>()) {
6030           mutableData.u = elem->ConvertToStructureConstructor(
6031               DerivedTypeSpec{name->source, ultimate});
6032         }
6033       }
6034     }
6035   }
6036   return true;
6037 }
6038 
6039 bool ConstructVisitor::Pre(const parser::DoConstruct &x) {
6040   if (x.IsDoConcurrent()) {
6041     PushScope(Scope::Kind::Block, nullptr);
6042   }
6043   return true;
6044 }
6045 void ConstructVisitor::Post(const parser::DoConstruct &x) {
6046   if (x.IsDoConcurrent()) {
6047     PopScope();
6048   }
6049 }
6050 
6051 bool ConstructVisitor::Pre(const parser::ForallConstruct &) {
6052   PushScope(Scope::Kind::Forall, nullptr);
6053   return true;
6054 }
6055 void ConstructVisitor::Post(const parser::ForallConstruct &) { PopScope(); }
6056 bool ConstructVisitor::Pre(const parser::ForallStmt &) {
6057   PushScope(Scope::Kind::Forall, nullptr);
6058   return true;
6059 }
6060 void ConstructVisitor::Post(const parser::ForallStmt &) { PopScope(); }
6061 
6062 bool ConstructVisitor::Pre(const parser::BlockStmt &x) {
6063   CheckDef(x.v);
6064   PushScope(Scope::Kind::Block, nullptr);
6065   return false;
6066 }
6067 bool ConstructVisitor::Pre(const parser::EndBlockStmt &x) {
6068   PopScope();
6069   CheckRef(x.v);
6070   return false;
6071 }
6072 
6073 void ConstructVisitor::Post(const parser::Selector &x) {
6074   GetCurrentAssociation().selector = ResolveSelector(x);
6075 }
6076 
6077 void ConstructVisitor::Post(const parser::AssociateStmt &x) {
6078   CheckDef(x.t);
6079   PushScope(Scope::Kind::Block, nullptr);
6080   const auto assocCount{std::get<std::list<parser::Association>>(x.t).size()};
6081   for (auto nthLastAssoc{assocCount}; nthLastAssoc > 0; --nthLastAssoc) {
6082     SetCurrentAssociation(nthLastAssoc);
6083     if (auto *symbol{MakeAssocEntity()}) {
6084       if (ExtractCoarrayRef(GetCurrentAssociation().selector.expr)) { // C1103
6085         Say("Selector must not be a coindexed object"_err_en_US);
6086       }
6087       SetTypeFromAssociation(*symbol);
6088       SetAttrsFromAssociation(*symbol);
6089     }
6090   }
6091   PopAssociation(assocCount);
6092 }
6093 
6094 void ConstructVisitor::Post(const parser::EndAssociateStmt &x) {
6095   PopScope();
6096   CheckRef(x.v);
6097 }
6098 
6099 bool ConstructVisitor::Pre(const parser::Association &x) {
6100   PushAssociation();
6101   const auto &name{std::get<parser::Name>(x.t)};
6102   GetCurrentAssociation().name = &name;
6103   return true;
6104 }
6105 
6106 bool ConstructVisitor::Pre(const parser::ChangeTeamStmt &x) {
6107   CheckDef(x.t);
6108   PushScope(Scope::Kind::Block, nullptr);
6109   PushAssociation();
6110   return true;
6111 }
6112 
6113 void ConstructVisitor::Post(const parser::CoarrayAssociation &x) {
6114   const auto &decl{std::get<parser::CodimensionDecl>(x.t)};
6115   const auto &name{std::get<parser::Name>(decl.t)};
6116   if (auto *symbol{FindInScope(name)}) {
6117     const auto &selector{std::get<parser::Selector>(x.t)};
6118     if (auto sel{ResolveSelector(selector)}) {
6119       const Symbol *whole{UnwrapWholeSymbolDataRef(sel.expr)};
6120       if (!whole || whole->Corank() == 0) {
6121         Say(sel.source, // C1116
6122             "Selector in coarray association must name a coarray"_err_en_US);
6123       } else if (auto dynType{sel.expr->GetType()}) {
6124         if (!symbol->GetType()) {
6125           symbol->SetType(ToDeclTypeSpec(std::move(*dynType)));
6126         }
6127       }
6128     }
6129   }
6130 }
6131 
6132 void ConstructVisitor::Post(const parser::EndChangeTeamStmt &x) {
6133   PopAssociation();
6134   PopScope();
6135   CheckRef(x.t);
6136 }
6137 
6138 bool ConstructVisitor::Pre(const parser::SelectTypeConstruct &) {
6139   PushAssociation();
6140   return true;
6141 }
6142 
6143 void ConstructVisitor::Post(const parser::SelectTypeConstruct &) {
6144   PopAssociation();
6145 }
6146 
6147 void ConstructVisitor::Post(const parser::SelectTypeStmt &x) {
6148   auto &association{GetCurrentAssociation()};
6149   if (const std::optional<parser::Name> &name{std::get<1>(x.t)}) {
6150     // This isn't a name in the current scope, it is in each TypeGuardStmt
6151     MakePlaceholder(*name, MiscDetails::Kind::SelectTypeAssociateName);
6152     association.name = &*name;
6153     auto exprType{association.selector.expr->GetType()};
6154     if (ExtractCoarrayRef(association.selector.expr)) { // C1103
6155       Say("Selector must not be a coindexed object"_err_en_US);
6156     }
6157     if (exprType && !exprType->IsPolymorphic()) { // C1159
6158       Say(association.selector.source,
6159           "Selector '%s' in SELECT TYPE statement must be "
6160           "polymorphic"_err_en_US);
6161     }
6162   } else {
6163     if (const Symbol *
6164         whole{UnwrapWholeSymbolDataRef(association.selector.expr)}) {
6165       ConvertToObjectEntity(const_cast<Symbol &>(*whole));
6166       if (!IsVariableName(*whole)) {
6167         Say(association.selector.source, // C901
6168             "Selector is not a variable"_err_en_US);
6169         association = {};
6170       }
6171       if (const DeclTypeSpec * type{whole->GetType()}) {
6172         if (!type->IsPolymorphic()) { // C1159
6173           Say(association.selector.source,
6174               "Selector '%s' in SELECT TYPE statement must be "
6175               "polymorphic"_err_en_US);
6176         }
6177       }
6178     } else {
6179       Say(association.selector.source, // C1157
6180           "Selector is not a named variable: 'associate-name =>' is required"_err_en_US);
6181       association = {};
6182     }
6183   }
6184 }
6185 
6186 void ConstructVisitor::Post(const parser::SelectRankStmt &x) {
6187   auto &association{GetCurrentAssociation()};
6188   if (const std::optional<parser::Name> &name{std::get<1>(x.t)}) {
6189     // This isn't a name in the current scope, it is in each SelectRankCaseStmt
6190     MakePlaceholder(*name, MiscDetails::Kind::SelectRankAssociateName);
6191     association.name = &*name;
6192   }
6193 }
6194 
6195 bool ConstructVisitor::Pre(const parser::SelectTypeConstruct::TypeCase &) {
6196   PushScope(Scope::Kind::Block, nullptr);
6197   return true;
6198 }
6199 void ConstructVisitor::Post(const parser::SelectTypeConstruct::TypeCase &) {
6200   PopScope();
6201 }
6202 
6203 bool ConstructVisitor::Pre(const parser::SelectRankConstruct::RankCase &) {
6204   PushScope(Scope::Kind::Block, nullptr);
6205   return true;
6206 }
6207 void ConstructVisitor::Post(const parser::SelectRankConstruct::RankCase &) {
6208   PopScope();
6209 }
6210 
6211 void ConstructVisitor::Post(const parser::TypeGuardStmt::Guard &x) {
6212   if (auto *symbol{MakeAssocEntity()}) {
6213     if (std::holds_alternative<parser::Default>(x.u)) {
6214       SetTypeFromAssociation(*symbol);
6215     } else if (const auto *type{GetDeclTypeSpec()}) {
6216       symbol->SetType(*type);
6217     }
6218     SetAttrsFromAssociation(*symbol);
6219   }
6220 }
6221 
6222 void ConstructVisitor::Post(const parser::SelectRankCaseStmt::Rank &x) {
6223   if (auto *symbol{MakeAssocEntity()}) {
6224     SetTypeFromAssociation(*symbol);
6225     SetAttrsFromAssociation(*symbol);
6226     if (const auto *init{std::get_if<parser::ScalarIntConstantExpr>(&x.u)}) {
6227       if (auto val{EvaluateInt64(context(), *init)}) {
6228         auto &details{symbol->get<AssocEntityDetails>()};
6229         details.set_rank(*val);
6230       }
6231     }
6232   }
6233 }
6234 
6235 bool ConstructVisitor::Pre(const parser::SelectRankConstruct &) {
6236   PushAssociation();
6237   return true;
6238 }
6239 
6240 void ConstructVisitor::Post(const parser::SelectRankConstruct &) {
6241   PopAssociation();
6242 }
6243 
6244 bool ConstructVisitor::CheckDef(const std::optional<parser::Name> &x) {
6245   if (x) {
6246     MakeSymbol(*x, MiscDetails{MiscDetails::Kind::ConstructName});
6247   }
6248   return true;
6249 }
6250 
6251 void ConstructVisitor::CheckRef(const std::optional<parser::Name> &x) {
6252   if (x) {
6253     // Just add an occurrence of this name; checking is done in ValidateLabels
6254     FindSymbol(*x);
6255   }
6256 }
6257 
6258 // Make a symbol for the associating entity of the current association.
6259 Symbol *ConstructVisitor::MakeAssocEntity() {
6260   Symbol *symbol{nullptr};
6261   auto &association{GetCurrentAssociation()};
6262   if (association.name) {
6263     symbol = &MakeSymbol(*association.name, UnknownDetails{});
6264     if (symbol->has<AssocEntityDetails>() && symbol->owner() == currScope()) {
6265       Say(*association.name, // C1102
6266           "The associate name '%s' is already used in this associate statement"_err_en_US);
6267       return nullptr;
6268     }
6269   } else if (const Symbol *
6270       whole{UnwrapWholeSymbolDataRef(association.selector.expr)}) {
6271     symbol = &MakeSymbol(whole->name());
6272   } else {
6273     return nullptr;
6274   }
6275   if (auto &expr{association.selector.expr}) {
6276     symbol->set_details(AssocEntityDetails{common::Clone(*expr)});
6277   } else {
6278     symbol->set_details(AssocEntityDetails{});
6279   }
6280   return symbol;
6281 }
6282 
6283 // Set the type of symbol based on the current association selector.
6284 void ConstructVisitor::SetTypeFromAssociation(Symbol &symbol) {
6285   auto &details{symbol.get<AssocEntityDetails>()};
6286   const MaybeExpr *pexpr{&details.expr()};
6287   if (!*pexpr) {
6288     pexpr = &GetCurrentAssociation().selector.expr;
6289   }
6290   if (*pexpr) {
6291     const SomeExpr &expr{**pexpr};
6292     if (std::optional<evaluate::DynamicType> type{expr.GetType()}) {
6293       if (const auto *charExpr{
6294               evaluate::UnwrapExpr<evaluate::Expr<evaluate::SomeCharacter>>(
6295                   expr)}) {
6296         symbol.SetType(ToDeclTypeSpec(std::move(*type),
6297             FoldExpr(common::visit(
6298                 [](const auto &kindChar) { return kindChar.LEN(); },
6299                 charExpr->u))));
6300       } else {
6301         symbol.SetType(ToDeclTypeSpec(std::move(*type)));
6302       }
6303     } else {
6304       // BOZ literals, procedure designators, &c. are not acceptable
6305       Say(symbol.name(), "Associate name '%s' must have a type"_err_en_US);
6306     }
6307   }
6308 }
6309 
6310 // If current selector is a variable, set some of its attributes on symbol.
6311 void ConstructVisitor::SetAttrsFromAssociation(Symbol &symbol) {
6312   Attrs attrs{evaluate::GetAttrs(GetCurrentAssociation().selector.expr)};
6313   symbol.attrs() |= attrs &
6314       Attrs{Attr::TARGET, Attr::ASYNCHRONOUS, Attr::VOLATILE, Attr::CONTIGUOUS};
6315   if (attrs.test(Attr::POINTER)) {
6316     symbol.attrs().set(Attr::TARGET);
6317   }
6318 }
6319 
6320 ConstructVisitor::Selector ConstructVisitor::ResolveSelector(
6321     const parser::Selector &x) {
6322   return common::visit(common::visitors{
6323                            [&](const parser::Expr &expr) {
6324                              return Selector{expr.source, EvaluateExpr(x)};
6325                            },
6326                            [&](const parser::Variable &var) {
6327                              return Selector{var.GetSource(), EvaluateExpr(x)};
6328                            },
6329                        },
6330       x.u);
6331 }
6332 
6333 // Set the current association to the nth to the last association on the
6334 // association stack.  The top of the stack is at n = 1.  This allows access
6335 // to the interior of a list of associations at the top of the stack.
6336 void ConstructVisitor::SetCurrentAssociation(std::size_t n) {
6337   CHECK(n > 0 && n <= associationStack_.size());
6338   currentAssociation_ = &associationStack_[associationStack_.size() - n];
6339 }
6340 
6341 ConstructVisitor::Association &ConstructVisitor::GetCurrentAssociation() {
6342   CHECK(currentAssociation_);
6343   return *currentAssociation_;
6344 }
6345 
6346 void ConstructVisitor::PushAssociation() {
6347   associationStack_.emplace_back(Association{});
6348   currentAssociation_ = &associationStack_.back();
6349 }
6350 
6351 void ConstructVisitor::PopAssociation(std::size_t count) {
6352   CHECK(count > 0 && count <= associationStack_.size());
6353   associationStack_.resize(associationStack_.size() - count);
6354   currentAssociation_ =
6355       associationStack_.empty() ? nullptr : &associationStack_.back();
6356 }
6357 
6358 const DeclTypeSpec &ConstructVisitor::ToDeclTypeSpec(
6359     evaluate::DynamicType &&type) {
6360   switch (type.category()) {
6361     SWITCH_COVERS_ALL_CASES
6362   case common::TypeCategory::Integer:
6363   case common::TypeCategory::Real:
6364   case common::TypeCategory::Complex:
6365     return context().MakeNumericType(type.category(), type.kind());
6366   case common::TypeCategory::Logical:
6367     return context().MakeLogicalType(type.kind());
6368   case common::TypeCategory::Derived:
6369     if (type.IsAssumedType()) {
6370       return currScope().MakeTypeStarType();
6371     } else if (type.IsUnlimitedPolymorphic()) {
6372       return currScope().MakeClassStarType();
6373     } else {
6374       return currScope().MakeDerivedType(
6375           type.IsPolymorphic() ? DeclTypeSpec::ClassDerived
6376                                : DeclTypeSpec::TypeDerived,
6377           common::Clone(type.GetDerivedTypeSpec())
6378 
6379       );
6380     }
6381   case common::TypeCategory::Character:
6382     CRASH_NO_CASE;
6383   }
6384 }
6385 
6386 const DeclTypeSpec &ConstructVisitor::ToDeclTypeSpec(
6387     evaluate::DynamicType &&type, MaybeSubscriptIntExpr &&length) {
6388   CHECK(type.category() == common::TypeCategory::Character);
6389   if (length) {
6390     return currScope().MakeCharacterType(
6391         ParamValue{SomeIntExpr{*std::move(length)}, common::TypeParamAttr::Len},
6392         KindExpr{type.kind()});
6393   } else {
6394     return currScope().MakeCharacterType(
6395         ParamValue::Deferred(common::TypeParamAttr::Len),
6396         KindExpr{type.kind()});
6397   }
6398 }
6399 
6400 // ResolveNamesVisitor implementation
6401 
6402 bool ResolveNamesVisitor::Pre(const parser::FunctionReference &x) {
6403   HandleCall(Symbol::Flag::Function, x.v);
6404   return false;
6405 }
6406 bool ResolveNamesVisitor::Pre(const parser::CallStmt &x) {
6407   HandleCall(Symbol::Flag::Subroutine, x.v);
6408   return false;
6409 }
6410 
6411 bool ResolveNamesVisitor::Pre(const parser::ImportStmt &x) {
6412   auto &scope{currScope()};
6413   // Check C896 and C899: where IMPORT statements are allowed
6414   switch (scope.kind()) {
6415   case Scope::Kind::Module:
6416     if (scope.IsModule()) {
6417       Say("IMPORT is not allowed in a module scoping unit"_err_en_US);
6418       return false;
6419     } else if (x.kind == common::ImportKind::None) {
6420       Say("IMPORT,NONE is not allowed in a submodule scoping unit"_err_en_US);
6421       return false;
6422     }
6423     break;
6424   case Scope::Kind::MainProgram:
6425     Say("IMPORT is not allowed in a main program scoping unit"_err_en_US);
6426     return false;
6427   case Scope::Kind::Subprogram:
6428     if (scope.parent().IsGlobal()) {
6429       Say("IMPORT is not allowed in an external subprogram scoping unit"_err_en_US);
6430       return false;
6431     }
6432     break;
6433   case Scope::Kind::BlockData: // C1415 (in part)
6434     Say("IMPORT is not allowed in a BLOCK DATA subprogram"_err_en_US);
6435     return false;
6436   default:;
6437   }
6438   if (auto error{scope.SetImportKind(x.kind)}) {
6439     Say(std::move(*error));
6440   }
6441   for (auto &name : x.names) {
6442     if (FindSymbol(scope.parent(), name)) {
6443       scope.add_importName(name.source);
6444     } else {
6445       Say(name, "'%s' not found in host scope"_err_en_US);
6446     }
6447   }
6448   prevImportStmt_ = currStmtSource();
6449   return false;
6450 }
6451 
6452 const parser::Name *DeclarationVisitor::ResolveStructureComponent(
6453     const parser::StructureComponent &x) {
6454   return FindComponent(ResolveDataRef(x.base), x.component);
6455 }
6456 
6457 const parser::Name *DeclarationVisitor::ResolveDesignator(
6458     const parser::Designator &x) {
6459   return common::visit(
6460       common::visitors{
6461           [&](const parser::DataRef &x) { return ResolveDataRef(x); },
6462           [&](const parser::Substring &x) {
6463             return ResolveDataRef(std::get<parser::DataRef>(x.t));
6464           },
6465       },
6466       x.u);
6467 }
6468 
6469 const parser::Name *DeclarationVisitor::ResolveDataRef(
6470     const parser::DataRef &x) {
6471   return common::visit(
6472       common::visitors{
6473           [=](const parser::Name &y) { return ResolveName(y); },
6474           [=](const Indirection<parser::StructureComponent> &y) {
6475             return ResolveStructureComponent(y.value());
6476           },
6477           [&](const Indirection<parser::ArrayElement> &y) {
6478             Walk(y.value().subscripts);
6479             const parser::Name *name{ResolveDataRef(y.value().base)};
6480             if (name && name->symbol) {
6481               if (!IsProcedure(*name->symbol)) {
6482                 ConvertToObjectEntity(*name->symbol);
6483               } else if (!context().HasError(*name->symbol)) {
6484                 SayWithDecl(*name, *name->symbol,
6485                     "Cannot reference function '%s' as data"_err_en_US);
6486               }
6487             }
6488             return name;
6489           },
6490           [&](const Indirection<parser::CoindexedNamedObject> &y) {
6491             Walk(y.value().imageSelector);
6492             return ResolveDataRef(y.value().base);
6493           },
6494       },
6495       x.u);
6496 }
6497 
6498 // If implicit types are allowed, ensure name is in the symbol table.
6499 // Otherwise, report an error if it hasn't been declared.
6500 const parser::Name *DeclarationVisitor::ResolveName(const parser::Name &name) {
6501   FindSymbol(name);
6502   if (CheckForHostAssociatedImplicit(name)) {
6503     NotePossibleBadForwardRef(name);
6504     return &name;
6505   }
6506   if (Symbol * symbol{name.symbol}) {
6507     if (CheckUseError(name)) {
6508       return nullptr; // reported an error
6509     }
6510     NotePossibleBadForwardRef(name);
6511     symbol->set(Symbol::Flag::ImplicitOrError, false);
6512     if (IsUplevelReference(*symbol)) {
6513       MakeHostAssocSymbol(name, *symbol);
6514     } else if (IsDummy(*symbol) ||
6515         (!symbol->GetType() && FindCommonBlockContaining(*symbol))) {
6516       ConvertToObjectEntity(*symbol);
6517       ApplyImplicitRules(*symbol);
6518     }
6519     if (checkIndexUseInOwnBounds_ &&
6520         *checkIndexUseInOwnBounds_ == name.source) {
6521       Say(name,
6522           "Implied DO index '%s' uses an object of the same name in its bounds expressions"_port_en_US,
6523           name.source);
6524     }
6525     return &name;
6526   }
6527   if (isImplicitNoneType()) {
6528     Say(name, "No explicit type declared for '%s'"_err_en_US);
6529     return nullptr;
6530   }
6531   // Create the symbol then ensure it is accessible
6532   if (checkIndexUseInOwnBounds_ && *checkIndexUseInOwnBounds_ == name.source) {
6533     Say(name,
6534         "Implied DO index '%s' uses itself in its own bounds expressions"_err_en_US,
6535         name.source);
6536   }
6537   MakeSymbol(InclusiveScope(), name.source, Attrs{});
6538   auto *symbol{FindSymbol(name)};
6539   if (!symbol) {
6540     Say(name,
6541         "'%s' from host scoping unit is not accessible due to IMPORT"_err_en_US);
6542     return nullptr;
6543   }
6544   ConvertToObjectEntity(*symbol);
6545   ApplyImplicitRules(*symbol);
6546   NotePossibleBadForwardRef(name);
6547   return &name;
6548 }
6549 
6550 // A specification expression may refer to a symbol in the host procedure that
6551 // is implicitly typed. Because specification parts are processed before
6552 // execution parts, this may be the first time we see the symbol. It can't be a
6553 // local in the current scope (because it's in a specification expression) so
6554 // either it is implicitly declared in the host procedure or it is an error.
6555 // We create a symbol in the host assuming it is the former; if that proves to
6556 // be wrong we report an error later in CheckDeclarations().
6557 bool DeclarationVisitor::CheckForHostAssociatedImplicit(
6558     const parser::Name &name) {
6559   if (!inSpecificationPart_) {
6560     return false;
6561   }
6562   if (name.symbol) {
6563     ApplyImplicitRules(*name.symbol, true);
6564   }
6565   Symbol *hostSymbol;
6566   Scope *host{GetHostProcedure()};
6567   if (!host || isImplicitNoneType(*host)) {
6568     return false;
6569   }
6570   if (!name.symbol) {
6571     hostSymbol = &MakeSymbol(*host, name.source, Attrs{});
6572     ConvertToObjectEntity(*hostSymbol);
6573     ApplyImplicitRules(*hostSymbol);
6574     hostSymbol->set(Symbol::Flag::ImplicitOrError);
6575   } else if (name.symbol->test(Symbol::Flag::ImplicitOrError)) {
6576     hostSymbol = name.symbol;
6577   } else {
6578     return false;
6579   }
6580   Symbol &symbol{MakeHostAssocSymbol(name, *hostSymbol)};
6581   if (isImplicitNoneType()) {
6582     symbol.get<HostAssocDetails>().implicitOrExplicitTypeError = true;
6583   } else {
6584     symbol.get<HostAssocDetails>().implicitOrSpecExprError = true;
6585   }
6586   return true;
6587 }
6588 
6589 bool DeclarationVisitor::IsUplevelReference(const Symbol &symbol) {
6590   const Scope &symbolUnit{GetProgramUnitContaining(symbol)};
6591   if (symbolUnit == GetProgramUnitContaining(currScope())) {
6592     return false;
6593   } else {
6594     Scope::Kind kind{symbolUnit.kind()};
6595     return kind == Scope::Kind::Subprogram || kind == Scope::Kind::MainProgram;
6596   }
6597 }
6598 
6599 // base is a part-ref of a derived type; find the named component in its type.
6600 // Also handles intrinsic type parameter inquiries (%kind, %len) and
6601 // COMPLEX component references (%re, %im).
6602 const parser::Name *DeclarationVisitor::FindComponent(
6603     const parser::Name *base, const parser::Name &component) {
6604   if (!base || !base->symbol) {
6605     return nullptr;
6606   }
6607   if (auto *misc{base->symbol->detailsIf<MiscDetails>()}) {
6608     if (component.source == "kind") {
6609       if (misc->kind() == MiscDetails::Kind::ComplexPartRe ||
6610           misc->kind() == MiscDetails::Kind::ComplexPartIm ||
6611           misc->kind() == MiscDetails::Kind::KindParamInquiry ||
6612           misc->kind() == MiscDetails::Kind::LenParamInquiry) {
6613         // x%{re,im,kind,len}%kind
6614         MakePlaceholder(component, MiscDetails::Kind::KindParamInquiry);
6615         return &component;
6616       }
6617     }
6618   }
6619   auto &symbol{base->symbol->GetUltimate()};
6620   if (!symbol.has<AssocEntityDetails>() && !ConvertToObjectEntity(symbol)) {
6621     SayWithDecl(*base, symbol,
6622         "'%s' is an invalid base for a component reference"_err_en_US);
6623     return nullptr;
6624   }
6625   auto *type{symbol.GetType()};
6626   if (!type) {
6627     return nullptr; // should have already reported error
6628   }
6629   if (const IntrinsicTypeSpec * intrinsic{type->AsIntrinsic()}) {
6630     auto category{intrinsic->category()};
6631     MiscDetails::Kind miscKind{MiscDetails::Kind::None};
6632     if (component.source == "kind") {
6633       miscKind = MiscDetails::Kind::KindParamInquiry;
6634     } else if (category == TypeCategory::Character) {
6635       if (component.source == "len") {
6636         miscKind = MiscDetails::Kind::LenParamInquiry;
6637       }
6638     } else if (category == TypeCategory::Complex) {
6639       if (component.source == "re") {
6640         miscKind = MiscDetails::Kind::ComplexPartRe;
6641       } else if (component.source == "im") {
6642         miscKind = MiscDetails::Kind::ComplexPartIm;
6643       }
6644     }
6645     if (miscKind != MiscDetails::Kind::None) {
6646       MakePlaceholder(component, miscKind);
6647       return &component;
6648     }
6649   } else if (const DerivedTypeSpec * derived{type->AsDerived()}) {
6650     if (const Scope * scope{derived->scope()}) {
6651       if (Resolve(component, scope->FindComponent(component.source))) {
6652         if (auto msg{
6653                 CheckAccessibleComponent(currScope(), *component.symbol)}) {
6654           context().Say(component.source, *msg);
6655         }
6656         return &component;
6657       } else {
6658         SayDerivedType(component.source,
6659             "Component '%s' not found in derived type '%s'"_err_en_US, *scope);
6660       }
6661     }
6662     return nullptr;
6663   }
6664   if (symbol.test(Symbol::Flag::Implicit)) {
6665     Say(*base,
6666         "'%s' is not an object of derived type; it is implicitly typed"_err_en_US);
6667   } else {
6668     SayWithDecl(
6669         *base, symbol, "'%s' is not an object of derived type"_err_en_US);
6670   }
6671   return nullptr;
6672 }
6673 
6674 void DeclarationVisitor::Initialization(const parser::Name &name,
6675     const parser::Initialization &init, bool inComponentDecl) {
6676   // Traversal of the initializer was deferred to here so that the
6677   // symbol being declared can be available for use in the expression, e.g.:
6678   //   real, parameter :: x = tiny(x)
6679   if (!name.symbol) {
6680     return;
6681   }
6682   Symbol &ultimate{name.symbol->GetUltimate()};
6683   if (IsAllocatable(ultimate)) {
6684     Say(name, "Allocatable object '%s' cannot be initialized"_err_en_US);
6685     return;
6686   }
6687   if (auto *object{ultimate.detailsIf<ObjectEntityDetails>()}) {
6688     // TODO: check C762 - all bounds and type parameters of component
6689     // are colons or constant expressions if component is initialized
6690     common::visit(
6691         common::visitors{
6692             [&](const parser::ConstantExpr &expr) {
6693               NonPointerInitialization(name, expr);
6694             },
6695             [&](const parser::NullInit &null) {
6696               Walk(null);
6697               if (auto nullInit{EvaluateExpr(null)}) {
6698                 if (!evaluate::IsNullPointer(*nullInit)) {
6699                   Say(name,
6700                       "Pointer initializer must be intrinsic NULL()"_err_en_US); // C813
6701                 } else if (IsPointer(ultimate)) {
6702                   object->set_init(std::move(*nullInit));
6703                 } else {
6704                   Say(name,
6705                       "Non-pointer component '%s' initialized with null pointer"_err_en_US);
6706                 }
6707               }
6708             },
6709             [&](const parser::InitialDataTarget &) {
6710               // Defer analysis to the end of the specification part
6711               // so that forward references and attribute checks like SAVE
6712               // work better.
6713               ultimate.set(Symbol::Flag::InDataStmt);
6714             },
6715             [&](const std::list<Indirection<parser::DataStmtValue>> &values) {
6716               // Handled later in data-to-inits conversion
6717               ultimate.set(Symbol::Flag::InDataStmt);
6718               Walk(values);
6719             },
6720         },
6721         init.u);
6722   }
6723 }
6724 
6725 void DeclarationVisitor::PointerInitialization(
6726     const parser::Name &name, const parser::InitialDataTarget &target) {
6727   if (name.symbol) {
6728     Symbol &ultimate{name.symbol->GetUltimate()};
6729     if (!context().HasError(ultimate)) {
6730       if (IsPointer(ultimate)) {
6731         if (auto *details{ultimate.detailsIf<ObjectEntityDetails>()}) {
6732           CHECK(!details->init());
6733           Walk(target);
6734           if (MaybeExpr expr{EvaluateExpr(target)}) {
6735             // Validation is done in declaration checking.
6736             details->set_init(std::move(*expr));
6737           }
6738         }
6739       } else {
6740         Say(name,
6741             "'%s' is not a pointer but is initialized like one"_err_en_US);
6742         context().SetError(ultimate);
6743       }
6744     }
6745   }
6746 }
6747 void DeclarationVisitor::PointerInitialization(
6748     const parser::Name &name, const parser::ProcPointerInit &target) {
6749   if (name.symbol) {
6750     Symbol &ultimate{name.symbol->GetUltimate()};
6751     if (!context().HasError(ultimate)) {
6752       if (IsProcedurePointer(ultimate)) {
6753         auto &details{ultimate.get<ProcEntityDetails>()};
6754         CHECK(!details.init());
6755         Walk(target);
6756         if (const auto *targetName{std::get_if<parser::Name>(&target.u)}) {
6757           if (targetName->symbol) {
6758             // Validation is done in declaration checking.
6759             details.set_init(*targetName->symbol);
6760           }
6761         } else {
6762           details.set_init(nullptr); // explicit NULL()
6763         }
6764       } else {
6765         Say(name,
6766             "'%s' is not a procedure pointer but is initialized "
6767             "like one"_err_en_US);
6768         context().SetError(ultimate);
6769       }
6770     }
6771   }
6772 }
6773 
6774 void DeclarationVisitor::NonPointerInitialization(
6775     const parser::Name &name, const parser::ConstantExpr &expr) {
6776   if (name.symbol) {
6777     Symbol &ultimate{name.symbol->GetUltimate()};
6778     if (!context().HasError(ultimate) && !context().HasError(name.symbol)) {
6779       if (IsPointer(ultimate)) {
6780         Say(name,
6781             "'%s' is a pointer but is not initialized like one"_err_en_US);
6782       } else if (auto *details{ultimate.detailsIf<ObjectEntityDetails>()}) {
6783         CHECK(!details->init());
6784         Walk(expr);
6785         if (ultimate.owner().IsParameterizedDerivedType()) {
6786           // Save the expression for per-instantiation analysis.
6787           details->set_unanalyzedPDTComponentInit(&expr.thing.value());
6788         } else {
6789           if (MaybeExpr folded{EvaluateNonPointerInitializer(
6790                   ultimate, expr, expr.thing.value().source)}) {
6791             details->set_init(std::move(*folded));
6792           }
6793         }
6794       }
6795     }
6796   }
6797 }
6798 
6799 void ResolveNamesVisitor::HandleCall(
6800     Symbol::Flag procFlag, const parser::Call &call) {
6801   common::visit(
6802       common::visitors{
6803           [&](const parser::Name &x) { HandleProcedureName(procFlag, x); },
6804           [&](const parser::ProcComponentRef &x) { Walk(x); },
6805       },
6806       std::get<parser::ProcedureDesignator>(call.t).u);
6807   Walk(std::get<std::list<parser::ActualArgSpec>>(call.t));
6808 }
6809 
6810 void ResolveNamesVisitor::HandleProcedureName(
6811     Symbol::Flag flag, const parser::Name &name) {
6812   CHECK(flag == Symbol::Flag::Function || flag == Symbol::Flag::Subroutine);
6813   auto *symbol{FindSymbol(NonDerivedTypeScope(), name)};
6814   if (!symbol) {
6815     if (IsIntrinsic(name.source, flag)) {
6816       symbol =
6817           &MakeSymbol(InclusiveScope(), name.source, Attrs{Attr::INTRINSIC});
6818     } else {
6819       symbol = &MakeSymbol(context().globalScope(), name.source, Attrs{});
6820     }
6821     Resolve(name, *symbol);
6822     if (!symbol->attrs().test(Attr::INTRINSIC)) {
6823       if (CheckImplicitNoneExternal(name.source, *symbol)) {
6824         MakeExternal(*symbol);
6825       }
6826     }
6827     ConvertToProcEntity(*symbol);
6828     SetProcFlag(name, *symbol, flag);
6829   } else if (CheckUseError(name)) {
6830     // error was reported
6831   } else {
6832     auto &nonUltimateSymbol{*symbol};
6833     symbol = &Resolve(name, symbol)->GetUltimate();
6834     bool convertedToProcEntity{ConvertToProcEntity(*symbol)};
6835     if (convertedToProcEntity && !symbol->attrs().test(Attr::EXTERNAL) &&
6836         IsIntrinsic(symbol->name(), flag) && !IsDummy(*symbol)) {
6837       AcquireIntrinsicProcedureFlags(*symbol);
6838     }
6839     if (!SetProcFlag(name, *symbol, flag)) {
6840       return; // reported error
6841     }
6842     if (!symbol->has<GenericDetails>()) {
6843       CheckImplicitNoneExternal(name.source, *symbol);
6844     }
6845     if (symbol->has<SubprogramDetails>() &&
6846         symbol->attrs().test(Attr::ABSTRACT)) {
6847       Say(name, "Abstract interface '%s' may not be called"_err_en_US);
6848     } else if (IsProcedure(*symbol) || symbol->has<DerivedTypeDetails>() ||
6849         symbol->has<AssocEntityDetails>()) {
6850       // Symbols with DerivedTypeDetails and AssocEntityDetails are accepted
6851       // here as procedure-designators because this means the related
6852       // FunctionReference are mis-parsed structure constructors or array
6853       // references that will be fixed later when analyzing expressions.
6854     } else if (symbol->has<ObjectEntityDetails>()) {
6855       // Symbols with ObjectEntityDetails are also accepted because this can be
6856       // a mis-parsed array references that will be fixed later. Ensure that if
6857       // this is a symbol from a host procedure, a symbol with HostAssocDetails
6858       // is created for the current scope.
6859       // Operate on non ultimate symbol so that HostAssocDetails are also
6860       // created for symbols used associated in the host procedure.
6861       if (IsUplevelReference(nonUltimateSymbol)) {
6862         MakeHostAssocSymbol(name, nonUltimateSymbol);
6863       }
6864     } else if (symbol->test(Symbol::Flag::Implicit)) {
6865       Say(name,
6866           "Use of '%s' as a procedure conflicts with its implicit definition"_err_en_US);
6867     } else {
6868       SayWithDecl(name, *symbol,
6869           "Use of '%s' as a procedure conflicts with its declaration"_err_en_US);
6870     }
6871   }
6872 }
6873 
6874 bool ResolveNamesVisitor::CheckImplicitNoneExternal(
6875     const SourceName &name, const Symbol &symbol) {
6876   if (isImplicitNoneExternal() && !symbol.attrs().test(Attr::EXTERNAL) &&
6877       !symbol.attrs().test(Attr::INTRINSIC) && !symbol.HasExplicitInterface()) {
6878     Say(name,
6879         "'%s' is an external procedure without the EXTERNAL"
6880         " attribute in a scope with IMPLICIT NONE(EXTERNAL)"_err_en_US);
6881     return false;
6882   }
6883   return true;
6884 }
6885 
6886 // Variant of HandleProcedureName() for use while skimming the executable
6887 // part of a subprogram to catch calls to dummy procedures that are part
6888 // of the subprogram's interface, and to mark as procedures any symbols
6889 // that might otherwise have been miscategorized as objects.
6890 void ResolveNamesVisitor::NoteExecutablePartCall(
6891     Symbol::Flag flag, const parser::Call &call) {
6892   auto &designator{std::get<parser::ProcedureDesignator>(call.t)};
6893   if (const auto *name{std::get_if<parser::Name>(&designator.u)}) {
6894     // Subtlety: The symbol pointers in the parse tree are not set, because
6895     // they might end up resolving elsewhere (e.g., construct entities in
6896     // SELECT TYPE).
6897     if (Symbol * symbol{currScope().FindSymbol(name->source)}) {
6898       Symbol::Flag other{flag == Symbol::Flag::Subroutine
6899               ? Symbol::Flag::Function
6900               : Symbol::Flag::Subroutine};
6901       if (!symbol->test(other)) {
6902         ConvertToProcEntity(*symbol);
6903         if (symbol->has<ProcEntityDetails>()) {
6904           symbol->set(flag);
6905           if (IsDummy(*symbol)) {
6906             symbol->attrs().set(Attr::EXTERNAL);
6907           }
6908           ApplyImplicitRules(*symbol);
6909         }
6910       }
6911     }
6912   }
6913 }
6914 
6915 static bool IsLocallyImplicitGlobalSymbol(
6916     const Symbol &symbol, const parser::Name &localName) {
6917   return symbol.owner().IsGlobal() &&
6918       (!symbol.scope() ||
6919           !symbol.scope()->sourceRange().Contains(localName.source));
6920 }
6921 
6922 static bool TypesMismatchIfNonNull(
6923     const DeclTypeSpec *type1, const DeclTypeSpec *type2) {
6924   return type1 && type2 && *type1 != *type2;
6925 }
6926 
6927 // Check and set the Function or Subroutine flag on symbol; false on error.
6928 bool ResolveNamesVisitor::SetProcFlag(
6929     const parser::Name &name, Symbol &symbol, Symbol::Flag flag) {
6930   if (symbol.test(Symbol::Flag::Function) && flag == Symbol::Flag::Subroutine) {
6931     SayWithDecl(
6932         name, symbol, "Cannot call function '%s' like a subroutine"_err_en_US);
6933     return false;
6934   } else if (symbol.test(Symbol::Flag::Subroutine) &&
6935       flag == Symbol::Flag::Function) {
6936     SayWithDecl(
6937         name, symbol, "Cannot call subroutine '%s' like a function"_err_en_US);
6938     return false;
6939   } else if (flag == Symbol::Flag::Function &&
6940       IsLocallyImplicitGlobalSymbol(symbol, name) &&
6941       TypesMismatchIfNonNull(symbol.GetType(), GetImplicitType(symbol))) {
6942     SayWithDecl(name, symbol,
6943         "Implicit declaration of function '%s' has a different result type than in previous declaration"_err_en_US);
6944     return false;
6945   } else if (symbol.has<ProcEntityDetails>()) {
6946     symbol.set(flag); // in case it hasn't been set yet
6947     if (flag == Symbol::Flag::Function) {
6948       ApplyImplicitRules(symbol);
6949     }
6950     if (symbol.attrs().test(Attr::INTRINSIC)) {
6951       AcquireIntrinsicProcedureFlags(symbol);
6952     }
6953   } else if (symbol.GetType() && flag == Symbol::Flag::Subroutine) {
6954     SayWithDecl(
6955         name, symbol, "Cannot call function '%s' like a subroutine"_err_en_US);
6956   } else if (symbol.attrs().test(Attr::INTRINSIC)) {
6957     AcquireIntrinsicProcedureFlags(symbol);
6958   }
6959   return true;
6960 }
6961 
6962 bool ModuleVisitor::Pre(const parser::AccessStmt &x) {
6963   Attr accessAttr{AccessSpecToAttr(std::get<parser::AccessSpec>(x.t))};
6964   if (!currScope().IsModule()) { // C869
6965     Say(currStmtSource().value(),
6966         "%s statement may only appear in the specification part of a module"_err_en_US,
6967         EnumToString(accessAttr));
6968     return false;
6969   }
6970   const auto &accessIds{std::get<std::list<parser::AccessId>>(x.t)};
6971   if (accessIds.empty()) {
6972     if (prevAccessStmt_) { // C869
6973       Say("The default accessibility of this module has already been declared"_err_en_US)
6974           .Attach(*prevAccessStmt_, "Previous declaration"_en_US);
6975     }
6976     prevAccessStmt_ = currStmtSource();
6977     defaultAccess_ = accessAttr;
6978   } else {
6979     for (const auto &accessId : accessIds) {
6980       common::visit(
6981           common::visitors{
6982               [=](const parser::Name &y) {
6983                 Resolve(y, SetAccess(y.source, accessAttr));
6984               },
6985               [=](const Indirection<parser::GenericSpec> &y) {
6986                 auto info{GenericSpecInfo{y.value()}};
6987                 const auto &symbolName{info.symbolName()};
6988                 if (auto *symbol{FindInScope(symbolName)}) {
6989                   info.Resolve(&SetAccess(symbolName, accessAttr, symbol));
6990                 } else if (info.kind().IsName()) {
6991                   info.Resolve(&SetAccess(symbolName, accessAttr));
6992                 } else {
6993                   Say(symbolName, "Generic spec '%s' not found"_err_en_US);
6994                 }
6995               },
6996           },
6997           accessId.u);
6998     }
6999   }
7000   return false;
7001 }
7002 
7003 // Set the access specification for this symbol.
7004 Symbol &ModuleVisitor::SetAccess(
7005     const SourceName &name, Attr attr, Symbol *symbol) {
7006   if (!symbol) {
7007     symbol = &MakeSymbol(name);
7008   }
7009   Attrs &attrs{symbol->attrs()};
7010   if (attrs.HasAny({Attr::PUBLIC, Attr::PRIVATE})) {
7011     // PUBLIC/PRIVATE already set: make it a fatal error if it changed
7012     Attr prev = attrs.test(Attr::PUBLIC) ? Attr::PUBLIC : Attr::PRIVATE;
7013     Say(name,
7014         WithSeverity(
7015             "The accessibility of '%s' has already been specified as %s"_warn_en_US,
7016             attr != prev ? parser::Severity::Error : parser::Severity::Warning),
7017         MakeOpName(name), EnumToString(prev));
7018   } else {
7019     attrs.set(attr);
7020   }
7021   return *symbol;
7022 }
7023 
7024 static bool NeedsExplicitType(const Symbol &symbol) {
7025   if (symbol.has<UnknownDetails>()) {
7026     return true;
7027   } else if (const auto *details{symbol.detailsIf<EntityDetails>()}) {
7028     return !details->type();
7029   } else if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) {
7030     return !details->type();
7031   } else if (const auto *details{symbol.detailsIf<ProcEntityDetails>()}) {
7032     return !details->interface().symbol() && !details->interface().type();
7033   } else {
7034     return false;
7035   }
7036 }
7037 
7038 bool ResolveNamesVisitor::Pre(const parser::SpecificationPart &x) {
7039   const auto &[accDecls, ompDecls, compilerDirectives, useStmts, importStmts,
7040       implicitPart, decls] = x.t;
7041   auto flagRestorer{common::ScopedSet(inSpecificationPart_, true)};
7042   auto stateRestorer{
7043       common::ScopedSet(specPartState_, SpecificationPartState{})};
7044   Walk(accDecls);
7045   Walk(ompDecls);
7046   Walk(compilerDirectives);
7047   Walk(useStmts);
7048   ClearUseRenames();
7049   ClearUseOnly();
7050   ClearExplicitIntrinsicUses();
7051   Walk(importStmts);
7052   Walk(implicitPart);
7053   for (const auto &decl : decls) {
7054     if (const auto *spec{
7055             std::get_if<parser::SpecificationConstruct>(&decl.u)}) {
7056       PreSpecificationConstruct(*spec);
7057     }
7058   }
7059   Walk(decls);
7060   FinishSpecificationPart(decls);
7061   return false;
7062 }
7063 
7064 // Initial processing on specification constructs, before visiting them.
7065 void ResolveNamesVisitor::PreSpecificationConstruct(
7066     const parser::SpecificationConstruct &spec) {
7067   common::visit(
7068       common::visitors{
7069           [&](const parser::Statement<Indirection<parser::GenericStmt>> &y) {
7070             CreateGeneric(std::get<parser::GenericSpec>(y.statement.value().t));
7071           },
7072           [&](const Indirection<parser::InterfaceBlock> &y) {
7073             const auto &stmt{std::get<parser::Statement<parser::InterfaceStmt>>(
7074                 y.value().t)};
7075             if (const auto *spec{parser::Unwrap<parser::GenericSpec>(stmt)}) {
7076               CreateGeneric(*spec);
7077             }
7078           },
7079           [&](const parser::Statement<parser::OtherSpecificationStmt> &y) {
7080             if (const auto *commonStmt{parser::Unwrap<parser::CommonStmt>(y)}) {
7081               CreateCommonBlockSymbols(*commonStmt);
7082             }
7083           },
7084           [&](const auto &) {},
7085       },
7086       spec.u);
7087 }
7088 
7089 void ResolveNamesVisitor::CreateCommonBlockSymbols(
7090     const parser::CommonStmt &commonStmt) {
7091   for (const parser::CommonStmt::Block &block : commonStmt.blocks) {
7092     const auto &[name, objects] = block.t;
7093     Symbol &commonBlock{MakeCommonBlockSymbol(name)};
7094     for (const auto &object : objects) {
7095       Symbol &obj{DeclareObjectEntity(std::get<parser::Name>(object.t))};
7096       if (auto *details{obj.detailsIf<ObjectEntityDetails>()}) {
7097         details->set_commonBlock(commonBlock);
7098         commonBlock.get<CommonBlockDetails>().add_object(obj);
7099       }
7100     }
7101   }
7102 }
7103 
7104 void ResolveNamesVisitor::CreateGeneric(const parser::GenericSpec &x) {
7105   auto info{GenericSpecInfo{x}};
7106   SourceName symbolName{info.symbolName()};
7107   if (IsLogicalConstant(context(), symbolName)) {
7108     Say(symbolName,
7109         "Logical constant '%s' may not be used as a defined operator"_err_en_US);
7110     return;
7111   }
7112   GenericDetails genericDetails;
7113   Symbol *existing{nullptr};
7114   // Check all variants of names, e.g. "operator(.ne.)" for "operator(/=)"
7115   for (const std::string &n : GetAllNames(context(), symbolName)) {
7116     if (auto iter{currScope().find(n)}; iter != currScope().end()) {
7117       existing = &*iter->second;
7118       break;
7119     }
7120   }
7121   if (existing) {
7122     Symbol &ultimate{existing->GetUltimate()};
7123     if (const auto *existingGeneric{ultimate.detailsIf<GenericDetails>()}) {
7124       if (const auto *existingUse{existing->detailsIf<UseDetails>()}) {
7125         // Create a local copy of a use associated generic so that
7126         // it can be locally extended without corrupting the original.
7127         genericDetails.CopyFrom(*existingGeneric);
7128         AddGenericUse(genericDetails, existing->name(), existingUse->symbol());
7129       } else if (existing == &ultimate) {
7130         // Extending an extant generic in the same scope
7131         info.Resolve(existing);
7132         return;
7133       } else {
7134         // Host association of a generic is handled in ResolveGeneric()
7135         CHECK(existing->has<HostAssocDetails>());
7136       }
7137     } else if (ultimate.has<SubprogramDetails>() ||
7138         ultimate.has<SubprogramNameDetails>()) {
7139       genericDetails.set_specific(ultimate);
7140     } else if (ultimate.has<DerivedTypeDetails>()) {
7141       genericDetails.set_derivedType(ultimate);
7142     } else {
7143       SayAlreadyDeclared(symbolName, *existing);
7144       return;
7145     }
7146     EraseSymbol(*existing);
7147   }
7148   info.Resolve(&MakeSymbol(symbolName, Attrs{}, std::move(genericDetails)));
7149 }
7150 
7151 void ResolveNamesVisitor::FinishSpecificationPart(
7152     const std::list<parser::DeclarationConstruct> &decls) {
7153   badStmtFuncFound_ = false;
7154   funcResultStack().CompleteFunctionResultType();
7155   CheckImports();
7156   bool inModule{currScope().kind() == Scope::Kind::Module};
7157   for (auto &pair : currScope()) {
7158     auto &symbol{*pair.second};
7159     if (NeedsExplicitType(symbol)) {
7160       ApplyImplicitRules(symbol);
7161     }
7162     if (IsDummy(symbol) && isImplicitNoneType() &&
7163         symbol.test(Symbol::Flag::Implicit) && !context().HasError(symbol)) {
7164       Say(symbol.name(),
7165           "No explicit type declared for dummy argument '%s'"_err_en_US);
7166       context().SetError(symbol);
7167     }
7168     if (symbol.has<GenericDetails>()) {
7169       CheckGenericProcedures(symbol);
7170     }
7171     if (inModule && symbol.attrs().test(Attr::EXTERNAL) &&
7172         !symbol.test(Symbol::Flag::Function) &&
7173         !symbol.test(Symbol::Flag::Subroutine)) {
7174       // in a module, external proc without return type is subroutine
7175       symbol.set(
7176           symbol.GetType() ? Symbol::Flag::Function : Symbol::Flag::Subroutine);
7177     }
7178     if (!symbol.has<HostAssocDetails>()) {
7179       CheckPossibleBadForwardRef(symbol);
7180     }
7181   }
7182   currScope().InstantiateDerivedTypes();
7183   for (const auto &decl : decls) {
7184     if (const auto *statement{std::get_if<
7185             parser::Statement<common::Indirection<parser::StmtFunctionStmt>>>(
7186             &decl.u)}) {
7187       AnalyzeStmtFunctionStmt(statement->statement.value());
7188     }
7189   }
7190   // TODO: what about instantiations in BLOCK?
7191   CheckSaveStmts();
7192   CheckCommonBlocks();
7193   if (!inInterfaceBlock()) {
7194     // TODO: warn for the case where the EQUIVALENCE statement is in a
7195     // procedure declaration in an interface block
7196     CheckEquivalenceSets();
7197   }
7198 }
7199 
7200 // Analyze the bodies of statement functions now that the symbols in this
7201 // specification part have been fully declared and implicitly typed.
7202 void ResolveNamesVisitor::AnalyzeStmtFunctionStmt(
7203     const parser::StmtFunctionStmt &stmtFunc) {
7204   Symbol *symbol{std::get<parser::Name>(stmtFunc.t).symbol};
7205   if (!symbol || !symbol->has<SubprogramDetails>()) {
7206     return;
7207   }
7208   auto &details{symbol->get<SubprogramDetails>()};
7209   auto expr{AnalyzeExpr(
7210       context(), std::get<parser::Scalar<parser::Expr>>(stmtFunc.t))};
7211   if (!expr) {
7212     context().SetError(*symbol);
7213     return;
7214   }
7215   if (auto type{evaluate::DynamicType::From(*symbol)}) {
7216     auto converted{ConvertToType(*type, std::move(*expr))};
7217     if (!converted) {
7218       context().SetError(*symbol);
7219       return;
7220     }
7221     details.set_stmtFunction(std::move(*converted));
7222   } else {
7223     details.set_stmtFunction(std::move(*expr));
7224   }
7225 }
7226 
7227 void ResolveNamesVisitor::CheckImports() {
7228   auto &scope{currScope()};
7229   switch (scope.GetImportKind()) {
7230   case common::ImportKind::None:
7231     break;
7232   case common::ImportKind::All:
7233     // C8102: all entities in host must not be hidden
7234     for (const auto &pair : scope.parent()) {
7235       auto &name{pair.first};
7236       std::optional<SourceName> scopeName{scope.GetName()};
7237       if (!scopeName || name != *scopeName) {
7238         CheckImport(prevImportStmt_.value(), name);
7239       }
7240     }
7241     break;
7242   case common::ImportKind::Default:
7243   case common::ImportKind::Only:
7244     // C8102: entities named in IMPORT must not be hidden
7245     for (auto &name : scope.importNames()) {
7246       CheckImport(name, name);
7247     }
7248     break;
7249   }
7250 }
7251 
7252 void ResolveNamesVisitor::CheckImport(
7253     const SourceName &location, const SourceName &name) {
7254   if (auto *symbol{FindInScope(name)}) {
7255     const Symbol &ultimate{symbol->GetUltimate()};
7256     if (&ultimate.owner() == &currScope()) {
7257       Say(location, "'%s' from host is not accessible"_err_en_US, name)
7258           .Attach(symbol->name(), "'%s' is hidden by this entity"_en_US,
7259               symbol->name());
7260     }
7261   }
7262 }
7263 
7264 bool ResolveNamesVisitor::Pre(const parser::ImplicitStmt &x) {
7265   return CheckNotInBlock("IMPLICIT") && // C1107
7266       ImplicitRulesVisitor::Pre(x);
7267 }
7268 
7269 void ResolveNamesVisitor::Post(const parser::PointerObject &x) {
7270   common::visit(common::visitors{
7271                     [&](const parser::Name &x) { ResolveName(x); },
7272                     [&](const parser::StructureComponent &x) {
7273                       ResolveStructureComponent(x);
7274                     },
7275                 },
7276       x.u);
7277 }
7278 void ResolveNamesVisitor::Post(const parser::AllocateObject &x) {
7279   common::visit(common::visitors{
7280                     [&](const parser::Name &x) { ResolveName(x); },
7281                     [&](const parser::StructureComponent &x) {
7282                       ResolveStructureComponent(x);
7283                     },
7284                 },
7285       x.u);
7286 }
7287 
7288 bool ResolveNamesVisitor::Pre(const parser::PointerAssignmentStmt &x) {
7289   const auto &dataRef{std::get<parser::DataRef>(x.t)};
7290   const auto &bounds{std::get<parser::PointerAssignmentStmt::Bounds>(x.t)};
7291   const auto &expr{std::get<parser::Expr>(x.t)};
7292   ResolveDataRef(dataRef);
7293   Walk(bounds);
7294   // Resolve unrestricted specific intrinsic procedures as in "p => cos".
7295   if (const parser::Name * name{parser::Unwrap<parser::Name>(expr)}) {
7296     if (NameIsKnownOrIntrinsic(*name)) {
7297       // If the name is known because it is an object entity from a host
7298       // procedure, create a host associated symbol.
7299       if (Symbol * symbol{name->symbol}; symbol &&
7300           symbol->GetUltimate().has<ObjectEntityDetails>() &&
7301           IsUplevelReference(*symbol)) {
7302         MakeHostAssocSymbol(*name, *symbol);
7303       }
7304       return false;
7305     }
7306   }
7307   Walk(expr);
7308   return false;
7309 }
7310 void ResolveNamesVisitor::Post(const parser::Designator &x) {
7311   ResolveDesignator(x);
7312 }
7313 
7314 void ResolveNamesVisitor::Post(const parser::ProcComponentRef &x) {
7315   ResolveStructureComponent(x.v.thing);
7316 }
7317 void ResolveNamesVisitor::Post(const parser::TypeGuardStmt &x) {
7318   DeclTypeSpecVisitor::Post(x);
7319   ConstructVisitor::Post(x);
7320 }
7321 bool ResolveNamesVisitor::Pre(const parser::StmtFunctionStmt &x) {
7322   CheckNotInBlock("STATEMENT FUNCTION"); // C1107
7323   if (HandleStmtFunction(x)) {
7324     return false;
7325   } else {
7326     // This is an array element assignment: resolve names of indices
7327     const auto &names{std::get<std::list<parser::Name>>(x.t)};
7328     for (auto &name : names) {
7329       ResolveName(name);
7330     }
7331     return true;
7332   }
7333 }
7334 
7335 bool ResolveNamesVisitor::Pre(const parser::DefinedOpName &x) {
7336   const parser::Name &name{x.v};
7337   if (FindSymbol(name)) {
7338     // OK
7339   } else if (IsLogicalConstant(context(), name.source)) {
7340     Say(name,
7341         "Logical constant '%s' may not be used as a defined operator"_err_en_US);
7342   } else {
7343     // Resolved later in expression semantics
7344     MakePlaceholder(name, MiscDetails::Kind::TypeBoundDefinedOp);
7345   }
7346   return false;
7347 }
7348 
7349 void ResolveNamesVisitor::Post(const parser::AssignStmt &x) {
7350   if (auto *name{ResolveName(std::get<parser::Name>(x.t))}) {
7351     ConvertToObjectEntity(DEREF(name->symbol));
7352   }
7353 }
7354 void ResolveNamesVisitor::Post(const parser::AssignedGotoStmt &x) {
7355   if (auto *name{ResolveName(std::get<parser::Name>(x.t))}) {
7356     ConvertToObjectEntity(DEREF(name->symbol));
7357   }
7358 }
7359 
7360 bool ResolveNamesVisitor::Pre(const parser::ProgramUnit &x) {
7361   if (std::holds_alternative<common::Indirection<parser::CompilerDirective>>(
7362           x.u)) {
7363     // TODO: global directives
7364     return true;
7365   }
7366   auto root{ProgramTree::Build(x)};
7367   SetScope(topScope_);
7368   ResolveSpecificationParts(root);
7369   FinishSpecificationParts(root);
7370   ResolveExecutionParts(root);
7371   ResolveAccParts(context(), x);
7372   ResolveOmpParts(context(), x);
7373   return false;
7374 }
7375 
7376 // References to procedures need to record that their symbols are known
7377 // to be procedures, so that they don't get converted to objects by default.
7378 class ExecutionPartSkimmer {
7379 public:
7380   explicit ExecutionPartSkimmer(ResolveNamesVisitor &resolver)
7381       : resolver_{resolver} {}
7382 
7383   void Walk(const parser::ExecutionPart *exec) {
7384     if (exec) {
7385       parser::Walk(*exec, *this);
7386     }
7387   }
7388 
7389   template <typename A> bool Pre(const A &) { return true; }
7390   template <typename A> void Post(const A &) {}
7391   void Post(const parser::FunctionReference &fr) {
7392     resolver_.NoteExecutablePartCall(Symbol::Flag::Function, fr.v);
7393   }
7394   void Post(const parser::CallStmt &cs) {
7395     resolver_.NoteExecutablePartCall(Symbol::Flag::Subroutine, cs.v);
7396   }
7397 
7398 private:
7399   ResolveNamesVisitor &resolver_;
7400 };
7401 
7402 // Build the scope tree and resolve names in the specification parts of this
7403 // node and its children
7404 void ResolveNamesVisitor::ResolveSpecificationParts(ProgramTree &node) {
7405   if (node.isSpecificationPartResolved()) {
7406     return; // been here already
7407   }
7408   node.set_isSpecificationPartResolved();
7409   if (!BeginScopeForNode(node)) {
7410     return; // an error prevented scope from being created
7411   }
7412   Scope &scope{currScope()};
7413   node.set_scope(scope);
7414   AddSubpNames(node);
7415   common::visit(
7416       [&](const auto *x) {
7417         if (x) {
7418           Walk(*x);
7419         }
7420       },
7421       node.stmt());
7422   Walk(node.spec());
7423   // If this is a function, convert result to an object. This is to prevent the
7424   // result from being converted later to a function symbol if it is called
7425   // inside the function.
7426   // If the result is function pointer, then ConvertToObjectEntity will not
7427   // convert the result to an object, and calling the symbol inside the function
7428   // will result in calls to the result pointer.
7429   // A function cannot be called recursively if RESULT was not used to define a
7430   // distinct result name (15.6.2.2 point 4.).
7431   if (Symbol * symbol{scope.symbol()}) {
7432     if (auto *details{symbol->detailsIf<SubprogramDetails>()}) {
7433       if (details->isFunction()) {
7434         ConvertToObjectEntity(const_cast<Symbol &>(details->result()));
7435       }
7436     }
7437   }
7438   if (node.IsModule()) {
7439     ApplyDefaultAccess();
7440   }
7441   for (auto &child : node.children()) {
7442     ResolveSpecificationParts(child);
7443   }
7444   ExecutionPartSkimmer{*this}.Walk(node.exec());
7445   EndScopeForNode(node);
7446   // Ensure that every object entity has a type.
7447   for (auto &pair : *node.scope()) {
7448     ApplyImplicitRules(*pair.second);
7449   }
7450 }
7451 
7452 // Add SubprogramNameDetails symbols for module and internal subprograms and
7453 // their ENTRY statements.
7454 void ResolveNamesVisitor::AddSubpNames(ProgramTree &node) {
7455   auto kind{
7456       node.IsModule() ? SubprogramKind::Module : SubprogramKind::Internal};
7457   for (auto &child : node.children()) {
7458     auto &symbol{MakeSymbol(child.name(), SubprogramNameDetails{kind, child})};
7459     auto childKind{child.GetKind()};
7460     if (childKind == ProgramTree::Kind::Function) {
7461       symbol.set(Symbol::Flag::Function);
7462     } else if (childKind == ProgramTree::Kind::Subroutine) {
7463       symbol.set(Symbol::Flag::Subroutine);
7464     } else {
7465       continue; // make ENTRY symbols only where valid
7466     }
7467     for (const auto &entryStmt : child.entryStmts()) {
7468       SubprogramNameDetails details{kind, child};
7469       auto &symbol{
7470           MakeSymbol(std::get<parser::Name>(entryStmt->t), std::move(details))};
7471       symbol.set(child.GetSubpFlag());
7472     }
7473   }
7474   for (const auto &generic : node.genericSpecs()) {
7475     if (const auto *name{std::get_if<parser::Name>(&generic->u)}) {
7476       if (currScope().find(name->source) != currScope().end()) {
7477         // If this scope has both a generic interface and a contained
7478         // subprogram with the same name, create the generic's symbol
7479         // now so that any other generics of the same name that are pulled
7480         // into scope later via USE association will properly merge instead
7481         // of raising a bogus error due a conflict with the subprogram.
7482         CreateGeneric(*generic);
7483       }
7484     }
7485   }
7486 }
7487 
7488 // Push a new scope for this node or return false on error.
7489 bool ResolveNamesVisitor::BeginScopeForNode(const ProgramTree &node) {
7490   switch (node.GetKind()) {
7491     SWITCH_COVERS_ALL_CASES
7492   case ProgramTree::Kind::Program:
7493     PushScope(Scope::Kind::MainProgram,
7494         &MakeSymbol(node.name(), MainProgramDetails{}));
7495     return true;
7496   case ProgramTree::Kind::Function:
7497   case ProgramTree::Kind::Subroutine:
7498     return BeginSubprogram(node.name(), node.GetSubpFlag(),
7499         node.HasModulePrefix(), node.bindingSpec(), &node.entryStmts());
7500   case ProgramTree::Kind::MpSubprogram:
7501     return BeginMpSubprogram(node.name());
7502   case ProgramTree::Kind::Module:
7503     BeginModule(node.name(), false);
7504     return true;
7505   case ProgramTree::Kind::Submodule:
7506     return BeginSubmodule(node.name(), node.GetParentId());
7507   case ProgramTree::Kind::BlockData:
7508     PushBlockDataScope(node.name());
7509     return true;
7510   }
7511 }
7512 
7513 void ResolveNamesVisitor::EndScopeForNode(const ProgramTree &node) {
7514   std::optional<parser::CharBlock> stmtSource;
7515   const std::optional<parser::LanguageBindingSpec> *binding{nullptr};
7516   common::visit(
7517       common::visitors{
7518           [&](const parser::Statement<parser::FunctionStmt> *stmt) {
7519             if (stmt) {
7520               stmtSource = stmt->source;
7521               if (const auto &maybeSuffix{
7522                       std::get<std::optional<parser::Suffix>>(
7523                           stmt->statement.t)}) {
7524                 binding = &maybeSuffix->binding;
7525               }
7526             }
7527           },
7528           [&](const parser::Statement<parser::SubroutineStmt> *stmt) {
7529             if (stmt) {
7530               stmtSource = stmt->source;
7531               binding = &std::get<std::optional<parser::LanguageBindingSpec>>(
7532                   stmt->statement.t);
7533             }
7534           },
7535           [](const auto *) {},
7536       },
7537       node.stmt());
7538   EndSubprogram(stmtSource, binding);
7539 }
7540 
7541 // Some analyses and checks, such as the processing of initializers of
7542 // pointers, are deferred until all of the pertinent specification parts
7543 // have been visited.  This deferred processing enables the use of forward
7544 // references in these circumstances.
7545 class DeferredCheckVisitor {
7546 public:
7547   explicit DeferredCheckVisitor(ResolveNamesVisitor &resolver)
7548       : resolver_{resolver} {}
7549 
7550   template <typename A> void Walk(const A &x) { parser::Walk(x, *this); }
7551 
7552   template <typename A> bool Pre(const A &) { return true; }
7553   template <typename A> void Post(const A &) {}
7554 
7555   void Post(const parser::DerivedTypeStmt &x) {
7556     const auto &name{std::get<parser::Name>(x.t)};
7557     if (Symbol * symbol{name.symbol}) {
7558       if (Scope * scope{symbol->scope()}) {
7559         if (scope->IsDerivedType()) {
7560           resolver_.PushScope(*scope);
7561           pushedScope_ = true;
7562         }
7563       }
7564     }
7565   }
7566   void Post(const parser::EndTypeStmt &) {
7567     if (pushedScope_) {
7568       resolver_.PopScope();
7569       pushedScope_ = false;
7570     }
7571   }
7572 
7573   void Post(const parser::ProcInterface &pi) {
7574     if (const auto *name{std::get_if<parser::Name>(&pi.u)}) {
7575       resolver_.CheckExplicitInterface(*name);
7576     }
7577   }
7578   bool Pre(const parser::EntityDecl &decl) {
7579     Init(std::get<parser::Name>(decl.t),
7580         std::get<std::optional<parser::Initialization>>(decl.t));
7581     return false;
7582   }
7583   bool Pre(const parser::ComponentDecl &decl) {
7584     Init(std::get<parser::Name>(decl.t),
7585         std::get<std::optional<parser::Initialization>>(decl.t));
7586     return false;
7587   }
7588   bool Pre(const parser::ProcDecl &decl) {
7589     if (const auto &init{
7590             std::get<std::optional<parser::ProcPointerInit>>(decl.t)}) {
7591       resolver_.PointerInitialization(std::get<parser::Name>(decl.t), *init);
7592     }
7593     return false;
7594   }
7595   void Post(const parser::TypeBoundProcedureStmt::WithInterface &tbps) {
7596     resolver_.CheckExplicitInterface(tbps.interfaceName);
7597   }
7598   void Post(const parser::TypeBoundProcedureStmt::WithoutInterface &tbps) {
7599     if (pushedScope_) {
7600       resolver_.CheckBindings(tbps);
7601     }
7602   }
7603 
7604 private:
7605   void Init(const parser::Name &name,
7606       const std::optional<parser::Initialization> &init) {
7607     if (init) {
7608       if (const auto *target{
7609               std::get_if<parser::InitialDataTarget>(&init->u)}) {
7610         resolver_.PointerInitialization(name, *target);
7611       }
7612     }
7613   }
7614 
7615   ResolveNamesVisitor &resolver_;
7616   bool pushedScope_{false};
7617 };
7618 
7619 // Perform checks and completions that need to happen after all of
7620 // the specification parts but before any of the execution parts.
7621 void ResolveNamesVisitor::FinishSpecificationParts(const ProgramTree &node) {
7622   if (!node.scope()) {
7623     return; // error occurred creating scope
7624   }
7625   SetScope(*node.scope());
7626   // The initializers of pointers, the default initializers of pointer
7627   // components, and non-deferred type-bound procedure bindings have not
7628   // yet been traversed.
7629   // We do that now, when any (formerly) forward references that appear
7630   // in those initializers will resolve to the right symbols without
7631   // incurring spurious errors with IMPLICIT NONE.
7632   DeferredCheckVisitor{*this}.Walk(node.spec());
7633   DeferredCheckVisitor{*this}.Walk(node.exec()); // for BLOCK
7634   for (Scope &childScope : currScope().children()) {
7635     if (childScope.IsParameterizedDerivedTypeInstantiation()) {
7636       FinishDerivedTypeInstantiation(childScope);
7637     }
7638   }
7639   for (const auto &child : node.children()) {
7640     FinishSpecificationParts(child);
7641   }
7642 }
7643 
7644 // Duplicate and fold component object pointer default initializer designators
7645 // using the actual type parameter values of each particular instantiation.
7646 // Validation is done later in declaration checking.
7647 void ResolveNamesVisitor::FinishDerivedTypeInstantiation(Scope &scope) {
7648   CHECK(scope.IsDerivedType() && !scope.symbol());
7649   if (DerivedTypeSpec * spec{scope.derivedTypeSpec()}) {
7650     spec->Instantiate(currScope());
7651     const Symbol &origTypeSymbol{spec->typeSymbol()};
7652     if (const Scope * origTypeScope{origTypeSymbol.scope()}) {
7653       CHECK(origTypeScope->IsDerivedType() &&
7654           origTypeScope->symbol() == &origTypeSymbol);
7655       auto &foldingContext{GetFoldingContext()};
7656       auto restorer{foldingContext.WithPDTInstance(*spec)};
7657       for (auto &pair : scope) {
7658         Symbol &comp{*pair.second};
7659         const Symbol &origComp{DEREF(FindInScope(*origTypeScope, comp.name()))};
7660         if (IsPointer(comp)) {
7661           if (auto *details{comp.detailsIf<ObjectEntityDetails>()}) {
7662             auto origDetails{origComp.get<ObjectEntityDetails>()};
7663             if (const MaybeExpr & init{origDetails.init()}) {
7664               SomeExpr newInit{*init};
7665               MaybeExpr folded{
7666                   evaluate::Fold(foldingContext, std::move(newInit))};
7667               details->set_init(std::move(folded));
7668             }
7669           }
7670         }
7671       }
7672     }
7673   }
7674 }
7675 
7676 // Resolve names in the execution part of this node and its children
7677 void ResolveNamesVisitor::ResolveExecutionParts(const ProgramTree &node) {
7678   if (!node.scope()) {
7679     return; // error occurred creating scope
7680   }
7681   SetScope(*node.scope());
7682   if (const auto *exec{node.exec()}) {
7683     Walk(*exec);
7684   }
7685   FinishNamelists();
7686   PopScope(); // converts unclassified entities into objects
7687   for (const auto &child : node.children()) {
7688     ResolveExecutionParts(child);
7689   }
7690 }
7691 
7692 void ResolveNamesVisitor::Post(const parser::Program &) {
7693   // ensure that all temps were deallocated
7694   CHECK(!attrs_);
7695   CHECK(!GetDeclTypeSpec());
7696 }
7697 
7698 // A singleton instance of the scope -> IMPLICIT rules mapping is
7699 // shared by all instances of ResolveNamesVisitor and accessed by this
7700 // pointer when the visitors (other than the top-level original) are
7701 // constructed.
7702 static ImplicitRulesMap *sharedImplicitRulesMap{nullptr};
7703 
7704 bool ResolveNames(
7705     SemanticsContext &context, const parser::Program &program, Scope &top) {
7706   ImplicitRulesMap implicitRulesMap;
7707   auto restorer{common::ScopedSet(sharedImplicitRulesMap, &implicitRulesMap)};
7708   ResolveNamesVisitor{context, implicitRulesMap, top}.Walk(program);
7709   return !context.AnyFatalError();
7710 }
7711 
7712 // Processes a module (but not internal) function when it is referenced
7713 // in a specification expression in a sibling procedure.
7714 void ResolveSpecificationParts(
7715     SemanticsContext &context, const Symbol &subprogram) {
7716   auto originalLocation{context.location()};
7717   ImplicitRulesMap implicitRulesMap;
7718   bool localImplicitRulesMap{false};
7719   if (!sharedImplicitRulesMap) {
7720     sharedImplicitRulesMap = &implicitRulesMap;
7721     localImplicitRulesMap = true;
7722   }
7723   ResolveNamesVisitor visitor{
7724       context, *sharedImplicitRulesMap, context.globalScope()};
7725   const auto &details{subprogram.get<SubprogramNameDetails>()};
7726   ProgramTree &node{details.node()};
7727   const Scope &moduleScope{subprogram.owner()};
7728   if (localImplicitRulesMap) {
7729     visitor.BeginScope(const_cast<Scope &>(moduleScope));
7730   } else {
7731     visitor.SetScope(const_cast<Scope &>(moduleScope));
7732   }
7733   visitor.ResolveSpecificationParts(node);
7734   context.set_location(std::move(originalLocation));
7735   if (localImplicitRulesMap) {
7736     sharedImplicitRulesMap = nullptr;
7737   }
7738 }
7739 
7740 } // namespace Fortran::semantics
7741