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