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