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