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