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   // Prohibit constant pointers.  The standard does not explicitly prohibit
1284   // them, but the PARAMETER attribute requires a entity-decl to have an
1285   // initialization that is a constant-expr, and the only form of
1286   // initialization that allows a constant-expr is the one that's not a "=>"
1287   // pointer initialization.  See C811, C807, and section 8.5.13.
1288   CheckConflicting(symbol, Attr::POINTER, Attr::PARAMETER);
1289   if (symbol.Corank() > 0) {
1290     messages_.Say(
1291         "'%s' may not have the POINTER attribute because it is a coarray"_err_en_US,
1292         symbol.name());
1293   }
1294 }
1295 
1296 // C760 constraints on the passed-object dummy argument
1297 // C757 constraints on procedure pointer components
1298 void CheckHelper::CheckPassArg(
1299     const Symbol &proc, const Symbol *interface, const WithPassArg &details) {
1300   if (proc.attrs().test(Attr::NOPASS)) {
1301     return;
1302   }
1303   const auto &name{proc.name()};
1304   if (!interface) {
1305     messages_.Say(name,
1306         "Procedure component '%s' must have NOPASS attribute or explicit interface"_err_en_US,
1307         name);
1308     return;
1309   }
1310   const auto *subprogram{interface->detailsIf<SubprogramDetails>()};
1311   if (!subprogram) {
1312     messages_.Say(name,
1313         "Procedure component '%s' has invalid interface '%s'"_err_en_US, name,
1314         interface->name());
1315     return;
1316   }
1317   std::optional<SourceName> passName{details.passName()};
1318   const auto &dummyArgs{subprogram->dummyArgs()};
1319   if (!passName) {
1320     if (dummyArgs.empty()) {
1321       messages_.Say(name,
1322           proc.has<ProcEntityDetails>()
1323               ? "Procedure component '%s' with no dummy arguments"
1324                 " must have NOPASS attribute"_err_en_US
1325               : "Procedure binding '%s' with no dummy arguments"
1326                 " must have NOPASS attribute"_err_en_US,
1327           name);
1328       return;
1329     }
1330     passName = dummyArgs[0]->name();
1331   }
1332   std::optional<int> passArgIndex{};
1333   for (std::size_t i{0}; i < dummyArgs.size(); ++i) {
1334     if (dummyArgs[i] && dummyArgs[i]->name() == *passName) {
1335       passArgIndex = i;
1336       break;
1337     }
1338   }
1339   if (!passArgIndex) { // C758
1340     messages_.Say(*passName,
1341         "'%s' is not a dummy argument of procedure interface '%s'"_err_en_US,
1342         *passName, interface->name());
1343     return;
1344   }
1345   const Symbol &passArg{*dummyArgs[*passArgIndex]};
1346   std::optional<parser::MessageFixedText> msg;
1347   if (!passArg.has<ObjectEntityDetails>()) {
1348     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1349           " must be a data object"_err_en_US;
1350   } else if (passArg.attrs().test(Attr::POINTER)) {
1351     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1352           " may not have the POINTER attribute"_err_en_US;
1353   } else if (passArg.attrs().test(Attr::ALLOCATABLE)) {
1354     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1355           " may not have the ALLOCATABLE attribute"_err_en_US;
1356   } else if (passArg.attrs().test(Attr::VALUE)) {
1357     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1358           " may not have the VALUE attribute"_err_en_US;
1359   } else if (passArg.Rank() > 0) {
1360     msg = "Passed-object dummy argument '%s' of procedure '%s'"
1361           " must be scalar"_err_en_US;
1362   }
1363   if (msg) {
1364     messages_.Say(name, std::move(*msg), passName.value(), name);
1365     return;
1366   }
1367   const DeclTypeSpec *type{passArg.GetType()};
1368   if (!type) {
1369     return; // an error already occurred
1370   }
1371   const Symbol &typeSymbol{*proc.owner().GetSymbol()};
1372   const DerivedTypeSpec *derived{type->AsDerived()};
1373   if (!derived || derived->typeSymbol() != typeSymbol) {
1374     messages_.Say(name,
1375         "Passed-object dummy argument '%s' of procedure '%s'"
1376         " must be of type '%s' but is '%s'"_err_en_US,
1377         passName.value(), name, typeSymbol.name(), type->AsFortran());
1378     return;
1379   }
1380   if (IsExtensibleType(derived) != type->IsPolymorphic()) {
1381     messages_.Say(name,
1382         type->IsPolymorphic()
1383             ? "Passed-object dummy argument '%s' of procedure '%s'"
1384               " may not be polymorphic because '%s' is not extensible"_err_en_US
1385             : "Passed-object dummy argument '%s' of procedure '%s'"
1386               " must be polymorphic because '%s' is extensible"_err_en_US,
1387         passName.value(), name, typeSymbol.name());
1388     return;
1389   }
1390   for (const auto &[paramName, paramValue] : derived->parameters()) {
1391     if (paramValue.isLen() && !paramValue.isAssumed()) {
1392       messages_.Say(name,
1393           "Passed-object dummy argument '%s' of procedure '%s'"
1394           " has non-assumed length parameter '%s'"_err_en_US,
1395           passName.value(), name, paramName);
1396     }
1397   }
1398 }
1399 
1400 void CheckHelper::CheckProcBinding(
1401     const Symbol &symbol, const ProcBindingDetails &binding) {
1402   const Scope &dtScope{symbol.owner()};
1403   CHECK(dtScope.kind() == Scope::Kind::DerivedType);
1404   if (const Symbol * dtSymbol{dtScope.symbol()}) {
1405     if (symbol.attrs().test(Attr::DEFERRED)) {
1406       if (!dtSymbol->attrs().test(Attr::ABSTRACT)) { // C733
1407         SayWithDeclaration(*dtSymbol,
1408             "Procedure bound to non-ABSTRACT derived type '%s' may not be DEFERRED"_err_en_US,
1409             dtSymbol->name());
1410       }
1411       if (symbol.attrs().test(Attr::NON_OVERRIDABLE)) {
1412         messages_.Say(
1413             "Type-bound procedure '%s' may not be both DEFERRED and NON_OVERRIDABLE"_err_en_US,
1414             symbol.name());
1415       }
1416     }
1417   }
1418   if (const Symbol * overridden{FindOverriddenBinding(symbol)}) {
1419     if (overridden->attrs().test(Attr::NON_OVERRIDABLE)) {
1420       SayWithDeclaration(*overridden,
1421           "Override of NON_OVERRIDABLE '%s' is not permitted"_err_en_US,
1422           symbol.name());
1423     }
1424     if (const auto *overriddenBinding{
1425             overridden->detailsIf<ProcBindingDetails>()}) {
1426       if (!IsPureProcedure(symbol) && IsPureProcedure(*overridden)) {
1427         SayWithDeclaration(*overridden,
1428             "An overridden pure type-bound procedure binding must also be pure"_err_en_US);
1429         return;
1430       }
1431       if (!binding.symbol().attrs().test(Attr::ELEMENTAL) &&
1432           overriddenBinding->symbol().attrs().test(Attr::ELEMENTAL)) {
1433         SayWithDeclaration(*overridden,
1434             "A type-bound procedure and its override must both, or neither, be ELEMENTAL"_err_en_US);
1435         return;
1436       }
1437       bool isNopass{symbol.attrs().test(Attr::NOPASS)};
1438       if (isNopass != overridden->attrs().test(Attr::NOPASS)) {
1439         SayWithDeclaration(*overridden,
1440             isNopass
1441                 ? "A NOPASS type-bound procedure may not override a passed-argument procedure"_err_en_US
1442                 : "A passed-argument type-bound procedure may not override a NOPASS procedure"_err_en_US);
1443       } else {
1444         const auto *bindingChars{Characterize(binding.symbol())};
1445         const auto *overriddenChars{Characterize(overriddenBinding->symbol())};
1446         if (bindingChars && overriddenChars) {
1447           if (isNopass) {
1448             if (!bindingChars->CanOverride(*overriddenChars, std::nullopt)) {
1449               SayWithDeclaration(*overridden,
1450                   "A type-bound procedure and its override must have compatible interfaces"_err_en_US);
1451             }
1452           } else {
1453             int passIndex{bindingChars->FindPassIndex(binding.passName())};
1454             int overriddenPassIndex{
1455                 overriddenChars->FindPassIndex(overriddenBinding->passName())};
1456             if (passIndex != overriddenPassIndex) {
1457               SayWithDeclaration(*overridden,
1458                   "A type-bound procedure and its override must use the same PASS argument"_err_en_US);
1459             } else if (!bindingChars->CanOverride(
1460                            *overriddenChars, passIndex)) {
1461               SayWithDeclaration(*overridden,
1462                   "A type-bound procedure and its override must have compatible interfaces apart from their passed argument"_err_en_US);
1463             }
1464           }
1465         }
1466       }
1467       if (symbol.attrs().test(Attr::PRIVATE) &&
1468           overridden->attrs().test(Attr::PUBLIC)) {
1469         SayWithDeclaration(*overridden,
1470             "A PRIVATE procedure may not override a PUBLIC procedure"_err_en_US);
1471       }
1472     } else {
1473       SayWithDeclaration(*overridden,
1474           "A type-bound procedure binding may not have the same name as a parent component"_err_en_US);
1475     }
1476   }
1477   CheckPassArg(symbol, &binding.symbol(), binding);
1478 }
1479 
1480 void CheckHelper::Check(const Scope &scope) {
1481   scope_ = &scope;
1482   common::Restorer<const Symbol *> restorer{innermostSymbol_};
1483   if (const Symbol * symbol{scope.symbol()}) {
1484     innermostSymbol_ = symbol;
1485   } else if (scope.IsDerivedType()) {
1486     // PDT instantiations have no symbol.
1487     return;
1488   }
1489   for (const auto &set : scope.equivalenceSets()) {
1490     CheckEquivalenceSet(set);
1491   }
1492   for (const auto &pair : scope) {
1493     Check(*pair.second);
1494   }
1495   for (const Scope &child : scope.children()) {
1496     Check(child);
1497   }
1498   if (scope.kind() == Scope::Kind::BlockData) {
1499     CheckBlockData(scope);
1500   }
1501   CheckGenericOps(scope);
1502 }
1503 
1504 void CheckHelper::CheckEquivalenceSet(const EquivalenceSet &set) {
1505   auto iter{
1506       std::find_if(set.begin(), set.end(), [](const EquivalenceObject &object) {
1507         return FindCommonBlockContaining(object.symbol) != nullptr;
1508       })};
1509   if (iter != set.end()) {
1510     const Symbol &commonBlock{DEREF(FindCommonBlockContaining(iter->symbol))};
1511     for (auto &object : set) {
1512       if (&object != &*iter) {
1513         if (auto *details{object.symbol.detailsIf<ObjectEntityDetails>()}) {
1514           if (details->commonBlock()) {
1515             if (details->commonBlock() != &commonBlock) { // 8.10.3 paragraph 1
1516               if (auto *msg{messages_.Say(object.symbol.name(),
1517                       "Two objects in the same EQUIVALENCE set may not be members of distinct COMMON blocks"_err_en_US)}) {
1518                 msg->Attach(iter->symbol.name(),
1519                        "Other object in EQUIVALENCE set"_en_US)
1520                     .Attach(details->commonBlock()->name(),
1521                         "COMMON block containing '%s'"_en_US,
1522                         object.symbol.name())
1523                     .Attach(commonBlock.name(),
1524                         "COMMON block containing '%s'"_en_US,
1525                         iter->symbol.name());
1526               }
1527             }
1528           } else {
1529             // Mark all symbols in the equivalence set with the same COMMON
1530             // block to prevent spurious error messages about initialization
1531             // in BLOCK DATA outside COMMON
1532             details->set_commonBlock(commonBlock);
1533           }
1534         }
1535       }
1536     }
1537   }
1538   // TODO: Move C8106 (&al.) checks here from resolve-names-utils.cpp
1539 }
1540 
1541 void CheckHelper::CheckBlockData(const Scope &scope) {
1542   // BLOCK DATA subprograms should contain only named common blocks.
1543   // C1415 presents a list of statements that shouldn't appear in
1544   // BLOCK DATA, but so long as the subprogram contains no executable
1545   // code and allocates no storage outside named COMMON, we're happy
1546   // (e.g., an ENUM is strictly not allowed).
1547   for (const auto &pair : scope) {
1548     const Symbol &symbol{*pair.second};
1549     if (!(symbol.has<CommonBlockDetails>() || symbol.has<UseDetails>() ||
1550             symbol.has<UseErrorDetails>() || symbol.has<DerivedTypeDetails>() ||
1551             symbol.has<SubprogramDetails>() ||
1552             symbol.has<ObjectEntityDetails>() ||
1553             (symbol.has<ProcEntityDetails>() &&
1554                 !symbol.attrs().test(Attr::POINTER)))) {
1555       messages_.Say(symbol.name(),
1556           "'%s' may not appear in a BLOCK DATA subprogram"_err_en_US,
1557           symbol.name());
1558     }
1559   }
1560 }
1561 
1562 // Check distinguishability of generic assignment and operators.
1563 // For these, generics and generic bindings must be considered together.
1564 void CheckHelper::CheckGenericOps(const Scope &scope) {
1565   DistinguishabilityHelper helper{context_};
1566   auto addSpecifics{[&](const Symbol &generic) {
1567     const auto *details{generic.GetUltimate().detailsIf<GenericDetails>()};
1568     if (!details) {
1569       return;
1570     }
1571     GenericKind kind{details->kind()};
1572     if (!kind.IsAssignment() && !kind.IsOperator()) {
1573       return;
1574     }
1575     const SymbolVector &specifics{details->specificProcs()};
1576     const std::vector<SourceName> &bindingNames{details->bindingNames()};
1577     for (std::size_t i{0}; i < specifics.size(); ++i) {
1578       const Symbol &specific{*specifics[i]};
1579       if (const Procedure * proc{Characterize(specific)}) {
1580         auto restorer{messages_.SetLocation(bindingNames[i])};
1581         if (kind.IsAssignment()) {
1582           if (!CheckDefinedAssignment(specific, *proc)) {
1583             continue;
1584           }
1585         } else {
1586           if (!CheckDefinedOperator(generic.name(), kind, specific, *proc)) {
1587             continue;
1588           }
1589         }
1590         helper.Add(generic, kind, specific, *proc);
1591       }
1592     }
1593   }};
1594   for (const auto &pair : scope) {
1595     const Symbol &symbol{*pair.second};
1596     addSpecifics(symbol);
1597     const Symbol &ultimate{symbol.GetUltimate()};
1598     if (ultimate.has<DerivedTypeDetails>()) {
1599       if (const Scope * typeScope{ultimate.scope()}) {
1600         for (const auto &pair2 : *typeScope) {
1601           addSpecifics(*pair2.second);
1602         }
1603       }
1604     }
1605   }
1606   helper.Check();
1607 }
1608 
1609 void SubprogramMatchHelper::Check(
1610     const Symbol &symbol1, const Symbol &symbol2) {
1611   const auto details1{symbol1.get<SubprogramDetails>()};
1612   const auto details2{symbol2.get<SubprogramDetails>()};
1613   if (details1.isFunction() != details2.isFunction()) {
1614     Say(symbol1, symbol2,
1615         details1.isFunction()
1616             ? "Module function '%s' was declared as a subroutine in the"
1617               " corresponding interface body"_err_en_US
1618             : "Module subroutine '%s' was declared as a function in the"
1619               " corresponding interface body"_err_en_US);
1620     return;
1621   }
1622   const auto &args1{details1.dummyArgs()};
1623   const auto &args2{details2.dummyArgs()};
1624   int nargs1{static_cast<int>(args1.size())};
1625   int nargs2{static_cast<int>(args2.size())};
1626   if (nargs1 != nargs2) {
1627     Say(symbol1, symbol2,
1628         "Module subprogram '%s' has %d args but the corresponding interface"
1629         " body has %d"_err_en_US,
1630         nargs1, nargs2);
1631     return;
1632   }
1633   bool nonRecursive1{symbol1.attrs().test(Attr::NON_RECURSIVE)};
1634   if (nonRecursive1 != symbol2.attrs().test(Attr::NON_RECURSIVE)) { // C1551
1635     Say(symbol1, symbol2,
1636         nonRecursive1
1637             ? "Module subprogram '%s' has NON_RECURSIVE prefix but"
1638               " the corresponding interface body does not"_err_en_US
1639             : "Module subprogram '%s' does not have NON_RECURSIVE prefix but "
1640               "the corresponding interface body does"_err_en_US);
1641   }
1642   MaybeExpr bindName1{details1.bindName()};
1643   MaybeExpr bindName2{details2.bindName()};
1644   if (bindName1.has_value() != bindName2.has_value()) {
1645     Say(symbol1, symbol2,
1646         bindName1.has_value()
1647             ? "Module subprogram '%s' has a binding label but the corresponding"
1648               " interface body does not"_err_en_US
1649             : "Module subprogram '%s' does not have a binding label but the"
1650               " corresponding interface body does"_err_en_US);
1651   } else if (bindName1) {
1652     std::string string1{bindName1->AsFortran()};
1653     std::string string2{bindName2->AsFortran()};
1654     if (string1 != string2) {
1655       Say(symbol1, symbol2,
1656           "Module subprogram '%s' has binding label %s but the corresponding"
1657           " interface body has %s"_err_en_US,
1658           string1, string2);
1659     }
1660   }
1661   const Procedure *proc1{checkHelper.Characterize(symbol1)};
1662   const Procedure *proc2{checkHelper.Characterize(symbol2)};
1663   if (!proc1 || !proc2) {
1664     return;
1665   }
1666   if (proc1->functionResult && proc2->functionResult &&
1667       *proc1->functionResult != *proc2->functionResult) {
1668     Say(symbol1, symbol2,
1669         "Return type of function '%s' does not match return type of"
1670         " the corresponding interface body"_err_en_US);
1671   }
1672   for (int i{0}; i < nargs1; ++i) {
1673     const Symbol *arg1{args1[i]};
1674     const Symbol *arg2{args2[i]};
1675     if (arg1 && !arg2) {
1676       Say(symbol1, symbol2,
1677           "Dummy argument %2$d of '%1$s' is not an alternate return indicator"
1678           " but the corresponding argument in the interface body is"_err_en_US,
1679           i + 1);
1680     } else if (!arg1 && arg2) {
1681       Say(symbol1, symbol2,
1682           "Dummy argument %2$d of '%1$s' is an alternate return indicator but"
1683           " the corresponding argument in the interface body is not"_err_en_US,
1684           i + 1);
1685     } else if (arg1 && arg2) {
1686       SourceName name1{arg1->name()};
1687       SourceName name2{arg2->name()};
1688       if (name1 != name2) {
1689         Say(*arg1, *arg2,
1690             "Dummy argument name '%s' does not match corresponding name '%s'"
1691             " in interface body"_err_en_US,
1692             name2);
1693       } else {
1694         CheckDummyArg(
1695             *arg1, *arg2, proc1->dummyArguments[i], proc2->dummyArguments[i]);
1696       }
1697     }
1698   }
1699 }
1700 
1701 void SubprogramMatchHelper::CheckDummyArg(const Symbol &symbol1,
1702     const Symbol &symbol2, const DummyArgument &arg1,
1703     const DummyArgument &arg2) {
1704   std::visit(common::visitors{
1705                  [&](const DummyDataObject &obj1, const DummyDataObject &obj2) {
1706                    CheckDummyDataObject(symbol1, symbol2, obj1, obj2);
1707                  },
1708                  [&](const DummyProcedure &proc1, const DummyProcedure &proc2) {
1709                    CheckDummyProcedure(symbol1, symbol2, proc1, proc2);
1710                  },
1711                  [&](const DummyDataObject &, const auto &) {
1712                    Say(symbol1, symbol2,
1713                        "Dummy argument '%s' is a data object; the corresponding"
1714                        " argument in the interface body is not"_err_en_US);
1715                  },
1716                  [&](const DummyProcedure &, const auto &) {
1717                    Say(symbol1, symbol2,
1718                        "Dummy argument '%s' is a procedure; the corresponding"
1719                        " argument in the interface body is not"_err_en_US);
1720                  },
1721                  [&](const auto &, const auto &) {
1722                    llvm_unreachable("Dummy arguments are not data objects or"
1723                                     "procedures");
1724                  },
1725              },
1726       arg1.u, arg2.u);
1727 }
1728 
1729 void SubprogramMatchHelper::CheckDummyDataObject(const Symbol &symbol1,
1730     const Symbol &symbol2, const DummyDataObject &obj1,
1731     const DummyDataObject &obj2) {
1732   if (!CheckSameIntent(symbol1, symbol2, obj1.intent, obj2.intent)) {
1733   } else if (!CheckSameAttrs(symbol1, symbol2, obj1.attrs, obj2.attrs)) {
1734   } else if (obj1.type.type() != obj2.type.type()) {
1735     Say(symbol1, symbol2,
1736         "Dummy argument '%s' has type %s; the corresponding argument in the"
1737         " interface body has type %s"_err_en_US,
1738         obj1.type.type().AsFortran(), obj2.type.type().AsFortran());
1739   } else if (!ShapesAreCompatible(obj1, obj2)) {
1740     Say(symbol1, symbol2,
1741         "The shape of dummy argument '%s' does not match the shape of the"
1742         " corresponding argument in the interface body"_err_en_US);
1743   }
1744   // TODO: coshape
1745 }
1746 
1747 void SubprogramMatchHelper::CheckDummyProcedure(const Symbol &symbol1,
1748     const Symbol &symbol2, const DummyProcedure &proc1,
1749     const DummyProcedure &proc2) {
1750   if (!CheckSameIntent(symbol1, symbol2, proc1.intent, proc2.intent)) {
1751   } else if (!CheckSameAttrs(symbol1, symbol2, proc1.attrs, proc2.attrs)) {
1752   } else if (proc1 != proc2) {
1753     Say(symbol1, symbol2,
1754         "Dummy procedure '%s' does not match the corresponding argument in"
1755         " the interface body"_err_en_US);
1756   }
1757 }
1758 
1759 bool SubprogramMatchHelper::CheckSameIntent(const Symbol &symbol1,
1760     const Symbol &symbol2, common::Intent intent1, common::Intent intent2) {
1761   if (intent1 == intent2) {
1762     return true;
1763   } else {
1764     Say(symbol1, symbol2,
1765         "The intent of dummy argument '%s' does not match the intent"
1766         " of the corresponding argument in the interface body"_err_en_US);
1767     return false;
1768   }
1769 }
1770 
1771 // Report an error referring to first symbol with declaration of second symbol
1772 template <typename... A>
1773 void SubprogramMatchHelper::Say(const Symbol &symbol1, const Symbol &symbol2,
1774     parser::MessageFixedText &&text, A &&...args) {
1775   auto &message{context().Say(symbol1.name(), std::move(text), symbol1.name(),
1776       std::forward<A>(args)...)};
1777   evaluate::AttachDeclaration(message, symbol2);
1778 }
1779 
1780 template <typename ATTRS>
1781 bool SubprogramMatchHelper::CheckSameAttrs(
1782     const Symbol &symbol1, const Symbol &symbol2, ATTRS attrs1, ATTRS attrs2) {
1783   if (attrs1 == attrs2) {
1784     return true;
1785   }
1786   attrs1.IterateOverMembers([&](auto attr) {
1787     if (!attrs2.test(attr)) {
1788       Say(symbol1, symbol2,
1789           "Dummy argument '%s' has the %s attribute; the corresponding"
1790           " argument in the interface body does not"_err_en_US,
1791           AsFortran(attr));
1792     }
1793   });
1794   attrs2.IterateOverMembers([&](auto attr) {
1795     if (!attrs1.test(attr)) {
1796       Say(symbol1, symbol2,
1797           "Dummy argument '%s' does not have the %s attribute; the"
1798           " corresponding argument in the interface body does"_err_en_US,
1799           AsFortran(attr));
1800     }
1801   });
1802   return false;
1803 }
1804 
1805 bool SubprogramMatchHelper::ShapesAreCompatible(
1806     const DummyDataObject &obj1, const DummyDataObject &obj2) {
1807   return characteristics::ShapesAreCompatible(
1808       FoldShape(obj1.type.shape()), FoldShape(obj2.type.shape()));
1809 }
1810 
1811 evaluate::Shape SubprogramMatchHelper::FoldShape(const evaluate::Shape &shape) {
1812   evaluate::Shape result;
1813   for (const auto &extent : shape) {
1814     result.emplace_back(
1815         evaluate::Fold(context().foldingContext(), common::Clone(extent)));
1816   }
1817   return result;
1818 }
1819 
1820 void DistinguishabilityHelper::Add(const Symbol &generic, GenericKind kind,
1821     const Symbol &specific, const Procedure &procedure) {
1822   if (!context_.HasError(specific)) {
1823     nameToInfo_[generic.name()].emplace_back(
1824         ProcedureInfo{kind, specific, procedure});
1825   }
1826 }
1827 
1828 void DistinguishabilityHelper::Check() {
1829   for (const auto &[name, info] : nameToInfo_) {
1830     auto count{info.size()};
1831     for (std::size_t i1{0}; i1 < count - 1; ++i1) {
1832       const auto &[kind1, symbol1, proc1] = info[i1];
1833       for (std::size_t i2{i1 + 1}; i2 < count; ++i2) {
1834         const auto &[kind2, symbol2, proc2] = info[i2];
1835         auto distinguishable{kind1.IsName()
1836                 ? evaluate::characteristics::Distinguishable
1837                 : evaluate::characteristics::DistinguishableOpOrAssign};
1838         if (!distinguishable(proc1, proc2)) {
1839           SayNotDistinguishable(name, kind1, symbol1, symbol2);
1840         }
1841       }
1842     }
1843   }
1844 }
1845 
1846 void DistinguishabilityHelper::SayNotDistinguishable(const SourceName &name,
1847     GenericKind kind, const Symbol &proc1, const Symbol &proc2) {
1848   std::string name1{proc1.name().ToString()};
1849   std::string name2{proc2.name().ToString()};
1850   if (kind.IsOperator() || kind.IsAssignment()) {
1851     // proc1 and proc2 may come from different scopes so qualify their names
1852     if (proc1.owner().IsDerivedType()) {
1853       name1 = proc1.owner().GetName()->ToString() + '%' + name1;
1854     }
1855     if (proc2.owner().IsDerivedType()) {
1856       name2 = proc2.owner().GetName()->ToString() + '%' + name2;
1857     }
1858   }
1859   auto &msg{context_.Say(name,
1860       "Generic '%s' may not have specific procedures '%s' and '%s'"
1861       " as their interfaces are not distinguishable"_err_en_US,
1862       MakeOpName(name), name1, name2)};
1863   evaluate::AttachDeclaration(msg, proc1);
1864   evaluate::AttachDeclaration(msg, proc2);
1865 }
1866 
1867 void CheckDeclarations(SemanticsContext &context) {
1868   CheckHelper{context}.Check();
1869 }
1870 
1871 void CheckInstantiatedDerivedType(
1872     SemanticsContext &context, const DerivedTypeSpec &type) {
1873   if (const Scope * scope{type.scope()}) {
1874     CheckHelper checker{context};
1875     for (const auto &pair : *scope) {
1876       checker.CheckInitialization(*pair.second);
1877     }
1878   }
1879 }
1880 
1881 } // namespace Fortran::semantics
1882