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