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