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   // See comment on the similar check in CheckProcEntity()
849   if (details.isDummy() && symbol.attrs().test(Attr::ELEMENTAL)) {
850     messages_.Say("A dummy procedure may not be ELEMENTAL"_err_en_US);
851   }
852 }
853 
854 void CheckHelper::CheckDerivedType(
855     const Symbol &derivedType, const DerivedTypeDetails &details) {
856   if (details.isForwardReferenced() && !context_.HasError(derivedType)) {
857     messages_.Say("The derived type '%s' has not been defined"_err_en_US,
858         derivedType.name());
859   }
860   const Scope *scope{derivedType.scope()};
861   if (!scope) {
862     CHECK(details.isForwardReferenced());
863     return;
864   }
865   CHECK(scope->symbol() == &derivedType);
866   CHECK(scope->IsDerivedType());
867   if (derivedType.attrs().test(Attr::ABSTRACT) && // C734
868       (derivedType.attrs().test(Attr::BIND_C) || details.sequence())) {
869     messages_.Say("An ABSTRACT derived type must be extensible"_err_en_US);
870   }
871   if (const DeclTypeSpec * parent{FindParentTypeSpec(derivedType)}) {
872     const DerivedTypeSpec *parentDerived{parent->AsDerived()};
873     if (!IsExtensibleType(parentDerived)) { // C705
874       messages_.Say("The parent type is not extensible"_err_en_US);
875     }
876     if (!derivedType.attrs().test(Attr::ABSTRACT) && parentDerived &&
877         parentDerived->typeSymbol().attrs().test(Attr::ABSTRACT)) {
878       ScopeComponentIterator components{*parentDerived};
879       for (const Symbol &component : components) {
880         if (component.attrs().test(Attr::DEFERRED)) {
881           if (scope->FindComponent(component.name()) == &component) {
882             SayWithDeclaration(component,
883                 "Non-ABSTRACT extension of ABSTRACT derived type '%s' lacks a binding for DEFERRED procedure '%s'"_err_en_US,
884                 parentDerived->typeSymbol().name(), component.name());
885           }
886         }
887       }
888     }
889     DerivedTypeSpec derived{derivedType.name(), derivedType};
890     derived.set_scope(*scope);
891     if (FindCoarrayUltimateComponent(derived) && // C736
892         !(parentDerived && FindCoarrayUltimateComponent(*parentDerived))) {
893       messages_.Say(
894           "Type '%s' has a coarray ultimate component so the type at the base "
895           "of its type extension chain ('%s') must be a type that has a "
896           "coarray ultimate component"_err_en_US,
897           derivedType.name(), scope->GetDerivedTypeBase().GetSymbol()->name());
898     }
899     if (FindEventOrLockPotentialComponent(derived) && // C737
900         !(FindEventOrLockPotentialComponent(*parentDerived) ||
901             IsEventTypeOrLockType(parentDerived))) {
902       messages_.Say(
903           "Type '%s' has an EVENT_TYPE or LOCK_TYPE component, so the type "
904           "at the base of its type extension chain ('%s') must either have an "
905           "EVENT_TYPE or LOCK_TYPE component, or be EVENT_TYPE or "
906           "LOCK_TYPE"_err_en_US,
907           derivedType.name(), scope->GetDerivedTypeBase().GetSymbol()->name());
908     }
909   }
910   if (HasIntrinsicTypeName(derivedType)) { // C729
911     messages_.Say("A derived type name cannot be the name of an intrinsic"
912                   " type"_err_en_US);
913   }
914   std::map<SourceName, SymbolRef> previous;
915   for (const auto &pair : details.finals()) {
916     SourceName source{pair.first};
917     const Symbol &ref{*pair.second};
918     if (CheckFinal(ref, source, derivedType) &&
919         std::all_of(previous.begin(), previous.end(),
920             [&](std::pair<SourceName, SymbolRef> prev) {
921               return CheckDistinguishableFinals(
922                   ref, source, *prev.second, prev.first, derivedType);
923             })) {
924       previous.emplace(source, ref);
925     }
926   }
927 }
928 
929 // C786
930 bool CheckHelper::CheckFinal(
931     const Symbol &subroutine, SourceName finalName, const Symbol &derivedType) {
932   if (!IsModuleProcedure(subroutine)) {
933     SayWithDeclaration(subroutine, finalName,
934         "FINAL subroutine '%s' of derived type '%s' must be a module procedure"_err_en_US,
935         subroutine.name(), derivedType.name());
936     return false;
937   }
938   const Procedure *proc{Characterize(subroutine)};
939   if (!proc) {
940     return false; // error recovery
941   }
942   if (!proc->IsSubroutine()) {
943     SayWithDeclaration(subroutine, finalName,
944         "FINAL subroutine '%s' of derived type '%s' must be a subroutine"_err_en_US,
945         subroutine.name(), derivedType.name());
946     return false;
947   }
948   if (proc->dummyArguments.size() != 1) {
949     SayWithDeclaration(subroutine, finalName,
950         "FINAL subroutine '%s' of derived type '%s' must have a single dummy argument"_err_en_US,
951         subroutine.name(), derivedType.name());
952     return false;
953   }
954   const auto &arg{proc->dummyArguments[0]};
955   const Symbol *errSym{&subroutine};
956   if (const auto *details{subroutine.detailsIf<SubprogramDetails>()}) {
957     if (!details->dummyArgs().empty()) {
958       if (const Symbol * argSym{details->dummyArgs()[0]}) {
959         errSym = argSym;
960       }
961     }
962   }
963   const auto *ddo{std::get_if<DummyDataObject>(&arg.u)};
964   if (!ddo) {
965     SayWithDeclaration(subroutine, finalName,
966         "FINAL subroutine '%s' of derived type '%s' must have a single dummy argument that is a data object"_err_en_US,
967         subroutine.name(), derivedType.name());
968     return false;
969   }
970   bool ok{true};
971   if (arg.IsOptional()) {
972     SayWithDeclaration(*errSym, finalName,
973         "FINAL subroutine '%s' of derived type '%s' must not have an OPTIONAL dummy argument"_err_en_US,
974         subroutine.name(), derivedType.name());
975     ok = false;
976   }
977   if (ddo->attrs.test(DummyDataObject::Attr::Allocatable)) {
978     SayWithDeclaration(*errSym, finalName,
979         "FINAL subroutine '%s' of derived type '%s' must not have an ALLOCATABLE dummy argument"_err_en_US,
980         subroutine.name(), derivedType.name());
981     ok = false;
982   }
983   if (ddo->attrs.test(DummyDataObject::Attr::Pointer)) {
984     SayWithDeclaration(*errSym, finalName,
985         "FINAL subroutine '%s' of derived type '%s' must not have a POINTER dummy argument"_err_en_US,
986         subroutine.name(), derivedType.name());
987     ok = false;
988   }
989   if (ddo->intent == common::Intent::Out) {
990     SayWithDeclaration(*errSym, finalName,
991         "FINAL subroutine '%s' of derived type '%s' must not have a dummy argument with INTENT(OUT)"_err_en_US,
992         subroutine.name(), derivedType.name());
993     ok = false;
994   }
995   if (ddo->attrs.test(DummyDataObject::Attr::Value)) {
996     SayWithDeclaration(*errSym, finalName,
997         "FINAL subroutine '%s' of derived type '%s' must not have a dummy argument with the VALUE attribute"_err_en_US,
998         subroutine.name(), derivedType.name());
999     ok = false;
1000   }
1001   if (ddo->type.corank() > 0) {
1002     SayWithDeclaration(*errSym, finalName,
1003         "FINAL subroutine '%s' of derived type '%s' must not have a coarray dummy argument"_err_en_US,
1004         subroutine.name(), derivedType.name());
1005     ok = false;
1006   }
1007   if (ddo->type.type().IsPolymorphic()) {
1008     SayWithDeclaration(*errSym, finalName,
1009         "FINAL subroutine '%s' of derived type '%s' must not have a polymorphic dummy argument"_err_en_US,
1010         subroutine.name(), derivedType.name());
1011     ok = false;
1012   } else if (ddo->type.type().category() != TypeCategory::Derived ||
1013       &ddo->type.type().GetDerivedTypeSpec().typeSymbol() != &derivedType) {
1014     SayWithDeclaration(*errSym, finalName,
1015         "FINAL subroutine '%s' of derived type '%s' must have a TYPE(%s) dummy argument"_err_en_US,
1016         subroutine.name(), derivedType.name(), derivedType.name());
1017     ok = false;
1018   } else { // check that all LEN type parameters are assumed
1019     for (auto ref : OrderParameterDeclarations(derivedType)) {
1020       if (IsLenTypeParameter(*ref)) {
1021         const auto *value{
1022             ddo->type.type().GetDerivedTypeSpec().FindParameter(ref->name())};
1023         if (!value || !value->isAssumed()) {
1024           SayWithDeclaration(*errSym, finalName,
1025               "FINAL subroutine '%s' of derived type '%s' must have a dummy argument with an assumed LEN type parameter '%s=*'"_err_en_US,
1026               subroutine.name(), derivedType.name(), ref->name());
1027           ok = false;
1028         }
1029       }
1030     }
1031   }
1032   return ok;
1033 }
1034 
1035 bool CheckHelper::CheckDistinguishableFinals(const Symbol &f1,
1036     SourceName f1Name, const Symbol &f2, SourceName f2Name,
1037     const Symbol &derivedType) {
1038   const Procedure *p1{Characterize(f1)};
1039   const Procedure *p2{Characterize(f2)};
1040   if (p1 && p2) {
1041     if (characteristics::Distinguishable(*p1, *p2)) {
1042       return true;
1043     }
1044     if (auto *msg{messages_.Say(f1Name,
1045             "FINAL subroutines '%s' and '%s' of derived type '%s' cannot be distinguished by rank or KIND type parameter value"_err_en_US,
1046             f1Name, f2Name, derivedType.name())}) {
1047       msg->Attach(f2Name, "FINAL declaration of '%s'"_en_US, f2.name())
1048           .Attach(f1.name(), "Definition of '%s'"_en_US, f1Name)
1049           .Attach(f2.name(), "Definition of '%s'"_en_US, f2Name);
1050     }
1051   }
1052   return false;
1053 }
1054 
1055 void CheckHelper::CheckHostAssoc(
1056     const Symbol &symbol, const HostAssocDetails &details) {
1057   const Symbol &hostSymbol{details.symbol()};
1058   if (hostSymbol.test(Symbol::Flag::ImplicitOrError)) {
1059     if (details.implicitOrSpecExprError) {
1060       messages_.Say("Implicitly typed local entity '%s' not allowed in"
1061                     " specification expression"_err_en_US,
1062           symbol.name());
1063     } else if (details.implicitOrExplicitTypeError) {
1064       messages_.Say(
1065           "No explicit type declared for '%s'"_err_en_US, symbol.name());
1066     }
1067   }
1068 }
1069 
1070 void CheckHelper::CheckGeneric(
1071     const Symbol &symbol, const GenericDetails &details) {
1072   CheckSpecificsAreDistinguishable(symbol, details);
1073   std::visit(common::visitors{
1074                  [&](const GenericKind::DefinedIo &io) {
1075                    CheckDefinedIoProc(symbol, details, io);
1076                  },
1077                  [](const auto &) {},
1078              },
1079       details.kind().u);
1080 }
1081 
1082 // Check that the specifics of this generic are distinguishable from each other
1083 void CheckHelper::CheckSpecificsAreDistinguishable(
1084     const Symbol &generic, const GenericDetails &details) {
1085   GenericKind kind{details.kind()};
1086   const SymbolVector &specifics{details.specificProcs()};
1087   std::size_t count{specifics.size()};
1088   if (count < 2 || !kind.IsName()) {
1089     return;
1090   }
1091   DistinguishabilityHelper helper{context_};
1092   for (const Symbol &specific : specifics) {
1093     if (const Procedure * procedure{Characterize(specific)}) {
1094       helper.Add(generic, kind, specific, *procedure);
1095     }
1096   }
1097   helper.Check(generic.owner());
1098 }
1099 
1100 static bool ConflictsWithIntrinsicAssignment(const Procedure &proc) {
1101   auto lhs{std::get<DummyDataObject>(proc.dummyArguments[0].u).type};
1102   auto rhs{std::get<DummyDataObject>(proc.dummyArguments[1].u).type};
1103   return Tristate::No ==
1104       IsDefinedAssignment(lhs.type(), lhs.Rank(), rhs.type(), rhs.Rank());
1105 }
1106 
1107 static bool ConflictsWithIntrinsicOperator(
1108     const GenericKind &kind, const Procedure &proc) {
1109   if (!kind.IsIntrinsicOperator()) {
1110     return false;
1111   }
1112   auto arg0{std::get<DummyDataObject>(proc.dummyArguments[0].u).type};
1113   auto type0{arg0.type()};
1114   if (proc.dummyArguments.size() == 1) { // unary
1115     return std::visit(
1116         common::visitors{
1117             [&](common::NumericOperator) { return IsIntrinsicNumeric(type0); },
1118             [&](common::LogicalOperator) { return IsIntrinsicLogical(type0); },
1119             [](const auto &) -> bool { DIE("bad generic kind"); },
1120         },
1121         kind.u);
1122   } else { // binary
1123     int rank0{arg0.Rank()};
1124     auto arg1{std::get<DummyDataObject>(proc.dummyArguments[1].u).type};
1125     auto type1{arg1.type()};
1126     int rank1{arg1.Rank()};
1127     return std::visit(
1128         common::visitors{
1129             [&](common::NumericOperator) {
1130               return IsIntrinsicNumeric(type0, rank0, type1, rank1);
1131             },
1132             [&](common::LogicalOperator) {
1133               return IsIntrinsicLogical(type0, rank0, type1, rank1);
1134             },
1135             [&](common::RelationalOperator opr) {
1136               return IsIntrinsicRelational(opr, type0, rank0, type1, rank1);
1137             },
1138             [&](GenericKind::OtherKind x) {
1139               CHECK(x == GenericKind::OtherKind::Concat);
1140               return IsIntrinsicConcat(type0, rank0, type1, rank1);
1141             },
1142             [](const auto &) -> bool { DIE("bad generic kind"); },
1143         },
1144         kind.u);
1145   }
1146 }
1147 
1148 // Check if this procedure can be used for defined operators (see 15.4.3.4.2).
1149 bool CheckHelper::CheckDefinedOperator(SourceName opName, GenericKind kind,
1150     const Symbol &specific, const Procedure &proc) {
1151   if (context_.HasError(specific)) {
1152     return false;
1153   }
1154   std::optional<parser::MessageFixedText> msg;
1155   if (specific.attrs().test(Attr::NOPASS)) { // C774
1156     msg = "%s procedure '%s' may not have NOPASS attribute"_err_en_US;
1157   } else if (!proc.functionResult.has_value()) {
1158     msg = "%s procedure '%s' must be a function"_err_en_US;
1159   } else if (proc.functionResult->IsAssumedLengthCharacter()) {
1160     msg = "%s function '%s' may not have assumed-length CHARACTER(*)"
1161           " result"_err_en_US;
1162   } else if (auto m{CheckNumberOfArgs(kind, proc.dummyArguments.size())}) {
1163     msg = std::move(m);
1164   } else if (!CheckDefinedOperatorArg(opName, specific, proc, 0) |
1165       !CheckDefinedOperatorArg(opName, specific, proc, 1)) {
1166     return false; // error was reported
1167   } else if (ConflictsWithIntrinsicOperator(kind, proc)) {
1168     msg = "%s function '%s' conflicts with intrinsic operator"_err_en_US;
1169   } else {
1170     return true; // OK
1171   }
1172   SayWithDeclaration(
1173       specific, std::move(*msg), MakeOpName(opName), specific.name());
1174   context_.SetError(specific);
1175   return false;
1176 }
1177 
1178 // If the number of arguments is wrong for this intrinsic operator, return
1179 // false and return the error message in msg.
1180 std::optional<parser::MessageFixedText> CheckHelper::CheckNumberOfArgs(
1181     const GenericKind &kind, std::size_t nargs) {
1182   if (!kind.IsIntrinsicOperator()) {
1183     return std::nullopt;
1184   }
1185   std::size_t min{2}, max{2}; // allowed number of args; default is binary
1186   std::visit(common::visitors{
1187                  [&](const common::NumericOperator &x) {
1188                    if (x == common::NumericOperator::Add ||
1189                        x == common::NumericOperator::Subtract) {
1190                      min = 1; // + and - are unary or binary
1191                    }
1192                  },
1193                  [&](const common::LogicalOperator &x) {
1194                    if (x == common::LogicalOperator::Not) {
1195                      min = 1; // .NOT. is unary
1196                      max = 1;
1197                    }
1198                  },
1199                  [](const common::RelationalOperator &) {
1200                    // all are binary
1201                  },
1202                  [](const GenericKind::OtherKind &x) {
1203                    CHECK(x == GenericKind::OtherKind::Concat);
1204                  },
1205                  [](const auto &) { DIE("expected intrinsic operator"); },
1206              },
1207       kind.u);
1208   if (nargs >= min && nargs <= max) {
1209     return std::nullopt;
1210   } else if (max == 1) {
1211     return "%s function '%s' must have one dummy argument"_err_en_US;
1212   } else if (min == 2) {
1213     return "%s function '%s' must have two dummy arguments"_err_en_US;
1214   } else {
1215     return "%s function '%s' must have one or two dummy arguments"_err_en_US;
1216   }
1217 }
1218 
1219 bool CheckHelper::CheckDefinedOperatorArg(const SourceName &opName,
1220     const Symbol &symbol, const Procedure &proc, std::size_t pos) {
1221   if (pos >= proc.dummyArguments.size()) {
1222     return true;
1223   }
1224   auto &arg{proc.dummyArguments.at(pos)};
1225   std::optional<parser::MessageFixedText> msg;
1226   if (arg.IsOptional()) {
1227     msg = "In %s function '%s', dummy argument '%s' may not be"
1228           " OPTIONAL"_err_en_US;
1229   } else if (const auto *dataObject{std::get_if<DummyDataObject>(&arg.u)};
1230              dataObject == nullptr) {
1231     msg = "In %s function '%s', dummy argument '%s' must be a"
1232           " data object"_err_en_US;
1233   } else if (dataObject->intent != common::Intent::In &&
1234       !dataObject->attrs.test(DummyDataObject::Attr::Value)) {
1235     msg = "In %s function '%s', dummy argument '%s' must have INTENT(IN)"
1236           " or VALUE attribute"_err_en_US;
1237   }
1238   if (msg) {
1239     SayWithDeclaration(symbol, std::move(*msg),
1240         parser::ToUpperCaseLetters(opName.ToString()), symbol.name(), arg.name);
1241     return false;
1242   }
1243   return true;
1244 }
1245 
1246 // Check if this procedure can be used for defined assignment (see 15.4.3.4.3).
1247 bool CheckHelper::CheckDefinedAssignment(
1248     const Symbol &specific, const Procedure &proc) {
1249   if (context_.HasError(specific)) {
1250     return false;
1251   }
1252   std::optional<parser::MessageFixedText> msg;
1253   if (specific.attrs().test(Attr::NOPASS)) { // C774
1254     msg = "Defined assignment procedure '%s' may not have"
1255           " NOPASS attribute"_err_en_US;
1256   } else if (!proc.IsSubroutine()) {
1257     msg = "Defined assignment procedure '%s' must be a subroutine"_err_en_US;
1258   } else if (proc.dummyArguments.size() != 2) {
1259     msg = "Defined assignment subroutine '%s' must have"
1260           " two dummy arguments"_err_en_US;
1261   } else if (!CheckDefinedAssignmentArg(specific, proc.dummyArguments[0], 0) |
1262       !CheckDefinedAssignmentArg(specific, proc.dummyArguments[1], 1)) {
1263     return false; // error was reported
1264   } else if (ConflictsWithIntrinsicAssignment(proc)) {
1265     msg = "Defined assignment subroutine '%s' conflicts with"
1266           " intrinsic assignment"_err_en_US;
1267   } else {
1268     return true; // OK
1269   }
1270   SayWithDeclaration(specific, std::move(msg.value()), specific.name());
1271   context_.SetError(specific);
1272   return false;
1273 }
1274 
1275 bool CheckHelper::CheckDefinedAssignmentArg(
1276     const Symbol &symbol, const DummyArgument &arg, int pos) {
1277   std::optional<parser::MessageFixedText> msg;
1278   if (arg.IsOptional()) {
1279     msg = "In defined assignment subroutine '%s', dummy argument '%s'"
1280           " may not be OPTIONAL"_err_en_US;
1281   } else if (const auto *dataObject{std::get_if<DummyDataObject>(&arg.u)}) {
1282     if (pos == 0) {
1283       if (dataObject->intent != common::Intent::Out &&
1284           dataObject->intent != common::Intent::InOut) {
1285         msg = "In defined assignment subroutine '%s', first dummy argument '%s'"
1286               " must have INTENT(OUT) or INTENT(INOUT)"_err_en_US;
1287       }
1288     } else if (pos == 1) {
1289       if (dataObject->intent != common::Intent::In &&
1290           !dataObject->attrs.test(DummyDataObject::Attr::Value)) {
1291         msg =
1292             "In defined assignment subroutine '%s', second dummy"
1293             " argument '%s' must have INTENT(IN) or VALUE attribute"_err_en_US;
1294       }
1295     } else {
1296       DIE("pos must be 0 or 1");
1297     }
1298   } else {
1299     msg = "In defined assignment subroutine '%s', dummy argument '%s'"
1300           " must be a data object"_err_en_US;
1301   }
1302   if (msg) {
1303     SayWithDeclaration(symbol, std::move(*msg), symbol.name(), arg.name);
1304     context_.SetError(symbol);
1305     return false;
1306   }
1307   return true;
1308 }
1309 
1310 // Report a conflicting attribute error if symbol has both of these attributes
1311 bool CheckHelper::CheckConflicting(const Symbol &symbol, Attr a1, Attr a2) {
1312   if (symbol.attrs().test(a1) && symbol.attrs().test(a2)) {
1313     messages_.Say("'%s' may not have both the %s and %s attributes"_err_en_US,
1314         symbol.name(), AttrToString(a1), AttrToString(a2));
1315     return true;
1316   } else {
1317     return false;
1318   }
1319 }
1320 
1321 void CheckHelper::WarnMissingFinal(const Symbol &symbol) {
1322   const auto *object{symbol.detailsIf<ObjectEntityDetails>()};
1323   if (!object || IsPointer(symbol)) {
1324     return;
1325   }
1326   const DeclTypeSpec *type{object->type()};
1327   const DerivedTypeSpec *derived{type ? type->AsDerived() : nullptr};
1328   const Symbol *derivedSym{derived ? &derived->typeSymbol() : nullptr};
1329   int rank{object->shape().Rank()};
1330   const Symbol *initialDerivedSym{derivedSym};
1331   while (const auto *derivedDetails{
1332       derivedSym ? derivedSym->detailsIf<DerivedTypeDetails>() : nullptr}) {
1333     if (!derivedDetails->finals().empty() &&
1334         !derivedDetails->GetFinalForRank(rank)) {
1335       if (auto *msg{derivedSym == initialDerivedSym
1336                   ? messages_.Say(symbol.name(),
1337                         "'%s' of derived type '%s' does not have a FINAL subroutine for its rank (%d)"_en_US,
1338                         symbol.name(), derivedSym->name(), rank)
1339                   : messages_.Say(symbol.name(),
1340                         "'%s' of derived type '%s' extended from '%s' does not have a FINAL subroutine for its rank (%d)"_en_US,
1341                         symbol.name(), initialDerivedSym->name(),
1342                         derivedSym->name(), rank)}) {
1343         msg->Attach(derivedSym->name(),
1344             "Declaration of derived type '%s'"_en_US, derivedSym->name());
1345       }
1346       return;
1347     }
1348     derived = derivedSym->GetParentTypeSpec();
1349     derivedSym = derived ? &derived->typeSymbol() : nullptr;
1350   }
1351 }
1352 
1353 const Procedure *CheckHelper::Characterize(const Symbol &symbol) {
1354   auto it{characterizeCache_.find(symbol)};
1355   if (it == characterizeCache_.end()) {
1356     auto pair{characterizeCache_.emplace(SymbolRef{symbol},
1357         Procedure::Characterize(symbol, context_.foldingContext()))};
1358     it = pair.first;
1359   }
1360   return common::GetPtrFromOptional(it->second);
1361 }
1362 
1363 void CheckHelper::CheckVolatile(const Symbol &symbol,
1364     const DerivedTypeSpec *derived) { // C866 - C868
1365   if (IsIntentIn(symbol)) {
1366     messages_.Say(
1367         "VOLATILE attribute may not apply to an INTENT(IN) argument"_err_en_US);
1368   }
1369   if (IsProcedure(symbol)) {
1370     messages_.Say("VOLATILE attribute may apply only to a variable"_err_en_US);
1371   }
1372   if (symbol.has<UseDetails>() || symbol.has<HostAssocDetails>()) {
1373     const Symbol &ultimate{symbol.GetUltimate()};
1374     if (IsCoarray(ultimate)) {
1375       messages_.Say(
1376           "VOLATILE attribute may not apply to a coarray accessed by USE or host association"_err_en_US);
1377     }
1378     if (derived) {
1379       if (FindCoarrayUltimateComponent(*derived)) {
1380         messages_.Say(
1381             "VOLATILE attribute may not apply to a type with a coarray ultimate component accessed by USE or host association"_err_en_US);
1382       }
1383     }
1384   }
1385 }
1386 
1387 void CheckHelper::CheckPointer(const Symbol &symbol) { // C852
1388   CheckConflicting(symbol, Attr::POINTER, Attr::TARGET);
1389   CheckConflicting(symbol, Attr::POINTER, Attr::ALLOCATABLE); // C751
1390   CheckConflicting(symbol, Attr::POINTER, Attr::INTRINSIC);
1391   // Prohibit constant pointers.  The standard does not explicitly prohibit
1392   // them, but the PARAMETER attribute requires a entity-decl to have an
1393   // initialization that is a constant-expr, and the only form of
1394   // initialization that allows a constant-expr is the one that's not a "=>"
1395   // pointer initialization.  See C811, C807, and section 8.5.13.
1396   CheckConflicting(symbol, Attr::POINTER, Attr::PARAMETER);
1397   if (symbol.Corank() > 0) {
1398     messages_.Say(
1399         "'%s' may not have the POINTER attribute because it is a coarray"_err_en_US,
1400         symbol.name());
1401   }
1402 }
1403 
1404 // C760 constraints on the passed-object dummy argument
1405 // C757 constraints on procedure pointer components
1406 void CheckHelper::CheckPassArg(
1407     const Symbol &proc, const Symbol *interface, const WithPassArg &details) {
1408   if (proc.attrs().test(Attr::NOPASS)) {
1409     return;
1410   }
1411   const auto &name{proc.name()};
1412   if (!interface) {
1413     messages_.Say(name,
1414         "Procedure component '%s' must have NOPASS attribute or explicit interface"_err_en_US,
1415         name);
1416     return;
1417   }
1418   const auto *subprogram{interface->detailsIf<SubprogramDetails>()};
1419   if (!subprogram) {
1420     messages_.Say(name,
1421         "Procedure component '%s' has invalid interface '%s'"_err_en_US, name,
1422         interface->name());
1423     return;
1424   }
1425   std::optional<SourceName> passName{details.passName()};
1426   const auto &dummyArgs{subprogram->dummyArgs()};
1427   if (!passName) {
1428     if (dummyArgs.empty()) {
1429       messages_.Say(name,
1430           proc.has<ProcEntityDetails>()
1431               ? "Procedure component '%s' with no dummy arguments"
1432                 " must have NOPASS attribute"_err_en_US
1433               : "Procedure binding '%s' with no dummy arguments"
1434                 " must have NOPASS attribute"_err_en_US,
1435           name);
1436       context_.SetError(*interface);
1437       return;
1438     }
1439     Symbol *argSym{dummyArgs[0]};
1440     if (!argSym) {
1441       messages_.Say(interface->name(),
1442           "Cannot use an alternate return as the passed-object dummy "
1443           "argument"_err_en_US);
1444       return;
1445     }
1446     passName = dummyArgs[0]->name();
1447   }
1448   std::optional<int> passArgIndex{};
1449   for (std::size_t i{0}; i < dummyArgs.size(); ++i) {
1450     if (dummyArgs[i] && dummyArgs[i]->name() == *passName) {
1451       passArgIndex = i;
1452       break;
1453     }
1454   }
1455   if (!passArgIndex) { // C758
1456     messages_.Say(*passName,
1457         "'%s' is not a dummy argument of procedure interface '%s'"_err_en_US,
1458         *passName, interface->name());
1459     return;
1460   }
1461   const Symbol &passArg{*dummyArgs[*passArgIndex]};
1462   std::optional<parser::MessageFixedText> msg;
1463   if (!passArg.has<ObjectEntityDetails>()) {
1464     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1465           " must be a data object"_err_en_US;
1466   } else if (passArg.attrs().test(Attr::POINTER)) {
1467     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1468           " may not have the POINTER attribute"_err_en_US;
1469   } else if (passArg.attrs().test(Attr::ALLOCATABLE)) {
1470     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1471           " may not have the ALLOCATABLE attribute"_err_en_US;
1472   } else if (passArg.attrs().test(Attr::VALUE)) {
1473     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1474           " may not have the VALUE attribute"_err_en_US;
1475   } else if (passArg.Rank() > 0) {
1476     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1477           " must be scalar"_err_en_US;
1478   }
1479   if (msg) {
1480     messages_.Say(name, std::move(*msg), passName.value(), name);
1481     return;
1482   }
1483   const DeclTypeSpec *type{passArg.GetType()};
1484   if (!type) {
1485     return; // an error already occurred
1486   }
1487   const Symbol &typeSymbol{*proc.owner().GetSymbol()};
1488   const DerivedTypeSpec *derived{type->AsDerived()};
1489   if (!derived || derived->typeSymbol() != typeSymbol) {
1490     messages_.Say(name,
1491         "Passed-object dummy argument '%s' of procedure '%s'"
1492         " must be of type '%s' but is '%s'"_err_en_US,
1493         passName.value(), name, typeSymbol.name(), type->AsFortran());
1494     return;
1495   }
1496   if (IsExtensibleType(derived) != type->IsPolymorphic()) {
1497     messages_.Say(name,
1498         type->IsPolymorphic()
1499             ? "Passed-object dummy argument '%s' of procedure '%s'"
1500               " may not be polymorphic because '%s' is not extensible"_err_en_US
1501             : "Passed-object dummy argument '%s' of procedure '%s'"
1502               " must be polymorphic because '%s' is extensible"_err_en_US,
1503         passName.value(), name, typeSymbol.name());
1504     return;
1505   }
1506   for (const auto &[paramName, paramValue] : derived->parameters()) {
1507     if (paramValue.isLen() && !paramValue.isAssumed()) {
1508       messages_.Say(name,
1509           "Passed-object dummy argument '%s' of procedure '%s'"
1510           " has non-assumed length parameter '%s'"_err_en_US,
1511           passName.value(), name, paramName);
1512     }
1513   }
1514 }
1515 
1516 void CheckHelper::CheckProcBinding(
1517     const Symbol &symbol, const ProcBindingDetails &binding) {
1518   const Scope &dtScope{symbol.owner()};
1519   CHECK(dtScope.kind() == Scope::Kind::DerivedType);
1520   if (symbol.attrs().test(Attr::DEFERRED)) {
1521     if (const Symbol * dtSymbol{dtScope.symbol()}) {
1522       if (!dtSymbol->attrs().test(Attr::ABSTRACT)) { // C733
1523         SayWithDeclaration(*dtSymbol,
1524             "Procedure bound to non-ABSTRACT derived type '%s' may not be DEFERRED"_err_en_US,
1525             dtSymbol->name());
1526       }
1527     }
1528     if (symbol.attrs().test(Attr::NON_OVERRIDABLE)) {
1529       messages_.Say(
1530           "Type-bound procedure '%s' may not be both DEFERRED and NON_OVERRIDABLE"_err_en_US,
1531           symbol.name());
1532     }
1533   }
1534   if (binding.symbol().attrs().test(Attr::INTRINSIC) &&
1535       !context_.intrinsics().IsSpecificIntrinsicFunction(
1536           binding.symbol().name().ToString())) {
1537     messages_.Say(
1538         "Intrinsic procedure '%s' is not a specific intrinsic permitted for use in the definition of binding '%s'"_err_en_US,
1539         binding.symbol().name(), symbol.name());
1540   }
1541   if (const Symbol * overridden{FindOverriddenBinding(symbol)}) {
1542     if (overridden->attrs().test(Attr::NON_OVERRIDABLE)) {
1543       SayWithDeclaration(*overridden,
1544           "Override of NON_OVERRIDABLE '%s' is not permitted"_err_en_US,
1545           symbol.name());
1546     }
1547     if (const auto *overriddenBinding{
1548             overridden->detailsIf<ProcBindingDetails>()}) {
1549       if (!IsPureProcedure(symbol) && IsPureProcedure(*overridden)) {
1550         SayWithDeclaration(*overridden,
1551             "An overridden pure type-bound procedure binding must also be pure"_err_en_US);
1552         return;
1553       }
1554       if (!binding.symbol().attrs().test(Attr::ELEMENTAL) &&
1555           overriddenBinding->symbol().attrs().test(Attr::ELEMENTAL)) {
1556         SayWithDeclaration(*overridden,
1557             "A type-bound procedure and its override must both, or neither, be ELEMENTAL"_err_en_US);
1558         return;
1559       }
1560       bool isNopass{symbol.attrs().test(Attr::NOPASS)};
1561       if (isNopass != overridden->attrs().test(Attr::NOPASS)) {
1562         SayWithDeclaration(*overridden,
1563             isNopass
1564                 ? "A NOPASS type-bound procedure may not override a passed-argument procedure"_err_en_US
1565                 : "A passed-argument type-bound procedure may not override a NOPASS procedure"_err_en_US);
1566       } else {
1567         const auto *bindingChars{Characterize(binding.symbol())};
1568         const auto *overriddenChars{Characterize(overriddenBinding->symbol())};
1569         if (bindingChars && overriddenChars) {
1570           if (isNopass) {
1571             if (!bindingChars->CanOverride(*overriddenChars, std::nullopt)) {
1572               SayWithDeclaration(*overridden,
1573                   "A type-bound procedure and its override must have compatible interfaces"_err_en_US);
1574             }
1575           } else if (!context_.HasError(binding.symbol())) {
1576             int passIndex{bindingChars->FindPassIndex(binding.passName())};
1577             int overriddenPassIndex{
1578                 overriddenChars->FindPassIndex(overriddenBinding->passName())};
1579             if (passIndex != overriddenPassIndex) {
1580               SayWithDeclaration(*overridden,
1581                   "A type-bound procedure and its override must use the same PASS argument"_err_en_US);
1582             } else if (!bindingChars->CanOverride(
1583                            *overriddenChars, passIndex)) {
1584               SayWithDeclaration(*overridden,
1585                   "A type-bound procedure and its override must have compatible interfaces apart from their passed argument"_err_en_US);
1586             }
1587           }
1588         }
1589       }
1590       if (symbol.attrs().test(Attr::PRIVATE) &&
1591           overridden->attrs().test(Attr::PUBLIC)) {
1592         SayWithDeclaration(*overridden,
1593             "A PRIVATE procedure may not override a PUBLIC procedure"_err_en_US);
1594       }
1595     } else {
1596       SayWithDeclaration(*overridden,
1597           "A type-bound procedure binding may not have the same name as a parent component"_err_en_US);
1598     }
1599   }
1600   CheckPassArg(symbol, &binding.symbol(), binding);
1601 }
1602 
1603 void CheckHelper::Check(const Scope &scope) {
1604   scope_ = &scope;
1605   common::Restorer<const Symbol *> restorer{innermostSymbol_, innermostSymbol_};
1606   if (const Symbol * symbol{scope.symbol()}) {
1607     innermostSymbol_ = symbol;
1608   }
1609   if (scope.IsParameterizedDerivedTypeInstantiation()) {
1610     auto restorer{common::ScopedSet(scopeIsUninstantiatedPDT_, false)};
1611     auto restorer2{context_.foldingContext().messages().SetContext(
1612         scope.instantiationContext().get())};
1613     for (const auto &pair : scope) {
1614       CheckPointerInitialization(*pair.second);
1615     }
1616   } else {
1617     auto restorer{common::ScopedSet(
1618         scopeIsUninstantiatedPDT_, scope.IsParameterizedDerivedType())};
1619     for (const auto &set : scope.equivalenceSets()) {
1620       CheckEquivalenceSet(set);
1621     }
1622     for (const auto &pair : scope) {
1623       Check(*pair.second);
1624     }
1625     for (const Scope &child : scope.children()) {
1626       Check(child);
1627     }
1628     if (scope.kind() == Scope::Kind::BlockData) {
1629       CheckBlockData(scope);
1630     }
1631     CheckGenericOps(scope);
1632   }
1633 }
1634 
1635 void CheckHelper::CheckEquivalenceSet(const EquivalenceSet &set) {
1636   auto iter{
1637       std::find_if(set.begin(), set.end(), [](const EquivalenceObject &object) {
1638         return FindCommonBlockContaining(object.symbol) != nullptr;
1639       })};
1640   if (iter != set.end()) {
1641     const Symbol &commonBlock{DEREF(FindCommonBlockContaining(iter->symbol))};
1642     for (auto &object : set) {
1643       if (&object != &*iter) {
1644         if (auto *details{object.symbol.detailsIf<ObjectEntityDetails>()}) {
1645           if (details->commonBlock()) {
1646             if (details->commonBlock() != &commonBlock) { // 8.10.3 paragraph 1
1647               if (auto *msg{messages_.Say(object.symbol.name(),
1648                       "Two objects in the same EQUIVALENCE set may not be members of distinct COMMON blocks"_err_en_US)}) {
1649                 msg->Attach(iter->symbol.name(),
1650                        "Other object in EQUIVALENCE set"_en_US)
1651                     .Attach(details->commonBlock()->name(),
1652                         "COMMON block containing '%s'"_en_US,
1653                         object.symbol.name())
1654                     .Attach(commonBlock.name(),
1655                         "COMMON block containing '%s'"_en_US,
1656                         iter->symbol.name());
1657               }
1658             }
1659           } else {
1660             // Mark all symbols in the equivalence set with the same COMMON
1661             // block to prevent spurious error messages about initialization
1662             // in BLOCK DATA outside COMMON
1663             details->set_commonBlock(commonBlock);
1664           }
1665         }
1666       }
1667     }
1668   }
1669   // TODO: Move C8106 (&al.) checks here from resolve-names-utils.cpp
1670 }
1671 
1672 void CheckHelper::CheckBlockData(const Scope &scope) {
1673   // BLOCK DATA subprograms should contain only named common blocks.
1674   // C1415 presents a list of statements that shouldn't appear in
1675   // BLOCK DATA, but so long as the subprogram contains no executable
1676   // code and allocates no storage outside named COMMON, we're happy
1677   // (e.g., an ENUM is strictly not allowed).
1678   for (const auto &pair : scope) {
1679     const Symbol &symbol{*pair.second};
1680     if (!(symbol.has<CommonBlockDetails>() || symbol.has<UseDetails>() ||
1681             symbol.has<UseErrorDetails>() || symbol.has<DerivedTypeDetails>() ||
1682             symbol.has<SubprogramDetails>() ||
1683             symbol.has<ObjectEntityDetails>() ||
1684             (symbol.has<ProcEntityDetails>() &&
1685                 !symbol.attrs().test(Attr::POINTER)))) {
1686       messages_.Say(symbol.name(),
1687           "'%s' may not appear in a BLOCK DATA subprogram"_err_en_US,
1688           symbol.name());
1689     }
1690   }
1691 }
1692 
1693 // Check distinguishability of generic assignment and operators.
1694 // For these, generics and generic bindings must be considered together.
1695 void CheckHelper::CheckGenericOps(const Scope &scope) {
1696   DistinguishabilityHelper helper{context_};
1697   auto addSpecifics{[&](const Symbol &generic) {
1698     const auto *details{generic.GetUltimate().detailsIf<GenericDetails>()};
1699     if (!details) {
1700       return;
1701     }
1702     GenericKind kind{details->kind()};
1703     if (!kind.IsAssignment() && !kind.IsOperator()) {
1704       return;
1705     }
1706     const SymbolVector &specifics{details->specificProcs()};
1707     const std::vector<SourceName> &bindingNames{details->bindingNames()};
1708     for (std::size_t i{0}; i < specifics.size(); ++i) {
1709       const Symbol &specific{*specifics[i]};
1710       if (const Procedure * proc{Characterize(specific)}) {
1711         auto restorer{messages_.SetLocation(bindingNames[i])};
1712         if (kind.IsAssignment()) {
1713           if (!CheckDefinedAssignment(specific, *proc)) {
1714             continue;
1715           }
1716         } else {
1717           if (!CheckDefinedOperator(generic.name(), kind, specific, *proc)) {
1718             continue;
1719           }
1720         }
1721         helper.Add(generic, kind, specific, *proc);
1722       }
1723     }
1724   }};
1725   for (const auto &pair : scope) {
1726     const Symbol &symbol{*pair.second};
1727     addSpecifics(symbol);
1728     const Symbol &ultimate{symbol.GetUltimate()};
1729     if (ultimate.has<DerivedTypeDetails>()) {
1730       if (const Scope * typeScope{ultimate.scope()}) {
1731         for (const auto &pair2 : *typeScope) {
1732           addSpecifics(*pair2.second);
1733         }
1734       }
1735     }
1736   }
1737   helper.Check(scope);
1738 }
1739 
1740 static const std::string *DefinesBindCName(const Symbol &symbol) {
1741   const auto *subp{symbol.detailsIf<SubprogramDetails>()};
1742   if ((subp && !subp->isInterface()) || symbol.has<ObjectEntityDetails>()) {
1743     // Symbol defines data or entry point
1744     return symbol.GetBindName();
1745   } else {
1746     return nullptr;
1747   }
1748 }
1749 
1750 // Check that BIND(C) names are distinct
1751 void CheckHelper::CheckBindCName(const Symbol &symbol) {
1752   if (const std::string * name{DefinesBindCName(symbol)}) {
1753     auto pair{bindC_.emplace(*name, symbol)};
1754     if (!pair.second) {
1755       const Symbol &other{*pair.first->second};
1756       if (DefinesBindCName(other) && !context_.HasError(other)) {
1757         if (auto *msg{messages_.Say(
1758                 "Two symbols have the same BIND(C) name '%s'"_err_en_US,
1759                 *name)}) {
1760           msg->Attach(other.name(), "Conflicting symbol"_en_US);
1761         }
1762         context_.SetError(symbol);
1763         context_.SetError(other);
1764       }
1765     }
1766   }
1767 }
1768 
1769 bool CheckHelper::CheckDioDummyIsData(
1770     const Symbol &subp, const Symbol *arg, std::size_t position) {
1771   if (arg && arg->detailsIf<ObjectEntityDetails>()) {
1772     return true;
1773   } else {
1774     if (arg) {
1775       messages_.Say(arg->name(),
1776           "Dummy argument '%s' must be a data object"_err_en_US, arg->name());
1777     } else {
1778       messages_.Say(subp.name(),
1779           "Dummy argument %d of '%s' must be a data object"_err_en_US, position,
1780           subp.name());
1781     }
1782     return false;
1783   }
1784 }
1785 
1786 void CheckHelper::CheckAlreadySeenDefinedIo(const DerivedTypeSpec *derivedType,
1787     GenericKind::DefinedIo ioKind, const Symbol &proc) {
1788   for (TypeWithDefinedIo definedIoType : seenDefinedIoTypes_) {
1789     if (*derivedType == *definedIoType.type && ioKind == definedIoType.ioKind &&
1790         proc != definedIoType.proc) {
1791       SayWithDeclaration(proc, definedIoType.proc.name(),
1792           "Derived type '%s' already has defined input/output procedure"
1793           " '%s'"_err_en_US,
1794           derivedType->name(),
1795           parser::ToUpperCaseLetters(GenericKind::EnumToString(ioKind)));
1796       return;
1797     }
1798   }
1799   seenDefinedIoTypes_.emplace_back(
1800       TypeWithDefinedIo{derivedType, ioKind, proc});
1801 }
1802 
1803 void CheckHelper::CheckDioDummyIsDerived(
1804     const Symbol &subp, const Symbol &arg, GenericKind::DefinedIo ioKind) {
1805   if (const DeclTypeSpec * type{arg.GetType()}) {
1806     if (const DerivedTypeSpec * derivedType{type->AsDerived()}) {
1807       CheckAlreadySeenDefinedIo(derivedType, ioKind, subp);
1808       bool isPolymorphic{type->IsPolymorphic()};
1809       if (isPolymorphic != IsExtensibleType(derivedType)) {
1810         messages_.Say(arg.name(),
1811             "Dummy argument '%s' of a defined input/output procedure must be %s when the derived type is %s"_err_en_US,
1812             arg.name(), isPolymorphic ? "TYPE()" : "CLASS()",
1813             isPolymorphic ? "not extensible" : "extensible");
1814       }
1815     } else {
1816       messages_.Say(arg.name(),
1817           "Dummy argument '%s' of a defined input/output procedure must have a"
1818           " derived type"_err_en_US,
1819           arg.name());
1820     }
1821   }
1822 }
1823 
1824 void CheckHelper::CheckDioDummyIsDefaultInteger(
1825     const Symbol &subp, const Symbol &arg) {
1826   if (const DeclTypeSpec * type{arg.GetType()};
1827       type && type->IsNumeric(TypeCategory::Integer)) {
1828     if (const auto kind{evaluate::ToInt64(type->numericTypeSpec().kind())};
1829         kind && *kind == context_.GetDefaultKind(TypeCategory::Integer)) {
1830       return;
1831     }
1832   }
1833   messages_.Say(arg.name(),
1834       "Dummy argument '%s' of a defined input/output procedure"
1835       " must be an INTEGER of default KIND"_err_en_US,
1836       arg.name());
1837 }
1838 
1839 void CheckHelper::CheckDioDummyIsScalar(const Symbol &subp, const Symbol &arg) {
1840   if (arg.Rank() > 0 || arg.Corank() > 0) {
1841     messages_.Say(arg.name(),
1842         "Dummy argument '%s' of a defined input/output procedure"
1843         " must be a scalar"_err_en_US,
1844         arg.name());
1845   }
1846 }
1847 
1848 void CheckHelper::CheckDioDtvArg(
1849     const Symbol &subp, const Symbol *arg, GenericKind::DefinedIo ioKind) {
1850   // Dtv argument looks like: dtv-type-spec, INTENT(INOUT) :: dtv
1851   if (CheckDioDummyIsData(subp, arg, 0)) {
1852     CheckDioDummyIsDerived(subp, *arg, ioKind);
1853     CheckDioDummyAttrs(subp, *arg,
1854         ioKind == GenericKind::DefinedIo::ReadFormatted ||
1855                 ioKind == GenericKind::DefinedIo::ReadUnformatted
1856             ? Attr::INTENT_INOUT
1857             : Attr::INTENT_IN);
1858   }
1859 }
1860 
1861 void CheckHelper::CheckDefaultIntegerArg(
1862     const Symbol &subp, const Symbol *arg, Attr intent) {
1863   // Argument looks like: INTEGER, INTENT(intent) :: arg
1864   if (CheckDioDummyIsData(subp, arg, 1)) {
1865     CheckDioDummyIsDefaultInteger(subp, *arg);
1866     CheckDioDummyIsScalar(subp, *arg);
1867     CheckDioDummyAttrs(subp, *arg, intent);
1868   }
1869 }
1870 
1871 void CheckHelper::CheckDioAssumedLenCharacterArg(const Symbol &subp,
1872     const Symbol *arg, std::size_t argPosition, Attr intent) {
1873   // Argument looks like: CHARACTER (LEN=*), INTENT(intent) :: (iotype OR iomsg)
1874   if (CheckDioDummyIsData(subp, arg, argPosition)) {
1875     CheckDioDummyAttrs(subp, *arg, intent);
1876     if (!IsAssumedLengthCharacter(*arg)) {
1877       messages_.Say(arg->name(),
1878           "Dummy argument '%s' of a defined input/output procedure"
1879           " must be assumed-length CHARACTER"_err_en_US,
1880           arg->name());
1881     }
1882   }
1883 }
1884 
1885 void CheckHelper::CheckDioVlistArg(
1886     const Symbol &subp, const Symbol *arg, std::size_t argPosition) {
1887   // Vlist argument looks like: INTEGER, INTENT(IN) :: v_list(:)
1888   if (CheckDioDummyIsData(subp, arg, argPosition)) {
1889     CheckDioDummyIsDefaultInteger(subp, *arg);
1890     CheckDioDummyAttrs(subp, *arg, Attr::INTENT_IN);
1891     if (const auto *objectDetails{arg->detailsIf<ObjectEntityDetails>()}) {
1892       if (objectDetails->shape().IsDeferredShape()) {
1893         return;
1894       }
1895     }
1896     messages_.Say(arg->name(),
1897         "Dummy argument '%s' of a defined input/output procedure must be"
1898         " deferred shape"_err_en_US,
1899         arg->name());
1900   }
1901 }
1902 
1903 void CheckHelper::CheckDioArgCount(
1904     const Symbol &subp, GenericKind::DefinedIo ioKind, std::size_t argCount) {
1905   const std::size_t requiredArgCount{
1906       (std::size_t)(ioKind == GenericKind::DefinedIo::ReadFormatted ||
1907                   ioKind == GenericKind::DefinedIo::WriteFormatted
1908               ? 6
1909               : 4)};
1910   if (argCount != requiredArgCount) {
1911     SayWithDeclaration(subp,
1912         "Defined input/output procedure '%s' must have"
1913         " %d dummy arguments rather than %d"_err_en_US,
1914         subp.name(), requiredArgCount, argCount);
1915     context_.SetError(subp);
1916   }
1917 }
1918 
1919 void CheckHelper::CheckDioDummyAttrs(
1920     const Symbol &subp, const Symbol &arg, Attr goodIntent) {
1921   // Defined I/O procedures can't have attributes other than INTENT
1922   Attrs attrs{arg.attrs()};
1923   if (!attrs.test(goodIntent)) {
1924     messages_.Say(arg.name(),
1925         "Dummy argument '%s' of a defined input/output procedure"
1926         " must have intent '%s'"_err_en_US,
1927         arg.name(), AttrToString(goodIntent));
1928   }
1929   attrs = attrs - Attr::INTENT_IN - Attr::INTENT_OUT - Attr::INTENT_INOUT;
1930   if (!attrs.empty()) {
1931     messages_.Say(arg.name(),
1932         "Dummy argument '%s' of a defined input/output procedure may not have"
1933         " any attributes"_err_en_US,
1934         arg.name());
1935   }
1936 }
1937 
1938 // Enforce semantics for defined input/output procedures (12.6.4.8.2) and C777
1939 void CheckHelper::CheckDefinedIoProc(const Symbol &symbol,
1940     const GenericDetails &details, GenericKind::DefinedIo ioKind) {
1941   for (auto ref : details.specificProcs()) {
1942     const auto *binding{ref->detailsIf<ProcBindingDetails>()};
1943     const Symbol &specific{*(binding ? &binding->symbol() : &*ref)};
1944     if (ref->attrs().test(Attr::NOPASS)) { // C774
1945       messages_.Say("Defined input/output procedure '%s' may not have NOPASS "
1946                     "attribute"_err_en_US,
1947           ref->name());
1948       context_.SetError(*ref);
1949     }
1950     if (const auto *subpDetails{specific.detailsIf<SubprogramDetails>()}) {
1951       const std::vector<Symbol *> &dummyArgs{subpDetails->dummyArgs()};
1952       CheckDioArgCount(specific, ioKind, dummyArgs.size());
1953       int argCount{0};
1954       for (auto *arg : dummyArgs) {
1955         switch (argCount++) {
1956         case 0:
1957           // dtv-type-spec, INTENT(INOUT) :: dtv
1958           CheckDioDtvArg(specific, arg, ioKind);
1959           break;
1960         case 1:
1961           // INTEGER, INTENT(IN) :: unit
1962           CheckDefaultIntegerArg(specific, arg, Attr::INTENT_IN);
1963           break;
1964         case 2:
1965           if (ioKind == GenericKind::DefinedIo::ReadFormatted ||
1966               ioKind == GenericKind::DefinedIo::WriteFormatted) {
1967             // CHARACTER (LEN=*), INTENT(IN) :: iotype
1968             CheckDioAssumedLenCharacterArg(
1969                 specific, arg, argCount, Attr::INTENT_IN);
1970           } else {
1971             // INTEGER, INTENT(OUT) :: iostat
1972             CheckDefaultIntegerArg(specific, arg, Attr::INTENT_OUT);
1973           }
1974           break;
1975         case 3:
1976           if (ioKind == GenericKind::DefinedIo::ReadFormatted ||
1977               ioKind == GenericKind::DefinedIo::WriteFormatted) {
1978             // INTEGER, INTENT(IN) :: v_list(:)
1979             CheckDioVlistArg(specific, arg, argCount);
1980           } else {
1981             // CHARACTER (LEN=*), INTENT(INOUT) :: iomsg
1982             CheckDioAssumedLenCharacterArg(
1983                 specific, arg, argCount, Attr::INTENT_INOUT);
1984           }
1985           break;
1986         case 4:
1987           // INTEGER, INTENT(OUT) :: iostat
1988           CheckDefaultIntegerArg(specific, arg, Attr::INTENT_OUT);
1989           break;
1990         case 5:
1991           // CHARACTER (LEN=*), INTENT(INOUT) :: iomsg
1992           CheckDioAssumedLenCharacterArg(
1993               specific, arg, argCount, Attr::INTENT_INOUT);
1994           break;
1995         default:;
1996         }
1997       }
1998     }
1999   }
2000 }
2001 
2002 void SubprogramMatchHelper::Check(
2003     const Symbol &symbol1, const Symbol &symbol2) {
2004   const auto details1{symbol1.get<SubprogramDetails>()};
2005   const auto details2{symbol2.get<SubprogramDetails>()};
2006   if (details1.isFunction() != details2.isFunction()) {
2007     Say(symbol1, symbol2,
2008         details1.isFunction()
2009             ? "Module function '%s' was declared as a subroutine in the"
2010               " corresponding interface body"_err_en_US
2011             : "Module subroutine '%s' was declared as a function in the"
2012               " corresponding interface body"_err_en_US);
2013     return;
2014   }
2015   const auto &args1{details1.dummyArgs()};
2016   const auto &args2{details2.dummyArgs()};
2017   int nargs1{static_cast<int>(args1.size())};
2018   int nargs2{static_cast<int>(args2.size())};
2019   if (nargs1 != nargs2) {
2020     Say(symbol1, symbol2,
2021         "Module subprogram '%s' has %d args but the corresponding interface"
2022         " body has %d"_err_en_US,
2023         nargs1, nargs2);
2024     return;
2025   }
2026   bool nonRecursive1{symbol1.attrs().test(Attr::NON_RECURSIVE)};
2027   if (nonRecursive1 != symbol2.attrs().test(Attr::NON_RECURSIVE)) { // C1551
2028     Say(symbol1, symbol2,
2029         nonRecursive1
2030             ? "Module subprogram '%s' has NON_RECURSIVE prefix but"
2031               " the corresponding interface body does not"_err_en_US
2032             : "Module subprogram '%s' does not have NON_RECURSIVE prefix but "
2033               "the corresponding interface body does"_err_en_US);
2034   }
2035   const std::string *bindName1{details1.bindName()};
2036   const std::string *bindName2{details2.bindName()};
2037   if (!bindName1 && !bindName2) {
2038     // OK - neither has a binding label
2039   } else if (!bindName1) {
2040     Say(symbol1, symbol2,
2041         "Module subprogram '%s' does not have a binding label but the"
2042         " corresponding interface body does"_err_en_US);
2043   } else if (!bindName2) {
2044     Say(symbol1, symbol2,
2045         "Module subprogram '%s' has a binding label but the"
2046         " corresponding interface body does not"_err_en_US);
2047   } else if (*bindName1 != *bindName2) {
2048     Say(symbol1, symbol2,
2049         "Module subprogram '%s' has binding label '%s' but the corresponding"
2050         " interface body has '%s'"_err_en_US,
2051         *details1.bindName(), *details2.bindName());
2052   }
2053   const Procedure *proc1{checkHelper.Characterize(symbol1)};
2054   const Procedure *proc2{checkHelper.Characterize(symbol2)};
2055   if (!proc1 || !proc2) {
2056     return;
2057   }
2058   if (proc1->functionResult && proc2->functionResult &&
2059       *proc1->functionResult != *proc2->functionResult) {
2060     Say(symbol1, symbol2,
2061         "Return type of function '%s' does not match return type of"
2062         " the corresponding interface body"_err_en_US);
2063   }
2064   for (int i{0}; i < nargs1; ++i) {
2065     const Symbol *arg1{args1[i]};
2066     const Symbol *arg2{args2[i]};
2067     if (arg1 && !arg2) {
2068       Say(symbol1, symbol2,
2069           "Dummy argument %2$d of '%1$s' is not an alternate return indicator"
2070           " but the corresponding argument in the interface body is"_err_en_US,
2071           i + 1);
2072     } else if (!arg1 && arg2) {
2073       Say(symbol1, symbol2,
2074           "Dummy argument %2$d of '%1$s' is an alternate return indicator but"
2075           " the corresponding argument in the interface body is not"_err_en_US,
2076           i + 1);
2077     } else if (arg1 && arg2) {
2078       SourceName name1{arg1->name()};
2079       SourceName name2{arg2->name()};
2080       if (name1 != name2) {
2081         Say(*arg1, *arg2,
2082             "Dummy argument name '%s' does not match corresponding name '%s'"
2083             " in interface body"_err_en_US,
2084             name2);
2085       } else {
2086         CheckDummyArg(
2087             *arg1, *arg2, proc1->dummyArguments[i], proc2->dummyArguments[i]);
2088       }
2089     }
2090   }
2091 }
2092 
2093 void SubprogramMatchHelper::CheckDummyArg(const Symbol &symbol1,
2094     const Symbol &symbol2, const DummyArgument &arg1,
2095     const DummyArgument &arg2) {
2096   std::visit(common::visitors{
2097                  [&](const DummyDataObject &obj1, const DummyDataObject &obj2) {
2098                    CheckDummyDataObject(symbol1, symbol2, obj1, obj2);
2099                  },
2100                  [&](const DummyProcedure &proc1, const DummyProcedure &proc2) {
2101                    CheckDummyProcedure(symbol1, symbol2, proc1, proc2);
2102                  },
2103                  [&](const DummyDataObject &, const auto &) {
2104                    Say(symbol1, symbol2,
2105                        "Dummy argument '%s' is a data object; the corresponding"
2106                        " argument in the interface body is not"_err_en_US);
2107                  },
2108                  [&](const DummyProcedure &, const auto &) {
2109                    Say(symbol1, symbol2,
2110                        "Dummy argument '%s' is a procedure; the corresponding"
2111                        " argument in the interface body is not"_err_en_US);
2112                  },
2113                  [&](const auto &, const auto &) {
2114                    llvm_unreachable("Dummy arguments are not data objects or"
2115                                     "procedures");
2116                  },
2117              },
2118       arg1.u, arg2.u);
2119 }
2120 
2121 void SubprogramMatchHelper::CheckDummyDataObject(const Symbol &symbol1,
2122     const Symbol &symbol2, const DummyDataObject &obj1,
2123     const DummyDataObject &obj2) {
2124   if (!CheckSameIntent(symbol1, symbol2, obj1.intent, obj2.intent)) {
2125   } else if (!CheckSameAttrs(symbol1, symbol2, obj1.attrs, obj2.attrs)) {
2126   } else if (obj1.type.type() != obj2.type.type()) {
2127     Say(symbol1, symbol2,
2128         "Dummy argument '%s' has type %s; the corresponding argument in the"
2129         " interface body has type %s"_err_en_US,
2130         obj1.type.type().AsFortran(), obj2.type.type().AsFortran());
2131   } else if (!ShapesAreCompatible(obj1, obj2)) {
2132     Say(symbol1, symbol2,
2133         "The shape of dummy argument '%s' does not match the shape of the"
2134         " corresponding argument in the interface body"_err_en_US);
2135   }
2136   // TODO: coshape
2137 }
2138 
2139 void SubprogramMatchHelper::CheckDummyProcedure(const Symbol &symbol1,
2140     const Symbol &symbol2, const DummyProcedure &proc1,
2141     const DummyProcedure &proc2) {
2142   if (!CheckSameIntent(symbol1, symbol2, proc1.intent, proc2.intent)) {
2143   } else if (!CheckSameAttrs(symbol1, symbol2, proc1.attrs, proc2.attrs)) {
2144   } else if (proc1 != proc2) {
2145     Say(symbol1, symbol2,
2146         "Dummy procedure '%s' does not match the corresponding argument in"
2147         " the interface body"_err_en_US);
2148   }
2149 }
2150 
2151 bool SubprogramMatchHelper::CheckSameIntent(const Symbol &symbol1,
2152     const Symbol &symbol2, common::Intent intent1, common::Intent intent2) {
2153   if (intent1 == intent2) {
2154     return true;
2155   } else {
2156     Say(symbol1, symbol2,
2157         "The intent of dummy argument '%s' does not match the intent"
2158         " of the corresponding argument in the interface body"_err_en_US);
2159     return false;
2160   }
2161 }
2162 
2163 // Report an error referring to first symbol with declaration of second symbol
2164 template <typename... A>
2165 void SubprogramMatchHelper::Say(const Symbol &symbol1, const Symbol &symbol2,
2166     parser::MessageFixedText &&text, A &&...args) {
2167   auto &message{context().Say(symbol1.name(), std::move(text), symbol1.name(),
2168       std::forward<A>(args)...)};
2169   evaluate::AttachDeclaration(message, symbol2);
2170 }
2171 
2172 template <typename ATTRS>
2173 bool SubprogramMatchHelper::CheckSameAttrs(
2174     const Symbol &symbol1, const Symbol &symbol2, ATTRS attrs1, ATTRS attrs2) {
2175   if (attrs1 == attrs2) {
2176     return true;
2177   }
2178   attrs1.IterateOverMembers([&](auto attr) {
2179     if (!attrs2.test(attr)) {
2180       Say(symbol1, symbol2,
2181           "Dummy argument '%s' has the %s attribute; the corresponding"
2182           " argument in the interface body does not"_err_en_US,
2183           AsFortran(attr));
2184     }
2185   });
2186   attrs2.IterateOverMembers([&](auto attr) {
2187     if (!attrs1.test(attr)) {
2188       Say(symbol1, symbol2,
2189           "Dummy argument '%s' does not have the %s attribute; the"
2190           " corresponding argument in the interface body does"_err_en_US,
2191           AsFortran(attr));
2192     }
2193   });
2194   return false;
2195 }
2196 
2197 bool SubprogramMatchHelper::ShapesAreCompatible(
2198     const DummyDataObject &obj1, const DummyDataObject &obj2) {
2199   return characteristics::ShapesAreCompatible(
2200       FoldShape(obj1.type.shape()), FoldShape(obj2.type.shape()));
2201 }
2202 
2203 evaluate::Shape SubprogramMatchHelper::FoldShape(const evaluate::Shape &shape) {
2204   evaluate::Shape result;
2205   for (const auto &extent : shape) {
2206     result.emplace_back(
2207         evaluate::Fold(context().foldingContext(), common::Clone(extent)));
2208   }
2209   return result;
2210 }
2211 
2212 void DistinguishabilityHelper::Add(const Symbol &generic, GenericKind kind,
2213     const Symbol &specific, const Procedure &procedure) {
2214   if (!context_.HasError(specific)) {
2215     nameToInfo_[generic.name()].emplace_back(
2216         ProcedureInfo{kind, specific, procedure});
2217   }
2218 }
2219 
2220 void DistinguishabilityHelper::Check(const Scope &scope) {
2221   for (const auto &[name, info] : nameToInfo_) {
2222     auto count{info.size()};
2223     for (std::size_t i1{0}; i1 < count - 1; ++i1) {
2224       const auto &[kind, symbol, proc]{info[i1]};
2225       for (std::size_t i2{i1 + 1}; i2 < count; ++i2) {
2226         auto distinguishable{kind.IsName()
2227                 ? evaluate::characteristics::Distinguishable
2228                 : evaluate::characteristics::DistinguishableOpOrAssign};
2229         if (!distinguishable(proc, info[i2].procedure)) {
2230           SayNotDistinguishable(GetTopLevelUnitContaining(scope), name, kind,
2231               symbol, info[i2].symbol);
2232         }
2233       }
2234     }
2235   }
2236 }
2237 
2238 void DistinguishabilityHelper::SayNotDistinguishable(const Scope &scope,
2239     const SourceName &name, GenericKind kind, const Symbol &proc1,
2240     const Symbol &proc2) {
2241   std::string name1{proc1.name().ToString()};
2242   std::string name2{proc2.name().ToString()};
2243   if (kind.IsOperator() || kind.IsAssignment()) {
2244     // proc1 and proc2 may come from different scopes so qualify their names
2245     if (proc1.owner().IsDerivedType()) {
2246       name1 = proc1.owner().GetName()->ToString() + '%' + name1;
2247     }
2248     if (proc2.owner().IsDerivedType()) {
2249       name2 = proc2.owner().GetName()->ToString() + '%' + name2;
2250     }
2251   }
2252   parser::Message *msg;
2253   if (scope.sourceRange().Contains(name)) {
2254     msg = &context_.Say(name,
2255         "Generic '%s' may not have specific procedures '%s' and"
2256         " '%s' as their interfaces are not distinguishable"_err_en_US,
2257         MakeOpName(name), name1, name2);
2258   } else {
2259     msg = &context_.Say(*GetTopLevelUnitContaining(proc1).GetName(),
2260         "USE-associated generic '%s' may not have specific procedures '%s' "
2261         "and"
2262         " '%s' as their interfaces are not distinguishable"_err_en_US,
2263         MakeOpName(name), name1, name2);
2264   }
2265   AttachDeclaration(*msg, scope, proc1);
2266   AttachDeclaration(*msg, scope, proc2);
2267 }
2268 
2269 // `evaluate::AttachDeclaration` doesn't handle the generic case where `proc`
2270 // comes from a different module but is not necessarily use-associated.
2271 void DistinguishabilityHelper::AttachDeclaration(
2272     parser::Message &msg, const Scope &scope, const Symbol &proc) {
2273   const Scope &unit{GetTopLevelUnitContaining(proc)};
2274   if (unit == scope) {
2275     evaluate::AttachDeclaration(msg, proc);
2276   } else {
2277     msg.Attach(unit.GetName().value(),
2278         "'%s' is USE-associated from module '%s'"_en_US, proc.name(),
2279         unit.GetName().value());
2280   }
2281 }
2282 
2283 void CheckDeclarations(SemanticsContext &context) {
2284   CheckHelper{context}.Check();
2285 }
2286 } // namespace Fortran::semantics
2287