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