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