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