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