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