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