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