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