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