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