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