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