1 //===-- lib/Semantics/check-declarations.cpp ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 // Static declaration checking
10 
11 #include "check-declarations.h"
12 #include "pointer-assignment.h"
13 #include "flang/Evaluate/check-expression.h"
14 #include "flang/Evaluate/fold.h"
15 #include "flang/Evaluate/tools.h"
16 #include "flang/Semantics/scope.h"
17 #include "flang/Semantics/semantics.h"
18 #include "flang/Semantics/symbol.h"
19 #include "flang/Semantics/tools.h"
20 #include "flang/Semantics/type.h"
21 #include <algorithm>
22 #include <map>
23 #include <string>
24 
25 namespace Fortran::semantics {
26 
27 namespace characteristics = evaluate::characteristics;
28 using characteristics::DummyArgument;
29 using characteristics::DummyDataObject;
30 using characteristics::DummyProcedure;
31 using characteristics::FunctionResult;
32 using characteristics::Procedure;
33 
34 class CheckHelper {
35 public:
36   explicit CheckHelper(SemanticsContext &c) : context_{c} {}
37   CheckHelper(SemanticsContext &c, const Scope &s) : context_{c}, scope_{&s} {}
38 
39   SemanticsContext &context() { return context_; }
40   void Check() { Check(context_.globalScope()); }
41   void Check(const ParamValue &, bool canBeAssumed);
42   void Check(const Bound &bound) { CheckSpecExpr(bound.GetExplicit()); }
43   void Check(const ShapeSpec &spec) {
44     Check(spec.lbound());
45     Check(spec.ubound());
46   }
47   void Check(const ArraySpec &);
48   void Check(const DeclTypeSpec &, bool canHaveAssumedTypeParameters);
49   void Check(const Symbol &);
50   void Check(const Scope &);
51   const Procedure *Characterize(const Symbol &);
52 
53 private:
54   template <typename A> void CheckSpecExpr(const A &x) {
55     evaluate::CheckSpecificationExpr(x, DEREF(scope_), foldingContext_);
56   }
57   void CheckValue(const Symbol &, const DerivedTypeSpec *);
58   void CheckVolatile(const Symbol &, const DerivedTypeSpec *);
59   void CheckPointer(const Symbol &);
60   void CheckPassArg(
61       const Symbol &proc, const Symbol *interface, const WithPassArg &);
62   void CheckProcBinding(const Symbol &, const ProcBindingDetails &);
63   void CheckObjectEntity(const Symbol &, const ObjectEntityDetails &);
64   void CheckPointerInitialization(const Symbol &);
65   void CheckArraySpec(const Symbol &, const ArraySpec &);
66   void CheckProcEntity(const Symbol &, const ProcEntityDetails &);
67   void CheckSubprogram(const Symbol &, const SubprogramDetails &);
68   void CheckAssumedTypeEntity(const Symbol &, const ObjectEntityDetails &);
69   void CheckDerivedType(const Symbol &, const DerivedTypeDetails &);
70   bool CheckFinal(
71       const Symbol &subroutine, SourceName, const Symbol &derivedType);
72   bool CheckDistinguishableFinals(const Symbol &f1, SourceName f1name,
73       const Symbol &f2, SourceName f2name, const Symbol &derivedType);
74   void CheckGeneric(const Symbol &, const GenericDetails &);
75   void CheckHostAssoc(const Symbol &, const HostAssocDetails &);
76   bool CheckDefinedOperator(
77       SourceName, GenericKind, const Symbol &, const Procedure &);
78   std::optional<parser::MessageFixedText> CheckNumberOfArgs(
79       const GenericKind &, std::size_t);
80   bool CheckDefinedOperatorArg(
81       const SourceName &, const Symbol &, const Procedure &, std::size_t);
82   bool CheckDefinedAssignment(const Symbol &, const Procedure &);
83   bool CheckDefinedAssignmentArg(const Symbol &, const DummyArgument &, int);
84   void CheckSpecificsAreDistinguishable(const Symbol &, const GenericDetails &);
85   void CheckEquivalenceSet(const EquivalenceSet &);
86   void CheckBlockData(const Scope &);
87   void CheckGenericOps(const Scope &);
88   bool CheckConflicting(const Symbol &, Attr, Attr);
89   void WarnMissingFinal(const Symbol &);
90   bool InPure() const {
91     return innermostSymbol_ && IsPureProcedure(*innermostSymbol_);
92   }
93   bool InFunction() const {
94     return innermostSymbol_ && IsFunction(*innermostSymbol_);
95   }
96   template <typename... A>
97   void SayWithDeclaration(const Symbol &symbol, A &&...x) {
98     if (parser::Message * msg{messages_.Say(std::forward<A>(x)...)}) {
99       if (messages_.at().begin() != symbol.name().begin()) {
100         evaluate::AttachDeclaration(*msg, symbol);
101       }
102     }
103   }
104   bool IsResultOkToDiffer(const FunctionResult &);
105   void CheckBindCName(const Symbol &);
106 
107   SemanticsContext &context_;
108   evaluate::FoldingContext &foldingContext_{context_.foldingContext()};
109   parser::ContextualMessages &messages_{foldingContext_.messages()};
110   const Scope *scope_{nullptr};
111   bool scopeIsUninstantiatedPDT_{false};
112   // This symbol is the one attached to the innermost enclosing scope
113   // that has a symbol.
114   const Symbol *innermostSymbol_{nullptr};
115   // Cache of calls to Procedure::Characterize(Symbol)
116   std::map<SymbolRef, std::optional<Procedure>, SymbolAddressCompare>
117       characterizeCache_;
118   // Collection of symbols with BIND(C) names
119   std::map<std::string, SymbolRef> bindC_;
120 };
121 
122 class DistinguishabilityHelper {
123 public:
124   DistinguishabilityHelper(SemanticsContext &context) : context_{context} {}
125   void Add(const Symbol &, GenericKind, const Symbol &, const Procedure &);
126   void Check(const Scope &);
127 
128 private:
129   void SayNotDistinguishable(const Scope &, const SourceName &, GenericKind,
130       const Symbol &, const Symbol &);
131   void AttachDeclaration(parser::Message &, const Scope &, const Symbol &);
132 
133   SemanticsContext &context_;
134   struct ProcedureInfo {
135     GenericKind kind;
136     const Symbol &symbol;
137     const Procedure &procedure;
138   };
139   std::map<SourceName, std::vector<ProcedureInfo>> nameToInfo_;
140 };
141 
142 void CheckHelper::Check(const ParamValue &value, bool canBeAssumed) {
143   if (value.isAssumed()) {
144     if (!canBeAssumed) { // C795, C721, C726
145       messages_.Say(
146           "An assumed (*) type parameter may be used only for a (non-statement"
147           " function) dummy argument, associate name, named constant, or"
148           " external function result"_err_en_US);
149     }
150   } else {
151     CheckSpecExpr(value.GetExplicit());
152   }
153 }
154 
155 void CheckHelper::Check(const ArraySpec &shape) {
156   for (const auto &spec : shape) {
157     Check(spec);
158   }
159 }
160 
161 void CheckHelper::Check(
162     const DeclTypeSpec &type, bool canHaveAssumedTypeParameters) {
163   if (type.category() == DeclTypeSpec::Character) {
164     Check(type.characterTypeSpec().length(), canHaveAssumedTypeParameters);
165   } else if (const DerivedTypeSpec * derived{type.AsDerived()}) {
166     for (auto &parm : derived->parameters()) {
167       Check(parm.second, canHaveAssumedTypeParameters);
168     }
169   }
170 }
171 
172 void CheckHelper::Check(const Symbol &symbol) {
173   if (context_.HasError(symbol)) {
174     return;
175   }
176   auto restorer{messages_.SetLocation(symbol.name())};
177   context_.set_location(symbol.name());
178   const DeclTypeSpec *type{symbol.GetType()};
179   const DerivedTypeSpec *derived{type ? type->AsDerived() : nullptr};
180   bool isDone{false};
181   std::visit(
182       common::visitors{
183           [&](const UseDetails &x) { isDone = true; },
184           [&](const HostAssocDetails &x) {
185             CheckHostAssoc(symbol, x);
186             isDone = true;
187           },
188           [&](const ProcBindingDetails &x) {
189             CheckProcBinding(symbol, x);
190             isDone = true;
191           },
192           [&](const ObjectEntityDetails &x) { CheckObjectEntity(symbol, x); },
193           [&](const ProcEntityDetails &x) { CheckProcEntity(symbol, x); },
194           [&](const SubprogramDetails &x) { CheckSubprogram(symbol, x); },
195           [&](const DerivedTypeDetails &x) { CheckDerivedType(symbol, x); },
196           [&](const GenericDetails &x) { CheckGeneric(symbol, x); },
197           [](const auto &) {},
198       },
199       symbol.details());
200   if (symbol.attrs().test(Attr::VOLATILE)) {
201     CheckVolatile(symbol, derived);
202   }
203   CheckBindCName(symbol);
204   if (isDone) {
205     return; // following checks do not apply
206   }
207   if (IsPointer(symbol)) {
208     CheckPointer(symbol);
209   }
210   if (InPure()) {
211     if (IsSaved(symbol)) {
212       messages_.Say(
213           "A pure subprogram may not have a variable with the SAVE attribute"_err_en_US);
214     }
215     if (symbol.attrs().test(Attr::VOLATILE)) {
216       messages_.Say(
217           "A pure subprogram may not have a variable with the VOLATILE attribute"_err_en_US);
218     }
219     if (IsProcedure(symbol) && !IsPureProcedure(symbol) && IsDummy(symbol)) {
220       messages_.Say(
221           "A dummy procedure of a pure subprogram must be pure"_err_en_US);
222     }
223     if (!IsDummy(symbol) && !IsFunctionResult(symbol)) {
224       if (IsPolymorphicAllocatable(symbol)) {
225         SayWithDeclaration(symbol,
226             "Deallocation of polymorphic object '%s' is not permitted in a pure subprogram"_err_en_US,
227             symbol.name());
228       } else if (derived) {
229         if (auto bad{FindPolymorphicAllocatableUltimateComponent(*derived)}) {
230           SayWithDeclaration(*bad,
231               "Deallocation of polymorphic object '%s%s' is not permitted in a pure subprogram"_err_en_US,
232               symbol.name(), bad.BuildResultDesignatorName());
233         }
234       }
235     }
236   }
237   if (type) { // Section 7.2, paragraph 7
238     bool canHaveAssumedParameter{IsNamedConstant(symbol) ||
239         (IsAssumedLengthCharacter(symbol) && // C722
240             IsExternal(symbol)) ||
241         symbol.test(Symbol::Flag::ParentComp)};
242     if (!IsStmtFunctionDummy(symbol)) { // C726
243       if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
244         canHaveAssumedParameter |= object->isDummy() ||
245             (object->isFuncResult() &&
246                 type->category() == DeclTypeSpec::Character) ||
247             IsStmtFunctionResult(symbol); // Avoids multiple messages
248       } else {
249         canHaveAssumedParameter |= symbol.has<AssocEntityDetails>();
250       }
251     }
252     Check(*type, canHaveAssumedParameter);
253     if (InPure() && InFunction() && IsFunctionResult(symbol)) {
254       if (derived && HasImpureFinal(*derived)) { // C1584
255         messages_.Say(
256             "Result of pure function may not have an impure FINAL subroutine"_err_en_US);
257       }
258       if (type->IsPolymorphic() && IsAllocatable(symbol)) { // C1585
259         messages_.Say(
260             "Result of pure function may not be both polymorphic and ALLOCATABLE"_err_en_US);
261       }
262       if (derived) {
263         if (auto bad{FindPolymorphicAllocatableUltimateComponent(*derived)}) {
264           SayWithDeclaration(*bad,
265               "Result of pure function may not have polymorphic ALLOCATABLE ultimate component '%s'"_err_en_US,
266               bad.BuildResultDesignatorName());
267         }
268       }
269     }
270   }
271   if (IsAssumedLengthCharacter(symbol) && IsExternal(symbol)) { // C723
272     if (symbol.attrs().test(Attr::RECURSIVE)) {
273       messages_.Say(
274           "An assumed-length CHARACTER(*) function cannot be RECURSIVE"_err_en_US);
275     }
276     if (symbol.Rank() > 0) {
277       messages_.Say(
278           "An assumed-length CHARACTER(*) function cannot return an array"_err_en_US);
279     }
280     if (symbol.attrs().test(Attr::PURE)) {
281       messages_.Say(
282           "An assumed-length CHARACTER(*) function cannot be PURE"_err_en_US);
283     }
284     if (symbol.attrs().test(Attr::ELEMENTAL)) {
285       messages_.Say(
286           "An assumed-length CHARACTER(*) function cannot be ELEMENTAL"_err_en_US);
287     }
288     if (const Symbol * result{FindFunctionResult(symbol)}) {
289       if (IsPointer(*result)) {
290         messages_.Say(
291             "An assumed-length CHARACTER(*) function cannot return a POINTER"_err_en_US);
292       }
293     }
294   }
295   if (symbol.attrs().test(Attr::VALUE)) {
296     CheckValue(symbol, derived);
297   }
298   if (symbol.attrs().test(Attr::CONTIGUOUS) && IsPointer(symbol) &&
299       symbol.Rank() == 0) { // C830
300     messages_.Say("CONTIGUOUS POINTER must be an array"_err_en_US);
301   }
302   if (IsDummy(symbol)) {
303     if (IsNamedConstant(symbol)) {
304       messages_.Say(
305           "A dummy argument may not also be a named constant"_err_en_US);
306     }
307     if (IsSaved(symbol)) {
308       messages_.Say(
309           "A dummy argument may not have the SAVE attribute"_err_en_US);
310     }
311   } else if (IsFunctionResult(symbol)) {
312     if (IsSaved(symbol)) {
313       messages_.Say(
314           "A function result may not have the SAVE attribute"_err_en_US);
315     }
316   }
317   if (symbol.owner().IsDerivedType() &&
318       (symbol.attrs().test(Attr::CONTIGUOUS) &&
319           !(IsPointer(symbol) && symbol.Rank() > 0))) { // C752
320     messages_.Say(
321         "A CONTIGUOUS component must be an array with the POINTER attribute"_err_en_US);
322   }
323   if (symbol.owner().IsModule() && IsAutomatic(symbol)) {
324     messages_.Say(
325         "Automatic data object '%s' may not appear in the specification part"
326         " of a module"_err_en_US,
327         symbol.name());
328   }
329 }
330 
331 void CheckHelper::CheckValue(
332     const Symbol &symbol, const DerivedTypeSpec *derived) { // C863 - C865
333   if (!IsDummy(symbol)) {
334     messages_.Say(
335         "VALUE attribute may apply only to a dummy argument"_err_en_US);
336   }
337   if (IsProcedure(symbol)) {
338     messages_.Say(
339         "VALUE attribute may apply only to a dummy data object"_err_en_US);
340   }
341   if (IsAssumedSizeArray(symbol)) {
342     messages_.Say(
343         "VALUE attribute may not apply to an assumed-size array"_err_en_US);
344   }
345   if (IsCoarray(symbol)) {
346     messages_.Say("VALUE attribute may not apply to a coarray"_err_en_US);
347   }
348   if (IsAllocatable(symbol)) {
349     messages_.Say("VALUE attribute may not apply to an ALLOCATABLE"_err_en_US);
350   } else if (IsPointer(symbol)) {
351     messages_.Say("VALUE attribute may not apply to a POINTER"_err_en_US);
352   }
353   if (IsIntentInOut(symbol)) {
354     messages_.Say(
355         "VALUE attribute may not apply to an INTENT(IN OUT) argument"_err_en_US);
356   } else if (IsIntentOut(symbol)) {
357     messages_.Say(
358         "VALUE attribute may not apply to an INTENT(OUT) argument"_err_en_US);
359   }
360   if (symbol.attrs().test(Attr::VOLATILE)) {
361     messages_.Say("VALUE attribute may not apply to a VOLATILE"_err_en_US);
362   }
363   if (innermostSymbol_ && IsBindCProcedure(*innermostSymbol_) &&
364       IsOptional(symbol)) {
365     messages_.Say(
366         "VALUE attribute may not apply to an OPTIONAL in a BIND(C) procedure"_err_en_US);
367   }
368   if (derived) {
369     if (FindCoarrayUltimateComponent(*derived)) {
370       messages_.Say(
371           "VALUE attribute may not apply to a type with a coarray ultimate component"_err_en_US);
372     }
373   }
374 }
375 
376 void CheckHelper::CheckAssumedTypeEntity( // C709
377     const Symbol &symbol, const ObjectEntityDetails &details) {
378   if (const DeclTypeSpec * type{symbol.GetType()};
379       type && type->category() == DeclTypeSpec::TypeStar) {
380     if (!IsDummy(symbol)) {
381       messages_.Say(
382           "Assumed-type entity '%s' must be a dummy argument"_err_en_US,
383           symbol.name());
384     } else {
385       if (symbol.attrs().test(Attr::ALLOCATABLE)) {
386         messages_.Say("Assumed-type argument '%s' cannot have the ALLOCATABLE"
387                       " attribute"_err_en_US,
388             symbol.name());
389       }
390       if (symbol.attrs().test(Attr::POINTER)) {
391         messages_.Say("Assumed-type argument '%s' cannot have the POINTER"
392                       " attribute"_err_en_US,
393             symbol.name());
394       }
395       if (symbol.attrs().test(Attr::VALUE)) {
396         messages_.Say("Assumed-type argument '%s' cannot have the VALUE"
397                       " attribute"_err_en_US,
398             symbol.name());
399       }
400       if (symbol.attrs().test(Attr::INTENT_OUT)) {
401         messages_.Say(
402             "Assumed-type argument '%s' cannot be INTENT(OUT)"_err_en_US,
403             symbol.name());
404       }
405       if (IsCoarray(symbol)) {
406         messages_.Say(
407             "Assumed-type argument '%s' cannot be a coarray"_err_en_US,
408             symbol.name());
409       }
410       if (details.IsArray() && details.shape().IsExplicitShape()) {
411         messages_.Say(
412             "Assumed-type array argument 'arg8' must be assumed shape,"
413             " assumed size, or assumed rank"_err_en_US,
414             symbol.name());
415       }
416     }
417   }
418 }
419 
420 void CheckHelper::CheckObjectEntity(
421     const Symbol &symbol, const ObjectEntityDetails &details) {
422   CheckArraySpec(symbol, details.shape());
423   Check(details.shape());
424   Check(details.coshape());
425   CheckAssumedTypeEntity(symbol, details);
426   WarnMissingFinal(symbol);
427   if (!details.coshape().empty()) {
428     bool isDeferredShape{details.coshape().IsDeferredShape()};
429     if (IsAllocatable(symbol)) {
430       if (!isDeferredShape) { // C827
431         messages_.Say("'%s' is an ALLOCATABLE coarray and must have a deferred"
432                       " coshape"_err_en_US,
433             symbol.name());
434       }
435     } else if (symbol.owner().IsDerivedType()) { // C746
436       std::string deferredMsg{
437           isDeferredShape ? "" : " and have a deferred coshape"};
438       messages_.Say("Component '%s' is a coarray and must have the ALLOCATABLE"
439                     " attribute%s"_err_en_US,
440           symbol.name(), deferredMsg);
441     } else {
442       if (!details.coshape().IsAssumedSize()) { // C828
443         messages_.Say(
444             "Component '%s' is a non-ALLOCATABLE coarray and must have"
445             " an explicit coshape"_err_en_US,
446             symbol.name());
447       }
448     }
449   }
450   if (details.isDummy()) {
451     if (symbol.attrs().test(Attr::INTENT_OUT)) {
452       if (FindUltimateComponent(symbol, [](const Symbol &x) {
453             return IsCoarray(x) && IsAllocatable(x);
454           })) { // C846
455         messages_.Say(
456             "An INTENT(OUT) dummy argument may not be, or contain, an ALLOCATABLE coarray"_err_en_US);
457       }
458       if (IsOrContainsEventOrLockComponent(symbol)) { // C847
459         messages_.Say(
460             "An INTENT(OUT) dummy argument may not be, or contain, EVENT_TYPE or LOCK_TYPE"_err_en_US);
461       }
462     }
463     if (InPure() && !IsStmtFunction(DEREF(innermostSymbol_)) &&
464         !IsPointer(symbol) && !IsIntentIn(symbol) &&
465         !symbol.attrs().test(Attr::VALUE)) {
466       if (InFunction()) { // C1583
467         messages_.Say(
468             "non-POINTER dummy argument of pure function must be INTENT(IN) or VALUE"_err_en_US);
469       } else if (IsIntentOut(symbol)) {
470         if (const DeclTypeSpec * type{details.type()}) {
471           if (type && type->IsPolymorphic()) { // C1588
472             messages_.Say(
473                 "An INTENT(OUT) dummy argument of a pure subroutine may not be polymorphic"_err_en_US);
474           } else if (const DerivedTypeSpec * derived{type->AsDerived()}) {
475             if (FindUltimateComponent(*derived, [](const Symbol &x) {
476                   const DeclTypeSpec *type{x.GetType()};
477                   return type && type->IsPolymorphic();
478                 })) { // C1588
479               messages_.Say(
480                   "An INTENT(OUT) dummy argument of a pure subroutine may not have a polymorphic ultimate component"_err_en_US);
481             }
482             if (HasImpureFinal(*derived)) { // C1587
483               messages_.Say(
484                   "An INTENT(OUT) dummy argument of a pure subroutine may not have an impure FINAL subroutine"_err_en_US);
485             }
486           }
487         }
488       } else if (!IsIntentInOut(symbol)) { // C1586
489         messages_.Say(
490             "non-POINTER dummy argument of pure subroutine must have INTENT() or VALUE attribute"_err_en_US);
491       }
492     }
493   }
494   if (IsStaticallyInitialized(symbol, true /* ignore DATA inits */)) { // C808
495     CheckPointerInitialization(symbol);
496     if (IsAutomatic(symbol)) {
497       messages_.Say(
498           "An automatic variable or component must not be initialized"_err_en_US);
499     } else if (IsDummy(symbol)) {
500       messages_.Say("A dummy argument must not be initialized"_err_en_US);
501     } else if (IsFunctionResult(symbol)) {
502       messages_.Say("A function result must not be initialized"_err_en_US);
503     } else if (IsInBlankCommon(symbol)) {
504       messages_.Say(
505           "A variable in blank COMMON should not be initialized"_en_US);
506     }
507   }
508   if (symbol.owner().kind() == Scope::Kind::BlockData) {
509     if (IsAllocatable(symbol)) {
510       messages_.Say(
511           "An ALLOCATABLE variable may not appear in a BLOCK DATA subprogram"_err_en_US);
512     } else if (IsInitialized(symbol) && !FindCommonBlockContaining(symbol)) {
513       messages_.Say(
514           "An initialized variable in BLOCK DATA must be in a COMMON block"_err_en_US);
515     }
516   }
517   if (const DeclTypeSpec * type{details.type()}) { // C708
518     if (type->IsPolymorphic() &&
519         !(type->IsAssumedType() || IsAllocatableOrPointer(symbol) ||
520             IsDummy(symbol))) {
521       messages_.Say("CLASS entity '%s' must be a dummy argument or have "
522                     "ALLOCATABLE or POINTER attribute"_err_en_US,
523           symbol.name());
524     }
525   }
526 }
527 
528 void CheckHelper::CheckPointerInitialization(const Symbol &symbol) {
529   if (IsPointer(symbol) && !context_.HasError(symbol) &&
530       !scopeIsUninstantiatedPDT_) {
531     if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
532       if (object->init()) { // C764, C765; C808
533         if (auto dyType{evaluate::DynamicType::From(symbol)}) {
534           if (auto designator{evaluate::TypedWrapper<evaluate::Designator>(
535                   *dyType, evaluate::DataRef{symbol})}) {
536             auto restorer{messages_.SetLocation(symbol.name())};
537             context_.set_location(symbol.name());
538             CheckInitialTarget(foldingContext_, *designator, *object->init());
539           }
540         }
541       }
542     } else if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}) {
543       if (proc->init() && *proc->init()) {
544         // C1519 - must be nonelemental external or module procedure,
545         // or an unrestricted specific intrinsic function.
546         const Symbol &ultimate{(*proc->init())->GetUltimate()};
547         if (ultimate.attrs().test(Attr::INTRINSIC)) {
548         } else if (!ultimate.attrs().test(Attr::EXTERNAL) &&
549             ultimate.owner().kind() != Scope::Kind::Module) {
550           context_.Say("Procedure pointer '%s' initializer '%s' is neither "
551                        "an external nor a module procedure"_err_en_US,
552               symbol.name(), ultimate.name());
553         } else if (ultimate.attrs().test(Attr::ELEMENTAL)) {
554           context_.Say("Procedure pointer '%s' cannot be initialized with the "
555                        "elemental procedure '%s"_err_en_US,
556               symbol.name(), ultimate.name());
557         } else {
558           // TODO: Check the "shalls" in the 15.4.3.6 paragraphs 7-10.
559         }
560       }
561     }
562   }
563 }
564 
565 // The six different kinds of array-specs:
566 //   array-spec     -> explicit-shape-list | deferred-shape-list
567 //                     | assumed-shape-list | implied-shape-list
568 //                     | assumed-size | assumed-rank
569 //   explicit-shape -> [ lb : ] ub
570 //   deferred-shape -> :
571 //   assumed-shape  -> [ lb ] :
572 //   implied-shape  -> [ lb : ] *
573 //   assumed-size   -> [ explicit-shape-list , ] [ lb : ] *
574 //   assumed-rank   -> ..
575 // Note:
576 // - deferred-shape is also an assumed-shape
577 // - A single "*" or "lb:*" might be assumed-size or implied-shape-list
578 void CheckHelper::CheckArraySpec(
579     const Symbol &symbol, const ArraySpec &arraySpec) {
580   if (arraySpec.Rank() == 0) {
581     return;
582   }
583   bool isExplicit{arraySpec.IsExplicitShape()};
584   bool isDeferred{arraySpec.IsDeferredShape()};
585   bool isImplied{arraySpec.IsImpliedShape()};
586   bool isAssumedShape{arraySpec.IsAssumedShape()};
587   bool isAssumedSize{arraySpec.IsAssumedSize()};
588   bool isAssumedRank{arraySpec.IsAssumedRank()};
589   std::optional<parser::MessageFixedText> msg;
590   if (symbol.test(Symbol::Flag::CrayPointee) && !isExplicit && !isAssumedSize) {
591     msg = "Cray pointee '%s' must have must have explicit shape or"
592           " assumed size"_err_en_US;
593   } else if (IsAllocatableOrPointer(symbol) && !isDeferred && !isAssumedRank) {
594     if (symbol.owner().IsDerivedType()) { // C745
595       if (IsAllocatable(symbol)) {
596         msg = "Allocatable array component '%s' must have"
597               " deferred shape"_err_en_US;
598       } else {
599         msg = "Array pointer component '%s' must have deferred shape"_err_en_US;
600       }
601     } else {
602       if (IsAllocatable(symbol)) { // C832
603         msg = "Allocatable array '%s' must have deferred shape or"
604               " assumed rank"_err_en_US;
605       } else {
606         msg = "Array pointer '%s' must have deferred shape or"
607               " assumed rank"_err_en_US;
608       }
609     }
610   } else if (IsDummy(symbol)) {
611     if (isImplied && !isAssumedSize) { // C836
612       msg = "Dummy array argument '%s' may not have implied shape"_err_en_US;
613     }
614   } else if (isAssumedShape && !isDeferred) {
615     msg = "Assumed-shape array '%s' must be a dummy argument"_err_en_US;
616   } else if (isAssumedSize && !isImplied) { // C833
617     msg = "Assumed-size array '%s' must be a dummy argument"_err_en_US;
618   } else if (isAssumedRank) { // C837
619     msg = "Assumed-rank array '%s' must be a dummy argument"_err_en_US;
620   } else if (isImplied) {
621     if (!IsNamedConstant(symbol)) { // C836
622       msg = "Implied-shape array '%s' must be a named constant"_err_en_US;
623     }
624   } else if (IsNamedConstant(symbol)) {
625     if (!isExplicit && !isImplied) {
626       msg = "Named constant '%s' array must have constant or"
627             " implied shape"_err_en_US;
628     }
629   } else if (!IsAllocatableOrPointer(symbol) && !isExplicit) {
630     if (symbol.owner().IsDerivedType()) { // C749
631       msg = "Component array '%s' without ALLOCATABLE or POINTER attribute must"
632             " have explicit shape"_err_en_US;
633     } else { // C816
634       msg = "Array '%s' without ALLOCATABLE or POINTER attribute must have"
635             " explicit shape"_err_en_US;
636     }
637   }
638   if (msg) {
639     context_.Say(std::move(*msg), symbol.name());
640   }
641 }
642 
643 void CheckHelper::CheckProcEntity(
644     const Symbol &symbol, const ProcEntityDetails &details) {
645   if (details.isDummy()) {
646     if (!symbol.attrs().test(Attr::POINTER) && // C843
647         (symbol.attrs().test(Attr::INTENT_IN) ||
648             symbol.attrs().test(Attr::INTENT_OUT) ||
649             symbol.attrs().test(Attr::INTENT_INOUT))) {
650       messages_.Say("A dummy procedure without the POINTER attribute"
651                     " may not have an INTENT attribute"_err_en_US);
652     }
653 
654     const Symbol *interface{details.interface().symbol()};
655     if (!symbol.attrs().test(Attr::INTRINSIC) &&
656         (symbol.attrs().test(Attr::ELEMENTAL) ||
657             (interface && !interface->attrs().test(Attr::INTRINSIC) &&
658                 interface->attrs().test(Attr::ELEMENTAL)))) {
659       // There's no explicit constraint or "shall" that we can find in the
660       // standard for this check, but it seems to be implied in multiple
661       // sites, and ELEMENTAL non-intrinsic actual arguments *are*
662       // explicitly forbidden.  But we allow "PROCEDURE(SIN)::dummy"
663       // because it is explicitly legal to *pass* the specific intrinsic
664       // function SIN as an actual argument.
665       messages_.Say("A dummy procedure may not be ELEMENTAL"_err_en_US);
666     }
667   } else if (symbol.owner().IsDerivedType()) {
668     if (!symbol.attrs().test(Attr::POINTER)) { // C756
669       const auto &name{symbol.name()};
670       messages_.Say(name,
671           "Procedure component '%s' must have POINTER attribute"_err_en_US,
672           name);
673     }
674     CheckPassArg(symbol, details.interface().symbol(), details);
675   }
676   if (symbol.attrs().test(Attr::POINTER)) {
677     CheckPointerInitialization(symbol);
678     if (const Symbol * interface{details.interface().symbol()}) {
679       if (interface->attrs().test(Attr::ELEMENTAL) &&
680           !interface->attrs().test(Attr::INTRINSIC)) {
681         messages_.Say("Procedure pointer '%s' may not be ELEMENTAL"_err_en_US,
682             symbol.name()); // C1517
683       }
684     }
685   } else if (symbol.attrs().test(Attr::SAVE)) {
686     messages_.Say(
687         "Procedure '%s' with SAVE attribute must also have POINTER attribute"_err_en_US,
688         symbol.name());
689   }
690 }
691 
692 // When a module subprogram has the MODULE prefix the following must match
693 // with the corresponding separate module procedure interface body:
694 // - C1549: characteristics and dummy argument names
695 // - C1550: binding label
696 // - C1551: NON_RECURSIVE prefix
697 class SubprogramMatchHelper {
698 public:
699   explicit SubprogramMatchHelper(CheckHelper &checkHelper)
700       : checkHelper{checkHelper} {}
701 
702   void Check(const Symbol &, const Symbol &);
703 
704 private:
705   SemanticsContext &context() { return checkHelper.context(); }
706   void CheckDummyArg(const Symbol &, const Symbol &, const DummyArgument &,
707       const DummyArgument &);
708   void CheckDummyDataObject(const Symbol &, const Symbol &,
709       const DummyDataObject &, const DummyDataObject &);
710   void CheckDummyProcedure(const Symbol &, const Symbol &,
711       const DummyProcedure &, const DummyProcedure &);
712   bool CheckSameIntent(
713       const Symbol &, const Symbol &, common::Intent, common::Intent);
714   template <typename... A>
715   void Say(
716       const Symbol &, const Symbol &, parser::MessageFixedText &&, A &&...);
717   template <typename ATTRS>
718   bool CheckSameAttrs(const Symbol &, const Symbol &, ATTRS, ATTRS);
719   bool ShapesAreCompatible(const DummyDataObject &, const DummyDataObject &);
720   evaluate::Shape FoldShape(const evaluate::Shape &);
721   std::string AsFortran(DummyDataObject::Attr attr) {
722     return parser::ToUpperCaseLetters(DummyDataObject::EnumToString(attr));
723   }
724   std::string AsFortran(DummyProcedure::Attr attr) {
725     return parser::ToUpperCaseLetters(DummyProcedure::EnumToString(attr));
726   }
727 
728   CheckHelper &checkHelper;
729 };
730 
731 // 15.6.2.6 para 3 - can the result of an ENTRY differ from its function?
732 bool CheckHelper::IsResultOkToDiffer(const FunctionResult &result) {
733   if (result.attrs.test(FunctionResult::Attr::Allocatable) ||
734       result.attrs.test(FunctionResult::Attr::Pointer)) {
735     return false;
736   }
737   const auto *typeAndShape{result.GetTypeAndShape()};
738   if (!typeAndShape || typeAndShape->Rank() != 0) {
739     return false;
740   }
741   auto category{typeAndShape->type().category()};
742   if (category == TypeCategory::Character ||
743       category == TypeCategory::Derived) {
744     return false;
745   }
746   int kind{typeAndShape->type().kind()};
747   return kind == context_.GetDefaultKind(category) ||
748       (category == TypeCategory::Real &&
749           kind == context_.doublePrecisionKind());
750 }
751 
752 void CheckHelper::CheckSubprogram(
753     const Symbol &symbol, const SubprogramDetails &details) {
754   if (const Symbol * iface{FindSeparateModuleSubprogramInterface(&symbol)}) {
755     SubprogramMatchHelper{*this}.Check(symbol, *iface);
756   }
757   if (const Scope * entryScope{details.entryScope()}) {
758     // ENTRY 15.6.2.6, esp. C1571
759     std::optional<parser::MessageFixedText> error;
760     const Symbol *subprogram{entryScope->symbol()};
761     const SubprogramDetails *subprogramDetails{nullptr};
762     if (subprogram) {
763       subprogramDetails = subprogram->detailsIf<SubprogramDetails>();
764     }
765     if (entryScope->kind() != Scope::Kind::Subprogram) {
766       error = "ENTRY may appear only in a subroutine or function"_err_en_US;
767     } else if (!(entryScope->parent().IsGlobal() ||
768                    entryScope->parent().IsModule() ||
769                    entryScope->parent().IsSubmodule())) {
770       error = "ENTRY may not appear in an internal subprogram"_err_en_US;
771     } else if (FindSeparateModuleSubprogramInterface(subprogram)) {
772       error = "ENTRY may not appear in a separate module procedure"_err_en_US;
773     } else if (subprogramDetails && details.isFunction() &&
774         subprogramDetails->isFunction()) {
775       auto result{FunctionResult::Characterize(
776           details.result(), context_.foldingContext())};
777       auto subpResult{FunctionResult::Characterize(
778           subprogramDetails->result(), context_.foldingContext())};
779       if (result && subpResult && *result != *subpResult &&
780           (!IsResultOkToDiffer(*result) || !IsResultOkToDiffer(*subpResult))) {
781         error =
782             "Result of ENTRY is not compatible with result of containing function"_err_en_US;
783       }
784     }
785     if (error) {
786       if (auto *msg{messages_.Say(symbol.name(), *error)}) {
787         if (subprogram) {
788           msg->Attach(subprogram->name(), "Containing subprogram"_en_US);
789         }
790       }
791     }
792   }
793 }
794 
795 void CheckHelper::CheckDerivedType(
796     const Symbol &derivedType, const DerivedTypeDetails &details) {
797   const Scope *scope{derivedType.scope()};
798   if (!scope) {
799     CHECK(details.isForwardReferenced());
800     return;
801   }
802   CHECK(scope->symbol() == &derivedType);
803   CHECK(scope->IsDerivedType());
804   if (derivedType.attrs().test(Attr::ABSTRACT) && // C734
805       (derivedType.attrs().test(Attr::BIND_C) || details.sequence())) {
806     messages_.Say("An ABSTRACT derived type must be extensible"_err_en_US);
807   }
808   if (const DeclTypeSpec * parent{FindParentTypeSpec(derivedType)}) {
809     const DerivedTypeSpec *parentDerived{parent->AsDerived()};
810     if (!IsExtensibleType(parentDerived)) { // C705
811       messages_.Say("The parent type is not extensible"_err_en_US);
812     }
813     if (!derivedType.attrs().test(Attr::ABSTRACT) && parentDerived &&
814         parentDerived->typeSymbol().attrs().test(Attr::ABSTRACT)) {
815       ScopeComponentIterator components{*parentDerived};
816       for (const Symbol &component : components) {
817         if (component.attrs().test(Attr::DEFERRED)) {
818           if (scope->FindComponent(component.name()) == &component) {
819             SayWithDeclaration(component,
820                 "Non-ABSTRACT extension of ABSTRACT derived type '%s' lacks a binding for DEFERRED procedure '%s'"_err_en_US,
821                 parentDerived->typeSymbol().name(), component.name());
822           }
823         }
824       }
825     }
826     DerivedTypeSpec derived{derivedType.name(), derivedType};
827     derived.set_scope(*scope);
828     if (FindCoarrayUltimateComponent(derived) && // C736
829         !(parentDerived && FindCoarrayUltimateComponent(*parentDerived))) {
830       messages_.Say(
831           "Type '%s' has a coarray ultimate component so the type at the base "
832           "of its type extension chain ('%s') must be a type that has a "
833           "coarray ultimate component"_err_en_US,
834           derivedType.name(), scope->GetDerivedTypeBase().GetSymbol()->name());
835     }
836     if (FindEventOrLockPotentialComponent(derived) && // C737
837         !(FindEventOrLockPotentialComponent(*parentDerived) ||
838             IsEventTypeOrLockType(parentDerived))) {
839       messages_.Say(
840           "Type '%s' has an EVENT_TYPE or LOCK_TYPE component, so the type "
841           "at the base of its type extension chain ('%s') must either have an "
842           "EVENT_TYPE or LOCK_TYPE component, or be EVENT_TYPE or "
843           "LOCK_TYPE"_err_en_US,
844           derivedType.name(), scope->GetDerivedTypeBase().GetSymbol()->name());
845     }
846   }
847   if (HasIntrinsicTypeName(derivedType)) { // C729
848     messages_.Say("A derived type name cannot be the name of an intrinsic"
849                   " type"_err_en_US);
850   }
851   std::map<SourceName, SymbolRef> previous;
852   for (const auto &pair : details.finals()) {
853     SourceName source{pair.first};
854     const Symbol &ref{*pair.second};
855     if (CheckFinal(ref, source, derivedType) &&
856         std::all_of(previous.begin(), previous.end(),
857             [&](std::pair<SourceName, SymbolRef> prev) {
858               return CheckDistinguishableFinals(
859                   ref, source, *prev.second, prev.first, derivedType);
860             })) {
861       previous.emplace(source, ref);
862     }
863   }
864 }
865 
866 // C786
867 bool CheckHelper::CheckFinal(
868     const Symbol &subroutine, SourceName finalName, const Symbol &derivedType) {
869   if (!IsModuleProcedure(subroutine)) {
870     SayWithDeclaration(subroutine, finalName,
871         "FINAL subroutine '%s' of derived type '%s' must be a module procedure"_err_en_US,
872         subroutine.name(), derivedType.name());
873     return false;
874   }
875   const Procedure *proc{Characterize(subroutine)};
876   if (!proc) {
877     return false; // error recovery
878   }
879   if (!proc->IsSubroutine()) {
880     SayWithDeclaration(subroutine, finalName,
881         "FINAL subroutine '%s' of derived type '%s' must be a subroutine"_err_en_US,
882         subroutine.name(), derivedType.name());
883     return false;
884   }
885   if (proc->dummyArguments.size() != 1) {
886     SayWithDeclaration(subroutine, finalName,
887         "FINAL subroutine '%s' of derived type '%s' must have a single dummy argument"_err_en_US,
888         subroutine.name(), derivedType.name());
889     return false;
890   }
891   const auto &arg{proc->dummyArguments[0]};
892   const Symbol *errSym{&subroutine};
893   if (const auto *details{subroutine.detailsIf<SubprogramDetails>()}) {
894     if (!details->dummyArgs().empty()) {
895       if (const Symbol * argSym{details->dummyArgs()[0]}) {
896         errSym = argSym;
897       }
898     }
899   }
900   const auto *ddo{std::get_if<DummyDataObject>(&arg.u)};
901   if (!ddo) {
902     SayWithDeclaration(subroutine, finalName,
903         "FINAL subroutine '%s' of derived type '%s' must have a single dummy argument that is a data object"_err_en_US,
904         subroutine.name(), derivedType.name());
905     return false;
906   }
907   bool ok{true};
908   if (arg.IsOptional()) {
909     SayWithDeclaration(*errSym, finalName,
910         "FINAL subroutine '%s' of derived type '%s' must not have an OPTIONAL dummy argument"_err_en_US,
911         subroutine.name(), derivedType.name());
912     ok = false;
913   }
914   if (ddo->attrs.test(DummyDataObject::Attr::Allocatable)) {
915     SayWithDeclaration(*errSym, finalName,
916         "FINAL subroutine '%s' of derived type '%s' must not have an ALLOCATABLE dummy argument"_err_en_US,
917         subroutine.name(), derivedType.name());
918     ok = false;
919   }
920   if (ddo->attrs.test(DummyDataObject::Attr::Pointer)) {
921     SayWithDeclaration(*errSym, finalName,
922         "FINAL subroutine '%s' of derived type '%s' must not have a POINTER dummy argument"_err_en_US,
923         subroutine.name(), derivedType.name());
924     ok = false;
925   }
926   if (ddo->intent == common::Intent::Out) {
927     SayWithDeclaration(*errSym, finalName,
928         "FINAL subroutine '%s' of derived type '%s' must not have a dummy argument with INTENT(OUT)"_err_en_US,
929         subroutine.name(), derivedType.name());
930     ok = false;
931   }
932   if (ddo->attrs.test(DummyDataObject::Attr::Value)) {
933     SayWithDeclaration(*errSym, finalName,
934         "FINAL subroutine '%s' of derived type '%s' must not have a dummy argument with the VALUE attribute"_err_en_US,
935         subroutine.name(), derivedType.name());
936     ok = false;
937   }
938   if (ddo->type.corank() > 0) {
939     SayWithDeclaration(*errSym, finalName,
940         "FINAL subroutine '%s' of derived type '%s' must not have a coarray dummy argument"_err_en_US,
941         subroutine.name(), derivedType.name());
942     ok = false;
943   }
944   if (ddo->type.type().IsPolymorphic()) {
945     SayWithDeclaration(*errSym, finalName,
946         "FINAL subroutine '%s' of derived type '%s' must not have a polymorphic dummy argument"_err_en_US,
947         subroutine.name(), derivedType.name());
948     ok = false;
949   } else if (ddo->type.type().category() != TypeCategory::Derived ||
950       &ddo->type.type().GetDerivedTypeSpec().typeSymbol() != &derivedType) {
951     SayWithDeclaration(*errSym, finalName,
952         "FINAL subroutine '%s' of derived type '%s' must have a TYPE(%s) dummy argument"_err_en_US,
953         subroutine.name(), derivedType.name(), derivedType.name());
954     ok = false;
955   } else { // check that all LEN type parameters are assumed
956     for (auto ref : OrderParameterDeclarations(derivedType)) {
957       if (IsLenTypeParameter(*ref)) {
958         const auto *value{
959             ddo->type.type().GetDerivedTypeSpec().FindParameter(ref->name())};
960         if (!value || !value->isAssumed()) {
961           SayWithDeclaration(*errSym, finalName,
962               "FINAL subroutine '%s' of derived type '%s' must have a dummy argument with an assumed LEN type parameter '%s=*'"_err_en_US,
963               subroutine.name(), derivedType.name(), ref->name());
964           ok = false;
965         }
966       }
967     }
968   }
969   return ok;
970 }
971 
972 bool CheckHelper::CheckDistinguishableFinals(const Symbol &f1,
973     SourceName f1Name, const Symbol &f2, SourceName f2Name,
974     const Symbol &derivedType) {
975   const Procedure *p1{Characterize(f1)};
976   const Procedure *p2{Characterize(f2)};
977   if (p1 && p2) {
978     if (characteristics::Distinguishable(*p1, *p2)) {
979       return true;
980     }
981     if (auto *msg{messages_.Say(f1Name,
982             "FINAL subroutines '%s' and '%s' of derived type '%s' cannot be distinguished by rank or KIND type parameter value"_err_en_US,
983             f1Name, f2Name, derivedType.name())}) {
984       msg->Attach(f2Name, "FINAL declaration of '%s'"_en_US, f2.name())
985           .Attach(f1.name(), "Definition of '%s'"_en_US, f1Name)
986           .Attach(f2.name(), "Definition of '%s'"_en_US, f2Name);
987     }
988   }
989   return false;
990 }
991 
992 void CheckHelper::CheckHostAssoc(
993     const Symbol &symbol, const HostAssocDetails &details) {
994   const Symbol &hostSymbol{details.symbol()};
995   if (hostSymbol.test(Symbol::Flag::ImplicitOrError)) {
996     if (details.implicitOrSpecExprError) {
997       messages_.Say("Implicitly typed local entity '%s' not allowed in"
998                     " specification expression"_err_en_US,
999           symbol.name());
1000     } else if (details.implicitOrExplicitTypeError) {
1001       messages_.Say(
1002           "No explicit type declared for '%s'"_err_en_US, symbol.name());
1003     }
1004   }
1005 }
1006 
1007 void CheckHelper::CheckGeneric(
1008     const Symbol &symbol, const GenericDetails &details) {
1009   CheckSpecificsAreDistinguishable(symbol, details);
1010 }
1011 
1012 // Check that the specifics of this generic are distinguishable from each other
1013 void CheckHelper::CheckSpecificsAreDistinguishable(
1014     const Symbol &generic, const GenericDetails &details) {
1015   GenericKind kind{details.kind()};
1016   const SymbolVector &specifics{details.specificProcs()};
1017   std::size_t count{specifics.size()};
1018   if (count < 2 || !kind.IsName()) {
1019     return;
1020   }
1021   DistinguishabilityHelper helper{context_};
1022   for (const Symbol &specific : specifics) {
1023     if (const Procedure * procedure{Characterize(specific)}) {
1024       helper.Add(generic, kind, specific, *procedure);
1025     }
1026   }
1027   helper.Check(generic.owner());
1028 }
1029 
1030 static bool ConflictsWithIntrinsicAssignment(const Procedure &proc) {
1031   auto lhs{std::get<DummyDataObject>(proc.dummyArguments[0].u).type};
1032   auto rhs{std::get<DummyDataObject>(proc.dummyArguments[1].u).type};
1033   return Tristate::No ==
1034       IsDefinedAssignment(lhs.type(), lhs.Rank(), rhs.type(), rhs.Rank());
1035 }
1036 
1037 static bool ConflictsWithIntrinsicOperator(
1038     const GenericKind &kind, const Procedure &proc) {
1039   if (!kind.IsIntrinsicOperator()) {
1040     return false;
1041   }
1042   auto arg0{std::get<DummyDataObject>(proc.dummyArguments[0].u).type};
1043   auto type0{arg0.type()};
1044   if (proc.dummyArguments.size() == 1) { // unary
1045     return std::visit(
1046         common::visitors{
1047             [&](common::NumericOperator) { return IsIntrinsicNumeric(type0); },
1048             [&](common::LogicalOperator) { return IsIntrinsicLogical(type0); },
1049             [](const auto &) -> bool { DIE("bad generic kind"); },
1050         },
1051         kind.u);
1052   } else { // binary
1053     int rank0{arg0.Rank()};
1054     auto arg1{std::get<DummyDataObject>(proc.dummyArguments[1].u).type};
1055     auto type1{arg1.type()};
1056     int rank1{arg1.Rank()};
1057     return std::visit(
1058         common::visitors{
1059             [&](common::NumericOperator) {
1060               return IsIntrinsicNumeric(type0, rank0, type1, rank1);
1061             },
1062             [&](common::LogicalOperator) {
1063               return IsIntrinsicLogical(type0, rank0, type1, rank1);
1064             },
1065             [&](common::RelationalOperator opr) {
1066               return IsIntrinsicRelational(opr, type0, rank0, type1, rank1);
1067             },
1068             [&](GenericKind::OtherKind x) {
1069               CHECK(x == GenericKind::OtherKind::Concat);
1070               return IsIntrinsicConcat(type0, rank0, type1, rank1);
1071             },
1072             [](const auto &) -> bool { DIE("bad generic kind"); },
1073         },
1074         kind.u);
1075   }
1076 }
1077 
1078 // Check if this procedure can be used for defined operators (see 15.4.3.4.2).
1079 bool CheckHelper::CheckDefinedOperator(SourceName opName, GenericKind kind,
1080     const Symbol &specific, const Procedure &proc) {
1081   if (context_.HasError(specific)) {
1082     return false;
1083   }
1084   std::optional<parser::MessageFixedText> msg;
1085   if (specific.attrs().test(Attr::NOPASS)) { // C774
1086     msg = "%s procedure '%s' may not have NOPASS attribute"_err_en_US;
1087   } else if (!proc.functionResult.has_value()) {
1088     msg = "%s procedure '%s' must be a function"_err_en_US;
1089   } else if (proc.functionResult->IsAssumedLengthCharacter()) {
1090     msg = "%s function '%s' may not have assumed-length CHARACTER(*)"
1091           " result"_err_en_US;
1092   } else if (auto m{CheckNumberOfArgs(kind, proc.dummyArguments.size())}) {
1093     msg = std::move(m);
1094   } else if (!CheckDefinedOperatorArg(opName, specific, proc, 0) |
1095       !CheckDefinedOperatorArg(opName, specific, proc, 1)) {
1096     return false; // error was reported
1097   } else if (ConflictsWithIntrinsicOperator(kind, proc)) {
1098     msg = "%s function '%s' conflicts with intrinsic operator"_err_en_US;
1099   } else {
1100     return true; // OK
1101   }
1102   SayWithDeclaration(
1103       specific, std::move(*msg), MakeOpName(opName), specific.name());
1104   context_.SetError(specific);
1105   return false;
1106 }
1107 
1108 // If the number of arguments is wrong for this intrinsic operator, return
1109 // false and return the error message in msg.
1110 std::optional<parser::MessageFixedText> CheckHelper::CheckNumberOfArgs(
1111     const GenericKind &kind, std::size_t nargs) {
1112   if (!kind.IsIntrinsicOperator()) {
1113     return std::nullopt;
1114   }
1115   std::size_t min{2}, max{2}; // allowed number of args; default is binary
1116   std::visit(common::visitors{
1117                  [&](const common::NumericOperator &x) {
1118                    if (x == common::NumericOperator::Add ||
1119                        x == common::NumericOperator::Subtract) {
1120                      min = 1; // + and - are unary or binary
1121                    }
1122                  },
1123                  [&](const common::LogicalOperator &x) {
1124                    if (x == common::LogicalOperator::Not) {
1125                      min = 1; // .NOT. is unary
1126                      max = 1;
1127                    }
1128                  },
1129                  [](const common::RelationalOperator &) {
1130                    // all are binary
1131                  },
1132                  [](const GenericKind::OtherKind &x) {
1133                    CHECK(x == GenericKind::OtherKind::Concat);
1134                  },
1135                  [](const auto &) { DIE("expected intrinsic operator"); },
1136              },
1137       kind.u);
1138   if (nargs >= min && nargs <= max) {
1139     return std::nullopt;
1140   } else if (max == 1) {
1141     return "%s function '%s' must have one dummy argument"_err_en_US;
1142   } else if (min == 2) {
1143     return "%s function '%s' must have two dummy arguments"_err_en_US;
1144   } else {
1145     return "%s function '%s' must have one or two dummy arguments"_err_en_US;
1146   }
1147 }
1148 
1149 bool CheckHelper::CheckDefinedOperatorArg(const SourceName &opName,
1150     const Symbol &symbol, const Procedure &proc, std::size_t pos) {
1151   if (pos >= proc.dummyArguments.size()) {
1152     return true;
1153   }
1154   auto &arg{proc.dummyArguments.at(pos)};
1155   std::optional<parser::MessageFixedText> msg;
1156   if (arg.IsOptional()) {
1157     msg = "In %s function '%s', dummy argument '%s' may not be"
1158           " OPTIONAL"_err_en_US;
1159   } else if (const auto *dataObject{std::get_if<DummyDataObject>(&arg.u)};
1160              dataObject == nullptr) {
1161     msg = "In %s function '%s', dummy argument '%s' must be a"
1162           " data object"_err_en_US;
1163   } else if (dataObject->intent != common::Intent::In &&
1164       !dataObject->attrs.test(DummyDataObject::Attr::Value)) {
1165     msg = "In %s function '%s', dummy argument '%s' must have INTENT(IN)"
1166           " or VALUE attribute"_err_en_US;
1167   }
1168   if (msg) {
1169     SayWithDeclaration(symbol, std::move(*msg),
1170         parser::ToUpperCaseLetters(opName.ToString()), symbol.name(), arg.name);
1171     return false;
1172   }
1173   return true;
1174 }
1175 
1176 // Check if this procedure can be used for defined assignment (see 15.4.3.4.3).
1177 bool CheckHelper::CheckDefinedAssignment(
1178     const Symbol &specific, const Procedure &proc) {
1179   if (context_.HasError(specific)) {
1180     return false;
1181   }
1182   std::optional<parser::MessageFixedText> msg;
1183   if (specific.attrs().test(Attr::NOPASS)) { // C774
1184     msg = "Defined assignment procedure '%s' may not have"
1185           " NOPASS attribute"_err_en_US;
1186   } else if (!proc.IsSubroutine()) {
1187     msg = "Defined assignment procedure '%s' must be a subroutine"_err_en_US;
1188   } else if (proc.dummyArguments.size() != 2) {
1189     msg = "Defined assignment subroutine '%s' must have"
1190           " two dummy arguments"_err_en_US;
1191   } else if (!CheckDefinedAssignmentArg(specific, proc.dummyArguments[0], 0) |
1192       !CheckDefinedAssignmentArg(specific, proc.dummyArguments[1], 1)) {
1193     return false; // error was reported
1194   } else if (ConflictsWithIntrinsicAssignment(proc)) {
1195     msg = "Defined assignment subroutine '%s' conflicts with"
1196           " intrinsic assignment"_err_en_US;
1197   } else {
1198     return true; // OK
1199   }
1200   SayWithDeclaration(specific, std::move(msg.value()), specific.name());
1201   context_.SetError(specific);
1202   return false;
1203 }
1204 
1205 bool CheckHelper::CheckDefinedAssignmentArg(
1206     const Symbol &symbol, const DummyArgument &arg, int pos) {
1207   std::optional<parser::MessageFixedText> msg;
1208   if (arg.IsOptional()) {
1209     msg = "In defined assignment subroutine '%s', dummy argument '%s'"
1210           " may not be OPTIONAL"_err_en_US;
1211   } else if (const auto *dataObject{std::get_if<DummyDataObject>(&arg.u)}) {
1212     if (pos == 0) {
1213       if (dataObject->intent != common::Intent::Out &&
1214           dataObject->intent != common::Intent::InOut) {
1215         msg = "In defined assignment subroutine '%s', first dummy argument '%s'"
1216               " must have INTENT(OUT) or INTENT(INOUT)"_err_en_US;
1217       }
1218     } else if (pos == 1) {
1219       if (dataObject->intent != common::Intent::In &&
1220           !dataObject->attrs.test(DummyDataObject::Attr::Value)) {
1221         msg =
1222             "In defined assignment subroutine '%s', second dummy"
1223             " argument '%s' must have INTENT(IN) or VALUE attribute"_err_en_US;
1224       }
1225     } else {
1226       DIE("pos must be 0 or 1");
1227     }
1228   } else {
1229     msg = "In defined assignment subroutine '%s', dummy argument '%s'"
1230           " must be a data object"_err_en_US;
1231   }
1232   if (msg) {
1233     SayWithDeclaration(symbol, std::move(*msg), symbol.name(), arg.name);
1234     context_.SetError(symbol);
1235     return false;
1236   }
1237   return true;
1238 }
1239 
1240 // Report a conflicting attribute error if symbol has both of these attributes
1241 bool CheckHelper::CheckConflicting(const Symbol &symbol, Attr a1, Attr a2) {
1242   if (symbol.attrs().test(a1) && symbol.attrs().test(a2)) {
1243     messages_.Say("'%s' may not have both the %s and %s attributes"_err_en_US,
1244         symbol.name(), EnumToString(a1), EnumToString(a2));
1245     return true;
1246   } else {
1247     return false;
1248   }
1249 }
1250 
1251 void CheckHelper::WarnMissingFinal(const Symbol &symbol) {
1252   const auto *object{symbol.detailsIf<ObjectEntityDetails>()};
1253   if (!object || IsPointer(symbol)) {
1254     return;
1255   }
1256   const DeclTypeSpec *type{object->type()};
1257   const DerivedTypeSpec *derived{type ? type->AsDerived() : nullptr};
1258   const Symbol *derivedSym{derived ? &derived->typeSymbol() : nullptr};
1259   int rank{object->shape().Rank()};
1260   const Symbol *initialDerivedSym{derivedSym};
1261   while (const auto *derivedDetails{
1262       derivedSym ? derivedSym->detailsIf<DerivedTypeDetails>() : nullptr}) {
1263     if (!derivedDetails->finals().empty() &&
1264         !derivedDetails->GetFinalForRank(rank)) {
1265       if (auto *msg{derivedSym == initialDerivedSym
1266                   ? messages_.Say(symbol.name(),
1267                         "'%s' of derived type '%s' does not have a FINAL subroutine for its rank (%d)"_en_US,
1268                         symbol.name(), derivedSym->name(), rank)
1269                   : messages_.Say(symbol.name(),
1270                         "'%s' of derived type '%s' extended from '%s' does not have a FINAL subroutine for its rank (%d)"_en_US,
1271                         symbol.name(), initialDerivedSym->name(),
1272                         derivedSym->name(), rank)}) {
1273         msg->Attach(derivedSym->name(),
1274             "Declaration of derived type '%s'"_en_US, derivedSym->name());
1275       }
1276       return;
1277     }
1278     derived = derivedSym->GetParentTypeSpec();
1279     derivedSym = derived ? &derived->typeSymbol() : nullptr;
1280   }
1281 }
1282 
1283 const Procedure *CheckHelper::Characterize(const Symbol &symbol) {
1284   auto it{characterizeCache_.find(symbol)};
1285   if (it == characterizeCache_.end()) {
1286     auto pair{characterizeCache_.emplace(SymbolRef{symbol},
1287         Procedure::Characterize(symbol, context_.foldingContext()))};
1288     it = pair.first;
1289   }
1290   return common::GetPtrFromOptional(it->second);
1291 }
1292 
1293 void CheckHelper::CheckVolatile(const Symbol &symbol,
1294     const DerivedTypeSpec *derived) { // C866 - C868
1295   if (IsIntentIn(symbol)) {
1296     messages_.Say(
1297         "VOLATILE attribute may not apply to an INTENT(IN) argument"_err_en_US);
1298   }
1299   if (IsProcedure(symbol)) {
1300     messages_.Say("VOLATILE attribute may apply only to a variable"_err_en_US);
1301   }
1302   if (symbol.has<UseDetails>() || symbol.has<HostAssocDetails>()) {
1303     const Symbol &ultimate{symbol.GetUltimate()};
1304     if (IsCoarray(ultimate)) {
1305       messages_.Say(
1306           "VOLATILE attribute may not apply to a coarray accessed by USE or host association"_err_en_US);
1307     }
1308     if (derived) {
1309       if (FindCoarrayUltimateComponent(*derived)) {
1310         messages_.Say(
1311             "VOLATILE attribute may not apply to a type with a coarray ultimate component accessed by USE or host association"_err_en_US);
1312       }
1313     }
1314   }
1315 }
1316 
1317 void CheckHelper::CheckPointer(const Symbol &symbol) { // C852
1318   CheckConflicting(symbol, Attr::POINTER, Attr::TARGET);
1319   CheckConflicting(symbol, Attr::POINTER, Attr::ALLOCATABLE); // C751
1320   CheckConflicting(symbol, Attr::POINTER, Attr::INTRINSIC);
1321   // Prohibit constant pointers.  The standard does not explicitly prohibit
1322   // them, but the PARAMETER attribute requires a entity-decl to have an
1323   // initialization that is a constant-expr, and the only form of
1324   // initialization that allows a constant-expr is the one that's not a "=>"
1325   // pointer initialization.  See C811, C807, and section 8.5.13.
1326   CheckConflicting(symbol, Attr::POINTER, Attr::PARAMETER);
1327   if (symbol.Corank() > 0) {
1328     messages_.Say(
1329         "'%s' may not have the POINTER attribute because it is a coarray"_err_en_US,
1330         symbol.name());
1331   }
1332 }
1333 
1334 // C760 constraints on the passed-object dummy argument
1335 // C757 constraints on procedure pointer components
1336 void CheckHelper::CheckPassArg(
1337     const Symbol &proc, const Symbol *interface, const WithPassArg &details) {
1338   if (proc.attrs().test(Attr::NOPASS)) {
1339     return;
1340   }
1341   const auto &name{proc.name()};
1342   if (!interface) {
1343     messages_.Say(name,
1344         "Procedure component '%s' must have NOPASS attribute or explicit interface"_err_en_US,
1345         name);
1346     return;
1347   }
1348   const auto *subprogram{interface->detailsIf<SubprogramDetails>()};
1349   if (!subprogram) {
1350     messages_.Say(name,
1351         "Procedure component '%s' has invalid interface '%s'"_err_en_US, name,
1352         interface->name());
1353     return;
1354   }
1355   std::optional<SourceName> passName{details.passName()};
1356   const auto &dummyArgs{subprogram->dummyArgs()};
1357   if (!passName) {
1358     if (dummyArgs.empty()) {
1359       messages_.Say(name,
1360           proc.has<ProcEntityDetails>()
1361               ? "Procedure component '%s' with no dummy arguments"
1362                 " must have NOPASS attribute"_err_en_US
1363               : "Procedure binding '%s' with no dummy arguments"
1364                 " must have NOPASS attribute"_err_en_US,
1365           name);
1366       context_.SetError(*interface);
1367       return;
1368     }
1369     Symbol *argSym{dummyArgs[0]};
1370     if (!argSym) {
1371       messages_.Say(interface->name(),
1372           "Cannot use an alternate return as the passed-object dummy "
1373           "argument"_err_en_US);
1374       return;
1375     }
1376     passName = dummyArgs[0]->name();
1377   }
1378   std::optional<int> passArgIndex{};
1379   for (std::size_t i{0}; i < dummyArgs.size(); ++i) {
1380     if (dummyArgs[i] && dummyArgs[i]->name() == *passName) {
1381       passArgIndex = i;
1382       break;
1383     }
1384   }
1385   if (!passArgIndex) { // C758
1386     messages_.Say(*passName,
1387         "'%s' is not a dummy argument of procedure interface '%s'"_err_en_US,
1388         *passName, interface->name());
1389     return;
1390   }
1391   const Symbol &passArg{*dummyArgs[*passArgIndex]};
1392   std::optional<parser::MessageFixedText> msg;
1393   if (!passArg.has<ObjectEntityDetails>()) {
1394     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1395           " must be a data object"_err_en_US;
1396   } else if (passArg.attrs().test(Attr::POINTER)) {
1397     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1398           " may not have the POINTER attribute"_err_en_US;
1399   } else if (passArg.attrs().test(Attr::ALLOCATABLE)) {
1400     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1401           " may not have the ALLOCATABLE attribute"_err_en_US;
1402   } else if (passArg.attrs().test(Attr::VALUE)) {
1403     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1404           " may not have the VALUE attribute"_err_en_US;
1405   } else if (passArg.Rank() > 0) {
1406     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1407           " must be scalar"_err_en_US;
1408   }
1409   if (msg) {
1410     messages_.Say(name, std::move(*msg), passName.value(), name);
1411     return;
1412   }
1413   const DeclTypeSpec *type{passArg.GetType()};
1414   if (!type) {
1415     return; // an error already occurred
1416   }
1417   const Symbol &typeSymbol{*proc.owner().GetSymbol()};
1418   const DerivedTypeSpec *derived{type->AsDerived()};
1419   if (!derived || derived->typeSymbol() != typeSymbol) {
1420     messages_.Say(name,
1421         "Passed-object dummy argument '%s' of procedure '%s'"
1422         " must be of type '%s' but is '%s'"_err_en_US,
1423         passName.value(), name, typeSymbol.name(), type->AsFortran());
1424     return;
1425   }
1426   if (IsExtensibleType(derived) != type->IsPolymorphic()) {
1427     messages_.Say(name,
1428         type->IsPolymorphic()
1429             ? "Passed-object dummy argument '%s' of procedure '%s'"
1430               " may not be polymorphic because '%s' is not extensible"_err_en_US
1431             : "Passed-object dummy argument '%s' of procedure '%s'"
1432               " must be polymorphic because '%s' is extensible"_err_en_US,
1433         passName.value(), name, typeSymbol.name());
1434     return;
1435   }
1436   for (const auto &[paramName, paramValue] : derived->parameters()) {
1437     if (paramValue.isLen() && !paramValue.isAssumed()) {
1438       messages_.Say(name,
1439           "Passed-object dummy argument '%s' of procedure '%s'"
1440           " has non-assumed length parameter '%s'"_err_en_US,
1441           passName.value(), name, paramName);
1442     }
1443   }
1444 }
1445 
1446 void CheckHelper::CheckProcBinding(
1447     const Symbol &symbol, const ProcBindingDetails &binding) {
1448   const Scope &dtScope{symbol.owner()};
1449   CHECK(dtScope.kind() == Scope::Kind::DerivedType);
1450   if (const Symbol * dtSymbol{dtScope.symbol()}) {
1451     if (symbol.attrs().test(Attr::DEFERRED)) {
1452       if (!dtSymbol->attrs().test(Attr::ABSTRACT)) { // C733
1453         SayWithDeclaration(*dtSymbol,
1454             "Procedure bound to non-ABSTRACT derived type '%s' may not be DEFERRED"_err_en_US,
1455             dtSymbol->name());
1456       }
1457       if (symbol.attrs().test(Attr::NON_OVERRIDABLE)) {
1458         messages_.Say(
1459             "Type-bound procedure '%s' may not be both DEFERRED and NON_OVERRIDABLE"_err_en_US,
1460             symbol.name());
1461       }
1462     }
1463   }
1464   if (const Symbol * overridden{FindOverriddenBinding(symbol)}) {
1465     if (overridden->attrs().test(Attr::NON_OVERRIDABLE)) {
1466       SayWithDeclaration(*overridden,
1467           "Override of NON_OVERRIDABLE '%s' is not permitted"_err_en_US,
1468           symbol.name());
1469     }
1470     if (const auto *overriddenBinding{
1471             overridden->detailsIf<ProcBindingDetails>()}) {
1472       if (!IsPureProcedure(symbol) && IsPureProcedure(*overridden)) {
1473         SayWithDeclaration(*overridden,
1474             "An overridden pure type-bound procedure binding must also be pure"_err_en_US);
1475         return;
1476       }
1477       if (!binding.symbol().attrs().test(Attr::ELEMENTAL) &&
1478           overriddenBinding->symbol().attrs().test(Attr::ELEMENTAL)) {
1479         SayWithDeclaration(*overridden,
1480             "A type-bound procedure and its override must both, or neither, be ELEMENTAL"_err_en_US);
1481         return;
1482       }
1483       bool isNopass{symbol.attrs().test(Attr::NOPASS)};
1484       if (isNopass != overridden->attrs().test(Attr::NOPASS)) {
1485         SayWithDeclaration(*overridden,
1486             isNopass
1487                 ? "A NOPASS type-bound procedure may not override a passed-argument procedure"_err_en_US
1488                 : "A passed-argument type-bound procedure may not override a NOPASS procedure"_err_en_US);
1489       } else {
1490         const auto *bindingChars{Characterize(binding.symbol())};
1491         const auto *overriddenChars{Characterize(overriddenBinding->symbol())};
1492         if (bindingChars && overriddenChars) {
1493           if (isNopass) {
1494             if (!bindingChars->CanOverride(*overriddenChars, std::nullopt)) {
1495               SayWithDeclaration(*overridden,
1496                   "A type-bound procedure and its override must have compatible interfaces"_err_en_US);
1497             }
1498           } else if (!context_.HasError(binding.symbol())) {
1499             int passIndex{bindingChars->FindPassIndex(binding.passName())};
1500             int overriddenPassIndex{
1501                 overriddenChars->FindPassIndex(overriddenBinding->passName())};
1502             if (passIndex != overriddenPassIndex) {
1503               SayWithDeclaration(*overridden,
1504                   "A type-bound procedure and its override must use the same PASS argument"_err_en_US);
1505             } else if (!bindingChars->CanOverride(
1506                            *overriddenChars, passIndex)) {
1507               SayWithDeclaration(*overridden,
1508                   "A type-bound procedure and its override must have compatible interfaces apart from their passed argument"_err_en_US);
1509             }
1510           }
1511         }
1512       }
1513       if (symbol.attrs().test(Attr::PRIVATE) &&
1514           overridden->attrs().test(Attr::PUBLIC)) {
1515         SayWithDeclaration(*overridden,
1516             "A PRIVATE procedure may not override a PUBLIC procedure"_err_en_US);
1517       }
1518     } else {
1519       SayWithDeclaration(*overridden,
1520           "A type-bound procedure binding may not have the same name as a parent component"_err_en_US);
1521     }
1522   }
1523   CheckPassArg(symbol, &binding.symbol(), binding);
1524 }
1525 
1526 void CheckHelper::Check(const Scope &scope) {
1527   scope_ = &scope;
1528   common::Restorer<const Symbol *> restorer{innermostSymbol_, innermostSymbol_};
1529   if (const Symbol * symbol{scope.symbol()}) {
1530     innermostSymbol_ = symbol;
1531   }
1532   if (scope.IsParameterizedDerivedTypeInstantiation()) {
1533     auto restorer{common::ScopedSet(scopeIsUninstantiatedPDT_, false)};
1534     auto restorer2{context_.foldingContext().messages().SetContext(
1535         scope.instantiationContext().get())};
1536     for (const auto &pair : scope) {
1537       CheckPointerInitialization(*pair.second);
1538     }
1539   } else {
1540     auto restorer{common::ScopedSet(
1541         scopeIsUninstantiatedPDT_, scope.IsParameterizedDerivedType())};
1542     for (const auto &set : scope.equivalenceSets()) {
1543       CheckEquivalenceSet(set);
1544     }
1545     for (const auto &pair : scope) {
1546       Check(*pair.second);
1547     }
1548     for (const Scope &child : scope.children()) {
1549       Check(child);
1550     }
1551     if (scope.kind() == Scope::Kind::BlockData) {
1552       CheckBlockData(scope);
1553     }
1554     CheckGenericOps(scope);
1555   }
1556 }
1557 
1558 void CheckHelper::CheckEquivalenceSet(const EquivalenceSet &set) {
1559   auto iter{
1560       std::find_if(set.begin(), set.end(), [](const EquivalenceObject &object) {
1561         return FindCommonBlockContaining(object.symbol) != nullptr;
1562       })};
1563   if (iter != set.end()) {
1564     const Symbol &commonBlock{DEREF(FindCommonBlockContaining(iter->symbol))};
1565     for (auto &object : set) {
1566       if (&object != &*iter) {
1567         if (auto *details{object.symbol.detailsIf<ObjectEntityDetails>()}) {
1568           if (details->commonBlock()) {
1569             if (details->commonBlock() != &commonBlock) { // 8.10.3 paragraph 1
1570               if (auto *msg{messages_.Say(object.symbol.name(),
1571                       "Two objects in the same EQUIVALENCE set may not be members of distinct COMMON blocks"_err_en_US)}) {
1572                 msg->Attach(iter->symbol.name(),
1573                        "Other object in EQUIVALENCE set"_en_US)
1574                     .Attach(details->commonBlock()->name(),
1575                         "COMMON block containing '%s'"_en_US,
1576                         object.symbol.name())
1577                     .Attach(commonBlock.name(),
1578                         "COMMON block containing '%s'"_en_US,
1579                         iter->symbol.name());
1580               }
1581             }
1582           } else {
1583             // Mark all symbols in the equivalence set with the same COMMON
1584             // block to prevent spurious error messages about initialization
1585             // in BLOCK DATA outside COMMON
1586             details->set_commonBlock(commonBlock);
1587           }
1588         }
1589       }
1590     }
1591   }
1592   // TODO: Move C8106 (&al.) checks here from resolve-names-utils.cpp
1593 }
1594 
1595 void CheckHelper::CheckBlockData(const Scope &scope) {
1596   // BLOCK DATA subprograms should contain only named common blocks.
1597   // C1415 presents a list of statements that shouldn't appear in
1598   // BLOCK DATA, but so long as the subprogram contains no executable
1599   // code and allocates no storage outside named COMMON, we're happy
1600   // (e.g., an ENUM is strictly not allowed).
1601   for (const auto &pair : scope) {
1602     const Symbol &symbol{*pair.second};
1603     if (!(symbol.has<CommonBlockDetails>() || symbol.has<UseDetails>() ||
1604             symbol.has<UseErrorDetails>() || symbol.has<DerivedTypeDetails>() ||
1605             symbol.has<SubprogramDetails>() ||
1606             symbol.has<ObjectEntityDetails>() ||
1607             (symbol.has<ProcEntityDetails>() &&
1608                 !symbol.attrs().test(Attr::POINTER)))) {
1609       messages_.Say(symbol.name(),
1610           "'%s' may not appear in a BLOCK DATA subprogram"_err_en_US,
1611           symbol.name());
1612     }
1613   }
1614 }
1615 
1616 // Check distinguishability of generic assignment and operators.
1617 // For these, generics and generic bindings must be considered together.
1618 void CheckHelper::CheckGenericOps(const Scope &scope) {
1619   DistinguishabilityHelper helper{context_};
1620   auto addSpecifics{[&](const Symbol &generic) {
1621     const auto *details{generic.GetUltimate().detailsIf<GenericDetails>()};
1622     if (!details) {
1623       return;
1624     }
1625     GenericKind kind{details->kind()};
1626     if (!kind.IsAssignment() && !kind.IsOperator()) {
1627       return;
1628     }
1629     const SymbolVector &specifics{details->specificProcs()};
1630     const std::vector<SourceName> &bindingNames{details->bindingNames()};
1631     for (std::size_t i{0}; i < specifics.size(); ++i) {
1632       const Symbol &specific{*specifics[i]};
1633       if (const Procedure * proc{Characterize(specific)}) {
1634         auto restorer{messages_.SetLocation(bindingNames[i])};
1635         if (kind.IsAssignment()) {
1636           if (!CheckDefinedAssignment(specific, *proc)) {
1637             continue;
1638           }
1639         } else {
1640           if (!CheckDefinedOperator(generic.name(), kind, specific, *proc)) {
1641             continue;
1642           }
1643         }
1644         helper.Add(generic, kind, specific, *proc);
1645       }
1646     }
1647   }};
1648   for (const auto &pair : scope) {
1649     const Symbol &symbol{*pair.second};
1650     addSpecifics(symbol);
1651     const Symbol &ultimate{symbol.GetUltimate()};
1652     if (ultimate.has<DerivedTypeDetails>()) {
1653       if (const Scope * typeScope{ultimate.scope()}) {
1654         for (const auto &pair2 : *typeScope) {
1655           addSpecifics(*pair2.second);
1656         }
1657       }
1658     }
1659   }
1660   helper.Check(scope);
1661 }
1662 
1663 static const std::string *DefinesBindCName(const Symbol &symbol) {
1664   const auto *subp{symbol.detailsIf<SubprogramDetails>()};
1665   if ((subp && !subp->isInterface()) || symbol.has<ObjectEntityDetails>()) {
1666     // Symbol defines data or entry point
1667     return symbol.GetBindName();
1668   } else {
1669     return nullptr;
1670   }
1671 }
1672 
1673 // Check that BIND(C) names are distinct
1674 void CheckHelper::CheckBindCName(const Symbol &symbol) {
1675   if (const std::string * name{DefinesBindCName(symbol)}) {
1676     auto pair{bindC_.emplace(*name, symbol)};
1677     if (!pair.second) {
1678       const Symbol &other{*pair.first->second};
1679       if (DefinesBindCName(other) && !context_.HasError(other)) {
1680         if (auto *msg{messages_.Say(
1681                 "Two symbols have the same BIND(C) name '%s'"_err_en_US,
1682                 *name)}) {
1683           msg->Attach(other.name(), "Conflicting symbol"_en_US);
1684         }
1685         context_.SetError(symbol);
1686         context_.SetError(other);
1687       }
1688     }
1689   }
1690 }
1691 
1692 void SubprogramMatchHelper::Check(
1693     const Symbol &symbol1, const Symbol &symbol2) {
1694   const auto details1{symbol1.get<SubprogramDetails>()};
1695   const auto details2{symbol2.get<SubprogramDetails>()};
1696   if (details1.isFunction() != details2.isFunction()) {
1697     Say(symbol1, symbol2,
1698         details1.isFunction()
1699             ? "Module function '%s' was declared as a subroutine in the"
1700               " corresponding interface body"_err_en_US
1701             : "Module subroutine '%s' was declared as a function in the"
1702               " corresponding interface body"_err_en_US);
1703     return;
1704   }
1705   const auto &args1{details1.dummyArgs()};
1706   const auto &args2{details2.dummyArgs()};
1707   int nargs1{static_cast<int>(args1.size())};
1708   int nargs2{static_cast<int>(args2.size())};
1709   if (nargs1 != nargs2) {
1710     Say(symbol1, symbol2,
1711         "Module subprogram '%s' has %d args but the corresponding interface"
1712         " body has %d"_err_en_US,
1713         nargs1, nargs2);
1714     return;
1715   }
1716   bool nonRecursive1{symbol1.attrs().test(Attr::NON_RECURSIVE)};
1717   if (nonRecursive1 != symbol2.attrs().test(Attr::NON_RECURSIVE)) { // C1551
1718     Say(symbol1, symbol2,
1719         nonRecursive1
1720             ? "Module subprogram '%s' has NON_RECURSIVE prefix but"
1721               " the corresponding interface body does not"_err_en_US
1722             : "Module subprogram '%s' does not have NON_RECURSIVE prefix but "
1723               "the corresponding interface body does"_err_en_US);
1724   }
1725   const std::string *bindName1{details1.bindName()};
1726   const std::string *bindName2{details2.bindName()};
1727   if (!bindName1 && !bindName2) {
1728     // OK - neither has a binding label
1729   } else if (!bindName1) {
1730     Say(symbol1, symbol2,
1731         "Module subprogram '%s' does not have a binding label but the"
1732         " corresponding interface body does"_err_en_US);
1733   } else if (!bindName2) {
1734     Say(symbol1, symbol2,
1735         "Module subprogram '%s' has a binding label but the"
1736         " corresponding interface body does not"_err_en_US);
1737   } else if (*bindName1 != *bindName2) {
1738     Say(symbol1, symbol2,
1739         "Module subprogram '%s' has binding label '%s' but the corresponding"
1740         " interface body has '%s'"_err_en_US,
1741         *details1.bindName(), *details2.bindName());
1742   }
1743   const Procedure *proc1{checkHelper.Characterize(symbol1)};
1744   const Procedure *proc2{checkHelper.Characterize(symbol2)};
1745   if (!proc1 || !proc2) {
1746     return;
1747   }
1748   if (proc1->functionResult && proc2->functionResult &&
1749       *proc1->functionResult != *proc2->functionResult) {
1750     Say(symbol1, symbol2,
1751         "Return type of function '%s' does not match return type of"
1752         " the corresponding interface body"_err_en_US);
1753   }
1754   for (int i{0}; i < nargs1; ++i) {
1755     const Symbol *arg1{args1[i]};
1756     const Symbol *arg2{args2[i]};
1757     if (arg1 && !arg2) {
1758       Say(symbol1, symbol2,
1759           "Dummy argument %2$d of '%1$s' is not an alternate return indicator"
1760           " but the corresponding argument in the interface body is"_err_en_US,
1761           i + 1);
1762     } else if (!arg1 && arg2) {
1763       Say(symbol1, symbol2,
1764           "Dummy argument %2$d of '%1$s' is an alternate return indicator but"
1765           " the corresponding argument in the interface body is not"_err_en_US,
1766           i + 1);
1767     } else if (arg1 && arg2) {
1768       SourceName name1{arg1->name()};
1769       SourceName name2{arg2->name()};
1770       if (name1 != name2) {
1771         Say(*arg1, *arg2,
1772             "Dummy argument name '%s' does not match corresponding name '%s'"
1773             " in interface body"_err_en_US,
1774             name2);
1775       } else {
1776         CheckDummyArg(
1777             *arg1, *arg2, proc1->dummyArguments[i], proc2->dummyArguments[i]);
1778       }
1779     }
1780   }
1781 }
1782 
1783 void SubprogramMatchHelper::CheckDummyArg(const Symbol &symbol1,
1784     const Symbol &symbol2, const DummyArgument &arg1,
1785     const DummyArgument &arg2) {
1786   std::visit(common::visitors{
1787                  [&](const DummyDataObject &obj1, const DummyDataObject &obj2) {
1788                    CheckDummyDataObject(symbol1, symbol2, obj1, obj2);
1789                  },
1790                  [&](const DummyProcedure &proc1, const DummyProcedure &proc2) {
1791                    CheckDummyProcedure(symbol1, symbol2, proc1, proc2);
1792                  },
1793                  [&](const DummyDataObject &, const auto &) {
1794                    Say(symbol1, symbol2,
1795                        "Dummy argument '%s' is a data object; the corresponding"
1796                        " argument in the interface body is not"_err_en_US);
1797                  },
1798                  [&](const DummyProcedure &, const auto &) {
1799                    Say(symbol1, symbol2,
1800                        "Dummy argument '%s' is a procedure; the corresponding"
1801                        " argument in the interface body is not"_err_en_US);
1802                  },
1803                  [&](const auto &, const auto &) {
1804                    llvm_unreachable("Dummy arguments are not data objects or"
1805                                     "procedures");
1806                  },
1807              },
1808       arg1.u, arg2.u);
1809 }
1810 
1811 void SubprogramMatchHelper::CheckDummyDataObject(const Symbol &symbol1,
1812     const Symbol &symbol2, const DummyDataObject &obj1,
1813     const DummyDataObject &obj2) {
1814   if (!CheckSameIntent(symbol1, symbol2, obj1.intent, obj2.intent)) {
1815   } else if (!CheckSameAttrs(symbol1, symbol2, obj1.attrs, obj2.attrs)) {
1816   } else if (obj1.type.type() != obj2.type.type()) {
1817     Say(symbol1, symbol2,
1818         "Dummy argument '%s' has type %s; the corresponding argument in the"
1819         " interface body has type %s"_err_en_US,
1820         obj1.type.type().AsFortran(), obj2.type.type().AsFortran());
1821   } else if (!ShapesAreCompatible(obj1, obj2)) {
1822     Say(symbol1, symbol2,
1823         "The shape of dummy argument '%s' does not match the shape of the"
1824         " corresponding argument in the interface body"_err_en_US);
1825   }
1826   // TODO: coshape
1827 }
1828 
1829 void SubprogramMatchHelper::CheckDummyProcedure(const Symbol &symbol1,
1830     const Symbol &symbol2, const DummyProcedure &proc1,
1831     const DummyProcedure &proc2) {
1832   if (!CheckSameIntent(symbol1, symbol2, proc1.intent, proc2.intent)) {
1833   } else if (!CheckSameAttrs(symbol1, symbol2, proc1.attrs, proc2.attrs)) {
1834   } else if (proc1 != proc2) {
1835     Say(symbol1, symbol2,
1836         "Dummy procedure '%s' does not match the corresponding argument in"
1837         " the interface body"_err_en_US);
1838   }
1839 }
1840 
1841 bool SubprogramMatchHelper::CheckSameIntent(const Symbol &symbol1,
1842     const Symbol &symbol2, common::Intent intent1, common::Intent intent2) {
1843   if (intent1 == intent2) {
1844     return true;
1845   } else {
1846     Say(symbol1, symbol2,
1847         "The intent of dummy argument '%s' does not match the intent"
1848         " of the corresponding argument in the interface body"_err_en_US);
1849     return false;
1850   }
1851 }
1852 
1853 // Report an error referring to first symbol with declaration of second symbol
1854 template <typename... A>
1855 void SubprogramMatchHelper::Say(const Symbol &symbol1, const Symbol &symbol2,
1856     parser::MessageFixedText &&text, A &&...args) {
1857   auto &message{context().Say(symbol1.name(), std::move(text), symbol1.name(),
1858       std::forward<A>(args)...)};
1859   evaluate::AttachDeclaration(message, symbol2);
1860 }
1861 
1862 template <typename ATTRS>
1863 bool SubprogramMatchHelper::CheckSameAttrs(
1864     const Symbol &symbol1, const Symbol &symbol2, ATTRS attrs1, ATTRS attrs2) {
1865   if (attrs1 == attrs2) {
1866     return true;
1867   }
1868   attrs1.IterateOverMembers([&](auto attr) {
1869     if (!attrs2.test(attr)) {
1870       Say(symbol1, symbol2,
1871           "Dummy argument '%s' has the %s attribute; the corresponding"
1872           " argument in the interface body does not"_err_en_US,
1873           AsFortran(attr));
1874     }
1875   });
1876   attrs2.IterateOverMembers([&](auto attr) {
1877     if (!attrs1.test(attr)) {
1878       Say(symbol1, symbol2,
1879           "Dummy argument '%s' does not have the %s attribute; the"
1880           " corresponding argument in the interface body does"_err_en_US,
1881           AsFortran(attr));
1882     }
1883   });
1884   return false;
1885 }
1886 
1887 bool SubprogramMatchHelper::ShapesAreCompatible(
1888     const DummyDataObject &obj1, const DummyDataObject &obj2) {
1889   return characteristics::ShapesAreCompatible(
1890       FoldShape(obj1.type.shape()), FoldShape(obj2.type.shape()));
1891 }
1892 
1893 evaluate::Shape SubprogramMatchHelper::FoldShape(const evaluate::Shape &shape) {
1894   evaluate::Shape result;
1895   for (const auto &extent : shape) {
1896     result.emplace_back(
1897         evaluate::Fold(context().foldingContext(), common::Clone(extent)));
1898   }
1899   return result;
1900 }
1901 
1902 void DistinguishabilityHelper::Add(const Symbol &generic, GenericKind kind,
1903     const Symbol &specific, const Procedure &procedure) {
1904   if (!context_.HasError(specific)) {
1905     nameToInfo_[generic.name()].emplace_back(
1906         ProcedureInfo{kind, specific, procedure});
1907   }
1908 }
1909 
1910 void DistinguishabilityHelper::Check(const Scope &scope) {
1911   for (const auto &[name, info] : nameToInfo_) {
1912     auto count{info.size()};
1913     for (std::size_t i1{0}; i1 < count - 1; ++i1) {
1914       const auto &[kind1, symbol1, proc1] = info[i1];
1915       for (std::size_t i2{i1 + 1}; i2 < count; ++i2) {
1916         const auto &[kind2, symbol2, proc2] = info[i2];
1917         auto distinguishable{kind1.IsName()
1918                 ? evaluate::characteristics::Distinguishable
1919                 : evaluate::characteristics::DistinguishableOpOrAssign};
1920         if (!distinguishable(proc1, proc2)) {
1921           SayNotDistinguishable(
1922               GetTopLevelUnitContaining(scope), name, kind1, symbol1, symbol2);
1923         }
1924       }
1925     }
1926   }
1927 }
1928 
1929 void DistinguishabilityHelper::SayNotDistinguishable(const Scope &scope,
1930     const SourceName &name, GenericKind kind, const Symbol &proc1,
1931     const Symbol &proc2) {
1932   std::string name1{proc1.name().ToString()};
1933   std::string name2{proc2.name().ToString()};
1934   if (kind.IsOperator() || kind.IsAssignment()) {
1935     // proc1 and proc2 may come from different scopes so qualify their names
1936     if (proc1.owner().IsDerivedType()) {
1937       name1 = proc1.owner().GetName()->ToString() + '%' + name1;
1938     }
1939     if (proc2.owner().IsDerivedType()) {
1940       name2 = proc2.owner().GetName()->ToString() + '%' + name2;
1941     }
1942   }
1943   parser::Message *msg;
1944   if (scope.sourceRange().Contains(name)) {
1945     msg = &context_.Say(name,
1946         "Generic '%s' may not have specific procedures '%s' and"
1947         " '%s' as their interfaces are not distinguishable"_err_en_US,
1948         MakeOpName(name), name1, name2);
1949   } else {
1950     msg = &context_.Say(*GetTopLevelUnitContaining(proc1).GetName(),
1951         "USE-associated generic '%s' may not have specific procedures '%s' and"
1952         " '%s' as their interfaces are not distinguishable"_err_en_US,
1953         MakeOpName(name), name1, name2);
1954   }
1955   AttachDeclaration(*msg, scope, proc1);
1956   AttachDeclaration(*msg, scope, proc2);
1957 }
1958 
1959 // `evaluate::AttachDeclaration` doesn't handle the generic case where `proc`
1960 // comes from a different module but is not necessarily use-associated.
1961 void DistinguishabilityHelper::AttachDeclaration(
1962     parser::Message &msg, const Scope &scope, const Symbol &proc) {
1963   const Scope &unit{GetTopLevelUnitContaining(proc)};
1964   if (unit == scope) {
1965     evaluate::AttachDeclaration(msg, proc);
1966   } else {
1967     msg.Attach(unit.GetName().value(),
1968         "'%s' is USE-associated from module '%s'"_en_US, proc.name(),
1969         unit.GetName().value());
1970   }
1971 }
1972 
1973 void CheckDeclarations(SemanticsContext &context) {
1974   CheckHelper{context}.Check();
1975 }
1976 } // namespace Fortran::semantics
1977