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