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