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 "flang/Evaluate/check-expression.h"
13 #include "flang/Evaluate/fold.h"
14 #include "flang/Evaluate/tools.h"
15 #include "flang/Semantics/scope.h"
16 #include "flang/Semantics/semantics.h"
17 #include "flang/Semantics/symbol.h"
18 #include "flang/Semantics/tools.h"
19 #include "flang/Semantics/type.h"
20 #include <algorithm>
21 
22 namespace Fortran::semantics {
23 
24 namespace characteristics = evaluate::characteristics;
25 using characteristics::DummyArgument;
26 using characteristics::DummyDataObject;
27 using characteristics::DummyProcedure;
28 using characteristics::FunctionResult;
29 using characteristics::Procedure;
30 
31 class CheckHelper {
32 public:
33   explicit CheckHelper(SemanticsContext &c) : context_{c} {}
34   CheckHelper(SemanticsContext &c, const Scope &s) : context_{c}, scope_{&s} {}
35 
36   SemanticsContext &context() { return context_; }
37   void Check() { Check(context_.globalScope()); }
38   void Check(const ParamValue &, bool canBeAssumed);
39   void Check(const Bound &bound) { CheckSpecExpr(bound.GetExplicit()); }
40   void Check(const ShapeSpec &spec) {
41     Check(spec.lbound());
42     Check(spec.ubound());
43   }
44   void Check(const ArraySpec &);
45   void Check(const DeclTypeSpec &, bool canHaveAssumedTypeParameters);
46   void Check(const Symbol &);
47   void Check(const Scope &);
48   void CheckInitialization(const Symbol &);
49   const Procedure *Characterize(const Symbol &);
50 
51 private:
52   template <typename A> void CheckSpecExpr(const A &x) {
53     evaluate::CheckSpecificationExpr(
54         x, messages_, DEREF(scope_), context_.intrinsics());
55   }
56   void CheckValue(const Symbol &, const DerivedTypeSpec *);
57   void CheckVolatile(
58       const Symbol &, bool isAssociated, const DerivedTypeSpec *);
59   void CheckPointer(const Symbol &);
60   void CheckPassArg(
61       const Symbol &proc, const Symbol *interface, const WithPassArg &);
62   void CheckProcBinding(const Symbol &, const ProcBindingDetails &);
63   void CheckObjectEntity(const Symbol &, const ObjectEntityDetails &);
64   void 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   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   bool IsScopePDT() const {
104     return scope_ && scope_->IsParameterizedDerivedType();
105   }
106 
107   SemanticsContext &context_;
108   evaluate::FoldingContext &foldingContext_{context_.foldingContext()};
109   parser::ContextualMessages &messages_{foldingContext_.messages()};
110   const Scope *scope_{nullptr};
111   // This symbol is the one attached to the innermost enclosing scope
112   // that has a symbol.
113   const Symbol *innermostSymbol_{nullptr};
114   // Cache of calls to Procedure::Characterize(Symbol)
115   std::map<SymbolRef, std::optional<Procedure>> characterizeCache_;
116 };
117 
118 class DistinguishabilityHelper {
119 public:
120   DistinguishabilityHelper(SemanticsContext &context) : context_{context} {}
121   void Add(const Symbol &, GenericKind, const Symbol &, const Procedure &);
122   void Check();
123 
124 private:
125   void SayNotDistinguishable(
126       const SourceName &, GenericKind, const Symbol &, 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   const DeclTypeSpec *type{symbol.GetType()};
172   const DerivedTypeSpec *derived{type ? type->AsDerived() : nullptr};
173   auto restorer{messages_.SetLocation(symbol.name())};
174   context_.set_location(symbol.name());
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   if (!details.coshape().empty()) {
416     bool isDeferredShape{details.coshape().IsDeferredShape()};
417     if (IsAllocatable(symbol)) {
418       if (!isDeferredShape) { // C827
419         messages_.Say("'%s' is an ALLOCATABLE coarray and must have a deferred"
420                       " coshape"_err_en_US,
421             symbol.name());
422       }
423     } else if (symbol.owner().IsDerivedType()) { // C746
424       std::string deferredMsg{
425           isDeferredShape ? "" : " and have a deferred coshape"};
426       messages_.Say("Component '%s' is a coarray and must have the ALLOCATABLE"
427                     " attribute%s"_err_en_US,
428           symbol.name(), deferredMsg);
429     } else {
430       if (!details.coshape().IsAssumedSize()) { // C828
431         messages_.Say(
432             "Component '%s' is a non-ALLOCATABLE coarray and must have"
433             " an explicit coshape"_err_en_US,
434             symbol.name());
435       }
436     }
437   }
438   if (details.isDummy()) {
439     if (symbol.attrs().test(Attr::INTENT_OUT)) {
440       if (FindUltimateComponent(symbol, [](const Symbol &x) {
441             return IsCoarray(x) && IsAllocatable(x);
442           })) { // C846
443         messages_.Say(
444             "An INTENT(OUT) dummy argument may not be, or contain, an ALLOCATABLE coarray"_err_en_US);
445       }
446       if (IsOrContainsEventOrLockComponent(symbol)) { // C847
447         messages_.Say(
448             "An INTENT(OUT) dummy argument may not be, or contain, EVENT_TYPE or LOCK_TYPE"_err_en_US);
449       }
450     }
451     if (InPure() && !IsStmtFunction(DEREF(innermostSymbol_)) &&
452         !IsPointer(symbol) && !IsIntentIn(symbol) &&
453         !symbol.attrs().test(Attr::VALUE)) {
454       if (InFunction()) { // C1583
455         messages_.Say(
456             "non-POINTER dummy argument of pure function must be INTENT(IN) or VALUE"_err_en_US);
457       } else if (IsIntentOut(symbol)) {
458         if (const DeclTypeSpec * type{details.type()}) {
459           if (type && type->IsPolymorphic()) { // C1588
460             messages_.Say(
461                 "An INTENT(OUT) dummy argument of a pure subroutine may not be polymorphic"_err_en_US);
462           } else if (const DerivedTypeSpec * derived{type->AsDerived()}) {
463             if (FindUltimateComponent(*derived, [](const Symbol &x) {
464                   const DeclTypeSpec *type{x.GetType()};
465                   return type && type->IsPolymorphic();
466                 })) { // C1588
467               messages_.Say(
468                   "An INTENT(OUT) dummy argument of a pure subroutine may not have a polymorphic ultimate component"_err_en_US);
469             }
470             if (HasImpureFinal(*derived)) { // C1587
471               messages_.Say(
472                   "An INTENT(OUT) dummy argument of a pure subroutine may not have an impure FINAL subroutine"_err_en_US);
473             }
474           }
475         }
476       } else if (!IsIntentInOut(symbol)) { // C1586
477         messages_.Say(
478             "non-POINTER dummy argument of pure subroutine must have INTENT() or VALUE attribute"_err_en_US);
479       }
480     }
481   }
482   bool badInit{false};
483   if (symbol.owner().kind() != Scope::Kind::DerivedType &&
484       IsInitialized(symbol, true /*ignore DATA, already caught*/)) { // C808
485     if (IsAutomatic(symbol)) {
486       badInit = true;
487       messages_.Say("An automatic variable must not be initialized"_err_en_US);
488     } else if (IsDummy(symbol)) {
489       badInit = true;
490       messages_.Say("A dummy argument must not be initialized"_err_en_US);
491     } else if (IsFunctionResult(symbol)) {
492       badInit = true;
493       messages_.Say("A function result must not be initialized"_err_en_US);
494     } else if (IsInBlankCommon(symbol)) {
495       badInit = true;
496       messages_.Say(
497           "A variable in blank COMMON should not be initialized"_en_US);
498     }
499   }
500   if (symbol.owner().kind() == Scope::Kind::BlockData &&
501       IsInitialized(symbol)) {
502     if (IsAllocatable(symbol)) {
503       messages_.Say(
504           "An ALLOCATABLE variable may not appear in a BLOCK DATA subprogram"_err_en_US);
505     } else if (!FindCommonBlockContaining(symbol)) {
506       messages_.Say(
507           "An initialized variable in BLOCK DATA must be in a COMMON block"_err_en_US);
508     }
509   }
510   if (const DeclTypeSpec * type{details.type()}) { // C708
511     if (type->IsPolymorphic() &&
512         !(type->IsAssumedType() || IsAllocatableOrPointer(symbol) ||
513             IsDummy(symbol))) {
514       messages_.Say("CLASS entity '%s' must be a dummy argument or have "
515                     "ALLOCATABLE or POINTER attribute"_err_en_US,
516           symbol.name());
517     }
518   }
519   if (!badInit && !IsScopePDT()) {
520     CheckInitialization(symbol);
521   }
522 }
523 
524 void CheckHelper::CheckInitialization(const Symbol &symbol) {
525   const auto *details{symbol.detailsIf<ObjectEntityDetails>()};
526   if (!details) {
527     // not an object
528   } else if (const auto &init{details->init()}) { // 8.2 para 4
529     int initRank{init->Rank()};
530     int symbolRank{details->shape().Rank()};
531     if (IsPointer(symbol)) {
532       // Pointer initialization rank/shape errors are caught earlier in
533       // name resolution
534     } else if (details->shape().IsImpliedShape() ||
535         details->shape().IsDeferredShape()) {
536       if (symbolRank != initRank) {
537         messages_.Say(
538             "%s-shape array '%s' has rank %d, but its initializer has rank %d"_err_en_US,
539             details->shape().IsImpliedShape() ? "Implied" : "Deferred",
540             symbol.name(), symbolRank, initRank);
541       }
542     } else if (symbolRank != initRank && initRank != 0) {
543       // Pointer initializer rank errors are caught elsewhere
544       messages_.Say(
545           "'%s' has rank %d, but its initializer has rank %d"_err_en_US,
546           symbol.name(), symbolRank, initRank);
547     } else if (auto symbolShape{evaluate::GetShape(foldingContext_, symbol)}) {
548       if (!evaluate::AsConstantExtents(foldingContext_, *symbolShape)) {
549         // C762
550         messages_.Say(
551             "Shape of '%s' is not implied, deferred, nor constant"_err_en_US,
552             symbol.name());
553       } else if (auto initShape{evaluate::GetShape(foldingContext_, *init)}) {
554         if (initRank == symbolRank) {
555           evaluate::CheckConformance(
556               messages_, *symbolShape, *initShape, "object", "initializer");
557         } else {
558           CHECK(initRank == 0);
559           // TODO: expand scalar now, or in lowering?
560         }
561       }
562     }
563   }
564 }
565 
566 // The six different kinds of array-specs:
567 //   array-spec     -> explicit-shape-list | deferred-shape-list
568 //                     | assumed-shape-list | implied-shape-list
569 //                     | assumed-size | assumed-rank
570 //   explicit-shape -> [ lb : ] ub
571 //   deferred-shape -> :
572 //   assumed-shape  -> [ lb ] :
573 //   implied-shape  -> [ lb : ] *
574 //   assumed-size   -> [ explicit-shape-list , ] [ lb : ] *
575 //   assumed-rank   -> ..
576 // Note:
577 // - deferred-shape is also an assumed-shape
578 // - A single "*" or "lb:*" might be assumed-size or implied-shape-list
579 void CheckHelper::CheckArraySpec(
580     const Symbol &symbol, const ArraySpec &arraySpec) {
581   if (arraySpec.Rank() == 0) {
582     return;
583   }
584   bool isExplicit{arraySpec.IsExplicitShape()};
585   bool isDeferred{arraySpec.IsDeferredShape()};
586   bool isImplied{arraySpec.IsImpliedShape()};
587   bool isAssumedShape{arraySpec.IsAssumedShape()};
588   bool isAssumedSize{arraySpec.IsAssumedSize()};
589   bool isAssumedRank{arraySpec.IsAssumedRank()};
590   std::optional<parser::MessageFixedText> msg;
591   if (symbol.test(Symbol::Flag::CrayPointee) && !isExplicit && !isAssumedSize) {
592     msg = "Cray pointee '%s' must have must have explicit shape or"
593           " assumed size"_err_en_US;
594   } else if (IsAllocatableOrPointer(symbol) && !isDeferred && !isAssumedRank) {
595     if (symbol.owner().IsDerivedType()) { // C745
596       if (IsAllocatable(symbol)) {
597         msg = "Allocatable array component '%s' must have"
598               " deferred shape"_err_en_US;
599       } else {
600         msg = "Array pointer component '%s' must have deferred shape"_err_en_US;
601       }
602     } else {
603       if (IsAllocatable(symbol)) { // C832
604         msg = "Allocatable array '%s' must have deferred shape or"
605               " assumed rank"_err_en_US;
606       } else {
607         msg = "Array pointer '%s' must have deferred shape or"
608               " assumed rank"_err_en_US;
609       }
610     }
611   } else if (IsDummy(symbol)) {
612     if (isImplied && !isAssumedSize) { // C836
613       msg = "Dummy array argument '%s' may not have implied shape"_err_en_US;
614     }
615   } else if (isAssumedShape && !isDeferred) {
616     msg = "Assumed-shape array '%s' must be a dummy argument"_err_en_US;
617   } else if (isAssumedSize && !isImplied) { // C833
618     msg = "Assumed-size array '%s' must be a dummy argument"_err_en_US;
619   } else if (isAssumedRank) { // C837
620     msg = "Assumed-rank array '%s' must be a dummy argument"_err_en_US;
621   } else if (isImplied) {
622     if (!IsNamedConstant(symbol)) { // C836
623       msg = "Implied-shape array '%s' must be a named constant"_err_en_US;
624     }
625   } else if (IsNamedConstant(symbol)) {
626     if (!isExplicit && !isImplied) {
627       msg = "Named constant '%s' array must have explicit or"
628             " implied shape"_err_en_US;
629     }
630   } else if (!IsAllocatableOrPointer(symbol) && !isExplicit) {
631     if (symbol.owner().IsDerivedType()) { // C749
632       msg = "Component array '%s' without ALLOCATABLE or POINTER attribute must"
633             " have explicit shape"_err_en_US;
634     } else { // C816
635       msg = "Array '%s' without ALLOCATABLE or POINTER attribute must have"
636             " explicit shape"_err_en_US;
637     }
638   }
639   if (msg) {
640     context_.Say(std::move(*msg), symbol.name());
641   }
642 }
643 
644 void CheckHelper::CheckProcEntity(
645     const Symbol &symbol, const ProcEntityDetails &details) {
646   if (details.isDummy()) {
647     const Symbol *interface{details.interface().symbol()};
648     if (!symbol.attrs().test(Attr::INTRINSIC) &&
649         (symbol.attrs().test(Attr::ELEMENTAL) ||
650             (interface && !interface->attrs().test(Attr::INTRINSIC) &&
651                 interface->attrs().test(Attr::ELEMENTAL)))) {
652       // There's no explicit constraint or "shall" that we can find in the
653       // standard for this check, but it seems to be implied in multiple
654       // sites, and ELEMENTAL non-intrinsic actual arguments *are*
655       // explicitly forbidden.  But we allow "PROCEDURE(SIN)::dummy"
656       // because it is explicitly legal to *pass* the specific intrinsic
657       // function SIN as an actual argument.
658       messages_.Say("A dummy procedure may not be ELEMENTAL"_err_en_US);
659     }
660   } else if (symbol.owner().IsDerivedType()) {
661     if (!symbol.attrs().test(Attr::POINTER)) { // C756
662       const auto &name{symbol.name()};
663       messages_.Say(name,
664           "Procedure component '%s' must have POINTER attribute"_err_en_US,
665           name);
666     }
667     CheckPassArg(symbol, details.interface().symbol(), details);
668   }
669   if (symbol.attrs().test(Attr::POINTER)) {
670     if (const Symbol * interface{details.interface().symbol()}) {
671       if (interface->attrs().test(Attr::ELEMENTAL) &&
672           !interface->attrs().test(Attr::INTRINSIC)) {
673         messages_.Say("Procedure pointer '%s' may not be ELEMENTAL"_err_en_US,
674             symbol.name()); // C1517
675       }
676     }
677   } else if (symbol.attrs().test(Attr::SAVE)) {
678     messages_.Say(
679         "Procedure '%s' with SAVE attribute must also have POINTER attribute"_err_en_US,
680         symbol.name());
681   }
682 }
683 
684 // When a module subprogram has the MODULE prefix the following must match
685 // with the corresponding separate module procedure interface body:
686 // - C1549: characteristics and dummy argument names
687 // - C1550: binding label
688 // - C1551: NON_RECURSIVE prefix
689 class SubprogramMatchHelper {
690 public:
691   explicit SubprogramMatchHelper(CheckHelper &checkHelper)
692       : checkHelper{checkHelper} {}
693 
694   void Check(const Symbol &, const Symbol &);
695 
696 private:
697   SemanticsContext &context() { return checkHelper.context(); }
698   void CheckDummyArg(const Symbol &, const Symbol &, const DummyArgument &,
699       const DummyArgument &);
700   void CheckDummyDataObject(const Symbol &, const Symbol &,
701       const DummyDataObject &, const DummyDataObject &);
702   void CheckDummyProcedure(const Symbol &, const Symbol &,
703       const DummyProcedure &, const DummyProcedure &);
704   bool CheckSameIntent(
705       const Symbol &, const Symbol &, common::Intent, common::Intent);
706   template <typename... A>
707   void Say(
708       const Symbol &, const Symbol &, parser::MessageFixedText &&, A &&...);
709   template <typename ATTRS>
710   bool CheckSameAttrs(const Symbol &, const Symbol &, ATTRS, ATTRS);
711   bool ShapesAreCompatible(const DummyDataObject &, const DummyDataObject &);
712   evaluate::Shape FoldShape(const evaluate::Shape &);
713   std::string AsFortran(DummyDataObject::Attr attr) {
714     return parser::ToUpperCaseLetters(DummyDataObject::EnumToString(attr));
715   }
716   std::string AsFortran(DummyProcedure::Attr attr) {
717     return parser::ToUpperCaseLetters(DummyProcedure::EnumToString(attr));
718   }
719 
720   CheckHelper &checkHelper;
721 };
722 
723 // 15.6.2.6 para 3 - can the result of an ENTRY differ from its function?
724 bool CheckHelper::IsResultOkToDiffer(const FunctionResult &result) {
725   if (result.attrs.test(FunctionResult::Attr::Allocatable) ||
726       result.attrs.test(FunctionResult::Attr::Pointer)) {
727     return false;
728   }
729   const auto *typeAndShape{result.GetTypeAndShape()};
730   if (!typeAndShape || typeAndShape->Rank() != 0) {
731     return false;
732   }
733   auto category{typeAndShape->type().category()};
734   if (category == TypeCategory::Character ||
735       category == TypeCategory::Derived) {
736     return false;
737   }
738   int kind{typeAndShape->type().kind()};
739   return kind == context_.GetDefaultKind(category) ||
740       (category == TypeCategory::Real &&
741           kind == context_.doublePrecisionKind());
742 }
743 
744 void CheckHelper::CheckSubprogram(
745     const Symbol &symbol, const SubprogramDetails &details) {
746   if (const Symbol * iface{FindSeparateModuleSubprogramInterface(&symbol)}) {
747     SubprogramMatchHelper{*this}.Check(symbol, *iface);
748   }
749   if (const Scope * entryScope{details.entryScope()}) {
750     // ENTRY 15.6.2.6, esp. C1571
751     std::optional<parser::MessageFixedText> error;
752     const Symbol *subprogram{entryScope->symbol()};
753     const SubprogramDetails *subprogramDetails{nullptr};
754     if (subprogram) {
755       subprogramDetails = subprogram->detailsIf<SubprogramDetails>();
756     }
757     if (entryScope->kind() != Scope::Kind::Subprogram) {
758       error = "ENTRY may appear only in a subroutine or function"_err_en_US;
759     } else if (!(entryScope->parent().IsGlobal() ||
760                    entryScope->parent().IsModule() ||
761                    entryScope->parent().IsSubmodule())) {
762       error = "ENTRY may not appear in an internal subprogram"_err_en_US;
763     } else if (FindSeparateModuleSubprogramInterface(subprogram)) {
764       error = "ENTRY may not appear in a separate module procedure"_err_en_US;
765     } else if (subprogramDetails && details.isFunction() &&
766         subprogramDetails->isFunction()) {
767       auto result{FunctionResult::Characterize(
768           details.result(), context_.intrinsics())};
769       auto subpResult{FunctionResult::Characterize(
770           subprogramDetails->result(), context_.intrinsics())};
771       if (result && subpResult && *result != *subpResult &&
772           (!IsResultOkToDiffer(*result) || !IsResultOkToDiffer(*subpResult))) {
773         error =
774             "Result of ENTRY is not compatible with result of containing function"_err_en_US;
775       }
776     }
777     if (error) {
778       if (auto *msg{messages_.Say(symbol.name(), *error)}) {
779         if (subprogram) {
780           msg->Attach(subprogram->name(), "Containing subprogram"_en_US);
781         }
782       }
783     }
784   }
785 }
786 
787 void CheckHelper::CheckDerivedType(
788     const Symbol &derivedType, const DerivedTypeDetails &details) {
789   const Scope *scope{derivedType.scope()};
790   if (!scope) {
791     CHECK(details.isForwardReferenced());
792     return;
793   }
794   CHECK(scope->symbol() == &derivedType);
795   CHECK(scope->IsDerivedType());
796   if (derivedType.attrs().test(Attr::ABSTRACT) && // C734
797       (derivedType.attrs().test(Attr::BIND_C) || details.sequence())) {
798     messages_.Say("An ABSTRACT derived type must be extensible"_err_en_US);
799   }
800   if (const DeclTypeSpec * parent{FindParentTypeSpec(derivedType)}) {
801     const DerivedTypeSpec *parentDerived{parent->AsDerived()};
802     if (!IsExtensibleType(parentDerived)) { // C705
803       messages_.Say("The parent type is not extensible"_err_en_US);
804     }
805     if (!derivedType.attrs().test(Attr::ABSTRACT) && parentDerived &&
806         parentDerived->typeSymbol().attrs().test(Attr::ABSTRACT)) {
807       ScopeComponentIterator components{*parentDerived};
808       for (const Symbol &component : components) {
809         if (component.attrs().test(Attr::DEFERRED)) {
810           if (scope->FindComponent(component.name()) == &component) {
811             SayWithDeclaration(component,
812                 "Non-ABSTRACT extension of ABSTRACT derived type '%s' lacks a binding for DEFERRED procedure '%s'"_err_en_US,
813                 parentDerived->typeSymbol().name(), component.name());
814           }
815         }
816       }
817     }
818     DerivedTypeSpec derived{derivedType.name(), derivedType};
819     derived.set_scope(*scope);
820     if (FindCoarrayUltimateComponent(derived) && // C736
821         !(parentDerived && FindCoarrayUltimateComponent(*parentDerived))) {
822       messages_.Say(
823           "Type '%s' has a coarray ultimate component so the type at the base "
824           "of its type extension chain ('%s') must be a type that has a "
825           "coarray ultimate component"_err_en_US,
826           derivedType.name(), scope->GetDerivedTypeBase().GetSymbol()->name());
827     }
828     if (FindEventOrLockPotentialComponent(derived) && // C737
829         !(FindEventOrLockPotentialComponent(*parentDerived) ||
830             IsEventTypeOrLockType(parentDerived))) {
831       messages_.Say(
832           "Type '%s' has an EVENT_TYPE or LOCK_TYPE component, so the type "
833           "at the base of its type extension chain ('%s') must either have an "
834           "EVENT_TYPE or LOCK_TYPE component, or be EVENT_TYPE or "
835           "LOCK_TYPE"_err_en_US,
836           derivedType.name(), scope->GetDerivedTypeBase().GetSymbol()->name());
837     }
838   }
839   if (HasIntrinsicTypeName(derivedType)) { // C729
840     messages_.Say("A derived type name cannot be the name of an intrinsic"
841                   " type"_err_en_US);
842   }
843   std::map<SourceName, SymbolRef> previous;
844   for (const auto &pair : details.finals()) {
845     SourceName source{pair.first};
846     const Symbol &ref{*pair.second};
847     if (CheckFinal(ref, source, derivedType) &&
848         std::all_of(previous.begin(), previous.end(),
849             [&](std::pair<SourceName, SymbolRef> prev) {
850               return CheckDistinguishableFinals(
851                   ref, source, *prev.second, prev.first, derivedType);
852             })) {
853       previous.emplace(source, ref);
854     }
855   }
856 }
857 
858 // C786
859 bool CheckHelper::CheckFinal(
860     const Symbol &subroutine, SourceName finalName, const Symbol &derivedType) {
861   if (!IsModuleProcedure(subroutine)) {
862     SayWithDeclaration(subroutine, finalName,
863         "FINAL subroutine '%s' of derived type '%s' must be a module procedure"_err_en_US,
864         subroutine.name(), derivedType.name());
865     return false;
866   }
867   const Procedure *proc{Characterize(subroutine)};
868   if (!proc) {
869     return false; // error recovery
870   }
871   if (!proc->IsSubroutine()) {
872     SayWithDeclaration(subroutine, finalName,
873         "FINAL subroutine '%s' of derived type '%s' must be a subroutine"_err_en_US,
874         subroutine.name(), derivedType.name());
875     return false;
876   }
877   if (proc->dummyArguments.size() != 1) {
878     SayWithDeclaration(subroutine, finalName,
879         "FINAL subroutine '%s' of derived type '%s' must have a single dummy argument"_err_en_US,
880         subroutine.name(), derivedType.name());
881     return false;
882   }
883   const auto &arg{proc->dummyArguments[0]};
884   const Symbol *errSym{&subroutine};
885   if (const auto *details{subroutine.detailsIf<SubprogramDetails>()}) {
886     if (!details->dummyArgs().empty()) {
887       if (const Symbol * argSym{details->dummyArgs()[0]}) {
888         errSym = argSym;
889       }
890     }
891   }
892   const auto *ddo{std::get_if<DummyDataObject>(&arg.u)};
893   if (!ddo) {
894     SayWithDeclaration(subroutine, finalName,
895         "FINAL subroutine '%s' of derived type '%s' must have a single dummy argument that is a data object"_err_en_US,
896         subroutine.name(), derivedType.name());
897     return false;
898   }
899   bool ok{true};
900   if (arg.IsOptional()) {
901     SayWithDeclaration(*errSym, finalName,
902         "FINAL subroutine '%s' of derived type '%s' must not have an OPTIONAL dummy argument"_err_en_US,
903         subroutine.name(), derivedType.name());
904     ok = false;
905   }
906   if (ddo->attrs.test(DummyDataObject::Attr::Allocatable)) {
907     SayWithDeclaration(*errSym, finalName,
908         "FINAL subroutine '%s' of derived type '%s' must not have an ALLOCATABLE dummy argument"_err_en_US,
909         subroutine.name(), derivedType.name());
910     ok = false;
911   }
912   if (ddo->attrs.test(DummyDataObject::Attr::Pointer)) {
913     SayWithDeclaration(*errSym, finalName,
914         "FINAL subroutine '%s' of derived type '%s' must not have a POINTER dummy argument"_err_en_US,
915         subroutine.name(), derivedType.name());
916     ok = false;
917   }
918   if (ddo->intent == common::Intent::Out) {
919     SayWithDeclaration(*errSym, finalName,
920         "FINAL subroutine '%s' of derived type '%s' must not have a dummy argument with INTENT(OUT)"_err_en_US,
921         subroutine.name(), derivedType.name());
922     ok = false;
923   }
924   if (ddo->attrs.test(DummyDataObject::Attr::Value)) {
925     SayWithDeclaration(*errSym, finalName,
926         "FINAL subroutine '%s' of derived type '%s' must not have a dummy argument with the VALUE attribute"_err_en_US,
927         subroutine.name(), derivedType.name());
928     ok = false;
929   }
930   if (ddo->type.corank() > 0) {
931     SayWithDeclaration(*errSym, finalName,
932         "FINAL subroutine '%s' of derived type '%s' must not have a coarray dummy argument"_err_en_US,
933         subroutine.name(), derivedType.name());
934     ok = false;
935   }
936   if (ddo->type.type().IsPolymorphic()) {
937     SayWithDeclaration(*errSym, finalName,
938         "FINAL subroutine '%s' of derived type '%s' must not have a polymorphic dummy argument"_err_en_US,
939         subroutine.name(), derivedType.name());
940     ok = false;
941   } else if (ddo->type.type().category() != TypeCategory::Derived ||
942       &ddo->type.type().GetDerivedTypeSpec().typeSymbol() != &derivedType) {
943     SayWithDeclaration(*errSym, finalName,
944         "FINAL subroutine '%s' of derived type '%s' must have a TYPE(%s) dummy argument"_err_en_US,
945         subroutine.name(), derivedType.name(), derivedType.name());
946     ok = false;
947   } else { // check that all LEN type parameters are assumed
948     for (auto ref : OrderParameterDeclarations(derivedType)) {
949       if (const auto *paramDetails{ref->detailsIf<TypeParamDetails>()}) {
950         if (paramDetails->attr() == common::TypeParamAttr::Len) {
951           const auto *value{
952               ddo->type.type().GetDerivedTypeSpec().FindParameter(ref->name())};
953           if (!value || !value->isAssumed()) {
954             SayWithDeclaration(*errSym, finalName,
955                 "FINAL subroutine '%s' of derived type '%s' must have a dummy argument with an assumed LEN type parameter '%s=*'"_err_en_US,
956                 subroutine.name(), derivedType.name(), ref->name());
957             ok = false;
958           }
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();
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 const Procedure *CheckHelper::Characterize(const Symbol &symbol) {
1246   auto it{characterizeCache_.find(symbol)};
1247   if (it == characterizeCache_.end()) {
1248     auto pair{characterizeCache_.emplace(SymbolRef{symbol},
1249         Procedure::Characterize(symbol, context_.intrinsics()))};
1250     it = pair.first;
1251   }
1252   return common::GetPtrFromOptional(it->second);
1253 }
1254 
1255 void CheckHelper::CheckVolatile(const Symbol &symbol, bool isAssociated,
1256     const DerivedTypeSpec *derived) { // C866 - C868
1257   if (IsIntentIn(symbol)) {
1258     messages_.Say(
1259         "VOLATILE attribute may not apply to an INTENT(IN) argument"_err_en_US);
1260   }
1261   if (IsProcedure(symbol)) {
1262     messages_.Say("VOLATILE attribute may apply only to a variable"_err_en_US);
1263   }
1264   if (isAssociated) {
1265     const Symbol &ultimate{symbol.GetUltimate()};
1266     if (IsCoarray(ultimate)) {
1267       messages_.Say(
1268           "VOLATILE attribute may not apply to a coarray accessed by USE or host association"_err_en_US);
1269     }
1270     if (derived) {
1271       if (FindCoarrayUltimateComponent(*derived)) {
1272         messages_.Say(
1273             "VOLATILE attribute may not apply to a type with a coarray ultimate component accessed by USE or host association"_err_en_US);
1274       }
1275     }
1276   }
1277 }
1278 
1279 void CheckHelper::CheckPointer(const Symbol &symbol) { // C852
1280   CheckConflicting(symbol, Attr::POINTER, Attr::TARGET);
1281   CheckConflicting(symbol, Attr::POINTER, Attr::ALLOCATABLE); // C751
1282   CheckConflicting(symbol, Attr::POINTER, Attr::INTRINSIC);
1283   if (symbol.Corank() > 0) {
1284     messages_.Say(
1285         "'%s' may not have the POINTER attribute because it is a coarray"_err_en_US,
1286         symbol.name());
1287   }
1288 }
1289 
1290 // C760 constraints on the passed-object dummy argument
1291 // C757 constraints on procedure pointer components
1292 void CheckHelper::CheckPassArg(
1293     const Symbol &proc, const Symbol *interface, const WithPassArg &details) {
1294   if (proc.attrs().test(Attr::NOPASS)) {
1295     return;
1296   }
1297   const auto &name{proc.name()};
1298   if (!interface) {
1299     messages_.Say(name,
1300         "Procedure component '%s' must have NOPASS attribute or explicit interface"_err_en_US,
1301         name);
1302     return;
1303   }
1304   const auto *subprogram{interface->detailsIf<SubprogramDetails>()};
1305   if (!subprogram) {
1306     messages_.Say(name,
1307         "Procedure component '%s' has invalid interface '%s'"_err_en_US, name,
1308         interface->name());
1309     return;
1310   }
1311   std::optional<SourceName> passName{details.passName()};
1312   const auto &dummyArgs{subprogram->dummyArgs()};
1313   if (!passName) {
1314     if (dummyArgs.empty()) {
1315       messages_.Say(name,
1316           proc.has<ProcEntityDetails>()
1317               ? "Procedure component '%s' with no dummy arguments"
1318                 " must have NOPASS attribute"_err_en_US
1319               : "Procedure binding '%s' with no dummy arguments"
1320                 " must have NOPASS attribute"_err_en_US,
1321           name);
1322       return;
1323     }
1324     passName = dummyArgs[0]->name();
1325   }
1326   std::optional<int> passArgIndex{};
1327   for (std::size_t i{0}; i < dummyArgs.size(); ++i) {
1328     if (dummyArgs[i] && dummyArgs[i]->name() == *passName) {
1329       passArgIndex = i;
1330       break;
1331     }
1332   }
1333   if (!passArgIndex) { // C758
1334     messages_.Say(*passName,
1335         "'%s' is not a dummy argument of procedure interface '%s'"_err_en_US,
1336         *passName, interface->name());
1337     return;
1338   }
1339   const Symbol &passArg{*dummyArgs[*passArgIndex]};
1340   std::optional<parser::MessageFixedText> msg;
1341   if (!passArg.has<ObjectEntityDetails>()) {
1342     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1343           " must be a data object"_err_en_US;
1344   } else if (passArg.attrs().test(Attr::POINTER)) {
1345     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1346           " may not have the POINTER attribute"_err_en_US;
1347   } else if (passArg.attrs().test(Attr::ALLOCATABLE)) {
1348     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1349           " may not have the ALLOCATABLE attribute"_err_en_US;
1350   } else if (passArg.attrs().test(Attr::VALUE)) {
1351     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1352           " may not have the VALUE attribute"_err_en_US;
1353   } else if (passArg.Rank() > 0) {
1354     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1355           " must be scalar"_err_en_US;
1356   }
1357   if (msg) {
1358     messages_.Say(name, std::move(*msg), passName.value(), name);
1359     return;
1360   }
1361   const DeclTypeSpec *type{passArg.GetType()};
1362   if (!type) {
1363     return; // an error already occurred
1364   }
1365   const Symbol &typeSymbol{*proc.owner().GetSymbol()};
1366   const DerivedTypeSpec *derived{type->AsDerived()};
1367   if (!derived || derived->typeSymbol() != typeSymbol) {
1368     messages_.Say(name,
1369         "Passed-object dummy argument '%s' of procedure '%s'"
1370         " must be of type '%s' but is '%s'"_err_en_US,
1371         passName.value(), name, typeSymbol.name(), type->AsFortran());
1372     return;
1373   }
1374   if (IsExtensibleType(derived) != type->IsPolymorphic()) {
1375     messages_.Say(name,
1376         type->IsPolymorphic()
1377             ? "Passed-object dummy argument '%s' of procedure '%s'"
1378               " may not be polymorphic because '%s' is not extensible"_err_en_US
1379             : "Passed-object dummy argument '%s' of procedure '%s'"
1380               " must be polymorphic because '%s' is extensible"_err_en_US,
1381         passName.value(), name, typeSymbol.name());
1382     return;
1383   }
1384   for (const auto &[paramName, paramValue] : derived->parameters()) {
1385     if (paramValue.isLen() && !paramValue.isAssumed()) {
1386       messages_.Say(name,
1387           "Passed-object dummy argument '%s' of procedure '%s'"
1388           " has non-assumed length parameter '%s'"_err_en_US,
1389           passName.value(), name, paramName);
1390     }
1391   }
1392 }
1393 
1394 void CheckHelper::CheckProcBinding(
1395     const Symbol &symbol, const ProcBindingDetails &binding) {
1396   const Scope &dtScope{symbol.owner()};
1397   CHECK(dtScope.kind() == Scope::Kind::DerivedType);
1398   if (const Symbol * dtSymbol{dtScope.symbol()}) {
1399     if (symbol.attrs().test(Attr::DEFERRED)) {
1400       if (!dtSymbol->attrs().test(Attr::ABSTRACT)) { // C733
1401         SayWithDeclaration(*dtSymbol,
1402             "Procedure bound to non-ABSTRACT derived type '%s' may not be DEFERRED"_err_en_US,
1403             dtSymbol->name());
1404       }
1405       if (symbol.attrs().test(Attr::NON_OVERRIDABLE)) {
1406         messages_.Say(
1407             "Type-bound procedure '%s' may not be both DEFERRED and NON_OVERRIDABLE"_err_en_US,
1408             symbol.name());
1409       }
1410     }
1411   }
1412   if (const Symbol * overridden{FindOverriddenBinding(symbol)}) {
1413     if (overridden->attrs().test(Attr::NON_OVERRIDABLE)) {
1414       SayWithDeclaration(*overridden,
1415           "Override of NON_OVERRIDABLE '%s' is not permitted"_err_en_US,
1416           symbol.name());
1417     }
1418     if (const auto *overriddenBinding{
1419             overridden->detailsIf<ProcBindingDetails>()}) {
1420       if (!IsPureProcedure(symbol) && IsPureProcedure(*overridden)) {
1421         SayWithDeclaration(*overridden,
1422             "An overridden pure type-bound procedure binding must also be pure"_err_en_US);
1423         return;
1424       }
1425       if (!binding.symbol().attrs().test(Attr::ELEMENTAL) &&
1426           overriddenBinding->symbol().attrs().test(Attr::ELEMENTAL)) {
1427         SayWithDeclaration(*overridden,
1428             "A type-bound procedure and its override must both, or neither, be ELEMENTAL"_err_en_US);
1429         return;
1430       }
1431       bool isNopass{symbol.attrs().test(Attr::NOPASS)};
1432       if (isNopass != overridden->attrs().test(Attr::NOPASS)) {
1433         SayWithDeclaration(*overridden,
1434             isNopass
1435                 ? "A NOPASS type-bound procedure may not override a passed-argument procedure"_err_en_US
1436                 : "A passed-argument type-bound procedure may not override a NOPASS procedure"_err_en_US);
1437       } else {
1438         const auto *bindingChars{Characterize(binding.symbol())};
1439         const auto *overriddenChars{Characterize(overriddenBinding->symbol())};
1440         if (bindingChars && overriddenChars) {
1441           if (isNopass) {
1442             if (!bindingChars->CanOverride(*overriddenChars, std::nullopt)) {
1443               SayWithDeclaration(*overridden,
1444                   "A type-bound procedure and its override must have compatible interfaces"_err_en_US);
1445             }
1446           } else {
1447             int passIndex{bindingChars->FindPassIndex(binding.passName())};
1448             int overriddenPassIndex{
1449                 overriddenChars->FindPassIndex(overriddenBinding->passName())};
1450             if (passIndex != overriddenPassIndex) {
1451               SayWithDeclaration(*overridden,
1452                   "A type-bound procedure and its override must use the same PASS argument"_err_en_US);
1453             } else if (!bindingChars->CanOverride(
1454                            *overriddenChars, passIndex)) {
1455               SayWithDeclaration(*overridden,
1456                   "A type-bound procedure and its override must have compatible interfaces apart from their passed argument"_err_en_US);
1457             }
1458           }
1459         }
1460       }
1461       if (symbol.attrs().test(Attr::PRIVATE) &&
1462           overridden->attrs().test(Attr::PUBLIC)) {
1463         SayWithDeclaration(*overridden,
1464             "A PRIVATE procedure may not override a PUBLIC procedure"_err_en_US);
1465       }
1466     } else {
1467       SayWithDeclaration(*overridden,
1468           "A type-bound procedure binding may not have the same name as a parent component"_err_en_US);
1469     }
1470   }
1471   CheckPassArg(symbol, &binding.symbol(), binding);
1472 }
1473 
1474 void CheckHelper::Check(const Scope &scope) {
1475   scope_ = &scope;
1476   common::Restorer<const Symbol *> restorer{innermostSymbol_};
1477   if (const Symbol * symbol{scope.symbol()}) {
1478     innermostSymbol_ = symbol;
1479   } else if (scope.IsDerivedType()) {
1480     // PDT instantiations have no symbol.
1481     return;
1482   }
1483   for (const auto &set : scope.equivalenceSets()) {
1484     CheckEquivalenceSet(set);
1485   }
1486   for (const auto &pair : scope) {
1487     Check(*pair.second);
1488   }
1489   for (const Scope &child : scope.children()) {
1490     Check(child);
1491   }
1492   if (scope.kind() == Scope::Kind::BlockData) {
1493     CheckBlockData(scope);
1494   }
1495   CheckGenericOps(scope);
1496 }
1497 
1498 void CheckHelper::CheckEquivalenceSet(const EquivalenceSet &set) {
1499   auto iter{
1500       std::find_if(set.begin(), set.end(), [](const EquivalenceObject &object) {
1501         return FindCommonBlockContaining(object.symbol) != nullptr;
1502       })};
1503   if (iter != set.end()) {
1504     const Symbol &commonBlock{DEREF(FindCommonBlockContaining(iter->symbol))};
1505     for (auto &object : set) {
1506       if (&object != &*iter) {
1507         if (auto *details{object.symbol.detailsIf<ObjectEntityDetails>()}) {
1508           if (details->commonBlock()) {
1509             if (details->commonBlock() != &commonBlock) { // 8.10.3 paragraph 1
1510               if (auto *msg{messages_.Say(object.symbol.name(),
1511                       "Two objects in the same EQUIVALENCE set may not be members of distinct COMMON blocks"_err_en_US)}) {
1512                 msg->Attach(iter->symbol.name(),
1513                        "Other object in EQUIVALENCE set"_en_US)
1514                     .Attach(details->commonBlock()->name(),
1515                         "COMMON block containing '%s'"_en_US,
1516                         object.symbol.name())
1517                     .Attach(commonBlock.name(),
1518                         "COMMON block containing '%s'"_en_US,
1519                         iter->symbol.name());
1520               }
1521             }
1522           } else {
1523             // Mark all symbols in the equivalence set with the same COMMON
1524             // block to prevent spurious error messages about initialization
1525             // in BLOCK DATA outside COMMON
1526             details->set_commonBlock(commonBlock);
1527           }
1528         }
1529       }
1530     }
1531   }
1532   // TODO: Move C8106 (&al.) checks here from resolve-names-utils.cpp
1533 }
1534 
1535 void CheckHelper::CheckBlockData(const Scope &scope) {
1536   // BLOCK DATA subprograms should contain only named common blocks.
1537   // C1415 presents a list of statements that shouldn't appear in
1538   // BLOCK DATA, but so long as the subprogram contains no executable
1539   // code and allocates no storage outside named COMMON, we're happy
1540   // (e.g., an ENUM is strictly not allowed).
1541   for (const auto &pair : scope) {
1542     const Symbol &symbol{*pair.second};
1543     if (!(symbol.has<CommonBlockDetails>() || symbol.has<UseDetails>() ||
1544             symbol.has<UseErrorDetails>() || symbol.has<DerivedTypeDetails>() ||
1545             symbol.has<SubprogramDetails>() ||
1546             symbol.has<ObjectEntityDetails>() ||
1547             (symbol.has<ProcEntityDetails>() &&
1548                 !symbol.attrs().test(Attr::POINTER)))) {
1549       messages_.Say(symbol.name(),
1550           "'%s' may not appear in a BLOCK DATA subprogram"_err_en_US,
1551           symbol.name());
1552     }
1553   }
1554 }
1555 
1556 // Check distinguishability of generic assignment and operators.
1557 // For these, generics and generic bindings must be considered together.
1558 void CheckHelper::CheckGenericOps(const Scope &scope) {
1559   DistinguishabilityHelper helper{context_};
1560   auto addSpecifics{[&](const Symbol &generic) {
1561     const auto *details{generic.GetUltimate().detailsIf<GenericDetails>()};
1562     if (!details) {
1563       return;
1564     }
1565     GenericKind kind{details->kind()};
1566     if (!kind.IsAssignment() && !kind.IsOperator()) {
1567       return;
1568     }
1569     const SymbolVector &specifics{details->specificProcs()};
1570     const std::vector<SourceName> &bindingNames{details->bindingNames()};
1571     for (std::size_t i{0}; i < specifics.size(); ++i) {
1572       const Symbol &specific{*specifics[i]};
1573       if (const Procedure * proc{Characterize(specific)}) {
1574         auto restorer{messages_.SetLocation(bindingNames[i])};
1575         if (kind.IsAssignment()) {
1576           if (!CheckDefinedAssignment(specific, *proc)) {
1577             continue;
1578           }
1579         } else {
1580           if (!CheckDefinedOperator(generic.name(), kind, specific, *proc)) {
1581             continue;
1582           }
1583         }
1584         helper.Add(generic, kind, specific, *proc);
1585       }
1586     }
1587   }};
1588   for (const auto &pair : scope) {
1589     const Symbol &symbol{*pair.second};
1590     addSpecifics(symbol);
1591     const Symbol &ultimate{symbol.GetUltimate()};
1592     if (ultimate.has<DerivedTypeDetails>()) {
1593       if (const Scope * typeScope{ultimate.scope()}) {
1594         for (const auto &pair2 : *typeScope) {
1595           addSpecifics(*pair2.second);
1596         }
1597       }
1598     }
1599   }
1600   helper.Check();
1601 }
1602 
1603 void SubprogramMatchHelper::Check(
1604     const Symbol &symbol1, const Symbol &symbol2) {
1605   const auto details1{symbol1.get<SubprogramDetails>()};
1606   const auto details2{symbol2.get<SubprogramDetails>()};
1607   if (details1.isFunction() != details2.isFunction()) {
1608     Say(symbol1, symbol2,
1609         details1.isFunction()
1610             ? "Module function '%s' was declared as a subroutine in the"
1611               " corresponding interface body"_err_en_US
1612             : "Module subroutine '%s' was declared as a function in the"
1613               " corresponding interface body"_err_en_US);
1614     return;
1615   }
1616   const auto &args1{details1.dummyArgs()};
1617   const auto &args2{details2.dummyArgs()};
1618   int nargs1{static_cast<int>(args1.size())};
1619   int nargs2{static_cast<int>(args2.size())};
1620   if (nargs1 != nargs2) {
1621     Say(symbol1, symbol2,
1622         "Module subprogram '%s' has %d args but the corresponding interface"
1623         " body has %d"_err_en_US,
1624         nargs1, nargs2);
1625     return;
1626   }
1627   bool nonRecursive1{symbol1.attrs().test(Attr::NON_RECURSIVE)};
1628   if (nonRecursive1 != symbol2.attrs().test(Attr::NON_RECURSIVE)) { // C1551
1629     Say(symbol1, symbol2,
1630         nonRecursive1
1631             ? "Module subprogram '%s' has NON_RECURSIVE prefix but"
1632               " the corresponding interface body does not"_err_en_US
1633             : "Module subprogram '%s' does not have NON_RECURSIVE prefix but "
1634               "the corresponding interface body does"_err_en_US);
1635   }
1636   MaybeExpr bindName1{details1.bindName()};
1637   MaybeExpr bindName2{details2.bindName()};
1638   if (bindName1.has_value() != bindName2.has_value()) {
1639     Say(symbol1, symbol2,
1640         bindName1.has_value()
1641             ? "Module subprogram '%s' has a binding label but the corresponding"
1642               " interface body does not"_err_en_US
1643             : "Module subprogram '%s' does not have a binding label but the"
1644               " corresponding interface body does"_err_en_US);
1645   } else if (bindName1) {
1646     std::string string1{bindName1->AsFortran()};
1647     std::string string2{bindName2->AsFortran()};
1648     if (string1 != string2) {
1649       Say(symbol1, symbol2,
1650           "Module subprogram '%s' has binding label %s but the corresponding"
1651           " interface body has %s"_err_en_US,
1652           string1, string2);
1653     }
1654   }
1655   const Procedure *proc1{checkHelper.Characterize(symbol1)};
1656   const Procedure *proc2{checkHelper.Characterize(symbol2)};
1657   if (!proc1 || !proc2) {
1658     return;
1659   }
1660   if (proc1->functionResult && proc2->functionResult &&
1661       *proc1->functionResult != *proc2->functionResult) {
1662     Say(symbol1, symbol2,
1663         "Return type of function '%s' does not match return type of"
1664         " the corresponding interface body"_err_en_US);
1665   }
1666   for (int i{0}; i < nargs1; ++i) {
1667     const Symbol *arg1{args1[i]};
1668     const Symbol *arg2{args2[i]};
1669     if (arg1 && !arg2) {
1670       Say(symbol1, symbol2,
1671           "Dummy argument %2$d of '%1$s' is not an alternate return indicator"
1672           " but the corresponding argument in the interface body is"_err_en_US,
1673           i + 1);
1674     } else if (!arg1 && arg2) {
1675       Say(symbol1, symbol2,
1676           "Dummy argument %2$d of '%1$s' is an alternate return indicator but"
1677           " the corresponding argument in the interface body is not"_err_en_US,
1678           i + 1);
1679     } else if (arg1 && arg2) {
1680       SourceName name1{arg1->name()};
1681       SourceName name2{arg2->name()};
1682       if (name1 != name2) {
1683         Say(*arg1, *arg2,
1684             "Dummy argument name '%s' does not match corresponding name '%s'"
1685             " in interface body"_err_en_US,
1686             name2);
1687       } else {
1688         CheckDummyArg(
1689             *arg1, *arg2, proc1->dummyArguments[i], proc2->dummyArguments[i]);
1690       }
1691     }
1692   }
1693 }
1694 
1695 void SubprogramMatchHelper::CheckDummyArg(const Symbol &symbol1,
1696     const Symbol &symbol2, const DummyArgument &arg1,
1697     const DummyArgument &arg2) {
1698   std::visit(common::visitors{
1699                  [&](const DummyDataObject &obj1, const DummyDataObject &obj2) {
1700                    CheckDummyDataObject(symbol1, symbol2, obj1, obj2);
1701                  },
1702                  [&](const DummyProcedure &proc1, const DummyProcedure &proc2) {
1703                    CheckDummyProcedure(symbol1, symbol2, proc1, proc2);
1704                  },
1705                  [&](const DummyDataObject &, const auto &) {
1706                    Say(symbol1, symbol2,
1707                        "Dummy argument '%s' is a data object; the corresponding"
1708                        " argument in the interface body is not"_err_en_US);
1709                  },
1710                  [&](const DummyProcedure &, const auto &) {
1711                    Say(symbol1, symbol2,
1712                        "Dummy argument '%s' is a procedure; the corresponding"
1713                        " argument in the interface body is not"_err_en_US);
1714                  },
1715                  [&](const auto &, const auto &) {
1716                    llvm_unreachable("Dummy arguments are not data objects or"
1717                                     "procedures");
1718                  },
1719              },
1720       arg1.u, arg2.u);
1721 }
1722 
1723 void SubprogramMatchHelper::CheckDummyDataObject(const Symbol &symbol1,
1724     const Symbol &symbol2, const DummyDataObject &obj1,
1725     const DummyDataObject &obj2) {
1726   if (!CheckSameIntent(symbol1, symbol2, obj1.intent, obj2.intent)) {
1727   } else if (!CheckSameAttrs(symbol1, symbol2, obj1.attrs, obj2.attrs)) {
1728   } else if (obj1.type.type() != obj2.type.type()) {
1729     Say(symbol1, symbol2,
1730         "Dummy argument '%s' has type %s; the corresponding argument in the"
1731         " interface body has type %s"_err_en_US,
1732         obj1.type.type().AsFortran(), obj2.type.type().AsFortran());
1733   } else if (!ShapesAreCompatible(obj1, obj2)) {
1734     Say(symbol1, symbol2,
1735         "The shape of dummy argument '%s' does not match the shape of the"
1736         " corresponding argument in the interface body"_err_en_US);
1737   }
1738   // TODO: coshape
1739 }
1740 
1741 void SubprogramMatchHelper::CheckDummyProcedure(const Symbol &symbol1,
1742     const Symbol &symbol2, const DummyProcedure &proc1,
1743     const DummyProcedure &proc2) {
1744   if (!CheckSameIntent(symbol1, symbol2, proc1.intent, proc2.intent)) {
1745   } else if (!CheckSameAttrs(symbol1, symbol2, proc1.attrs, proc2.attrs)) {
1746   } else if (proc1 != proc2) {
1747     Say(symbol1, symbol2,
1748         "Dummy procedure '%s' does not match the corresponding argument in"
1749         " the interface body"_err_en_US);
1750   }
1751 }
1752 
1753 bool SubprogramMatchHelper::CheckSameIntent(const Symbol &symbol1,
1754     const Symbol &symbol2, common::Intent intent1, common::Intent intent2) {
1755   if (intent1 == intent2) {
1756     return true;
1757   } else {
1758     Say(symbol1, symbol2,
1759         "The intent of dummy argument '%s' does not match the intent"
1760         " of the corresponding argument in the interface body"_err_en_US);
1761     return false;
1762   }
1763 }
1764 
1765 // Report an error referring to first symbol with declaration of second symbol
1766 template <typename... A>
1767 void SubprogramMatchHelper::Say(const Symbol &symbol1, const Symbol &symbol2,
1768     parser::MessageFixedText &&text, A &&...args) {
1769   auto &message{context().Say(symbol1.name(), std::move(text), symbol1.name(),
1770       std::forward<A>(args)...)};
1771   evaluate::AttachDeclaration(message, symbol2);
1772 }
1773 
1774 template <typename ATTRS>
1775 bool SubprogramMatchHelper::CheckSameAttrs(
1776     const Symbol &symbol1, const Symbol &symbol2, ATTRS attrs1, ATTRS attrs2) {
1777   if (attrs1 == attrs2) {
1778     return true;
1779   }
1780   attrs1.IterateOverMembers([&](auto attr) {
1781     if (!attrs2.test(attr)) {
1782       Say(symbol1, symbol2,
1783           "Dummy argument '%s' has the %s attribute; the corresponding"
1784           " argument in the interface body does not"_err_en_US,
1785           AsFortran(attr));
1786     }
1787   });
1788   attrs2.IterateOverMembers([&](auto attr) {
1789     if (!attrs1.test(attr)) {
1790       Say(symbol1, symbol2,
1791           "Dummy argument '%s' does not have the %s attribute; the"
1792           " corresponding argument in the interface body does"_err_en_US,
1793           AsFortran(attr));
1794     }
1795   });
1796   return false;
1797 }
1798 
1799 bool SubprogramMatchHelper::ShapesAreCompatible(
1800     const DummyDataObject &obj1, const DummyDataObject &obj2) {
1801   return characteristics::ShapesAreCompatible(
1802       FoldShape(obj1.type.shape()), FoldShape(obj2.type.shape()));
1803 }
1804 
1805 evaluate::Shape SubprogramMatchHelper::FoldShape(const evaluate::Shape &shape) {
1806   evaluate::Shape result;
1807   for (const auto &extent : shape) {
1808     result.emplace_back(
1809         evaluate::Fold(context().foldingContext(), common::Clone(extent)));
1810   }
1811   return result;
1812 }
1813 
1814 void DistinguishabilityHelper::Add(const Symbol &generic, GenericKind kind,
1815     const Symbol &specific, const Procedure &procedure) {
1816   if (!context_.HasError(specific)) {
1817     nameToInfo_[generic.name()].emplace_back(
1818         ProcedureInfo{kind, specific, procedure});
1819   }
1820 }
1821 
1822 void DistinguishabilityHelper::Check() {
1823   for (const auto &[name, info] : nameToInfo_) {
1824     auto count{info.size()};
1825     for (std::size_t i1{0}; i1 < count - 1; ++i1) {
1826       const auto &[kind1, symbol1, proc1] = info[i1];
1827       for (std::size_t i2{i1 + 1}; i2 < count; ++i2) {
1828         const auto &[kind2, symbol2, proc2] = info[i2];
1829         auto distinguishable{kind1.IsName()
1830                 ? evaluate::characteristics::Distinguishable
1831                 : evaluate::characteristics::DistinguishableOpOrAssign};
1832         if (!distinguishable(proc1, proc2)) {
1833           SayNotDistinguishable(name, kind1, symbol1, symbol2);
1834         }
1835       }
1836     }
1837   }
1838 }
1839 
1840 void DistinguishabilityHelper::SayNotDistinguishable(const SourceName &name,
1841     GenericKind kind, const Symbol &proc1, const Symbol &proc2) {
1842   std::string name1{proc1.name().ToString()};
1843   std::string name2{proc2.name().ToString()};
1844   if (kind.IsOperator() || kind.IsAssignment()) {
1845     // proc1 and proc2 may come from different scopes so qualify their names
1846     if (proc1.owner().IsDerivedType()) {
1847       name1 = proc1.owner().GetName()->ToString() + '%' + name1;
1848     }
1849     if (proc2.owner().IsDerivedType()) {
1850       name2 = proc2.owner().GetName()->ToString() + '%' + name2;
1851     }
1852   }
1853   auto &msg{context_.Say(name,
1854       "Generic '%s' may not have specific procedures '%s' and '%s'"
1855       " as their interfaces are not distinguishable"_err_en_US,
1856       MakeOpName(name), name1, name2)};
1857   evaluate::AttachDeclaration(msg, proc1);
1858   evaluate::AttachDeclaration(msg, proc2);
1859 }
1860 
1861 void CheckDeclarations(SemanticsContext &context) {
1862   CheckHelper{context}.Check();
1863 }
1864 
1865 void CheckInstantiatedDerivedType(
1866     SemanticsContext &context, const DerivedTypeSpec &type) {
1867   if (const Scope * scope{type.scope()}) {
1868     CheckHelper checker{context};
1869     for (const auto &pair : *scope) {
1870       checker.CheckInitialization(*pair.second);
1871     }
1872   }
1873 }
1874 
1875 } // namespace Fortran::semantics
1876