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