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