Debian Codegraph @

flang/lib/Semantics/check-declarations.cpp

raw
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 "definable.h"
13 #include "pointer-assignment.h"
14 #include "flang/Evaluate/check-expression.h"
15 #include "flang/Evaluate/fold.h"
16 #include "flang/Evaluate/tools.h"
17 #include "flang/Parser/characters.h"
18 #include "flang/Semantics/scope.h"
19 #include "flang/Semantics/semantics.h"
20 #include "flang/Semantics/symbol.h"
21 #include "flang/Semantics/tools.h"
22 #include "flang/Semantics/type.h"
23 #include <algorithm>
24 #include <map>
25 #include <string>
26
27 namespace Fortran::semantics {
28
29 namespace characteristics = evaluate::characteristics;
30 using characteristics::DummyArgument;
31 using characteristics::DummyDataObject;
32 using characteristics::DummyProcedure;
33 using characteristics::FunctionResult;
34 using characteristics::Procedure;
35
36 class CheckHelper {
37 public:
38 explicit CheckHelper(SemanticsContext &c) : context_{c} {}
39
40 SemanticsContext &context() { return context_; }
41 void Check() { Check(context_.globalScope()); }
42 void Check(const ParamValue &, bool canBeAssumed);
43 void Check(const Bound &bound) {
44 CheckSpecExpr(bound.GetExplicit(), /*forElementalFunctionResult=*/false);
45 }
46 void Check(const ShapeSpec &spec) {
47 Check(spec.lbound());
48 Check(spec.ubound());
49 }
50 void Check(const ArraySpec &);
51 void Check(const DeclTypeSpec &, bool canHaveAssumedTypeParameters);
52 void Check(const Symbol &);
53 void CheckCommonBlock(const Symbol &);
54 void Check(const Scope &);
55 const Procedure *Characterize(const Symbol &);
56
57 private:
58 template <typename A>
59 void CheckSpecExpr(const A &x, bool forElementalFunctionResult) {
60 evaluate::CheckSpecificationExpr(
61 x, DEREF(scope_), foldingContext_, forElementalFunctionResult);
62 }
63 void CheckValue(const Symbol &, const DerivedTypeSpec *);
64 void CheckVolatile(const Symbol &, const DerivedTypeSpec *);
65 void CheckContiguous(const Symbol &);
66 void CheckPointer(const Symbol &);
67 void CheckPassArg(
68 const Symbol &proc, const Symbol *interface, const WithPassArg &);
69 void CheckProcBinding(const Symbol &, const ProcBindingDetails &);
70 void CheckObjectEntity(const Symbol &, const ObjectEntityDetails &);
71 void CheckPointerInitialization(const Symbol &);
72 void CheckArraySpec(const Symbol &, const ArraySpec &);
73 void CheckProcEntity(const Symbol &, const ProcEntityDetails &);
74 void CheckSubprogram(const Symbol &, const SubprogramDetails &);
75 void CheckExternal(const Symbol &);
76 void CheckAssumedTypeEntity(const Symbol &, const ObjectEntityDetails &);
77 void CheckDerivedType(const Symbol &, const DerivedTypeDetails &);
78 bool CheckFinal(
79 const Symbol &subroutine, SourceName, const Symbol &derivedType);
80 bool CheckDistinguishableFinals(const Symbol &f1, SourceName f1name,
81 const Symbol &f2, SourceName f2name, const Symbol &derivedType);
82 void CheckGeneric(const Symbol &, const GenericDetails &);
83 void CheckHostAssoc(const Symbol &, const HostAssocDetails &);
84 bool CheckDefinedOperator(
85 SourceName, GenericKind, const Symbol &, const Procedure &);
86 std::optional<parser::MessageFixedText> CheckNumberOfArgs(
87 const GenericKind &, std::size_t);
88 bool CheckDefinedOperatorArg(
89 const SourceName &, const Symbol &, const Procedure &, std::size_t);
90 bool CheckDefinedAssignment(const Symbol &, const Procedure &);
91 bool CheckDefinedAssignmentArg(const Symbol &, const DummyArgument &, int);
92 void CheckSpecifics(const Symbol &, const GenericDetails &);
93 void CheckEquivalenceSet(const EquivalenceSet &);
94 void CheckEquivalenceObject(const EquivalenceObject &);
95 void CheckBlockData(const Scope &);
96 void CheckGenericOps(const Scope &);
97 bool CheckConflicting(const Symbol &, Attr, Attr);
98 void WarnMissingFinal(const Symbol &);
99 void CheckSymbolType(const Symbol &); // C702
100 bool InPure() const {
101 return innermostSymbol_ && IsPureProcedure(*innermostSymbol_);
102 }
103 bool InElemental() const {
104 return innermostSymbol_ && IsElementalProcedure(*innermostSymbol_);
105 }
106 bool InFunction() const {
107 return innermostSymbol_ && IsFunction(*innermostSymbol_);
108 }
109 bool InInterface() const {
110 const SubprogramDetails *subp{innermostSymbol_
111 ? innermostSymbol_->detailsIf<SubprogramDetails>()
112 : nullptr};
113 return subp && subp->isInterface();
114 }
115 template <typename... A>
116 parser::Message *SayWithDeclaration(const Symbol &symbol, A &&...x) {
117 parser::Message *msg{messages_.Say(std::forward<A>(x)...)};
118 if (msg && messages_.at().begin() != symbol.name().begin()) {
119 evaluate::AttachDeclaration(*msg, symbol);
120 }
121 return msg;
122 }
123 bool InModuleFile() const {
124 return FindModuleFileContaining(context_.FindScope(messages_.at())) !=
125 nullptr;
126 }
127 template <typename... A> parser::Message *WarnIfNotInModuleFile(A &&...x) {
128 if (InModuleFile()) {
129 return nullptr;
130 } else {
131 return messages_.Say(std::forward<A>(x)...);
132 }
133 }
134 template <typename... A>
135 parser::Message *WarnIfNotInModuleFile(parser::CharBlock source, A &&...x) {
136 if (FindModuleFileContaining(context_.FindScope(source))) {
137 return nullptr;
138 }
139 return messages_.Say(source, std::forward<A>(x)...);
140 }
141 bool IsResultOkToDiffer(const FunctionResult &);
142 void CheckGlobalName(const Symbol &);
143 void CheckProcedureAssemblyName(const Symbol &symbol);
144 void CheckExplicitSave(const Symbol &);
145 parser::Messages WhyNotInteroperableDerivedType(const Symbol &);
146 parser::Messages WhyNotInteroperableObject(const Symbol &);
147 parser::Messages WhyNotInteroperableFunctionResult(const Symbol &);
148 parser::Messages WhyNotInteroperableProcedure(const Symbol &, bool isError);
149 void CheckBindC(const Symbol &);
150 // Check functions for defined I/O procedures
151 void CheckDefinedIoProc(
152 const Symbol &, const GenericDetails &, common::DefinedIo);
153 bool CheckDioDummyIsData(const Symbol &, const Symbol *, std::size_t);
154 void CheckDioDummyIsDerived(
155 const Symbol &, const Symbol &, common::DefinedIo ioKind, const Symbol &);
156 void CheckDioDummyIsDefaultInteger(const Symbol &, const Symbol &);
157 void CheckDioDummyIsScalar(const Symbol &, const Symbol &);
158 void CheckDioDummyAttrs(const Symbol &, const Symbol &, Attr);
159 void CheckDioDtvArg(
160 const Symbol &, const Symbol *, common::DefinedIo, const Symbol &);
161 void CheckGenericVsIntrinsic(const Symbol &, const GenericDetails &);
162 void CheckDefaultIntegerArg(const Symbol &, const Symbol *, Attr);
163 void CheckDioAssumedLenCharacterArg(
164 const Symbol &, const Symbol *, std::size_t, Attr);
165 void CheckDioVlistArg(const Symbol &, const Symbol *, std::size_t);
166 void CheckDioArgCount(const Symbol &, common::DefinedIo ioKind, std::size_t);
167 struct TypeWithDefinedIo {
168 const DerivedTypeSpec &type;
169 common::DefinedIo ioKind;
170 const Symbol &proc;
171 const Symbol &generic;
172 };
173 void CheckAlreadySeenDefinedIo(const DerivedTypeSpec &, common::DefinedIo,
174 const Symbol &, const Symbol &generic);
175 void CheckModuleProcedureDef(const Symbol &);
176
177 SemanticsContext &context_;
178 evaluate::FoldingContext &foldingContext_{context_.foldingContext()};
179 parser::ContextualMessages &messages_{foldingContext_.messages()};
180 const Scope *scope_{nullptr};
181 bool scopeIsUninstantiatedPDT_{false};
182 // This symbol is the one attached to the innermost enclosing scope
183 // that has a symbol.
184 const Symbol *innermostSymbol_{nullptr};
185 // Cache of calls to Procedure::Characterize(Symbol)
186 std::map<SymbolRef, std::optional<Procedure>, SymbolAddressCompare>
187 characterizeCache_;
188 // Collection of module procedure symbols with non-BIND(C)
189 // global names, qualified by their module.
190 std::map<std::pair<SourceName, const Symbol *>, SymbolRef> moduleProcs_;
191 // Collection of symbols with global names, BIND(C) or otherwise
192 std::map<std::string, SymbolRef> globalNames_;
193 // Collection of external procedures without global definitions
194 std::map<std::string, SymbolRef> externalNames_;
195 // Collection of target dependent assembly names of external and BIND(C)
196 // procedures.
197 std::map<std::string, SymbolRef> procedureAssemblyNames_;
198 // Derived types that have been examined by WhyNotInteroperable_XXX
199 UnorderedSymbolSet examinedByWhyNotInteroperable_;
200 };
201
202 class DistinguishabilityHelper {
203 public:
204 DistinguishabilityHelper(SemanticsContext &context) : context_{context} {}
205 void Add(const Symbol &, GenericKind, const Symbol &, const Procedure &);
206 void Check(const Scope &);
207
208 private:
209 void SayNotDistinguishable(const Scope &, const SourceName &, GenericKind,
210 const Symbol &, const Symbol &, bool isHardConflict);
211 void AttachDeclaration(parser::Message &, const Scope &, const Symbol &);
212
213 SemanticsContext &context_;
214 struct ProcedureInfo {
215 GenericKind kind;
216 const Procedure &procedure;
217 };
218 std::map<SourceName, std::map<const Symbol *, ProcedureInfo>>
219 nameToSpecifics_;
220 };
221
222 void CheckHelper::Check(const ParamValue &value, bool canBeAssumed) {
223 if (value.isAssumed()) {
224 if (!canBeAssumed) { // C795, C721, C726
225 messages_.Say(
226 "An assumed (*) type parameter may be used only for a (non-statement function) dummy argument, associate name, character named constant, or external function result"_err_en_US);
227 }
228 } else {
229 CheckSpecExpr(value.GetExplicit(), /*forElementalFunctionResult=*/false);
230 }
231 }
232
233 void CheckHelper::Check(const ArraySpec &shape) {
234 for (const auto &spec : shape) {
235 Check(spec);
236 }
237 }
238
239 void CheckHelper::Check(
240 const DeclTypeSpec &type, bool canHaveAssumedTypeParameters) {
241 if (type.category() == DeclTypeSpec::Character) {
242 Check(type.characterTypeSpec().length(), canHaveAssumedTypeParameters);
243 } else if (const DerivedTypeSpec *derived{type.AsDerived()}) {
244 for (auto &parm : derived->parameters()) {
245 Check(parm.second, canHaveAssumedTypeParameters);
246 }
247 }
248 }
249
250 void CheckHelper::Check(const Symbol &symbol) {
251 if (symbol.name().size() > common::maxNameLen &&
252 &symbol == &symbol.GetUltimate()) {
253 if (context_.ShouldWarn(common::LanguageFeature::LongNames)) {
254 WarnIfNotInModuleFile(symbol.name(),
255 "%s has length %d, which is greater than the maximum name length %d"_port_en_US,
256 symbol.name(), symbol.name().size(), common::maxNameLen);
257 }
258 }
259 if (context_.HasError(symbol)) {
260 return;
261 }
262 auto restorer{messages_.SetLocation(symbol.name())};
263 context_.set_location(symbol.name());
264 const DeclTypeSpec *type{symbol.GetType()};
265 const DerivedTypeSpec *derived{type ? type->AsDerived() : nullptr};
266 bool isDone{false};
267 common::visit(
268 common::visitors{
269 [&](const UseDetails &x) { isDone = true; },
270 [&](const HostAssocDetails &x) {
271 CheckHostAssoc(symbol, x);
272 isDone = true;
273 },
274 [&](const ProcBindingDetails &x) {
275 CheckProcBinding(symbol, x);
276 isDone = true;
277 },
278 [&](const ObjectEntityDetails &x) { CheckObjectEntity(symbol, x); },
279 [&](const ProcEntityDetails &x) { CheckProcEntity(symbol, x); },
280 [&](const SubprogramDetails &x) { CheckSubprogram(symbol, x); },
281 [&](const DerivedTypeDetails &x) { CheckDerivedType(symbol, x); },
282 [&](const GenericDetails &x) { CheckGeneric(symbol, x); },
283 [](const auto &) {},
284 },
285 symbol.details());
286 if (symbol.attrs().test(Attr::VOLATILE)) {
287 CheckVolatile(symbol, derived);
288 }
289 if (symbol.attrs().test(Attr::BIND_C)) {
290 CheckBindC(symbol);
291 }
292 if (symbol.attrs().test(Attr::SAVE) &&
293 !symbol.implicitAttrs().test(Attr::SAVE)) {
294 CheckExplicitSave(symbol);
295 }
296 if (symbol.attrs().test(Attr::CONTIGUOUS)) {
297 CheckContiguous(symbol);
298 }
299 CheckGlobalName(symbol);
300 CheckProcedureAssemblyName(symbol);
301 if (symbol.attrs().test(Attr::ASYNCHRONOUS) &&
302 !evaluate::IsVariable(symbol)) {
303 messages_.Say(
304 "An entity may not have the ASYNCHRONOUS attribute unless it is a variable"_err_en_US);
305 }
306 if (symbol.attrs().HasAny({Attr::INTENT_IN, Attr::INTENT_INOUT,
307 Attr::INTENT_OUT, Attr::OPTIONAL, Attr::VALUE}) &&
308 !IsDummy(symbol)) {
309 messages_.Say(
310 "Only a dummy argument may have an INTENT, VALUE, or OPTIONAL attribute"_err_en_US);
311 } else if (symbol.attrs().test(Attr::VALUE)) {
312 CheckValue(symbol, derived);
313 }
314
315 if (isDone) {
316 return; // following checks do not apply
317 }
318
319 if (symbol.attrs().test(Attr::PROTECTED)) {
320 if (symbol.owner().kind() != Scope::Kind::Module) { // C854
321 messages_.Say(
322 "A PROTECTED entity must be in the specification part of a module"_err_en_US);
323 }
324 if (!evaluate::IsVariable(symbol) && !IsProcedurePointer(symbol)) { // C855
325 messages_.Say(
326 "A PROTECTED entity must be a variable or pointer"_err_en_US);
327 }
328 if (FindCommonBlockContaining(symbol)) { // C856
329 messages_.Say(
330 "A PROTECTED entity may not be in a common block"_err_en_US);
331 }
332 }
333 if (IsPointer(symbol)) {
334 CheckPointer(symbol);
335 }
336 if (InPure()) {
337 if (InInterface()) {
338 // Declarations in interface definitions "have no effect" if they
339 // are not pertinent to the characteristics of the procedure.
340 // Restrictions on entities in pure procedure interfaces don't need
341 // enforcement.
342 } else if (!FindCommonBlockContaining(symbol) && IsSaved(symbol)) {
343 if (IsInitialized(symbol)) {
344 messages_.Say(
345 "A pure subprogram may not initialize a variable"_err_en_US);
346 } else {
347 messages_.Say(
348 "A pure subprogram may not have a variable with the SAVE attribute"_err_en_US);
349 }
350 }
351 if (symbol.attrs().test(Attr::VOLATILE) &&
352 (IsDummy(symbol) || !InInterface())) {
353 messages_.Say(
354 "A pure subprogram may not have a variable with the VOLATILE attribute"_err_en_US);
355 }
356 if (innermostSymbol_ && innermostSymbol_->name() == "__builtin_c_funloc") {
357 // The intrinsic procedure C_FUNLOC() gets a pass on this check.
358 } else if (IsProcedure(symbol) && !IsPureProcedure(symbol) &&
359 IsDummy(symbol)) {
360 messages_.Say(
361 "A dummy procedure of a pure subprogram must be pure"_err_en_US);
362 }
363 }
364 const auto *object{symbol.detailsIf<ObjectEntityDetails>()};
365 if (type) { // Section 7.2, paragraph 7; C795
366 bool isChar{type->category() == DeclTypeSpec::Character};
367 bool canHaveAssumedParameter{(isChar && IsNamedConstant(symbol)) ||
368 (IsAssumedLengthCharacter(symbol) && // C722
369 (IsExternal(symbol) ||
370 ClassifyProcedure(symbol) ==
371 ProcedureDefinitionClass::Dummy)) ||
372 symbol.test(Symbol::Flag::ParentComp)};
373 if (!IsStmtFunctionDummy(symbol)) { // C726
374 if (object) {
375 canHaveAssumedParameter |= object->isDummy() ||
376 (isChar && object->isFuncResult()) ||
377 IsStmtFunctionResult(symbol); // Avoids multiple messages
378 } else {
379 canHaveAssumedParameter |= symbol.has<AssocEntityDetails>();
380 }
381 }
382 if (IsProcedurePointer(symbol) && symbol.HasExplicitInterface()) {
383 // Don't check function result types here
384 } else {
385 Check(*type, canHaveAssumedParameter);
386 }
387 if (InFunction() && IsFunctionResult(symbol)) {
388 if (InPure()) {
389 if (type->IsPolymorphic() && IsAllocatable(symbol)) { // C1585
390 messages_.Say(
391 "Result of pure function may not be both polymorphic and ALLOCATABLE"_err_en_US);
392 }
393 if (derived) {
394 // These cases would be caught be the general validation of local
395 // variables in a pure context, but these messages are more specific.
396 if (HasImpureFinal(symbol)) { // C1584
397 messages_.Say(
398 "Result of pure function may not have an impure FINAL subroutine"_err_en_US);
399 }
400 if (auto bad{FindPolymorphicAllocatableUltimateComponent(*derived)}) {
401 SayWithDeclaration(*bad,
402 "Result of pure function may not have polymorphic ALLOCATABLE ultimate component '%s'"_err_en_US,
403 bad.BuildResultDesignatorName());
404 }
405 }
406 }
407 if (InElemental() && isChar) { // F'2023 C15121
408 CheckSpecExpr(type->characterTypeSpec().length().GetExplicit(),
409 /*forElementalFunctionResult=*/true);
410 // TODO: check PDT LEN parameters
411 }
412 }
413 }
414 if (IsAssumedLengthCharacter(symbol) && IsFunction(symbol)) { // C723
415 if (symbol.attrs().test(Attr::RECURSIVE)) {
416 messages_.Say(
417 "An assumed-length CHARACTER(*) function cannot be RECURSIVE"_err_en_US);
418 }
419 if (symbol.Rank() > 0) {
420 messages_.Say(
421 "An assumed-length CHARACTER(*) function cannot return an array"_err_en_US);
422 }
423 if (!IsStmtFunction(symbol)) {
424 if (IsElementalProcedure(symbol)) {
425 messages_.Say(
426 "An assumed-length CHARACTER(*) function cannot be ELEMENTAL"_err_en_US);
427 } else if (IsPureProcedure(symbol)) {
428 messages_.Say(
429 "An assumed-length CHARACTER(*) function cannot be PURE"_err_en_US);
430 }
431 }
432 if (const Symbol *result{FindFunctionResult(symbol)}) {
433 if (IsPointer(*result)) {
434 messages_.Say(
435 "An assumed-length CHARACTER(*) function cannot return a POINTER"_err_en_US);
436 }
437 }
438 if (IsProcedurePointer(symbol) && IsDummy(symbol)) {
439 if (context_.ShouldWarn(common::UsageWarning::Portability)) {
440 messages_.Say(
441 "A dummy procedure pointer should not have assumed-length CHARACTER(*) result type"_port_en_US);
442 }
443 // The non-dummy case is a hard error that's caught elsewhere.
444 }
445 }
446 if (IsDummy(symbol)) {
447 if (IsNamedConstant(symbol)) {
448 messages_.Say(
449 "A dummy argument may not also be a named constant"_err_en_US);
450 }
451 } else if (IsFunctionResult(symbol)) {
452 if (IsNamedConstant(symbol)) {
453 messages_.Say(
454 "A function result may not also be a named constant"_err_en_US);
455 }
456 }
457 if (IsAutomatic(symbol)) {
458 if (const Symbol * common{FindCommonBlockContaining(symbol)}) {
459 messages_.Say(
460 "Automatic data object '%s' may not appear in COMMON block /%s/"_err_en_US,
461 symbol.name(), common->name());
462 } else if (symbol.owner().IsModule()) {
463 messages_.Say(
464 "Automatic data object '%s' may not appear in a module"_err_en_US,
465 symbol.name());
466 }
467 }
468 if (IsProcedure(symbol)) {
469 if (IsAllocatable(symbol)) {
470 messages_.Say(
471 "Procedure '%s' may not be ALLOCATABLE"_err_en_US, symbol.name());
472 }
473 if (!symbol.HasExplicitInterface() && symbol.Rank() > 0) {
474 messages_.Say(
475 "Procedure '%s' may not be an array without an explicit interface"_err_en_US,
476 symbol.name());
477 }
478 }
479 }
480
481 void CheckHelper::CheckCommonBlock(const Symbol &symbol) {
482 CheckGlobalName(symbol);
483 if (symbol.attrs().test(Attr::BIND_C)) {
484 CheckBindC(symbol);
485 }
486 for (MutableSymbolRef ref : symbol.get<CommonBlockDetails>().objects()) {
487 if (ref->test(Symbol::Flag::CrayPointee)) {
488 messages_.Say(ref->name(),
489 "Cray pointee '%s' may not be a member of a COMMON block"_err_en_US,
490 ref->name());
491 }
492 }
493 }
494
495 // C859, C860
496 void CheckHelper::CheckExplicitSave(const Symbol &symbol) {
497 const Symbol &ultimate{symbol.GetUltimate()};
498 if (ultimate.test(Symbol::Flag::InDataStmt)) {
499 // checked elsewhere
500 } else if (symbol.has<UseDetails>()) {
501 messages_.Say(
502 "The USE-associated name '%s' may not have an explicit SAVE attribute"_err_en_US,
503 symbol.name());
504 } else if (IsDummy(ultimate)) {
505 messages_.Say(
506 "The dummy argument '%s' may not have an explicit SAVE attribute"_err_en_US,
507 symbol.name());
508 } else if (IsFunctionResult(ultimate)) {
509 messages_.Say(
510 "The function result variable '%s' may not have an explicit SAVE attribute"_err_en_US,
511 symbol.name());
512 } else if (const Symbol * common{FindCommonBlockContaining(ultimate)}) {
513 messages_.Say(
514 "The entity '%s' in COMMON block /%s/ may not have an explicit SAVE attribute"_err_en_US,
515 symbol.name(), common->name());
516 } else if (IsAutomatic(ultimate)) {
517 messages_.Say(
518 "The automatic object '%s' may not have an explicit SAVE attribute"_err_en_US,
519 symbol.name());
520 } else if (!evaluate::IsVariable(ultimate) && !IsProcedurePointer(ultimate)) {
521 messages_.Say(
522 "The entity '%s' with an explicit SAVE attribute must be a variable, procedure pointer, or COMMON block"_err_en_US,
523 symbol.name());
524 }
525 }
526
527 void CheckHelper::CheckValue(
528 const Symbol &symbol, const DerivedTypeSpec *derived) { // C863 - C865
529 if (IsProcedure(symbol)) {
530 messages_.Say(
531 "VALUE attribute may apply only to a dummy data object"_err_en_US);
532 return; // don't pile on
533 }
534 if (IsAssumedSizeArray(symbol)) {
535 messages_.Say(
536 "VALUE attribute may not apply to an assumed-size array"_err_en_US);
537 }
538 if (evaluate::IsCoarray(symbol)) {
539 messages_.Say("VALUE attribute may not apply to a coarray"_err_en_US);
540 }
541 if (IsAllocatable(symbol)) {
542 messages_.Say("VALUE attribute may not apply to an ALLOCATABLE"_err_en_US);
543 } else if (IsPointer(symbol)) {
544 messages_.Say("VALUE attribute may not apply to a POINTER"_err_en_US);
545 }
546 if (IsIntentInOut(symbol)) {
547 messages_.Say(
548 "VALUE attribute may not apply to an INTENT(IN OUT) argument"_err_en_US);
549 } else if (IsIntentOut(symbol)) {
550 messages_.Say(
551 "VALUE attribute may not apply to an INTENT(OUT) argument"_err_en_US);
552 }
553 if (symbol.attrs().test(Attr::VOLATILE)) {
554 messages_.Say("VALUE attribute may not apply to a VOLATILE"_err_en_US);
555 }
556 if (innermostSymbol_ && IsBindCProcedure(*innermostSymbol_)) {
557 if (IsOptional(symbol)) {
558 messages_.Say(
559 "VALUE attribute may not apply to an OPTIONAL in a BIND(C) procedure"_err_en_US);
560 }
561 if (symbol.Rank() > 0) {
562 messages_.Say(
563 "VALUE attribute may not apply to an array in a BIND(C) procedure"_err_en_US);
564 }
565 }
566 if (derived) {
567 if (FindCoarrayUltimateComponent(*derived)) {
568 messages_.Say(
569 "VALUE attribute may not apply to a type with a coarray ultimate component"_err_en_US);
570 }
571 }
572 if (evaluate::IsAssumedRank(symbol)) {
573 messages_.Say(
574 "VALUE attribute may not apply to an assumed-rank array"_err_en_US);
575 }
576 if (context_.ShouldWarn(common::UsageWarning::Portability) &&
577 IsAssumedLengthCharacter(symbol)) {
578 // F'2008 feature not widely implemented
579 messages_.Say(
580 "VALUE attribute on assumed-length CHARACTER may not be portable"_port_en_US);
581 }
582 }
583
584 void CheckHelper::CheckAssumedTypeEntity( // C709
585 const Symbol &symbol, const ObjectEntityDetails &details) {
586 if (const DeclTypeSpec *type{symbol.GetType()};
587 type && type->category() == DeclTypeSpec::TypeStar) {
588 if (!IsDummy(symbol)) {
589 messages_.Say(
590 "Assumed-type entity '%s' must be a dummy argument"_err_en_US,
591 symbol.name());
592 } else {
593 if (symbol.attrs().test(Attr::ALLOCATABLE)) {
594 messages_.Say("Assumed-type argument '%s' cannot have the ALLOCATABLE"
595 " attribute"_err_en_US,
596 symbol.name());
597 }
598 if (symbol.attrs().test(Attr::POINTER)) {
599 messages_.Say("Assumed-type argument '%s' cannot have the POINTER"
600 " attribute"_err_en_US,
601 symbol.name());
602 }
603 if (symbol.attrs().test(Attr::VALUE)) {
604 messages_.Say("Assumed-type argument '%s' cannot have the VALUE"
605 " attribute"_err_en_US,
606 symbol.name());
607 }
608 if (symbol.attrs().test(Attr::INTENT_OUT)) {
609 messages_.Say(
610 "Assumed-type argument '%s' cannot be INTENT(OUT)"_err_en_US,
611 symbol.name());
612 }
613 if (evaluate::IsCoarray(symbol)) {
614 messages_.Say(
615 "Assumed-type argument '%s' cannot be a coarray"_err_en_US,
616 symbol.name());
617 }
618 if (details.IsArray() && details.shape().IsExplicitShape()) {
619 messages_.Say("Assumed-type array argument '%s' must be assumed shape,"
620 " assumed size, or assumed rank"_err_en_US,
621 symbol.name());
622 }
623 }
624 }
625 }
626
627 void CheckHelper::CheckObjectEntity(
628 const Symbol &symbol, const ObjectEntityDetails &details) {
629 CheckSymbolType(symbol);
630 CheckArraySpec(symbol, details.shape());
631 CheckConflicting(symbol, Attr::ALLOCATABLE, Attr::PARAMETER);
632 CheckConflicting(symbol, Attr::ASYNCHRONOUS, Attr::PARAMETER);
633 CheckConflicting(symbol, Attr::SAVE, Attr::PARAMETER);
634 CheckConflicting(symbol, Attr::TARGET, Attr::PARAMETER);
635 CheckConflicting(symbol, Attr::VOLATILE, Attr::PARAMETER);
636 Check(details.shape());
637 Check(details.coshape());
638 if (details.shape().Rank() > common::maxRank) {
639 messages_.Say(
640 "'%s' has rank %d, which is greater than the maximum supported rank %d"_err_en_US,
641 symbol.name(), details.shape().Rank(), common::maxRank);
642 } else if (details.shape().Rank() + details.coshape().Rank() >
643 common::maxRank) {
644 messages_.Say(
645 "'%s' has rank %d and corank %d, whose sum is greater than the maximum supported rank %d"_err_en_US,
646 symbol.name(), details.shape().Rank(), details.coshape().Rank(),
647 common::maxRank);
648 }
649 CheckAssumedTypeEntity(symbol, details);
650 WarnMissingFinal(symbol);
651 const DeclTypeSpec *type{details.type()};
652 const DerivedTypeSpec *derived{type ? type->AsDerived() : nullptr};
653 bool isComponent{symbol.owner().IsDerivedType()};
654 if (!details.coshape().empty()) {
655 bool isDeferredCoshape{details.coshape().CanBeDeferredShape()};
656 if (IsAllocatable(symbol)) {
657 if (!isDeferredCoshape) { // C827
658 messages_.Say("'%s' is an ALLOCATABLE coarray and must have a deferred"
659 " coshape"_err_en_US,
660 symbol.name());
661 }
662 } else if (isComponent) { // C746
663 std::string deferredMsg{
664 isDeferredCoshape ? "" : " and have a deferred coshape"};
665 messages_.Say("Component '%s' is a coarray and must have the ALLOCATABLE"
666 " attribute%s"_err_en_US,
667 symbol.name(), deferredMsg);
668 } else {
669 if (!details.coshape().CanBeAssumedSize()) { // C828
670 messages_.Say(
671 "'%s' is a non-ALLOCATABLE coarray and must have an explicit coshape"_err_en_US,
672 symbol.name());
673 }
674 }
675 if (IsBadCoarrayType(derived)) { // C747 & C824
676 messages_.Say(
677 "Coarray '%s' may not have type TEAM_TYPE, C_PTR, or C_FUNPTR"_err_en_US,
678 symbol.name());
679 }
680 if (evaluate::IsAssumedRank(symbol)) {
681 messages_.Say("Coarray '%s' may not be an assumed-rank array"_err_en_US,
682 symbol.name());
683 }
684 }
685 if (details.isDummy()) {
686 if (IsIntentOut(symbol)) {
687 // Some of these errors would also be caught by the general check
688 // for definability of automatically deallocated local variables,
689 // but these messages are more specific.
690 if (FindUltimateComponent(symbol, [](const Symbol &x) {
691 return evaluate::IsCoarray(x) && IsAllocatable(x);
692 })) { // C846
693 messages_.Say(
694 "An INTENT(OUT) dummy argument may not be, or contain, an ALLOCATABLE coarray"_err_en_US);
695 }
696 if (IsOrContainsEventOrLockComponent(symbol)) { // C847
697 messages_.Say(
698 "An INTENT(OUT) dummy argument may not be, or contain, EVENT_TYPE or LOCK_TYPE"_err_en_US);
699 }
700 if (IsAssumedSizeArray(symbol)) { // C834
701 if (type && type->IsPolymorphic()) {
702 messages_.Say(
703 "An INTENT(OUT) assumed-size dummy argument array may not be polymorphic"_err_en_US);
704 }
705 if (derived) {
706 if (derived->HasDefaultInitialization()) {
707 messages_.Say(
708 "An INTENT(OUT) assumed-size dummy argument array may not have a derived type with any default component initialization"_err_en_US);
709 }
710 if (IsFinalizable(*derived)) {
711 messages_.Say(
712 "An INTENT(OUT) assumed-size dummy argument array may not be finalizable"_err_en_US);
713 }
714 }
715 }
716 }
717 if (InPure() && !IsStmtFunction(DEREF(innermostSymbol_)) &&
718 !IsPointer(symbol) && !IsIntentIn(symbol) &&
719 !symbol.attrs().test(Attr::VALUE)) {
720 const char *what{InFunction() ? "function" : "subroutine"};
721 bool ok{true};
722 if (IsIntentOut(symbol)) {
723 if (type && type->IsPolymorphic()) { // C1588
724 messages_.Say(
725 "An INTENT(OUT) dummy argument of a pure %s may not be polymorphic"_err_en_US,
726 what);
727 ok = false;
728 } else if (derived) {
729 if (FindUltimateComponent(*derived, [](const Symbol &x) {
730 const DeclTypeSpec *type{x.GetType()};
731 return type && type->IsPolymorphic();
732 })) { // C1588
733 messages_.Say(
734 "An INTENT(OUT) dummy argument of a pure %s may not have a polymorphic ultimate component"_err_en_US,
735 what);
736 ok = false;
737 }
738 if (HasImpureFinal(symbol)) { // C1587
739 messages_.Say(
740 "An INTENT(OUT) dummy argument of a pure %s may not have an impure FINAL subroutine"_err_en_US,
741 what);
742 ok = false;
743 }
744 }
745 } else if (!IsIntentInOut(symbol)) { // C1586
746 messages_.Say(
747 "non-POINTER dummy argument of pure %s must have INTENT() or VALUE attribute"_err_en_US,
748 what);
749 ok = false;
750 }
751 if (ok && InFunction() && !InModuleFile() && !InElemental()) {
752 if (context_.IsEnabled(common::LanguageFeature::RelaxedPureDummy)) {
753 if (context_.ShouldWarn(common::LanguageFeature::RelaxedPureDummy)) {
754 messages_.Say(
755 "non-POINTER dummy argument of pure function should be INTENT(IN) or VALUE"_warn_en_US);
756 }
757 } else {
758 messages_.Say(
759 "non-POINTER dummy argument of pure function must be INTENT(IN) or VALUE"_err_en_US);
760 }
761 }
762 }
763 if (auto ignoreTKR{GetIgnoreTKR(symbol)}; !ignoreTKR.empty()) {
764 const Symbol *ownerSymbol{symbol.owner().symbol()};
765 bool inModuleProc{ownerSymbol && IsModuleProcedure(*ownerSymbol)};
766 bool inExplicitExternalInterface{
767 InInterface() && !IsSeparateModuleProcedureInterface(ownerSymbol)};
768 if (!InInterface() && !inModuleProc) {
769 messages_.Say(
770 "!DIR$ IGNORE_TKR may apply only in an interface or a module procedure"_err_en_US);
771 }
772 if (ownerSymbol && ownerSymbol->attrs().test(Attr::ELEMENTAL) &&
773 details.ignoreTKR().test(common::IgnoreTKR::Rank)) {
774 messages_.Say(
775 "!DIR$ IGNORE_TKR(R) may not apply in an ELEMENTAL procedure"_err_en_US);
776 }
777 if (IsPassedViaDescriptor(symbol)) {
778 if (IsAllocatableOrObjectPointer(&symbol)) {
779 if (inExplicitExternalInterface) {
780 if (context_.ShouldWarn(common::UsageWarning::IgnoreTKRUsage)) {
781 WarnIfNotInModuleFile(
782 "!DIR$ IGNORE_TKR should not apply to an allocatable or pointer"_warn_en_US);
783 }
784 } else {
785 messages_.Say(
786 "!DIR$ IGNORE_TKR may not apply to an allocatable or pointer"_err_en_US);
787 }
788 } else if (ignoreTKR.test(common::IgnoreTKR::Rank)) {
789 if (ignoreTKR.count() == 1 && evaluate::IsAssumedRank(symbol)) {
790 if (context_.ShouldWarn(common::UsageWarning::IgnoreTKRUsage)) {
791 WarnIfNotInModuleFile(
792 "!DIR$ IGNORE_TKR(R) is not meaningful for an assumed-rank array"_warn_en_US);
793 }
794 } else if (inExplicitExternalInterface) {
795 if (context_.ShouldWarn(common::UsageWarning::IgnoreTKRUsage)) {
796 WarnIfNotInModuleFile(
797 "!DIR$ IGNORE_TKR(R) should not apply to a dummy argument passed via descriptor"_warn_en_US);
798 }
799 } else {
800 messages_.Say(
801 "!DIR$ IGNORE_TKR(R) may not apply to a dummy argument passed via descriptor"_err_en_US);
802 }
803 }
804 }
805 }
806 } else if (!details.ignoreTKR().empty()) {
807 messages_.Say(
808 "!DIR$ IGNORE_TKR directive may apply only to a dummy data argument"_err_en_US);
809 }
810 if (InElemental()) {
811 if (details.isDummy()) { // C15100
812 if (details.shape().Rank() > 0) {
813 messages_.Say(
814 "A dummy argument of an ELEMENTAL procedure must be scalar"_err_en_US);
815 }
816 if (IsAllocatable(symbol)) {
817 messages_.Say(
818 "A dummy argument of an ELEMENTAL procedure may not be ALLOCATABLE"_err_en_US);
819 }
820 if (evaluate::IsCoarray(symbol)) {
821 messages_.Say(
822 "A dummy argument of an ELEMENTAL procedure may not be a coarray"_err_en_US);
823 }
824 if (IsPointer(symbol)) {
825 messages_.Say(
826 "A dummy argument of an ELEMENTAL procedure may not be a POINTER"_err_en_US);
827 }
828 if (!symbol.attrs().HasAny(Attrs{Attr::VALUE, Attr::INTENT_IN,
829 Attr::INTENT_INOUT, Attr::INTENT_OUT})) { // F'2023 C15120
830 messages_.Say(
831 "A dummy argument of an ELEMENTAL procedure must have an INTENT() or VALUE attribute"_err_en_US);
832 }
833 } else if (IsFunctionResult(symbol)) { // C15101
834 if (details.shape().Rank() > 0) {
835 messages_.Say(
836 "The result of an ELEMENTAL function must be scalar"_err_en_US);
837 }
838 if (IsAllocatable(symbol)) {
839 messages_.Say(
840 "The result of an ELEMENTAL function may not be ALLOCATABLE"_err_en_US);
841 }
842 if (IsPointer(symbol)) {
843 messages_.Say(
844 "The result of an ELEMENTAL function may not be a POINTER"_err_en_US);
845 }
846 }
847 }
848 if (HasDeclarationInitializer(symbol)) { // C808; ignore DATA initialization
849 CheckPointerInitialization(symbol);
850 if (IsAutomatic(symbol)) {
851 messages_.Say(
852 "An automatic variable or component must not be initialized"_err_en_US);
853 } else if (IsDummy(symbol)) {
854 messages_.Say("A dummy argument must not be initialized"_err_en_US);
855 } else if (IsFunctionResult(symbol)) {
856 messages_.Say("A function result must not be initialized"_err_en_US);
857 } else if (IsInBlankCommon(symbol)) {
858 if (context_.ShouldWarn(common::LanguageFeature::InitBlankCommon)) {
859 WarnIfNotInModuleFile(
860 "A variable in blank COMMON should not be initialized"_port_en_US);
861 }
862 }
863 }
864 if (symbol.owner().kind() == Scope::Kind::BlockData) {
865 if (IsAllocatable(symbol)) {
866 messages_.Say(
867 "An ALLOCATABLE variable may not appear in a BLOCK DATA subprogram"_err_en_US);
868 } else if (IsInitialized(symbol) && !FindCommonBlockContaining(symbol)) {
869 messages_.Say(
870 "An initialized variable in BLOCK DATA must be in a COMMON block"_err_en_US);
871 }
872 }
873 if (derived && InPure() && !InInterface() &&
874 IsAutomaticallyDestroyed(symbol) &&
875 !IsIntentOut(symbol) /*has better messages*/ &&
876 !IsFunctionResult(symbol) /*ditto*/) {
877 // Check automatically deallocated local variables for possible
878 // problems with finalization in PURE.
879 if (auto whyNot{
880 WhyNotDefinable(symbol.name(), symbol.owner(), {}, symbol)}) {
881 if (auto *msg{messages_.Say(
882 "'%s' may not be a local variable in a pure subprogram"_err_en_US,
883 symbol.name())}) {
884 msg->Attach(std::move(whyNot->set_severity(parser::Severity::Because)));
885 }
886 }
887 }
888 if (symbol.attrs().test(Attr::EXTERNAL)) {
889 SayWithDeclaration(symbol,
890 "'%s' is a data object and may not be EXTERNAL"_err_en_US,
891 symbol.name());
892 }
893
894 // Check CUDA attributes and special circumstances of being in device
895 // subprograms
896 const Scope &progUnit{GetProgramUnitContaining(symbol)};
897 const auto *subpDetails{!isComponent && progUnit.symbol()
898 ? progUnit.symbol()->detailsIf<SubprogramDetails>()
899 : nullptr};
900 bool inDeviceSubprogram{IsCUDADeviceContext(&symbol.owner())};
901 if (inDeviceSubprogram) {
902 if (IsSaved(symbol)) {
903 if (context_.ShouldWarn(common::UsageWarning::CUDAUsage)) {
904 WarnIfNotInModuleFile(
905 "'%s' should not have the SAVE attribute or initialization in a device subprogram"_warn_en_US,
906 symbol.name());
907 }
908 }
909 if (IsPointer(symbol)) {
910 if (context_.ShouldWarn(common::UsageWarning::CUDAUsage)) {
911 WarnIfNotInModuleFile(
912 "Pointer '%s' may not be associated in a device subprogram"_warn_en_US,
913 symbol.name());
914 }
915 }
916 if (details.isDummy() &&
917 details.cudaDataAttr().value_or(common::CUDADataAttr::Device) !=
918 common::CUDADataAttr::Device &&
919 details.cudaDataAttr().value_or(common::CUDADataAttr::Device) !=
920 common::CUDADataAttr::Managed) {
921 if (context_.ShouldWarn(common::UsageWarning::CUDAUsage)) {
922 WarnIfNotInModuleFile(
923 "Dummy argument '%s' may not have ATTRIBUTES(%s) in a device subprogram"_warn_en_US,
924 symbol.name(),
925 parser::ToUpperCaseLetters(
926 common::EnumToString(*details.cudaDataAttr())));
927 }
928 }
929 }
930 if (details.cudaDataAttr()) {
931 if (auto dyType{evaluate::DynamicType::From(symbol)}) {
932 if (dyType->category() != TypeCategory::Derived) {
933 if (!IsCUDAIntrinsicType(*dyType)) {
934 messages_.Say(
935 "'%s' has intrinsic type '%s' that is not available on the device"_err_en_US,
936 symbol.name(), dyType->AsFortran());
937 }
938 }
939 }
940 auto attr{*details.cudaDataAttr()};
941 switch (attr) {
942 case common::CUDADataAttr::Constant:
943 if (subpDetails && !inDeviceSubprogram) {
944 messages_.Say(
945 "Object '%s' with ATTRIBUTES(CONSTANT) may not be declared in a host subprogram"_err_en_US,
946 symbol.name());
947 } else if (IsAllocatableOrPointer(symbol) ||
948 symbol.attrs().test(Attr::TARGET)) {
949 messages_.Say(
950 "Object '%s' with ATTRIBUTES(CONSTANT) may not be allocatable, pointer, or target"_err_en_US,
951 symbol.name());
952 } else if (auto shape{evaluate::GetShape(foldingContext_, symbol)};
953 !shape ||
954 !evaluate::AsConstantExtents(foldingContext_, *shape)) {
955 messages_.Say(
956 "Object '%s' with ATTRIBUTES(CONSTANT) must have constant array bounds"_err_en_US,
957 symbol.name());
958 }
959 break;
960 case common::CUDADataAttr::Device:
961 if (isComponent && !IsAllocatable(symbol)) {
962 messages_.Say(
963 "Component '%s' with ATTRIBUTES(DEVICE) must also be allocatable"_err_en_US,
964 symbol.name());
965 }
966 break;
967 case common::CUDADataAttr::Managed:
968 if (!IsAutomatic(symbol) && !IsAllocatable(symbol) &&
969 !details.isDummy() && !evaluate::IsExplicitShape(symbol)) {
970 messages_.Say(
971 "Object '%s' with ATTRIBUTES(MANAGED) must also be allocatable, automatic, explicit shape, or a dummy argument"_err_en_US,
972 symbol.name());
973 }
974 break;
975 case common::CUDADataAttr::Pinned:
976 if (inDeviceSubprogram) {
977 if (context_.ShouldWarn(common::UsageWarning::CUDAUsage)) {
978 WarnIfNotInModuleFile(
979 "Object '%s' with ATTRIBUTES(PINNED) may not be declared in a device subprogram"_warn_en_US,
980 symbol.name());
981 }
982 } else if (IsPointer(symbol)) {
983 if (context_.ShouldWarn(common::UsageWarning::CUDAUsage)) {
984 WarnIfNotInModuleFile(
985 "Object '%s' with ATTRIBUTES(PINNED) may not be a pointer"_warn_en_US,
986 symbol.name());
987 }
988 } else if (!IsAllocatable(symbol)) {
989 if (context_.ShouldWarn(common::UsageWarning::CUDAUsage)) {
990 WarnIfNotInModuleFile(
991 "Object '%s' with ATTRIBUTES(PINNED) should also be allocatable"_warn_en_US,
992 symbol.name());
993 }
994 }
995 break;
996 case common::CUDADataAttr::Shared:
997 if (IsAllocatableOrPointer(symbol) || symbol.attrs().test(Attr::TARGET)) {
998 messages_.Say(
999 "Object '%s' with ATTRIBUTES(SHARED) may not be allocatable, pointer, or target"_err_en_US,
1000 symbol.name());
1001 } else if (!inDeviceSubprogram) {
1002 messages_.Say(
1003 "Object '%s' with ATTRIBUTES(SHARED) must be declared in a device subprogram"_err_en_US,
1004 symbol.name());
1005 }
1006 break;
1007 case common::CUDADataAttr::Unified:
1008 if (((!subpDetails &&
1009 symbol.owner().kind() != Scope::Kind::MainProgram) ||
1010 inDeviceSubprogram) &&
1011 !isComponent) {
1012 messages_.Say(
1013 "Object '%s' with ATTRIBUTES(UNIFIED) must be declared in a host subprogram"_err_en_US,
1014 symbol.name());
1015 }
1016 break;
1017 case common::CUDADataAttr::Texture:
1018 messages_.Say(
1019 "ATTRIBUTES(TEXTURE) is obsolete and no longer supported"_err_en_US);
1020 break;
1021 }
1022 if (attr != common::CUDADataAttr::Pinned) {
1023 if (details.commonBlock()) {
1024 messages_.Say(
1025 "Object '%s' with ATTRIBUTES(%s) may not be in COMMON"_err_en_US,
1026 symbol.name(),
1027 parser::ToUpperCaseLetters(common::EnumToString(attr)));
1028 } else if (FindEquivalenceSet(symbol)) {
1029 messages_.Say(
1030 "Object '%s' with ATTRIBUTES(%s) may not be in an equivalence group"_err_en_US,
1031 symbol.name(),
1032 parser::ToUpperCaseLetters(common::EnumToString(attr)));
1033 }
1034 }
1035 if (subpDetails /* not a module variable */ && IsSaved(symbol) &&
1036 !inDeviceSubprogram && !IsAllocatable(symbol) &&
1037 attr == common::CUDADataAttr::Device) {
1038 messages_.Say(
1039 "Saved object '%s' in host code may not have ATTRIBUTES(DEVICE) unless allocatable"_err_en_US,
1040 symbol.name(),
1041 parser::ToUpperCaseLetters(common::EnumToString(attr)));
1042 }
1043 if (isComponent) {
1044 if (attr == common::CUDADataAttr::Device) {
1045 const DeclTypeSpec *type{symbol.GetType()};
1046 if (const DerivedTypeSpec *
1047 derived{type ? type->AsDerived() : nullptr}) {
1048 DirectComponentIterator directs{*derived};
1049 if (auto iter{std::find_if(directs.begin(), directs.end(),
1050 [](const Symbol &) { return false; })}) {
1051 messages_.Say(
1052 "Derived type component '%s' may not have ATTRIBUTES(DEVICE) as it has a direct device component '%s'"_err_en_US,
1053 symbol.name(), iter.BuildResultDesignatorName());
1054 }
1055 }
1056 } else if (attr == common::CUDADataAttr::Constant ||
1057 attr == common::CUDADataAttr::Shared) {
1058 messages_.Say(
1059 "Derived type component '%s' may not have ATTRIBUTES(%s)"_err_en_US,
1060 symbol.name(),
1061 parser::ToUpperCaseLetters(common::EnumToString(attr)));
1062 }
1063 } else if (!subpDetails && symbol.owner().kind() != Scope::Kind::Module &&
1064 symbol.owner().kind() != Scope::Kind::MainProgram &&
1065 symbol.owner().kind() != Scope::Kind::BlockConstruct) {
1066 messages_.Say(
1067 "ATTRIBUTES(%s) may apply only to module, host subprogram, block, or device subprogram data"_err_en_US,
1068 parser::ToUpperCaseLetters(common::EnumToString(attr)));
1069 }
1070 }
1071
1072 if (derived && derived->IsVectorType()) {
1073 CHECK(type);
1074 std::string typeName{type->AsFortran()};
1075 if (IsAssumedShape(symbol)) {
1076 SayWithDeclaration(symbol,
1077 "Assumed-shape entity of %s type is not supported"_err_en_US,
1078 typeName);
1079 } else if (IsDeferredShape(symbol)) {
1080 SayWithDeclaration(symbol,
1081 "Deferred-shape entity of %s type is not supported"_err_en_US,
1082 typeName);
1083 } else if (evaluate::IsAssumedRank(symbol)) {
1084 SayWithDeclaration(symbol,
1085 "Assumed Rank entity of %s type is not supported"_err_en_US,
1086 typeName);
1087 }
1088 }
1089 }
1090
1091 void CheckHelper::CheckPointerInitialization(const Symbol &symbol) {
1092 if (IsPointer(symbol) && !context_.HasError(symbol) &&
1093 !scopeIsUninstantiatedPDT_) {
1094 if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
1095 if (object->init()) { // C764, C765; C808
1096 if (auto designator{evaluate::AsGenericExpr(symbol)}) {
1097 auto restorer{messages_.SetLocation(symbol.name())};
1098 context_.set_location(symbol.name());
1099 CheckInitialDataPointerTarget(
1100 context_, *designator, *object->init(), DEREF(scope_));
1101 }
1102 }
1103 } else if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}) {
1104 if (proc->init() && *proc->init()) {
1105 // C1519 - must be nonelemental external or module procedure,
1106 // or an unrestricted specific intrinsic function.
1107 const Symbol &ultimate{(*proc->init())->GetUltimate()};
1108 bool checkTarget{true};
1109 if (ultimate.attrs().test(Attr::INTRINSIC)) {
1110 if (auto intrinsic{context_.intrinsics().IsSpecificIntrinsicFunction(
1111 ultimate.name().ToString())};
1112 !intrinsic || intrinsic->isRestrictedSpecific) { // C1030
1113 context_.Say(
1114 "Intrinsic procedure '%s' is not an unrestricted specific "
1115 "intrinsic permitted for use as the initializer for procedure "
1116 "pointer '%s'"_err_en_US,
1117 ultimate.name(), symbol.name());
1118 checkTarget = false;
1119 }
1120 } else if ((!ultimate.attrs().test(Attr::EXTERNAL) &&
1121 ultimate.owner().kind() != Scope::Kind::Module) ||
1122 IsDummy(ultimate) || IsPointer(ultimate)) {
1123 context_.Say("Procedure pointer '%s' initializer '%s' is neither "
1124 "an external nor a module procedure"_err_en_US,
1125 symbol.name(), ultimate.name());
1126 checkTarget = false;
1127 } else if (IsElementalProcedure(ultimate)) {
1128 context_.Say("Procedure pointer '%s' cannot be initialized with the "
1129 "elemental procedure '%s'"_err_en_US,
1130 symbol.name(), ultimate.name());
1131 checkTarget = false;
1132 }
1133 if (checkTarget) {
1134 SomeExpr lhs{evaluate::ProcedureDesignator{symbol}};
1135 SomeExpr rhs{evaluate::ProcedureDesignator{**proc->init()}};
1136 CheckPointerAssignment(context_, lhs, rhs,
1137 GetProgramUnitOrBlockConstructContaining(symbol),
1138 /*isBoundsRemapping=*/false, /*isAssumedRank=*/false);
1139 }
1140 }
1141 }
1142 }
1143 }
1144
1145 // The six different kinds of array-specs:
1146 // array-spec -> explicit-shape-list | deferred-shape-list
1147 // | assumed-shape-list | implied-shape-list
1148 // | assumed-size | assumed-rank
1149 // explicit-shape -> [ lb : ] ub
1150 // deferred-shape -> :
1151 // assumed-shape -> [ lb ] :
1152 // implied-shape -> [ lb : ] *
1153 // assumed-size -> [ explicit-shape-list , ] [ lb : ] *
1154 // assumed-rank -> ..
1155 // Note:
1156 // - deferred-shape is also an assumed-shape
1157 // - A single "*" or "lb:*" might be assumed-size or implied-shape-list
1158 void CheckHelper::CheckArraySpec(
1159 const Symbol &symbol, const ArraySpec &arraySpec) {
1160 if (arraySpec.Rank() == 0) {
1161 return;
1162 }
1163 bool isExplicit{arraySpec.IsExplicitShape()};
1164 bool canBeDeferred{arraySpec.CanBeDeferredShape()};
1165 bool canBeImplied{arraySpec.CanBeImpliedShape()};
1166 bool canBeAssumedShape{arraySpec.CanBeAssumedShape()};
1167 bool canBeAssumedSize{arraySpec.CanBeAssumedSize()};
1168 bool isAssumedRank{arraySpec.IsAssumedRank()};
1169 bool isCUDAShared{
1170 GetCUDADataAttr(&symbol).value_or(common::CUDADataAttr::Device) ==
1171 common::CUDADataAttr::Shared};
1172 bool isCrayPointee{symbol.test(Symbol::Flag::CrayPointee)};
1173 std::optional<parser::MessageFixedText> msg;
1174 if (isCrayPointee && !isExplicit && !canBeAssumedSize) {
1175 msg =
1176 "Cray pointee '%s' must have explicit shape or assumed size"_err_en_US;
1177 } else if (IsAllocatableOrPointer(symbol) && !canBeDeferred &&
1178 !isAssumedRank) {
1179 if (symbol.owner().IsDerivedType()) { // C745
1180 if (IsAllocatable(symbol)) {
1181 msg = "Allocatable array component '%s' must have"
1182 " deferred shape"_err_en_US;
1183 } else {
1184 msg = "Array pointer component '%s' must have deferred shape"_err_en_US;
1185 }
1186 } else {
1187 if (IsAllocatable(symbol)) { // C832
1188 msg = "Allocatable array '%s' must have deferred shape or"
1189 " assumed rank"_err_en_US;
1190 } else {
1191 msg = "Array pointer '%s' must have deferred shape or"
1192 " assumed rank"_err_en_US;
1193 }
1194 }
1195 } else if (IsDummy(symbol)) {
1196 if (canBeImplied && !canBeAssumedSize) { // C836
1197 msg = "Dummy array argument '%s' may not have implied shape"_err_en_US;
1198 }
1199 } else if (canBeAssumedShape && !canBeDeferred) {
1200 msg = "Assumed-shape array '%s' must be a dummy argument"_err_en_US;
1201 } else if (isAssumedRank) { // C837
1202 msg = "Assumed-rank array '%s' must be a dummy argument"_err_en_US;
1203 } else if (canBeAssumedSize && !canBeImplied && !isCUDAShared &&
1204 !isCrayPointee) { // C833
1205 msg = "Assumed-size array '%s' must be a dummy argument"_err_en_US;
1206 } else if (canBeImplied) {
1207 if (!IsNamedConstant(symbol) && !isCUDAShared &&
1208 !isCrayPointee) { // C835, C836
1209 msg = "Implied-shape array '%s' must be a named constant or a "
1210 "dummy argument"_err_en_US;
1211 }
1212 } else if (IsNamedConstant(symbol)) {
1213 if (!isExplicit && !canBeImplied) {
1214 msg = "Named constant '%s' array must have constant or"
1215 " implied shape"_err_en_US;
1216 }
1217 } else if (!isExplicit &&
1218 !(IsAllocatableOrPointer(symbol) || isCrayPointee)) {
1219 if (symbol.owner().IsDerivedType()) { // C749
1220 msg = "Component array '%s' without ALLOCATABLE or POINTER attribute must"
1221 " have explicit shape"_err_en_US;
1222 } else { // C816
1223 msg = "Array '%s' without ALLOCATABLE or POINTER attribute must have"
1224 " explicit shape"_err_en_US;
1225 }
1226 }
1227 if (msg) {
1228 context_.Say(std::move(*msg), symbol.name());
1229 }
1230 }
1231
1232 void CheckHelper::CheckProcEntity(
1233 const Symbol &symbol, const ProcEntityDetails &details) {
1234 CheckSymbolType(symbol);
1235 const Symbol *interface{details.procInterface()};
1236 if (details.isDummy()) {
1237 if (!symbol.attrs().test(Attr::POINTER) && // C843
1238 symbol.attrs().HasAny(
1239 {Attr::INTENT_IN, Attr::INTENT_OUT, Attr::INTENT_INOUT})) {
1240 messages_.Say("A dummy procedure without the POINTER attribute"
1241 " may not have an INTENT attribute"_err_en_US);
1242 }
1243 if (InElemental()) { // C15100
1244 messages_.Say(
1245 "An ELEMENTAL subprogram may not have a dummy procedure"_err_en_US);
1246 }
1247 if (interface && IsElementalProcedure(*interface)) {
1248 // There's no explicit constraint or "shall" that we can find in the
1249 // standard for this check, but it seems to be implied in multiple
1250 // sites, and ELEMENTAL non-intrinsic actual arguments *are*
1251 // explicitly forbidden. But we allow "PROCEDURE(SIN)::dummy"
1252 // because it is explicitly legal to *pass* the specific intrinsic
1253 // function SIN as an actual argument.
1254 if (interface->attrs().test(Attr::INTRINSIC)) {
1255 if (context_.ShouldWarn(common::UsageWarning::Portability)) {
1256 messages_.Say(
1257 "A dummy procedure should not have an ELEMENTAL intrinsic as its interface"_port_en_US);
1258 }
1259 } else {
1260 messages_.Say("A dummy procedure may not be ELEMENTAL"_err_en_US);
1261 }
1262 }
1263 } else if (IsPointer(symbol)) {
1264 CheckPointerInitialization(symbol);
1265 if (interface) {
1266 if (interface->attrs().test(Attr::INTRINSIC)) {
1267 auto intrinsic{context_.intrinsics().IsSpecificIntrinsicFunction(
1268 interface->name().ToString())};
1269 if (!intrinsic || intrinsic->isRestrictedSpecific) { // C1515
1270 messages_.Say(
1271 "Intrinsic procedure '%s' is not an unrestricted specific "
1272 "intrinsic permitted for use as the definition of the interface "
1273 "to procedure pointer '%s'"_err_en_US,
1274 interface->name(), symbol.name());
1275 } else if (IsElementalProcedure(*interface)) {
1276 if (context_.ShouldWarn(common::UsageWarning::Portability)) {
1277 messages_.Say(
1278 "Procedure pointer '%s' should not have an ELEMENTAL intrinsic as its interface"_port_en_US,
1279 symbol.name()); // C1517
1280 }
1281 }
1282 } else if (IsElementalProcedure(*interface)) {
1283 messages_.Say("Procedure pointer '%s' may not be ELEMENTAL"_err_en_US,
1284 symbol.name()); // C1517
1285 }
1286 }
1287 if (symbol.owner().IsDerivedType()) {
1288 CheckPassArg(symbol, interface, details);
1289 }
1290 } else if (symbol.owner().IsDerivedType()) {
1291 const auto &name{symbol.name()};
1292 messages_.Say(name,
1293 "Procedure component '%s' must have POINTER attribute"_err_en_US, name);
1294 }
1295 CheckExternal(symbol);
1296 }
1297
1298 // When a module subprogram has the MODULE prefix the following must match
1299 // with the corresponding separate module procedure interface body:
1300 // - C1549: characteristics and dummy argument names
1301 // - C1550: binding label
1302 // - C1551: NON_RECURSIVE prefix
1303 class SubprogramMatchHelper {
1304 public:
1305 explicit SubprogramMatchHelper(CheckHelper &checkHelper)
1306 : checkHelper{checkHelper} {}
1307
1308 void Check(const Symbol &, const Symbol &);
1309
1310 private:
1311 SemanticsContext &context() { return checkHelper.context(); }
1312 void CheckDummyArg(const Symbol &, const Symbol &, const DummyArgument &,
1313 const DummyArgument &);
1314 void CheckDummyDataObject(const Symbol &, const Symbol &,
1315 const DummyDataObject &, const DummyDataObject &);
1316 void CheckDummyProcedure(const Symbol &, const Symbol &,
1317 const DummyProcedure &, const DummyProcedure &);
1318 bool CheckSameIntent(
1319 const Symbol &, const Symbol &, common::Intent, common::Intent);
1320 template <typename... A>
1321 void Say(
1322 const Symbol &, const Symbol &, parser::MessageFixedText &&, A &&...);
1323 template <typename ATTRS>
1324 bool CheckSameAttrs(const Symbol &, const Symbol &, ATTRS, ATTRS);
1325 bool ShapesAreCompatible(const DummyDataObject &, const DummyDataObject &);
1326 evaluate::Shape FoldShape(const evaluate::Shape &);
1327 std::optional<evaluate::Shape> FoldShape(
1328 const std::optional<evaluate::Shape> &shape) {
1329 if (shape) {
1330 return FoldShape(*shape);
1331 }
1332 return std::nullopt;
1333 }
1334 std::string AsFortran(DummyDataObject::Attr attr) {
1335 return parser::ToUpperCaseLetters(DummyDataObject::EnumToString(attr));
1336 }
1337 std::string AsFortran(DummyProcedure::Attr attr) {
1338 return parser::ToUpperCaseLetters(DummyProcedure::EnumToString(attr));
1339 }
1340
1341 CheckHelper &checkHelper;
1342 };
1343
1344 // 15.6.2.6 para 3 - can the result of an ENTRY differ from its function?
1345 bool CheckHelper::IsResultOkToDiffer(const FunctionResult &result) {
1346 if (result.attrs.test(FunctionResult::Attr::Allocatable) ||
1347 result.attrs.test(FunctionResult::Attr::Pointer)) {
1348 return false;
1349 }
1350 const auto *typeAndShape{result.GetTypeAndShape()};
1351 if (!typeAndShape || typeAndShape->Rank() != 0) {
1352 return false;
1353 }
1354 auto category{typeAndShape->type().category()};
1355 if (category == TypeCategory::Character ||
1356 category == TypeCategory::Derived) {
1357 return false;
1358 }
1359 int kind{typeAndShape->type().kind()};
1360 return kind == context_.GetDefaultKind(category) ||
1361 (category == TypeCategory::Real &&
1362 kind == context_.doublePrecisionKind());
1363 }
1364
1365 void CheckHelper::CheckSubprogram(
1366 const Symbol &symbol, const SubprogramDetails &details) {
1367 // Evaluate a procedure definition's characteristics to flush out
1368 // any errors that analysis might expose, in case this subprogram hasn't
1369 // had any calls in this compilation unit that would have validated them.
1370 if (!context_.HasError(symbol) && !details.isDummy() &&
1371 !details.isInterface() && !details.stmtFunction()) {
1372 if (!Procedure::Characterize(symbol, foldingContext_)) {
1373 context_.SetError(symbol);
1374 }
1375 }
1376 if (const Symbol *iface{FindSeparateModuleSubprogramInterface(&symbol)}) {
1377 SubprogramMatchHelper{*this}.Check(symbol, *iface);
1378 }
1379 if (const Scope *entryScope{details.entryScope()}) {
1380 // ENTRY F'2023 15.6.2.6
1381 std::optional<parser::MessageFixedText> error;
1382 const Symbol *subprogram{entryScope->symbol()};
1383 const SubprogramDetails *subprogramDetails{nullptr};
1384 if (subprogram) {
1385 subprogramDetails = subprogram->detailsIf<SubprogramDetails>();
1386 }
1387 if (!(entryScope->parent().IsGlobal() || entryScope->parent().IsModule() ||
1388 entryScope->parent().IsSubmodule())) {
1389 error = "ENTRY may not appear in an internal subprogram"_err_en_US;
1390 } else if (subprogramDetails && details.isFunction() &&
1391 subprogramDetails->isFunction() &&
1392 !context_.HasError(details.result()) &&
1393 !context_.HasError(subprogramDetails->result())) {
1394 auto result{FunctionResult::Characterize(
1395 details.result(), context_.foldingContext())};
1396 auto subpResult{FunctionResult::Characterize(
1397 subprogramDetails->result(), context_.foldingContext())};
1398 if (result && subpResult && *result != *subpResult &&
1399 (!IsResultOkToDiffer(*result) || !IsResultOkToDiffer(*subpResult))) {
1400 error =
1401 "Result of ENTRY is not compatible with result of containing function"_err_en_US;
1402 }
1403 }
1404 if (error) {
1405 if (auto *msg{messages_.Say(symbol.name(), *error)}) {
1406 if (subprogram) {
1407 msg->Attach(subprogram->name(), "Containing subprogram"_en_US);
1408 }
1409 }
1410 }
1411 }
1412 if (details.isFunction() &&
1413 details.result().name() != symbol.name()) { // F'2023 C1569 & C1583
1414 if (auto iter{symbol.owner().find(details.result().name())};
1415 iter != symbol.owner().end()) {
1416 const Symbol &resNameSym{*iter->second};
1417 if (const auto *resNameSubp{resNameSym.detailsIf<SubprogramDetails>()}) {
1418 if (const Scope * resNameEntryScope{resNameSubp->entryScope()}) {
1419 const Scope *myScope{
1420 details.entryScope() ? details.entryScope() : symbol.scope()};
1421 if (resNameEntryScope == myScope) {
1422 if (auto *msg{messages_.Say(symbol.name(),
1423 "Explicit RESULT('%s') of function '%s' cannot have the same name as a distinct ENTRY into the same scope"_err_en_US,
1424 details.result().name(), symbol.name())}) {
1425 msg->Attach(
1426 resNameSym.name(), "ENTRY with conflicting name"_en_US);
1427 }
1428 }
1429 }
1430 }
1431 }
1432 }
1433 if (const MaybeExpr & stmtFunction{details.stmtFunction()}) {
1434 if (auto msg{evaluate::CheckStatementFunction(
1435 symbol, *stmtFunction, context_.foldingContext())}) {
1436 SayWithDeclaration(symbol, std::move(*msg));
1437 } else if (IsPointer(symbol)) {
1438 SayWithDeclaration(symbol,
1439 "A statement function must not have the POINTER attribute"_err_en_US);
1440 } else if (details.result().flags().test(Symbol::Flag::Implicit)) {
1441 // 15.6.4 p2 weird requirement
1442 if (const Symbol *
1443 host{symbol.owner().parent().FindSymbol(symbol.name())}) {
1444 if (context_.ShouldWarn(
1445 common::LanguageFeature::StatementFunctionExtensions)) {
1446 evaluate::AttachDeclaration(
1447 messages_.Say(symbol.name(),
1448 "An implicitly typed statement function should not appear when the same symbol is available in its host scope"_port_en_US),
1449 *host);
1450 }
1451 }
1452 }
1453 if (GetProgramUnitOrBlockConstructContaining(symbol).kind() ==
1454 Scope::Kind::BlockConstruct) { // C1107
1455 messages_.Say(symbol.name(),
1456 "A statement function definition may not appear in a BLOCK construct"_err_en_US);
1457 }
1458 }
1459 if (IsElementalProcedure(symbol)) {
1460 // See comment on the similar check in CheckProcEntity()
1461 if (details.isDummy()) {
1462 messages_.Say("A dummy procedure may not be ELEMENTAL"_err_en_US);
1463 } else {
1464 for (const Symbol *dummy : details.dummyArgs()) {
1465 if (!dummy) { // C15100
1466 messages_.Say(
1467 "An ELEMENTAL subroutine may not have an alternate return dummy argument"_err_en_US);
1468 }
1469 }
1470 }
1471 }
1472 if (details.isInterface()) {
1473 if (!details.isDummy() && details.isFunction() &&
1474 IsAssumedLengthCharacter(details.result())) { // C721
1475 messages_.Say(details.result().name(),
1476 "A function interface may not declare an assumed-length CHARACTER(*) result"_err_en_US);
1477 }
1478 }
1479 CheckExternal(symbol);
1480 CheckModuleProcedureDef(symbol);
1481 auto cudaAttrs{details.cudaSubprogramAttrs()};
1482 if (cudaAttrs &&
1483 (*cudaAttrs == common::CUDASubprogramAttrs::Global ||
1484 *cudaAttrs == common::CUDASubprogramAttrs::Grid_Global) &&
1485 details.isFunction()) {
1486 messages_.Say(symbol.name(),
1487 "A function may not have ATTRIBUTES(GLOBAL) or ATTRIBUTES(GRID_GLOBAL)"_err_en_US);
1488 }
1489 if (cudaAttrs &&
1490 (*cudaAttrs == common::CUDASubprogramAttrs::Global ||
1491 *cudaAttrs == common::CUDASubprogramAttrs::Grid_Global) &&
1492 symbol.attrs().HasAny({Attr::RECURSIVE, Attr::PURE, Attr::ELEMENTAL})) {
1493 messages_.Say(symbol.name(),
1494 "A kernel subprogram may not be RECURSIVE, PURE, or ELEMENTAL"_err_en_US);
1495 }
1496 if (cudaAttrs && *cudaAttrs != common::CUDASubprogramAttrs::Host) {
1497 // CUDA device subprogram checks
1498 if (ClassifyProcedure(symbol) == ProcedureDefinitionClass::Internal) {
1499 messages_.Say(symbol.name(),
1500 "A device subprogram may not be an internal subprogram"_err_en_US);
1501 }
1502 }
1503 if ((!details.cudaLaunchBounds().empty() ||
1504 !details.cudaClusterDims().empty()) &&
1505 !(cudaAttrs &&
1506 (*cudaAttrs == common::CUDASubprogramAttrs::Global ||
1507 *cudaAttrs == common::CUDASubprogramAttrs::Grid_Global))) {
1508 messages_.Say(symbol.name(),
1509 "A subroutine may not have LAUNCH_BOUNDS() or CLUSTER_DIMS() unless it has ATTRIBUTES(GLOBAL) or ATTRIBUTES(GRID_GLOBAL)"_err_en_US);
1510 }
1511 if (!IsStmtFunction(symbol)) {
1512 if (const Scope * outerDevice{FindCUDADeviceContext(&symbol.owner())};
1513 outerDevice && outerDevice->symbol()) {
1514 if (auto *msg{messages_.Say(symbol.name(),
1515 "'%s' may not be an internal procedure of CUDA device subprogram '%s'"_err_en_US,
1516 symbol.name(), outerDevice->symbol()->name())}) {
1517 msg->Attach(outerDevice->symbol()->name(),
1518 "Containing CUDA device subprogram"_en_US);
1519 }
1520 }
1521 }
1522 }
1523
1524 void CheckHelper::CheckExternal(const Symbol &symbol) {
1525 if (IsExternal(symbol)) {
1526 std::string interfaceName{symbol.name().ToString()};
1527 if (const auto *bind{symbol.GetBindName()}) {
1528 interfaceName = *bind;
1529 }
1530 if (const Symbol * global{FindGlobal(symbol)};
1531 global && global != &symbol) {
1532 std::string definitionName{global->name().ToString()};
1533 if (const auto *bind{global->GetBindName()}) {
1534 definitionName = *bind;
1535 }
1536 if (interfaceName == definitionName) {
1537 parser::Message *msg{nullptr};
1538 if (!IsProcedure(*global)) {
1539 if ((symbol.flags().test(Symbol::Flag::Function) ||
1540 symbol.flags().test(Symbol::Flag::Subroutine)) &&
1541 context_.ShouldWarn(common::UsageWarning::ExternalNameConflict)) {
1542 msg = WarnIfNotInModuleFile(
1543 "The global entity '%s' corresponding to the local procedure '%s' is not a callable subprogram"_warn_en_US,
1544 global->name(), symbol.name());
1545 }
1546 } else if (auto chars{Characterize(symbol)}) {
1547 if (auto globalChars{Characterize(*global)}) {
1548 if (chars->HasExplicitInterface()) {
1549 std::string whyNot;
1550 if (!chars->IsCompatibleWith(*globalChars,
1551 /*ignoreImplicitVsExplicit=*/false, &whyNot) &&
1552 context_.ShouldWarn(
1553 common::UsageWarning::ExternalInterfaceMismatch)) {
1554 msg = WarnIfNotInModuleFile(
1555 "The global subprogram '%s' is not compatible with its local procedure declaration (%s)"_warn_en_US,
1556 global->name(), whyNot);
1557 }
1558 } else if (!globalChars->CanBeCalledViaImplicitInterface() &&
1559 context_.ShouldWarn(
1560 common::UsageWarning::ExternalInterfaceMismatch)) {
1561 msg = messages_.Say(
1562 "The global subprogram '%s' may not be referenced via the implicit interface '%s'"_err_en_US,
1563 global->name(), symbol.name());
1564 }
1565 }
1566 }
1567 if (msg) {
1568 if (msg->IsFatal()) {
1569 context_.SetError(symbol);
1570 }
1571 evaluate::AttachDeclaration(msg, *global);
1572 evaluate::AttachDeclaration(msg, symbol);
1573 }
1574 }
1575 } else if (auto iter{externalNames_.find(interfaceName)};
1576 iter != externalNames_.end()) {
1577 const Symbol &previous{*iter->second};
1578 if (auto chars{Characterize(symbol)}) {
1579 if (auto previousChars{Characterize(previous)}) {
1580 std::string whyNot;
1581 if (!chars->IsCompatibleWith(*previousChars,
1582 /*ignoreImplicitVsExplicit=*/false, &whyNot) &&
1583 context_.ShouldWarn(
1584 common::UsageWarning::ExternalInterfaceMismatch)) {
1585 if (auto *msg{WarnIfNotInModuleFile(
1586 "The external interface '%s' is not compatible with an earlier definition (%s)"_warn_en_US,
1587 symbol.name(), whyNot)}) {
1588 evaluate::AttachDeclaration(msg, previous);
1589 evaluate::AttachDeclaration(msg, symbol);
1590 }
1591 }
1592 }
1593 }
1594 } else {
1595 externalNames_.emplace(interfaceName, symbol);
1596 }
1597 }
1598 }
1599
1600 void CheckHelper::CheckDerivedType(
1601 const Symbol &derivedType, const DerivedTypeDetails &details) {
1602 if (details.isForwardReferenced() && !context_.HasError(derivedType)) {
1603 messages_.Say("The derived type '%s' has not been defined"_err_en_US,
1604 derivedType.name());
1605 }
1606 const Scope *scope{derivedType.scope()};
1607 if (!scope) {
1608 CHECK(details.isForwardReferenced());
1609 return;
1610 }
1611 CHECK(scope->symbol() == &derivedType);
1612 CHECK(scope->IsDerivedType());
1613 if (derivedType.attrs().test(Attr::ABSTRACT) && // C734
1614 (derivedType.attrs().test(Attr::BIND_C) || details.sequence())) {
1615 messages_.Say("An ABSTRACT derived type must be extensible"_err_en_US);
1616 }
1617 if (const DeclTypeSpec *parent{FindParentTypeSpec(derivedType)}) {
1618 const DerivedTypeSpec *parentDerived{parent->AsDerived()};
1619 if (!IsExtensibleType(parentDerived)) { // C705
1620 messages_.Say("The parent type is not extensible"_err_en_US);
1621 }
1622 if (!derivedType.attrs().test(Attr::ABSTRACT) && parentDerived &&
1623 parentDerived->typeSymbol().attrs().test(Attr::ABSTRACT)) {
1624 ScopeComponentIterator components{*parentDerived};
1625 for (const Symbol &component : components) {
1626 if (component.attrs().test(Attr::DEFERRED)) {
1627 if (scope->FindComponent(component.name()) == &component) {
1628 SayWithDeclaration(component,
1629 "Non-ABSTRACT extension of ABSTRACT derived type '%s' lacks a binding for DEFERRED procedure '%s'"_err_en_US,
1630 parentDerived->typeSymbol().name(), component.name());
1631 }
1632 }
1633 }
1634 }
1635 DerivedTypeSpec derived{derivedType.name(), derivedType};
1636 derived.set_scope(*scope);
1637 if (FindCoarrayUltimateComponent(derived) && // C736
1638 !(parentDerived && FindCoarrayUltimateComponent(*parentDerived))) {
1639 messages_.Say(
1640 "Type '%s' has a coarray ultimate component so the type at the base "
1641 "of its type extension chain ('%s') must be a type that has a "
1642 "coarray ultimate component"_err_en_US,
1643 derivedType.name(), scope->GetDerivedTypeBase().GetSymbol()->name());
1644 }
1645 if (FindEventOrLockPotentialComponent(derived) && // C737
1646 !(FindEventOrLockPotentialComponent(*parentDerived) ||
1647 IsEventTypeOrLockType(parentDerived))) {
1648 messages_.Say(
1649 "Type '%s' has an EVENT_TYPE or LOCK_TYPE component, so the type "
1650 "at the base of its type extension chain ('%s') must either have an "
1651 "EVENT_TYPE or LOCK_TYPE component, or be EVENT_TYPE or "
1652 "LOCK_TYPE"_err_en_US,
1653 derivedType.name(), scope->GetDerivedTypeBase().GetSymbol()->name());
1654 }
1655 }
1656 if (HasIntrinsicTypeName(derivedType)) { // C729
1657 messages_.Say("A derived type name cannot be the name of an intrinsic"
1658 " type"_err_en_US);
1659 }
1660 std::map<SourceName, SymbolRef> previous;
1661 for (const auto &pair : details.finals()) {
1662 SourceName source{pair.first};
1663 const Symbol &ref{*pair.second};
1664 if (CheckFinal(ref, source, derivedType) &&
1665 std::all_of(previous.begin(), previous.end(),
1666 [&](std::pair<SourceName, SymbolRef> prev) {
1667 return CheckDistinguishableFinals(
1668 ref, source, *prev.second, prev.first, derivedType);
1669 })) {
1670 previous.emplace(source, ref);
1671 }
1672 }
1673 }
1674
1675 // C786
1676 bool CheckHelper::CheckFinal(
1677 const Symbol &subroutine, SourceName finalName, const Symbol &derivedType) {
1678 if (!IsModuleProcedure(subroutine)) {
1679 SayWithDeclaration(subroutine, finalName,
1680 "FINAL subroutine '%s' of derived type '%s' must be a module procedure"_err_en_US,
1681 subroutine.name(), derivedType.name());
1682 return false;
1683 }
1684 const Procedure *proc{Characterize(subroutine)};
1685 if (!proc) {
1686 return false; // error recovery
1687 }
1688 if (!proc->IsSubroutine()) {
1689 SayWithDeclaration(subroutine, finalName,
1690 "FINAL subroutine '%s' of derived type '%s' must be a subroutine"_err_en_US,
1691 subroutine.name(), derivedType.name());
1692 return false;
1693 }
1694 if (proc->dummyArguments.size() != 1) {
1695 SayWithDeclaration(subroutine, finalName,
1696 "FINAL subroutine '%s' of derived type '%s' must have a single dummy argument"_err_en_US,
1697 subroutine.name(), derivedType.name());
1698 return false;
1699 }
1700 const auto &arg{proc->dummyArguments[0]};
1701 const Symbol *errSym{&subroutine};
1702 if (const auto *details{subroutine.detailsIf<SubprogramDetails>()}) {
1703 if (!details->dummyArgs().empty()) {
1704 if (const Symbol *argSym{details->dummyArgs()[0]}) {
1705 errSym = argSym;
1706 }
1707 }
1708 }
1709 const auto *ddo{std::get_if<DummyDataObject>(&arg.u)};
1710 if (!ddo) {
1711 SayWithDeclaration(subroutine, finalName,
1712 "FINAL subroutine '%s' of derived type '%s' must have a single dummy argument that is a data object"_err_en_US,
1713 subroutine.name(), derivedType.name());
1714 return false;
1715 }
1716 bool ok{true};
1717 if (arg.IsOptional()) {
1718 SayWithDeclaration(*errSym, finalName,
1719 "FINAL subroutine '%s' of derived type '%s' must not have an OPTIONAL dummy argument"_err_en_US,
1720 subroutine.name(), derivedType.name());
1721 ok = false;
1722 }
1723 if (ddo->attrs.test(DummyDataObject::Attr::Allocatable)) {
1724 SayWithDeclaration(*errSym, finalName,
1725 "FINAL subroutine '%s' of derived type '%s' must not have an ALLOCATABLE dummy argument"_err_en_US,
1726 subroutine.name(), derivedType.name());
1727 ok = false;
1728 }
1729 if (ddo->attrs.test(DummyDataObject::Attr::Pointer)) {
1730 SayWithDeclaration(*errSym, finalName,
1731 "FINAL subroutine '%s' of derived type '%s' must not have a POINTER dummy argument"_err_en_US,
1732 subroutine.name(), derivedType.name());
1733 ok = false;
1734 }
1735 if (ddo->intent == common::Intent::Out) {
1736 SayWithDeclaration(*errSym, finalName,
1737 "FINAL subroutine '%s' of derived type '%s' must not have a dummy argument with INTENT(OUT)"_err_en_US,
1738 subroutine.name(), derivedType.name());
1739 ok = false;
1740 }
1741 if (ddo->attrs.test(DummyDataObject::Attr::Value)) {
1742 SayWithDeclaration(*errSym, finalName,
1743 "FINAL subroutine '%s' of derived type '%s' must not have a dummy argument with the VALUE attribute"_err_en_US,
1744 subroutine.name(), derivedType.name());
1745 ok = false;
1746 }
1747 if (ddo->type.corank() > 0) {
1748 SayWithDeclaration(*errSym, finalName,
1749 "FINAL subroutine '%s' of derived type '%s' must not have a coarray dummy argument"_err_en_US,
1750 subroutine.name(), derivedType.name());
1751 ok = false;
1752 }
1753 if (ddo->type.type().IsPolymorphic()) {
1754 SayWithDeclaration(*errSym, finalName,
1755 "FINAL subroutine '%s' of derived type '%s' must not have a polymorphic dummy argument"_err_en_US,
1756 subroutine.name(), derivedType.name());
1757 ok = false;
1758 } else if (ddo->type.type().category() != TypeCategory::Derived ||
1759 &ddo->type.type().GetDerivedTypeSpec().typeSymbol() != &derivedType) {
1760 SayWithDeclaration(*errSym, finalName,
1761 "FINAL subroutine '%s' of derived type '%s' must have a TYPE(%s) dummy argument"_err_en_US,
1762 subroutine.name(), derivedType.name(), derivedType.name());
1763 ok = false;
1764 } else { // check that all LEN type parameters are assumed
1765 for (auto ref : OrderParameterDeclarations(derivedType)) {
1766 if (IsLenTypeParameter(*ref)) {
1767 const auto *value{
1768 ddo->type.type().GetDerivedTypeSpec().FindParameter(ref->name())};
1769 if (!value || !value->isAssumed()) {
1770 SayWithDeclaration(*errSym, finalName,
1771 "FINAL subroutine '%s' of derived type '%s' must have a dummy argument with an assumed LEN type parameter '%s=*'"_err_en_US,
1772 subroutine.name(), derivedType.name(), ref->name());
1773 ok = false;
1774 }
1775 }
1776 }
1777 }
1778 return ok;
1779 }
1780
1781 bool CheckHelper::CheckDistinguishableFinals(const Symbol &f1,
1782 SourceName f1Name, const Symbol &f2, SourceName f2Name,
1783 const Symbol &derivedType) {
1784 const Procedure *p1{Characterize(f1)};
1785 const Procedure *p2{Characterize(f2)};
1786 if (p1 && p2) {
1787 std::optional<bool> areDistinct{characteristics::Distinguishable(
1788 context_.languageFeatures(), *p1, *p2)};
1789 if (areDistinct.value_or(false)) {
1790 return true;
1791 }
1792 if (auto *msg{messages_.Say(f1Name,
1793 "FINAL subroutines '%s' and '%s' of derived type '%s' cannot be distinguished by rank or KIND type parameter value"_err_en_US,
1794 f1Name, f2Name, derivedType.name())}) {
1795 msg->Attach(f2Name, "FINAL declaration of '%s'"_en_US, f2.name())
1796 .Attach(f1.name(), "Definition of '%s'"_en_US, f1Name)
1797 .Attach(f2.name(), "Definition of '%s'"_en_US, f2Name);
1798 }
1799 }
1800 return false;
1801 }
1802
1803 void CheckHelper::CheckHostAssoc(
1804 const Symbol &symbol, const HostAssocDetails &details) {
1805 const Symbol &hostSymbol{details.symbol()};
1806 if (hostSymbol.test(Symbol::Flag::ImplicitOrError)) {
1807 if (details.implicitOrSpecExprError) {
1808 messages_.Say("Implicitly typed local entity '%s' not allowed in"
1809 " specification expression"_err_en_US,
1810 symbol.name());
1811 } else if (details.implicitOrExplicitTypeError) {
1812 messages_.Say(
1813 "No explicit type declared for '%s'"_err_en_US, symbol.name());
1814 }
1815 }
1816 }
1817
1818 void CheckHelper::CheckGeneric(
1819 const Symbol &symbol, const GenericDetails &details) {
1820 CheckSpecifics(symbol, details);
1821 common::visit(common::visitors{
1822 [&](const common::DefinedIo &io) {
1823 CheckDefinedIoProc(symbol, details, io);
1824 },
1825 [&](const GenericKind::OtherKind &other) {
1826 if (other == GenericKind::OtherKind::Name) {
1827 CheckGenericVsIntrinsic(symbol, details);
1828 }
1829 },
1830 [](const auto &) {},
1831 },
1832 details.kind().u);
1833 // Ensure that shadowed symbols are checked
1834 if (details.specific()) {
1835 Check(*details.specific());
1836 }
1837 if (details.derivedType()) {
1838 Check(*details.derivedType());
1839 }
1840 }
1841
1842 // Check that the specifics of this generic are distinguishable from each other
1843 void CheckHelper::CheckSpecifics(
1844 const Symbol &generic, const GenericDetails &details) {
1845 GenericKind kind{details.kind()};
1846 DistinguishabilityHelper helper{context_};
1847 for (const Symbol &specific : details.specificProcs()) {
1848 if (specific.attrs().test(Attr::ABSTRACT)) {
1849 if (auto *msg{messages_.Say(generic.name(),
1850 "Generic interface '%s' must not use abstract interface '%s' as a specific procedure"_err_en_US,
1851 generic.name(), specific.name())}) {
1852 msg->Attach(
1853 specific.name(), "Definition of '%s'"_en_US, specific.name());
1854 }
1855 continue;
1856 }
1857 if (specific.attrs().test(Attr::INTRINSIC)) {
1858 // GNU Fortran allows INTRINSIC procedures in generics.
1859 auto intrinsic{context_.intrinsics().IsSpecificIntrinsicFunction(
1860 specific.name().ToString())};
1861 if (intrinsic && !intrinsic->isRestrictedSpecific) {
1862 if (context_.ShouldWarn(common::LanguageFeature::IntrinsicAsSpecific)) {
1863 if (auto *msg{messages_.Say(specific.name(),
1864 "Specific procedure '%s' of generic interface '%s' should not be INTRINSIC"_port_en_US,
1865 specific.name(), generic.name())}) {
1866 msg->Attach(
1867 generic.name(), "Definition of '%s'"_en_US, generic.name());
1868 }
1869 }
1870 } else {
1871 if (context_.ShouldWarn(common::LanguageFeature::IntrinsicAsSpecific)) {
1872 if (auto *msg{messages_.Say(specific.name(),
1873 "Procedure '%s' of generic interface '%s' is INTRINSIC but not an unrestricted specific intrinsic function"_port_en_US,
1874 specific.name(), generic.name())}) {
1875 msg->Attach(
1876 generic.name(), "Definition of '%s'"_en_US, generic.name());
1877 }
1878 }
1879 continue;
1880 }
1881 }
1882 if (IsStmtFunction(specific)) {
1883 if (auto *msg{messages_.Say(specific.name(),
1884 "Specific procedure '%s' of generic interface '%s' may not be a statement function"_err_en_US,
1885 specific.name(), generic.name())}) {
1886 msg->Attach(generic.name(), "Definition of '%s'"_en_US, generic.name());
1887 }
1888 continue;
1889 }
1890 if (const Procedure *procedure{Characterize(specific)}) {
1891 if (procedure->HasExplicitInterface()) {
1892 helper.Add(generic, kind, specific, *procedure);
1893 } else {
1894 if (auto *msg{messages_.Say(specific.name(),
1895 "Specific procedure '%s' of generic interface '%s' must have an explicit interface"_err_en_US,
1896 specific.name(), generic.name())}) {
1897 msg->Attach(
1898 generic.name(), "Definition of '%s'"_en_US, generic.name());
1899 }
1900 }
1901 }
1902 }
1903 helper.Check(generic.owner());
1904 }
1905
1906 static bool CUDAHostDeviceDiffer(
1907 const Procedure &proc, const DummyDataObject &arg) {
1908 auto procCUDA{
1909 proc.cudaSubprogramAttrs.value_or(common::CUDASubprogramAttrs::Host)};
1910 bool procIsHostOnly{procCUDA == common::CUDASubprogramAttrs::Host};
1911 bool procIsDeviceOnly{
1912 !procIsHostOnly && procCUDA != common::CUDASubprogramAttrs::HostDevice};
1913 const auto &argCUDA{arg.cudaDataAttr};
1914 bool argIsHostOnly{!argCUDA || *argCUDA == common::CUDADataAttr::Pinned};
1915 bool argIsDeviceOnly{(!argCUDA && procIsDeviceOnly) ||
1916 (argCUDA &&
1917 (*argCUDA != common::CUDADataAttr::Managed &&
1918 *argCUDA != common::CUDADataAttr::Pinned &&
1919 *argCUDA != common::CUDADataAttr::Unified))};
1920 return (procIsHostOnly && argIsDeviceOnly) ||
1921 (procIsDeviceOnly && argIsHostOnly);
1922 }
1923
1924 static bool ConflictsWithIntrinsicAssignment(const Procedure &proc) {
1925 const auto &lhsData{std::get<DummyDataObject>(proc.dummyArguments[0].u)};
1926 const auto &lhsTnS{lhsData.type};
1927 const auto &rhsData{std::get<DummyDataObject>(proc.dummyArguments[1].u)};
1928 const auto &rhsTnS{rhsData.type};
1929 return !CUDAHostDeviceDiffer(proc, lhsData) &&
1930 !CUDAHostDeviceDiffer(proc, rhsData) &&
1931 Tristate::No ==
1932 IsDefinedAssignment(
1933 lhsTnS.type(), lhsTnS.Rank(), rhsTnS.type(), rhsTnS.Rank());
1934 }
1935
1936 static bool ConflictsWithIntrinsicOperator(
1937 const GenericKind &kind, const Procedure &proc) {
1938 if (!kind.IsIntrinsicOperator()) {
1939 return false;
1940 }
1941 const auto &arg0Data{std::get<DummyDataObject>(proc.dummyArguments[0].u)};
1942 if (CUDAHostDeviceDiffer(proc, arg0Data)) {
1943 return false;
1944 }
1945 const auto &arg0TnS{arg0Data.type};
1946 auto type0{arg0TnS.type()};
1947 if (proc.dummyArguments.size() == 1) { // unary
1948 return common::visit(
1949 common::visitors{
1950 [&](common::NumericOperator) { return IsIntrinsicNumeric(type0); },
1951 [&](common::LogicalOperator) { return IsIntrinsicLogical(type0); },
1952 [](const auto &) -> bool { DIE("bad generic kind"); },
1953 },
1954 kind.u);
1955 } else { // binary
1956 int rank0{arg0TnS.Rank()};
1957 const auto &arg1Data{std::get<DummyDataObject>(proc.dummyArguments[1].u)};
1958 if (CUDAHostDeviceDiffer(proc, arg1Data)) {
1959 return false;
1960 }
1961 const auto &arg1TnS{arg1Data.type};
1962 auto type1{arg1TnS.type()};
1963 int rank1{arg1TnS.Rank()};
1964 return common::visit(
1965 common::visitors{
1966 [&](common::NumericOperator) {
1967 return IsIntrinsicNumeric(type0, rank0, type1, rank1);
1968 },
1969 [&](common::LogicalOperator) {
1970 return IsIntrinsicLogical(type0, rank0, type1, rank1);
1971 },
1972 [&](common::RelationalOperator opr) {
1973 return IsIntrinsicRelational(opr, type0, rank0, type1, rank1);
1974 },
1975 [&](GenericKind::OtherKind x) {
1976 CHECK(x == GenericKind::OtherKind::Concat);
1977 return IsIntrinsicConcat(type0, rank0, type1, rank1);
1978 },
1979 [](const auto &) -> bool { DIE("bad generic kind"); },
1980 },
1981 kind.u);
1982 }
1983 }
1984
1985 // Check if this procedure can be used for defined operators (see 15.4.3.4.2).
1986 bool CheckHelper::CheckDefinedOperator(SourceName opName, GenericKind kind,
1987 const Symbol &specific, const Procedure &proc) {
1988 if (context_.HasError(specific)) {
1989 return false;
1990 }
1991 std::optional<parser::MessageFixedText> msg;
1992 auto checkDefinedOperatorArgs{
1993 [&](SourceName opName, const Symbol &specific, const Procedure &proc) {
1994 bool arg0Defined{CheckDefinedOperatorArg(opName, specific, proc, 0)};
1995 bool arg1Defined{CheckDefinedOperatorArg(opName, specific, proc, 1)};
1996 return arg0Defined && arg1Defined;
1997 }};
1998 if (specific.attrs().test(Attr::NOPASS)) { // C774
1999 msg = "%s procedure '%s' may not have NOPASS attribute"_err_en_US;
2000 } else if (!proc.functionResult.has_value()) {
2001 msg = "%s procedure '%s' must be a function"_err_en_US;
2002 } else if (proc.functionResult->IsAssumedLengthCharacter()) {
2003 const auto *subpDetails{specific.detailsIf<SubprogramDetails>()};
2004 if (subpDetails && !subpDetails->isDummy() && subpDetails->isInterface()) {
2005 // Error is caught by more general test for interfaces with
2006 // assumed-length character function results
2007 return true;
2008 }
2009 msg = "%s function '%s' may not have assumed-length CHARACTER(*)"
2010 " result"_err_en_US;
2011 } else if (auto m{CheckNumberOfArgs(kind, proc.dummyArguments.size())}) {
2012 msg = std::move(m);
2013 } else if (!checkDefinedOperatorArgs(opName, specific, proc)) {
2014 return false; // error was reported
2015 } else if (ConflictsWithIntrinsicOperator(kind, proc)) {
2016 msg = "%s function '%s' conflicts with intrinsic operator"_err_en_US;
2017 } else {
2018 return true; // OK
2019 }
2020 bool isFatal{msg->IsFatal()};
2021 if (isFatal || !FindModuleFileContaining(specific.owner())) {
2022 SayWithDeclaration(
2023 specific, std::move(*msg), MakeOpName(opName), specific.name());
2024 }
2025 if (isFatal) {
2026 context_.SetError(specific);
2027 }
2028 return !isFatal;
2029 }
2030
2031 // If the number of arguments is wrong for this intrinsic operator, return
2032 // false and return the error message in msg.
2033 std::optional<parser::MessageFixedText> CheckHelper::CheckNumberOfArgs(
2034 const GenericKind &kind, std::size_t nargs) {
2035 if (!kind.IsIntrinsicOperator()) {
2036 if (nargs < 1 || nargs > 2) {
2037 if (context_.ShouldWarn(common::UsageWarning::DefinedOperatorArgs)) {
2038 return "%s function '%s' should have 1 or 2 dummy arguments"_warn_en_US;
2039 }
2040 }
2041 return std::nullopt;
2042 }
2043 std::size_t min{2}, max{2}; // allowed number of args; default is binary
2044 common::visit(common::visitors{
2045 [&](const common::NumericOperator &x) {
2046 if (x == common::NumericOperator::Add ||
2047 x == common::NumericOperator::Subtract) {
2048 min = 1; // + and - are unary or binary
2049 }
2050 },
2051 [&](const common::LogicalOperator &x) {
2052 if (x == common::LogicalOperator::Not) {
2053 min = 1; // .NOT. is unary
2054 max = 1;
2055 }
2056 },
2057 [](const common::RelationalOperator &) {
2058 // all are binary
2059 },
2060 [](const GenericKind::OtherKind &x) {
2061 CHECK(x == GenericKind::OtherKind::Concat);
2062 },
2063 [](const auto &) { DIE("expected intrinsic operator"); },
2064 },
2065 kind.u);
2066 if (nargs >= min && nargs <= max) {
2067 return std::nullopt;
2068 } else if (max == 1) {
2069 return "%s function '%s' must have one dummy argument"_err_en_US;
2070 } else if (min == 2) {
2071 return "%s function '%s' must have two dummy arguments"_err_en_US;
2072 } else {
2073 return "%s function '%s' must have one or two dummy arguments"_err_en_US;
2074 }
2075 }
2076
2077 bool CheckHelper::CheckDefinedOperatorArg(const SourceName &opName,
2078 const Symbol &symbol, const Procedure &proc, std::size_t pos) {
2079 if (pos >= proc.dummyArguments.size()) {
2080 return true;
2081 }
2082 auto &arg{proc.dummyArguments.at(pos)};
2083 std::optional<parser::MessageFixedText> msg;
2084 if (arg.IsOptional()) {
2085 msg = "In %s function '%s', dummy argument '%s' may not be"
2086 " OPTIONAL"_err_en_US;
2087 } else if (const auto *dataObject{std::get_if<DummyDataObject>(&arg.u)};
2088 dataObject == nullptr) {
2089 msg = "In %s function '%s', dummy argument '%s' must be a"
2090 " data object"_err_en_US;
2091 } else if (dataObject->intent == common::Intent::Out) {
2092 msg =
2093 "In %s function '%s', dummy argument '%s' may not be INTENT(OUT)"_err_en_US;
2094 } else if (dataObject->intent != common::Intent::In &&
2095 !dataObject->attrs.test(DummyDataObject::Attr::Value)) {
2096 if (context_.ShouldWarn(common::UsageWarning::DefinedOperatorArgs)) {
2097 msg =
2098 "In %s function '%s', dummy argument '%s' should have INTENT(IN) or VALUE attribute"_warn_en_US;
2099 }
2100 }
2101 if (msg) {
2102 bool isFatal{msg->IsFatal()};
2103 if (isFatal || !FindModuleFileContaining(symbol.owner())) {
2104 SayWithDeclaration(symbol, std::move(*msg),
2105 parser::ToUpperCaseLetters(opName.ToString()), symbol.name(),
2106 arg.name);
2107 }
2108 if (isFatal) {
2109 return false;
2110 }
2111 }
2112 return true;
2113 }
2114
2115 // Check if this procedure can be used for defined assignment (see 15.4.3.4.3).
2116 bool CheckHelper::CheckDefinedAssignment(
2117 const Symbol &specific, const Procedure &proc) {
2118 if (context_.HasError(specific)) {
2119 return false;
2120 }
2121 std::optional<parser::MessageFixedText> msg;
2122 if (specific.attrs().test(Attr::NOPASS)) { // C774
2123 msg = "Defined assignment procedure '%s' may not have"
2124 " NOPASS attribute"_err_en_US;
2125 } else if (!proc.IsSubroutine()) {
2126 msg = "Defined assignment procedure '%s' must be a subroutine"_err_en_US;
2127 } else if (proc.dummyArguments.size() != 2) {
2128 msg = "Defined assignment subroutine '%s' must have"
2129 " two dummy arguments"_err_en_US;
2130 } else {
2131 // Check both arguments even if the first has an error.
2132 bool ok0{CheckDefinedAssignmentArg(specific, proc.dummyArguments[0], 0)};
2133 bool ok1{CheckDefinedAssignmentArg(specific, proc.dummyArguments[1], 1)};
2134 if (!(ok0 && ok1)) {
2135 return false; // error was reported
2136 } else if (ConflictsWithIntrinsicAssignment(proc)) {
2137 msg =
2138 "Defined assignment subroutine '%s' conflicts with intrinsic assignment"_err_en_US;
2139 } else {
2140 return true; // OK
2141 }
2142 }
2143 SayWithDeclaration(specific, std::move(msg.value()), specific.name());
2144 context_.SetError(specific);
2145 return false;
2146 }
2147
2148 bool CheckHelper::CheckDefinedAssignmentArg(
2149 const Symbol &symbol, const DummyArgument &arg, int pos) {
2150 std::optional<parser::MessageFixedText> msg;
2151 if (arg.IsOptional()) {
2152 msg = "In defined assignment subroutine '%s', dummy argument '%s'"
2153 " may not be OPTIONAL"_err_en_US;
2154 } else if (const auto *dataObject{std::get_if<DummyDataObject>(&arg.u)}) {
2155 if (pos == 0) {
2156 if (dataObject->intent == common::Intent::In) {
2157 msg = "In defined assignment subroutine '%s', first dummy argument '%s'"
2158 " may not have INTENT(IN)"_err_en_US;
2159 } else if (dataObject->intent != common::Intent::Out &&
2160 dataObject->intent != common::Intent::InOut) {
2161 if (context_.ShouldWarn(common::UsageWarning::DefinedOperatorArgs)) {
2162 msg =
2163 "In defined assignment subroutine '%s', first dummy argument '%s' should have INTENT(OUT) or INTENT(INOUT)"_warn_en_US;
2164 }
2165 }
2166 } else if (pos == 1) {
2167 if (dataObject->intent == common::Intent::Out) {
2168 msg = "In defined assignment subroutine '%s', second dummy"
2169 " argument '%s' may not have INTENT(OUT)"_err_en_US;
2170 } else if (dataObject->intent != common::Intent::In &&
2171 !dataObject->attrs.test(DummyDataObject::Attr::Value)) {
2172 if (context_.ShouldWarn(common::UsageWarning::DefinedOperatorArgs)) {
2173 msg =
2174 "In defined assignment subroutine '%s', second dummy argument '%s' should have INTENT(IN) or VALUE attribute"_warn_en_US;
2175 }
2176 } else if (dataObject->attrs.test(DummyDataObject::Attr::Pointer)) {
2177 msg =
2178 "In defined assignment subroutine '%s', second dummy argument '%s' must not be a pointer"_err_en_US;
2179 } else if (dataObject->attrs.test(DummyDataObject::Attr::Allocatable)) {
2180 msg =
2181 "In defined assignment subroutine '%s', second dummy argument '%s' must not be an allocatable"_err_en_US;
2182 }
2183 } else {
2184 DIE("pos must be 0 or 1");
2185 }
2186 } else {
2187 msg = "In defined assignment subroutine '%s', dummy argument '%s'"
2188 " must be a data object"_err_en_US;
2189 }
2190 if (msg) {
2191 bool isFatal{msg->IsFatal()};
2192 if (isFatal || !FindModuleFileContaining(symbol.owner())) {
2193 SayWithDeclaration(symbol, std::move(*msg), symbol.name(), arg.name);
2194 }
2195 if (isFatal) {
2196 context_.SetError(symbol);
2197 return false;
2198 }
2199 }
2200 return true;
2201 }
2202
2203 // Report a conflicting attribute error if symbol has both of these attributes
2204 bool CheckHelper::CheckConflicting(const Symbol &symbol, Attr a1, Attr a2) {
2205 if (symbol.attrs().test(a1) && symbol.attrs().test(a2)) {
2206 messages_.Say("'%s' may not have both the %s and %s attributes"_err_en_US,
2207 symbol.name(), AttrToString(a1), AttrToString(a2));
2208 return true;
2209 } else {
2210 return false;
2211 }
2212 }
2213
2214 void CheckHelper::WarnMissingFinal(const Symbol &symbol) {
2215 const auto *object{symbol.detailsIf<ObjectEntityDetails>()};
2216 if (!object || object->IsAssumedRank() ||
2217 (!IsAutomaticallyDestroyed(symbol) &&
2218 symbol.owner().kind() != Scope::Kind::DerivedType)) {
2219 return;
2220 }
2221 const DeclTypeSpec *type{object->type()};
2222 const DerivedTypeSpec *derived{type ? type->AsDerived() : nullptr};
2223 const Symbol *derivedSym{derived ? &derived->typeSymbol() : nullptr};
2224 int rank{object->shape().Rank()};
2225 const Symbol *initialDerivedSym{derivedSym};
2226 while (const auto *derivedDetails{
2227 derivedSym ? derivedSym->detailsIf<DerivedTypeDetails>() : nullptr}) {
2228 if (!derivedDetails->finals().empty() &&
2229 !derivedDetails->GetFinalForRank(rank) &&
2230 context_.ShouldWarn(common::UsageWarning::Final)) {
2231 if (auto *msg{derivedSym == initialDerivedSym
2232 ? WarnIfNotInModuleFile(symbol.name(),
2233 "'%s' of derived type '%s' does not have a FINAL subroutine for its rank (%d)"_warn_en_US,
2234 symbol.name(), derivedSym->name(), rank)
2235 : WarnIfNotInModuleFile(symbol.name(),
2236 "'%s' of derived type '%s' extended from '%s' does not have a FINAL subroutine for its rank (%d)"_warn_en_US,
2237 symbol.name(), initialDerivedSym->name(),
2238 derivedSym->name(), rank)}) {
2239 msg->Attach(derivedSym->name(),
2240 "Declaration of derived type '%s'"_en_US, derivedSym->name());
2241 }
2242 return;
2243 }
2244 derived = derivedSym->GetParentTypeSpec();
2245 derivedSym = derived ? &derived->typeSymbol() : nullptr;
2246 }
2247 }
2248
2249 const Procedure *CheckHelper::Characterize(const Symbol &symbol) {
2250 auto it{characterizeCache_.find(symbol)};
2251 if (it == characterizeCache_.end()) {
2252 auto pair{characterizeCache_.emplace(SymbolRef{symbol},
2253 Procedure::Characterize(symbol, context_.foldingContext()))};
2254 it = pair.first;
2255 }
2256 return common::GetPtrFromOptional(it->second);
2257 }
2258
2259 void CheckHelper::CheckVolatile(const Symbol &symbol,
2260 const DerivedTypeSpec *derived) { // C866 - C868
2261 if (IsIntentIn(symbol)) {
2262 messages_.Say(
2263 "VOLATILE attribute may not apply to an INTENT(IN) argument"_err_en_US);
2264 }
2265 if (IsProcedure(symbol)) {
2266 messages_.Say("VOLATILE attribute may apply only to a variable"_err_en_US);
2267 }
2268 if (symbol.has<UseDetails>() || symbol.has<HostAssocDetails>()) {
2269 const Symbol &ultimate{symbol.GetUltimate()};
2270 if (evaluate::IsCoarray(ultimate)) {
2271 messages_.Say(
2272 "VOLATILE attribute may not apply to a coarray accessed by USE or host association"_err_en_US);
2273 }
2274 if (derived) {
2275 if (FindCoarrayUltimateComponent(*derived)) {
2276 messages_.Say(
2277 "VOLATILE attribute may not apply to a type with a coarray ultimate component accessed by USE or host association"_err_en_US);
2278 }
2279 }
2280 }
2281 }
2282
2283 void CheckHelper::CheckContiguous(const Symbol &symbol) {
2284 if (evaluate::IsVariable(symbol) &&
2285 ((IsPointer(symbol) && symbol.Rank() > 0) || IsAssumedShape(symbol) ||
2286 evaluate::IsAssumedRank(symbol))) {
2287 } else if (!context_.IsEnabled(
2288 common::LanguageFeature::RedundantContiguous) ||
2289 context_.ShouldWarn(common::LanguageFeature::RedundantContiguous)) {
2290 parser::MessageFixedText msg{symbol.owner().IsDerivedType()
2291 ? "CONTIGUOUS component '%s' should be an array with the POINTER attribute"_port_en_US
2292 : "CONTIGUOUS entity '%s' should be an array pointer, assumed-shape, or assumed-rank"_port_en_US};
2293 if (!context_.IsEnabled(common::LanguageFeature::RedundantContiguous)) {
2294 msg.set_severity(parser::Severity::Error);
2295 }
2296 messages_.Say(std::move(msg), symbol.name());
2297 }
2298 }
2299
2300 void CheckHelper::CheckPointer(const Symbol &symbol) { // C852
2301 CheckConflicting(symbol, Attr::POINTER, Attr::TARGET);
2302 CheckConflicting(symbol, Attr::POINTER, Attr::ALLOCATABLE); // C751
2303 CheckConflicting(symbol, Attr::POINTER, Attr::INTRINSIC);
2304 // Prohibit constant pointers. The standard does not explicitly prohibit
2305 // them, but the PARAMETER attribute requires a entity-decl to have an
2306 // initialization that is a constant-expr, and the only form of
2307 // initialization that allows a constant-expr is the one that's not a "=>"
2308 // pointer initialization. See C811, C807, and section 8.5.13.
2309 CheckConflicting(symbol, Attr::POINTER, Attr::PARAMETER);
2310 if (symbol.Corank() > 0) {
2311 messages_.Say(
2312 "'%s' may not have the POINTER attribute because it is a coarray"_err_en_US,
2313 symbol.name());
2314 }
2315 }
2316
2317 // C760 constraints on the passed-object dummy argument
2318 // C757 constraints on procedure pointer components
2319 void CheckHelper::CheckPassArg(
2320 const Symbol &proc, const Symbol *interface0, const WithPassArg &details) {
2321 if (proc.attrs().test(Attr::NOPASS)) {
2322 return;
2323 }
2324 const auto &name{proc.name()};
2325 const Symbol *interface {
2326 interface0 ? FindInterface(*interface0) : nullptr
2327 };
2328 if (!interface) {
2329 messages_.Say(name,
2330 "Procedure component '%s' must have NOPASS attribute or explicit interface"_err_en_US,
2331 name);
2332 return;
2333 }
2334 const auto *subprogram{interface->detailsIf<SubprogramDetails>()};
2335 if (!subprogram) {
2336 messages_.Say(name,
2337 "Procedure component '%s' has invalid interface '%s'"_err_en_US, name,
2338 interface->name());
2339 return;
2340 }
2341 std::optional<SourceName> passName{details.passName()};
2342 const auto &dummyArgs{subprogram->dummyArgs()};
2343 if (!passName) {
2344 if (dummyArgs.empty()) {
2345 messages_.Say(name,
2346 proc.has<ProcEntityDetails>()
2347 ? "Procedure component '%s' with no dummy arguments"
2348 " must have NOPASS attribute"_err_en_US
2349 : "Procedure binding '%s' with no dummy arguments"
2350 " must have NOPASS attribute"_err_en_US,
2351 name);
2352 context_.SetError(*interface);
2353 return;
2354 }
2355 Symbol *argSym{dummyArgs[0]};
2356 if (!argSym) {
2357 messages_.Say(interface->name(),
2358 "Cannot use an alternate return as the passed-object dummy "
2359 "argument"_err_en_US);
2360 return;
2361 }
2362 passName = dummyArgs[0]->name();
2363 }
2364 std::optional<int> passArgIndex{};
2365 for (std::size_t i{0}; i < dummyArgs.size(); ++i) {
2366 if (dummyArgs[i] && dummyArgs[i]->name() == *passName) {
2367 passArgIndex = i;
2368 break;
2369 }
2370 }
2371 if (!passArgIndex) { // C758
2372 messages_.Say(*passName,
2373 "'%s' is not a dummy argument of procedure interface '%s'"_err_en_US,
2374 *passName, interface->name());
2375 return;
2376 }
2377 const Symbol &passArg{*dummyArgs[*passArgIndex]};
2378 std::optional<parser::MessageFixedText> msg;
2379 if (!passArg.has<ObjectEntityDetails>()) {
2380 msg = "Passed-object dummy argument '%s' of procedure '%s'"
2381 " must be a data object"_err_en_US;
2382 } else if (passArg.attrs().test(Attr::POINTER)) {
2383 msg = "Passed-object dummy argument '%s' of procedure '%s'"
2384 " may not have the POINTER attribute"_err_en_US;
2385 } else if (passArg.attrs().test(Attr::ALLOCATABLE)) {
2386 msg = "Passed-object dummy argument '%s' of procedure '%s'"
2387 " may not have the ALLOCATABLE attribute"_err_en_US;
2388 } else if (passArg.attrs().test(Attr::VALUE)) {
2389 msg = "Passed-object dummy argument '%s' of procedure '%s'"
2390 " may not have the VALUE attribute"_err_en_US;
2391 } else if (passArg.Rank() > 0) {
2392 msg = "Passed-object dummy argument '%s' of procedure '%s'"
2393 " must be scalar"_err_en_US;
2394 }
2395 if (msg) {
2396 messages_.Say(name, std::move(*msg), passName.value(), name);
2397 return;
2398 }
2399 const DeclTypeSpec *type{passArg.GetType()};
2400 if (!type) {
2401 return; // an error already occurred
2402 }
2403 const Symbol &typeSymbol{*proc.owner().GetSymbol()};
2404 const DerivedTypeSpec *derived{type->AsDerived()};
2405 if (!derived || derived->typeSymbol() != typeSymbol) {
2406 messages_.Say(name,
2407 "Passed-object dummy argument '%s' of procedure '%s'"
2408 " must be of type '%s' but is '%s'"_err_en_US,
2409 passName.value(), name, typeSymbol.name(), type->AsFortran());
2410 return;
2411 }
2412 if (IsExtensibleType(derived) != type->IsPolymorphic()) {
2413 messages_.Say(name,
2414 type->IsPolymorphic()
2415 ? "Passed-object dummy argument '%s' of procedure '%s'"
2416 " may not be polymorphic because '%s' is not extensible"_err_en_US
2417 : "Passed-object dummy argument '%s' of procedure '%s'"
2418 " must be polymorphic because '%s' is extensible"_err_en_US,
2419 passName.value(), name, typeSymbol.name());
2420 return;
2421 }
2422 for (const auto &[paramName, paramValue] : derived->parameters()) {
2423 if (paramValue.isLen() && !paramValue.isAssumed()) {
2424 messages_.Say(name,
2425 "Passed-object dummy argument '%s' of procedure '%s'"
2426 " has non-assumed length parameter '%s'"_err_en_US,
2427 passName.value(), name, paramName);
2428 }
2429 }
2430 }
2431
2432 void CheckHelper::CheckProcBinding(
2433 const Symbol &symbol, const ProcBindingDetails &binding) {
2434 const Scope &dtScope{symbol.owner()};
2435 CHECK(dtScope.kind() == Scope::Kind::DerivedType);
2436 if (symbol.attrs().test(Attr::DEFERRED)) {
2437 if (const Symbol *dtSymbol{dtScope.symbol()}) {
2438 if (!dtSymbol->attrs().test(Attr::ABSTRACT)) { // C733
2439 SayWithDeclaration(*dtSymbol,
2440 "Procedure bound to non-ABSTRACT derived type '%s' may not be DEFERRED"_err_en_US,
2441 dtSymbol->name());
2442 }
2443 }
2444 if (symbol.attrs().test(Attr::NON_OVERRIDABLE)) {
2445 messages_.Say(
2446 "Type-bound procedure '%s' may not be both DEFERRED and NON_OVERRIDABLE"_err_en_US,
2447 symbol.name());
2448 }
2449 }
2450 if (binding.symbol().attrs().test(Attr::INTRINSIC) &&
2451 !context_.intrinsics().IsSpecificIntrinsicFunction(
2452 binding.symbol().name().ToString())) {
2453 messages_.Say(
2454 "Intrinsic procedure '%s' is not a specific intrinsic permitted for use in the definition of binding '%s'"_err_en_US,
2455 binding.symbol().name(), symbol.name());
2456 }
2457 bool isInaccessibleDeferred{false};
2458 if (const Symbol *
2459 overridden{FindOverriddenBinding(symbol, isInaccessibleDeferred)}) {
2460 if (isInaccessibleDeferred) {
2461 SayWithDeclaration(*overridden,
2462 "Override of PRIVATE DEFERRED '%s' must appear in its module"_err_en_US,
2463 symbol.name());
2464 }
2465 if (overridden->attrs().test(Attr::NON_OVERRIDABLE)) {
2466 SayWithDeclaration(*overridden,
2467 "Override of NON_OVERRIDABLE '%s' is not permitted"_err_en_US,
2468 symbol.name());
2469 }
2470 if (const auto *overriddenBinding{
2471 overridden->detailsIf<ProcBindingDetails>()}) {
2472 if (!IsPureProcedure(symbol) && IsPureProcedure(*overridden)) {
2473 SayWithDeclaration(*overridden,
2474 "An overridden pure type-bound procedure binding must also be pure"_err_en_US);
2475 return;
2476 }
2477 if (!IsElementalProcedure(binding.symbol()) &&
2478 IsElementalProcedure(*overridden)) {
2479 SayWithDeclaration(*overridden,
2480 "A type-bound procedure and its override must both, or neither, be ELEMENTAL"_err_en_US);
2481 return;
2482 }
2483 bool isNopass{symbol.attrs().test(Attr::NOPASS)};
2484 if (isNopass != overridden->attrs().test(Attr::NOPASS)) {
2485 SayWithDeclaration(*overridden,
2486 isNopass
2487 ? "A NOPASS type-bound procedure may not override a passed-argument procedure"_err_en_US
2488 : "A passed-argument type-bound procedure may not override a NOPASS procedure"_err_en_US);
2489 } else {
2490 const auto *bindingChars{Characterize(binding.symbol())};
2491 const auto *overriddenChars{Characterize(*overridden)};
2492 if (bindingChars && overriddenChars) {
2493 if (isNopass) {
2494 if (!bindingChars->CanOverride(*overriddenChars, std::nullopt)) {
2495 SayWithDeclaration(*overridden,
2496 "A NOPASS type-bound procedure and its override must have identical interfaces"_err_en_US);
2497 }
2498 } else if (!context_.HasError(binding.symbol())) {
2499 auto passIndex{bindingChars->FindPassIndex(binding.passName())};
2500 auto overriddenPassIndex{
2501 overriddenChars->FindPassIndex(overriddenBinding->passName())};
2502 if (passIndex && overriddenPassIndex) {
2503 if (*passIndex != *overriddenPassIndex) {
2504 SayWithDeclaration(*overridden,
2505 "A type-bound procedure and its override must use the same PASS argument"_err_en_US);
2506 } else if (!bindingChars->CanOverride(
2507 *overriddenChars, passIndex)) {
2508 SayWithDeclaration(*overridden,
2509 "A type-bound procedure and its override must have compatible interfaces"_err_en_US);
2510 }
2511 }
2512 }
2513 }
2514 }
2515 if (symbol.attrs().test(Attr::PRIVATE)) {
2516 if (FindModuleContaining(dtScope) ==
2517 FindModuleContaining(overridden->owner())) {
2518 // types declared in same madule
2519 if (!overridden->attrs().test(Attr::PRIVATE)) {
2520 SayWithDeclaration(*overridden,
2521 "A PRIVATE procedure may not override a PUBLIC procedure"_err_en_US);
2522 }
2523 } else { // types declared in distinct madules
2524 if (!CheckAccessibleSymbol(dtScope.parent(), *overridden)) {
2525 SayWithDeclaration(*overridden,
2526 "A PRIVATE procedure may not override an accessible procedure"_err_en_US);
2527 }
2528 }
2529 }
2530 } else {
2531 SayWithDeclaration(*overridden,
2532 "A type-bound procedure binding may not have the same name as a parent component"_err_en_US);
2533 }
2534 }
2535 CheckPassArg(symbol, &binding.symbol(), binding);
2536 }
2537
2538 void CheckHelper::Check(const Scope &scope) {
2539 scope_ = &scope;
2540 common::Restorer<const Symbol *> restorer{innermostSymbol_, innermostSymbol_};
2541 if (const Symbol *symbol{scope.symbol()}) {
2542 innermostSymbol_ = symbol;
2543 }
2544 if (scope.IsParameterizedDerivedTypeInstantiation()) {
2545 auto restorer{common::ScopedSet(scopeIsUninstantiatedPDT_, false)};
2546 auto restorer2{context_.foldingContext().messages().SetContext(
2547 scope.instantiationContext().get())};
2548 for (const auto &pair : scope) {
2549 CheckPointerInitialization(*pair.second);
2550 }
2551 } else {
2552 auto restorer{common::ScopedSet(
2553 scopeIsUninstantiatedPDT_, scope.IsParameterizedDerivedType())};
2554 for (const auto &set : scope.equivalenceSets()) {
2555 CheckEquivalenceSet(set);
2556 }
2557 for (const auto &pair : scope) {
2558 Check(*pair.second);
2559 }
2560 if (scope.IsSubmodule() && scope.symbol()) {
2561 // Submodule names are not in their parent's scopes
2562 Check(*scope.symbol());
2563 }
2564 for (const auto &pair : scope.commonBlocks()) {
2565 CheckCommonBlock(*pair.second);
2566 }
2567 int mainProgCnt{0};
2568 for (const Scope &child : scope.children()) {
2569 Check(child);
2570 // A program shall consist of exactly one main program (5.2.2).
2571 if (child.kind() == Scope::Kind::MainProgram) {
2572 ++mainProgCnt;
2573 if (mainProgCnt > 1) {
2574 messages_.Say(child.sourceRange(),
2575 "A source file cannot contain more than one main program"_err_en_US);
2576 }
2577 }
2578 }
2579 if (scope.kind() == Scope::Kind::BlockData) {
2580 CheckBlockData(scope);
2581 }
2582 if (auto name{scope.GetName()}) {
2583 auto iter{scope.find(*name)};
2584 if (iter != scope.end()) {
2585 const char *kind{nullptr};
2586 if (context_.ShouldWarn(common::LanguageFeature::BenignNameClash)) {
2587 switch (scope.kind()) {
2588 case Scope::Kind::Module:
2589 kind = scope.symbol()->get<ModuleDetails>().isSubmodule()
2590 ? "submodule"
2591 : "module";
2592 break;
2593 case Scope::Kind::MainProgram:
2594 kind = "main program";
2595 break;
2596 case Scope::Kind::BlockData:
2597 kind = "BLOCK DATA subprogram";
2598 break;
2599 default:;
2600 }
2601 if (kind) {
2602 messages_.Say(iter->second->name(),
2603 "Name '%s' declared in a %s should not have the same name as the %s"_port_en_US,
2604 *name, kind, kind);
2605 }
2606 }
2607 }
2608 }
2609 CheckGenericOps(scope);
2610 }
2611 }
2612
2613 void CheckHelper::CheckEquivalenceSet(const EquivalenceSet &set) {
2614 auto iter{
2615 std::find_if(set.begin(), set.end(), [](const EquivalenceObject &object) {
2616 return FindCommonBlockContaining(object.symbol) != nullptr;
2617 })};
2618 if (iter != set.end()) {
2619 const Symbol &commonBlock{DEREF(FindCommonBlockContaining(iter->symbol))};
2620 for (auto &object : set) {
2621 if (&object != &*iter) {
2622 if (auto *details{object.symbol.detailsIf<ObjectEntityDetails>()}) {
2623 if (details->commonBlock()) {
2624 if (details->commonBlock() != &commonBlock) { // 8.10.3 paragraph 1
2625 if (auto *msg{messages_.Say(object.symbol.name(),
2626 "Two objects in the same EQUIVALENCE set may not be members of distinct COMMON blocks"_err_en_US)}) {
2627 msg->Attach(iter->symbol.name(),
2628 "Other object in EQUIVALENCE set"_en_US)
2629 .Attach(details->commonBlock()->name(),
2630 "COMMON block containing '%s'"_en_US,
2631 object.symbol.name())
2632 .Attach(commonBlock.name(),
2633 "COMMON block containing '%s'"_en_US,
2634 iter->symbol.name());
2635 }
2636 }
2637 } else {
2638 // Mark all symbols in the equivalence set with the same COMMON
2639 // block to prevent spurious error messages about initialization
2640 // in BLOCK DATA outside COMMON
2641 details->set_commonBlock(commonBlock);
2642 }
2643 }
2644 }
2645 }
2646 }
2647 for (const EquivalenceObject &object : set) {
2648 CheckEquivalenceObject(object);
2649 }
2650 }
2651
2652 static bool InCommonWithBind(const Symbol &symbol) {
2653 if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) {
2654 const Symbol *commonBlock{details->commonBlock()};
2655 return commonBlock && commonBlock->attrs().test(Attr::BIND_C);
2656 } else {
2657 return false;
2658 }
2659 }
2660
2661 void CheckHelper::CheckEquivalenceObject(const EquivalenceObject &object) {
2662 parser::MessageFixedText msg;
2663 const Symbol &symbol{object.symbol};
2664 if (symbol.owner().IsDerivedType()) {
2665 msg =
2666 "Derived type component '%s' is not allowed in an equivalence set"_err_en_US;
2667 } else if (IsDummy(symbol)) {
2668 msg = "Dummy argument '%s' is not allowed in an equivalence set"_err_en_US;
2669 } else if (symbol.IsFuncResult()) {
2670 msg = "Function result '%s' is not allow in an equivalence set"_err_en_US;
2671 } else if (IsPointer(symbol)) {
2672 msg = "Pointer '%s' is not allowed in an equivalence set"_err_en_US;
2673 } else if (IsAllocatable(symbol)) {
2674 msg =
2675 "Allocatable variable '%s' is not allowed in an equivalence set"_err_en_US;
2676 } else if (symbol.Corank() > 0) {
2677 msg = "Coarray '%s' is not allowed in an equivalence set"_err_en_US;
2678 } else if (symbol.has<UseDetails>()) {
2679 msg =
2680 "Use-associated variable '%s' is not allowed in an equivalence set"_err_en_US;
2681 } else if (symbol.attrs().test(Attr::BIND_C)) {
2682 msg =
2683 "Variable '%s' with BIND attribute is not allowed in an equivalence set"_err_en_US;
2684 } else if (symbol.attrs().test(Attr::TARGET)) {
2685 msg =
2686 "Variable '%s' with TARGET attribute is not allowed in an equivalence set"_err_en_US;
2687 } else if (IsNamedConstant(symbol)) {
2688 msg = "Named constant '%s' is not allowed in an equivalence set"_err_en_US;
2689 } else if (InCommonWithBind(symbol)) {
2690 msg =
2691 "Variable '%s' in common block with BIND attribute is not allowed in an equivalence set"_err_en_US;
2692 } else if (!symbol.has<ObjectEntityDetails>()) {
2693 msg = "'%s' in equivalence set is not a data object"_err_en_US;
2694 } else if (const auto *type{symbol.GetType()}) {
2695 const auto *derived{type->AsDerived()};
2696 if (derived && !derived->IsVectorType()) {
2697 if (const auto *comp{
2698 FindUltimateComponent(*derived, IsAllocatableOrPointer)}) {
2699 msg = IsPointer(*comp)
2700 ? "Derived type object '%s' with pointer ultimate component is not allowed in an equivalence set"_err_en_US
2701 : "Derived type object '%s' with allocatable ultimate component is not allowed in an equivalence set"_err_en_US;
2702 } else if (!derived->typeSymbol().get<DerivedTypeDetails>().sequence()) {
2703 msg =
2704 "Nonsequence derived type object '%s' is not allowed in an equivalence set"_err_en_US;
2705 }
2706 } else if (IsAutomatic(symbol)) {
2707 msg =
2708 "Automatic object '%s' is not allowed in an equivalence set"_err_en_US;
2709 } else if (symbol.test(Symbol::Flag::CrayPointee)) {
2710 messages_.Say(object.symbol.name(),
2711 "Cray pointee '%s' may not be a member of an EQUIVALENCE group"_err_en_US,
2712 object.symbol.name());
2713 }
2714 }
2715 if (!msg.text().empty()) {
2716 context_.Say(object.source, std::move(msg), symbol.name());
2717 }
2718 }
2719
2720 void CheckHelper::CheckBlockData(const Scope &scope) {
2721 // BLOCK DATA subprograms should contain only named common blocks.
2722 // C1415 presents a list of statements that shouldn't appear in
2723 // BLOCK DATA, but so long as the subprogram contains no executable
2724 // code and allocates no storage outside named COMMON, we're happy
2725 // (e.g., an ENUM is strictly not allowed).
2726 for (const auto &pair : scope) {
2727 const Symbol &symbol{*pair.second};
2728 if (!(symbol.has<CommonBlockDetails>() || symbol.has<UseDetails>() ||
2729 symbol.has<UseErrorDetails>() || symbol.has<DerivedTypeDetails>() ||
2730 symbol.has<SubprogramDetails>() ||
2731 symbol.has<ObjectEntityDetails>() ||
2732 (symbol.has<ProcEntityDetails>() &&
2733 !symbol.attrs().test(Attr::POINTER)))) {
2734 messages_.Say(symbol.name(),
2735 "'%s' may not appear in a BLOCK DATA subprogram"_err_en_US,
2736 symbol.name());
2737 }
2738 }
2739 }
2740
2741 // Check distinguishability of generic assignment and operators.
2742 // For these, generics and generic bindings must be considered together.
2743 void CheckHelper::CheckGenericOps(const Scope &scope) {
2744 DistinguishabilityHelper helper{context_};
2745 auto addSpecifics{[&](const Symbol &generic) {
2746 const auto *details{generic.GetUltimate().detailsIf<GenericDetails>()};
2747 if (!details) {
2748 // Not a generic; ensure characteristics are defined if a function.
2749 auto restorer{messages_.SetLocation(generic.name())};
2750 if (IsFunction(generic) && !context_.HasError(generic)) {
2751 if (const Symbol *result{FindFunctionResult(generic)};
2752 result && !context_.HasError(*result)) {
2753 Characterize(generic);
2754 }
2755 }
2756 return;
2757 }
2758 GenericKind kind{details->kind()};
2759 if (!kind.IsAssignment() && !kind.IsOperator()) {
2760 return;
2761 }
2762 const SymbolVector &specifics{details->specificProcs()};
2763 const std::vector<SourceName> &bindingNames{details->bindingNames()};
2764 for (std::size_t i{0}; i < specifics.size(); ++i) {
2765 const Symbol &specific{*specifics[i]};
2766 auto restorer{messages_.SetLocation(bindingNames[i])};
2767 if (const Procedure *proc{Characterize(specific)}) {
2768 if (kind.IsAssignment()) {
2769 if (!CheckDefinedAssignment(specific, *proc)) {
2770 continue;
2771 }
2772 } else {
2773 if (!CheckDefinedOperator(generic.name(), kind, specific, *proc)) {
2774 continue;
2775 }
2776 }
2777 helper.Add(generic, kind, specific, *proc);
2778 }
2779 }
2780 }};
2781 for (const auto &pair : scope) {
2782 const Symbol &symbol{*pair.second};
2783 addSpecifics(symbol);
2784 const Symbol &ultimate{symbol.GetUltimate()};
2785 if (ultimate.has<DerivedTypeDetails>()) {
2786 if (const Scope *typeScope{ultimate.scope()}) {
2787 for (const auto &pair2 : *typeScope) {
2788 addSpecifics(*pair2.second);
2789 }
2790 }
2791 }
2792 }
2793 helper.Check(scope);
2794 }
2795
2796 static bool IsSubprogramDefinition(const Symbol &symbol) {
2797 const auto *subp{symbol.detailsIf<SubprogramDetails>()};
2798 return subp && !subp->isInterface() && symbol.scope() &&
2799 symbol.scope()->kind() == Scope::Kind::Subprogram;
2800 }
2801
2802 static bool IsBlockData(const Symbol &symbol) {
2803 return symbol.scope() && symbol.scope()->kind() == Scope::Kind::BlockData;
2804 }
2805
2806 static bool IsExternalProcedureDefinition(const Symbol &symbol) {
2807 return IsBlockData(symbol) ||
2808 (IsSubprogramDefinition(symbol) &&
2809 (IsExternal(symbol) || symbol.GetBindName()));
2810 }
2811
2812 static std::optional<std::string> DefinesGlobalName(const Symbol &symbol) {
2813 if (const auto *module{symbol.detailsIf<ModuleDetails>()}) {
2814 if (!module->isSubmodule() && !symbol.owner().IsIntrinsicModules()) {
2815 return symbol.name().ToString();
2816 }
2817 } else if (IsBlockData(symbol)) {
2818 return symbol.name().ToString();
2819 } else {
2820 const std::string *bindC{symbol.GetBindName()};
2821 if (symbol.has<CommonBlockDetails>() ||
2822 IsExternalProcedureDefinition(symbol) ||
2823 (symbol.owner().IsGlobal() && IsExternal(symbol))) {
2824 return bindC ? *bindC : symbol.name().ToString();
2825 } else if (bindC &&
2826 (symbol.has<ObjectEntityDetails>() || IsModuleProcedure(symbol))) {
2827 return *bindC;
2828 }
2829 }
2830 return std::nullopt;
2831 }
2832
2833 // 19.2 p2
2834 void CheckHelper::CheckGlobalName(const Symbol &symbol) {
2835 if (auto global{DefinesGlobalName(symbol)}) {
2836 auto pair{globalNames_.emplace(std::move(*global), symbol)};
2837 if (!pair.second) {
2838 const Symbol &other{*pair.first->second};
2839 if (context_.HasError(symbol) || context_.HasError(other)) {
2840 // don't pile on
2841 } else if (symbol.has<CommonBlockDetails>() &&
2842 other.has<CommonBlockDetails>() && symbol.name() == other.name()) {
2843 // Two common blocks can have the same global name so long as
2844 // they're not in the same scope.
2845 } else if ((IsProcedure(symbol) || IsBlockData(symbol)) &&
2846 (IsProcedure(other) || IsBlockData(other)) &&
2847 (!IsExternalProcedureDefinition(symbol) ||
2848 !IsExternalProcedureDefinition(other))) {
2849 // both are procedures/BLOCK DATA, not both definitions
2850 } else if (symbol.has<ModuleDetails>()) {
2851 if (context_.ShouldWarn(common::LanguageFeature::BenignNameClash)) {
2852 messages_.Say(symbol.name(),
2853 "Module '%s' conflicts with a global name"_port_en_US,
2854 pair.first->first);
2855 }
2856 } else if (other.has<ModuleDetails>()) {
2857 if (context_.ShouldWarn(common::LanguageFeature::BenignNameClash)) {
2858 messages_.Say(symbol.name(),
2859 "Global name '%s' conflicts with a module"_port_en_US,
2860 pair.first->first);
2861 }
2862 } else if (auto *msg{messages_.Say(symbol.name(),
2863 "Two entities have the same global name '%s'"_err_en_US,
2864 pair.first->first)}) {
2865 msg->Attach(other.name(), "Conflicting declaration"_en_US);
2866 context_.SetError(symbol);
2867 context_.SetError(other);
2868 }
2869 }
2870 }
2871 }
2872
2873 void CheckHelper::CheckProcedureAssemblyName(const Symbol &symbol) {
2874 if (!IsProcedure(symbol) || symbol != symbol.GetUltimate())
2875 return;
2876 const std::string *bindName{symbol.GetBindName()};
2877 const bool hasExplicitBindingLabel{
2878 symbol.GetIsExplicitBindName() && bindName};
2879 if (hasExplicitBindingLabel || IsExternal(symbol)) {
2880 const std::string assemblyName{hasExplicitBindingLabel
2881 ? *bindName
2882 : common::GetExternalAssemblyName(
2883 symbol.name().ToString(), context_.underscoring())};
2884 auto pair{procedureAssemblyNames_.emplace(std::move(assemblyName), symbol)};
2885 if (!pair.second) {
2886 const Symbol &other{*pair.first->second};
2887 const bool otherHasExplicitBindingLabel{
2888 other.GetIsExplicitBindName() && other.GetBindName()};
2889 if (otherHasExplicitBindingLabel != hasExplicitBindingLabel) {
2890 // The BIND(C,NAME="...") binding label is the same as the name that
2891 // will be used in LLVM IR for an external procedure declared without
2892 // BIND(C) in the same file. While this is not forbidden by the
2893 // standard, this name collision would lead to a crash when producing
2894 // the IR.
2895 if (auto *msg{messages_.Say(symbol.name(),
2896 "%s procedure assembly name conflicts with %s procedure assembly name"_err_en_US,
2897 hasExplicitBindingLabel ? "BIND(C)" : "Non BIND(C)",
2898 hasExplicitBindingLabel ? "non BIND(C)" : "BIND(C)")}) {
2899 msg->Attach(other.name(), "Conflicting declaration"_en_US);
2900 }
2901 context_.SetError(symbol);
2902 context_.SetError(other);
2903 }
2904 // Otherwise, the global names also match and the conflict is analyzed
2905 // by CheckGlobalName.
2906 }
2907 }
2908 }
2909
2910 parser::Messages CheckHelper::WhyNotInteroperableDerivedType(
2911 const Symbol &symbol) {
2912 parser::Messages msgs;
2913 if (examinedByWhyNotInteroperable_.find(symbol) !=
2914 examinedByWhyNotInteroperable_.end()) {
2915 return msgs;
2916 }
2917 examinedByWhyNotInteroperable_.insert(symbol);
2918 if (const auto *derived{symbol.detailsIf<DerivedTypeDetails>()}) {
2919 if (derived->sequence()) { // C1801
2920 msgs.Say(symbol.name(),
2921 "An interoperable derived type cannot have the SEQUENCE attribute"_err_en_US);
2922 } else if (!derived->paramDecls().empty()) { // C1802
2923 msgs.Say(symbol.name(),
2924 "An interoperable derived type cannot have a type parameter"_err_en_US);
2925 } else if (const auto *parent{
2926 symbol.scope()->GetDerivedTypeParent()}) { // C1803
2927 if (symbol.attrs().test(Attr::BIND_C)) {
2928 msgs.Say(symbol.name(),
2929 "A derived type with the BIND attribute cannot be an extended derived type"_err_en_US);
2930 } else {
2931 bool interoperableParent{true};
2932 if (parent->symbol()) {
2933 auto bad{WhyNotInteroperableDerivedType(*parent->symbol())};
2934 if (bad.AnyFatalError()) {
2935 auto &msg{msgs.Say(symbol.name(),
2936 "The parent of an interoperable type is not interoperable"_err_en_US)};
2937 bad.AttachTo(msg, parser::Severity::None);
2938 interoperableParent = false;
2939 }
2940 }
2941 if (interoperableParent) {
2942 msgs.Say(symbol.name(),
2943 "An interoperable type should not be an extended derived type"_warn_en_US);
2944 }
2945 }
2946 }
2947 const Symbol *parentComponent{symbol.scope()
2948 ? derived->GetParentComponent(*symbol.scope())
2949 : nullptr};
2950 for (const auto &pair : *symbol.scope()) {
2951 const Symbol &component{*pair.second};
2952 if (&component == parentComponent) {
2953 continue; // was checked above
2954 }
2955 if (IsProcedure(component)) { // C1804
2956 msgs.Say(component.name(),
2957 "An interoperable derived type cannot have a type bound procedure"_err_en_US);
2958 } else if (IsAllocatableOrPointer(component)) { // C1806
2959 msgs.Say(component.name(),
2960 "An interoperable derived type cannot have a pointer or allocatable component"_err_en_US);
2961 } else if (const auto *type{component.GetType()}) {
2962 if (const auto *derived{type->AsDerived()}) {
2963 auto bad{WhyNotInteroperableDerivedType(derived->typeSymbol())};
2964 if (bad.AnyFatalError()) {
2965 auto &msg{msgs.Say(component.name(),
2966 "Component '%s' of an interoperable derived type must have an interoperable type but does not"_err_en_US,
2967 component.name())};
2968 bad.AttachTo(msg, parser::Severity::None);
2969 } else if (!derived->typeSymbol().GetUltimate().attrs().test(
2970 Attr::BIND_C)) {
2971 auto &msg{
2972 msgs.Say(component.name(),
2973 "Derived type of component '%s' of an interoperable derived type should have the BIND attribute"_warn_en_US,
2974 component.name())
2975 .Attach(derived->typeSymbol().name(),
2976 "Non-BIND(C) component type"_en_US)};
2977 bad.AttachTo(msg, parser::Severity::None);
2978 } else {
2979 msgs.Annex(std::move(bad));
2980 }
2981 } else if (!IsInteroperableIntrinsicType(
2982 *type, context_.languageFeatures())
2983 .value_or(false)) {
2984 auto maybeDyType{evaluate::DynamicType::From(*type)};
2985 if (type->category() == DeclTypeSpec::Logical) {
2986 if (context_.ShouldWarn(common::UsageWarning::LogicalVsCBool)) {
2987 msgs.Say(component.name(),
2988 "A LOGICAL component of an interoperable type should have the interoperable KIND=C_BOOL"_port_en_US);
2989 }
2990 } else if (type->category() == DeclTypeSpec::Character &&
2991 maybeDyType && maybeDyType->kind() == 1) {
2992 if (context_.ShouldWarn(common::UsageWarning::BindCCharLength)) {
2993 msgs.Say(component.name(),
2994 "A CHARACTER component of an interoperable type should have length 1"_port_en_US);
2995 }
2996 } else {
2997 msgs.Say(component.name(),
2998 "Each component of an interoperable derived type must have an interoperable type"_err_en_US);
2999 }
3000 }
3001 }
3002 if (auto extents{
3003 evaluate::GetConstantExtents(foldingContext_, &component)};
3004 extents && evaluate::GetSize(*extents) == 0) {
3005 msgs.Say(component.name(),
3006 "An array component of an interoperable type must have at least one element"_err_en_US);
3007 }
3008 }
3009 if (derived->componentNames().empty()) { // F'2023 C1805
3010 if (context_.ShouldWarn(common::LanguageFeature::EmptyBindCDerivedType)) {
3011 msgs.Say(symbol.name(),
3012 "A derived type with the BIND attribute should not be empty"_warn_en_US);
3013 }
3014 }
3015 }
3016 if (msgs.AnyFatalError()) {
3017 examinedByWhyNotInteroperable_.erase(symbol);
3018 }
3019 return msgs;
3020 }
3021
3022 parser::Messages CheckHelper::WhyNotInteroperableObject(const Symbol &symbol) {
3023 parser::Messages msgs;
3024 if (examinedByWhyNotInteroperable_.find(symbol) !=
3025 examinedByWhyNotInteroperable_.end()) {
3026 return msgs;
3027 }
3028 bool isExplicitBindC{symbol.attrs().test(Attr::BIND_C)};
3029 examinedByWhyNotInteroperable_.insert(symbol);
3030 CHECK(symbol.has<ObjectEntityDetails>());
3031 if (isExplicitBindC && !symbol.owner().IsModule()) {
3032 msgs.Say(symbol.name(),
3033 "A variable with BIND(C) attribute may only appear in the specification part of a module"_err_en_US);
3034 }
3035 auto shape{evaluate::GetShape(foldingContext_, symbol)};
3036 if (shape) {
3037 if (evaluate::GetRank(*shape) == 0) { // 18.3.4
3038 if (IsAllocatableOrPointer(symbol) && !IsDummy(symbol)) {
3039 msgs.Say(symbol.name(),
3040 "A scalar interoperable variable may not be ALLOCATABLE or POINTER"_err_en_US);
3041 }
3042 } else if (auto extents{
3043 evaluate::AsConstantExtents(foldingContext_, *shape)}) {
3044 if (evaluate::GetSize(*extents) == 0) {
3045 msgs.Say(symbol.name(),
3046 "Interoperable array must have at least one element"_err_en_US);
3047 }
3048 } else if (!evaluate::IsExplicitShape(symbol) &&
3049 !IsAssumedSizeArray(symbol) &&
3050 !(IsDummy(symbol) && !symbol.attrs().test(Attr::VALUE))) {
3051 msgs.Say(symbol.name(),
3052 "BIND(C) array must have explicit shape or be assumed-size unless a dummy argument without the VALUE attribute"_err_en_US);
3053 }
3054 }
3055 if (const auto *type{symbol.GetType()}) {
3056 const auto *derived{type->AsDerived()};
3057 if (derived && !derived->typeSymbol().attrs().test(Attr::BIND_C)) {
3058 if (!context_.IsEnabled(
3059 common::LanguageFeature::NonBindCInteroperability)) {
3060 msgs.Say(symbol.name(),
3061 "The derived type of an interoperable object must be BIND(C)"_err_en_US)
3062 .Attach(derived->typeSymbol().name(), "Non-BIND(C) type"_en_US);
3063 } else if (auto bad{
3064 WhyNotInteroperableDerivedType(derived->typeSymbol())};
3065 bad.AnyFatalError()) {
3066 bad.AttachTo(
3067 msgs.Say(symbol.name(),
3068 "The derived type of an interoperable object must be interoperable, but is not"_err_en_US)
3069 .Attach(derived->typeSymbol().name(),
3070 "Non-interoperable type"_en_US),
3071 parser::Severity::None);
3072 } else {
3073 msgs.Say(symbol.name(),
3074 "The derived type of an interoperable object should be BIND(C)"_warn_en_US)
3075 .Attach(derived->typeSymbol().name(), "Non-BIND(C) type"_en_US);
3076 }
3077 }
3078 if (type->IsAssumedType()) { // ok
3079 } else if (IsAssumedLengthCharacter(symbol)) {
3080 } else if (IsAllocatableOrPointer(symbol) &&
3081 type->category() == DeclTypeSpec::Character &&
3082 type->characterTypeSpec().length().isDeferred()) {
3083 // ok; F'2023 18.3.7 p2(6)
3084 } else if (derived ||
3085 IsInteroperableIntrinsicType(*type, context_.languageFeatures())
3086 .value_or(false)) {
3087 // F'2023 18.3.7 p2(4,5)
3088 } else if (type->category() == DeclTypeSpec::Logical) {
3089 if (context_.ShouldWarn(common::UsageWarning::LogicalVsCBool) &&
3090 !InModuleFile()) {
3091 if (IsDummy(symbol)) {
3092 msgs.Say(symbol.name(),
3093 "A BIND(C) LOGICAL dummy argument should have the interoperable KIND=C_BOOL"_port_en_US);
3094 } else {
3095 msgs.Say(symbol.name(),
3096 "A BIND(C) LOGICAL object should have the interoperable KIND=C_BOOL"_port_en_US);
3097 }
3098 }
3099 } else if (symbol.attrs().test(Attr::VALUE)) {
3100 msgs.Say(symbol.name(),
3101 "A BIND(C) VALUE dummy argument must have an interoperable type"_err_en_US);
3102 } else {
3103 msgs.Say(symbol.name(),
3104 "A BIND(C) object must have an interoperable type"_err_en_US);
3105 }
3106 }
3107 if (IsOptional(symbol) && !symbol.attrs().test(Attr::VALUE)) {
3108 msgs.Say(symbol.name(),
3109 "An interoperable procedure with an OPTIONAL dummy argument might not be portable"_port_en_US);
3110 }
3111 if (IsDescriptor(symbol) && IsPointer(symbol) &&
3112 symbol.attrs().test(Attr::CONTIGUOUS)) {
3113 msgs.Say(symbol.name(),
3114 "An interoperable pointer must not be CONTIGUOUS"_err_en_US);
3115 }
3116 if (msgs.AnyFatalError()) {
3117 examinedByWhyNotInteroperable_.erase(symbol);
3118 }
3119 return msgs;
3120 }
3121
3122 parser::Messages CheckHelper::WhyNotInteroperableFunctionResult(
3123 const Symbol &symbol) {
3124 parser::Messages msgs;
3125 if (IsPointer(symbol) || IsAllocatable(symbol)) {
3126 msgs.Say(symbol.name(),
3127 "Interoperable function result may not have ALLOCATABLE or POINTER attribute"_err_en_US);
3128 }
3129 if (const DeclTypeSpec * type{symbol.GetType()};
3130 type && type->category() == DeclTypeSpec::Character) {
3131 bool isConstOne{false}; // 18.3.1(1)
3132 if (const auto &len{type->characterTypeSpec().length().GetExplicit()}) {
3133 if (auto constLen{evaluate::ToInt64(*len)}) {
3134 isConstOne = constLen == 1;
3135 }
3136 }
3137 if (!isConstOne) {
3138 msgs.Say(symbol.name(),
3139 "Interoperable character function result must have length one"_err_en_US);
3140 }
3141 }
3142 if (symbol.Rank() > 0) {
3143 msgs.Say(symbol.name(),
3144 "Interoperable function result must be scalar"_err_en_US);
3145 }
3146 if (symbol.Corank()) {
3147 msgs.Say(symbol.name(),
3148 "Interoperable function result may not be a coarray"_err_en_US);
3149 }
3150 return msgs;
3151 }
3152
3153 parser::Messages CheckHelper::WhyNotInteroperableProcedure(
3154 const Symbol &symbol, bool isError) {
3155 parser::Messages msgs;
3156 if (examinedByWhyNotInteroperable_.find(symbol) !=
3157 examinedByWhyNotInteroperable_.end()) {
3158 return msgs;
3159 }
3160 isError |= symbol.attrs().test(Attr::BIND_C);
3161 examinedByWhyNotInteroperable_.insert(symbol);
3162 if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}) {
3163 if (isError) {
3164 if (!proc->procInterface() ||
3165 !proc->procInterface()->attrs().test(Attr::BIND_C)) {
3166 msgs.Say(symbol.name(),
3167 "An interface name with the BIND attribute must appear if the BIND attribute appears in a procedure declaration"_err_en_US);
3168 }
3169 } else if (!proc->procInterface()) {
3170 msgs.Say(symbol.name(),
3171 "An interoperable procedure should have an interface"_port_en_US);
3172 } else if (!proc->procInterface()->attrs().test(Attr::BIND_C)) {
3173 auto bad{WhyNotInteroperableProcedure(
3174 *proc->procInterface(), /*isError=*/false)};
3175 if (bad.AnyFatalError()) {
3176 bad.AttachTo(msgs.Say(symbol.name(),
3177 "An interoperable procedure must have an interoperable interface"_err_en_US));
3178 } else {
3179 msgs.Say(symbol.name(),
3180 "An interoperable procedure should have an interface with the BIND attribute"_warn_en_US);
3181 }
3182 }
3183 } else if (const auto *subp{symbol.detailsIf<SubprogramDetails>()}) {
3184 for (const Symbol *dummy : subp->dummyArgs()) {
3185 if (dummy) {
3186 parser::Messages dummyMsgs;
3187 if (dummy->has<ProcEntityDetails>() ||
3188 dummy->has<SubprogramDetails>()) {
3189 dummyMsgs = WhyNotInteroperableProcedure(*dummy, /*isError=*/false);
3190 if (dummyMsgs.empty() && !dummy->attrs().test(Attr::BIND_C)) {
3191 dummyMsgs.Say(dummy->name(),
3192 "A dummy procedure of an interoperable procedure should be BIND(C)"_warn_en_US);
3193 }
3194 } else if (dummy->has<ObjectEntityDetails>()) {
3195 dummyMsgs = WhyNotInteroperableObject(*dummy);
3196 } else {
3197 CheckBindC(*dummy);
3198 }
3199 msgs.Annex(std::move(dummyMsgs));
3200 } else {
3201 msgs.Say(symbol.name(),
3202 "A subprogram interface with the BIND attribute may not have an alternate return argument"_err_en_US);
3203 }
3204 }
3205 if (subp->isFunction()) {
3206 if (subp->result().has<ObjectEntityDetails>()) {
3207 msgs.Annex(WhyNotInteroperableFunctionResult(subp->result()));
3208 } else {
3209 msgs.Say(subp->result().name(),
3210 "The result of an interoperable function must be a data object"_err_en_US);
3211 }
3212 }
3213 }
3214 if (msgs.AnyFatalError()) {
3215 examinedByWhyNotInteroperable_.erase(symbol);
3216 }
3217 return msgs;
3218 }
3219
3220 void CheckHelper::CheckBindC(const Symbol &symbol) {
3221 bool isExplicitBindC{symbol.attrs().test(Attr::BIND_C)};
3222 if (isExplicitBindC) {
3223 CheckConflicting(symbol, Attr::BIND_C, Attr::ELEMENTAL);
3224 CheckConflicting(symbol, Attr::BIND_C, Attr::INTRINSIC);
3225 CheckConflicting(symbol, Attr::BIND_C, Attr::PARAMETER);
3226 } else {
3227 // symbol must be interoperable (e.g., dummy argument of interoperable
3228 // procedure interface) but is not itself BIND(C).
3229 }
3230 parser::Messages whyNot;
3231 if (const std::string * bindName{symbol.GetBindName()};
3232 bindName) { // has a binding name
3233 if (!bindName->empty()) {
3234 bool ok{bindName->front() == '_' || parser::IsLetter(bindName->front())};
3235 for (char ch : *bindName) {
3236 ok &= ch == '_' || parser::IsLetter(ch) || parser::IsDecimalDigit(ch);
3237 }
3238 if (!ok) {
3239 messages_.Say(symbol.name(),
3240 "Symbol has a BIND(C) name that is not a valid C language identifier"_err_en_US);
3241 context_.SetError(symbol);
3242 }
3243 }
3244 }
3245 if (symbol.GetIsExplicitBindName()) { // BIND(C,NAME=...); C1552, C1529
3246 auto defClass{ClassifyProcedure(symbol)};
3247 if (IsProcedurePointer(symbol)) {
3248 messages_.Say(symbol.name(),
3249 "A procedure pointer may not have a BIND attribute with a name"_err_en_US);
3250 context_.SetError(symbol);
3251 } else if (defClass == ProcedureDefinitionClass::None ||
3252 IsExternal(symbol)) {
3253 } else if (symbol.attrs().test(Attr::ABSTRACT)) {
3254 messages_.Say(symbol.name(),
3255 "An ABSTRACT interface may not have a BIND attribute with a name"_err_en_US);
3256 context_.SetError(symbol);
3257 } else if (defClass == ProcedureDefinitionClass::Internal ||
3258 defClass == ProcedureDefinitionClass::Dummy) {
3259 messages_.Say(symbol.name(),
3260 "An internal or dummy procedure may not have a BIND(C,NAME=) binding label"_err_en_US);
3261 context_.SetError(symbol);
3262 }
3263 }
3264 if (symbol.has<ObjectEntityDetails>()) {
3265 whyNot = WhyNotInteroperableObject(symbol);
3266 } else if (symbol.has<ProcEntityDetails>() ||
3267 symbol.has<SubprogramDetails>()) {
3268 whyNot = WhyNotInteroperableProcedure(symbol, /*isError=*/isExplicitBindC);
3269 } else if (symbol.has<DerivedTypeDetails>()) {
3270 whyNot = WhyNotInteroperableDerivedType(symbol);
3271 }
3272 if (!whyNot.empty()) {
3273 bool anyFatal{whyNot.AnyFatalError()};
3274 if (anyFatal ||
3275 (!InModuleFile() &&
3276 context_.ShouldWarn(
3277 common::LanguageFeature::NonBindCInteroperability))) {
3278 context_.messages().Annex(std::move(whyNot));
3279 }
3280 if (anyFatal) {
3281 context_.SetError(symbol);
3282 }
3283 }
3284 }
3285
3286 bool CheckHelper::CheckDioDummyIsData(
3287 const Symbol &subp, const Symbol *arg, std::size_t position) {
3288 if (arg && arg->detailsIf<ObjectEntityDetails>()) {
3289 return true;
3290 } else {
3291 if (arg) {
3292 messages_.Say(arg->name(),
3293 "Dummy argument '%s' must be a data object"_err_en_US, arg->name());
3294 } else {
3295 messages_.Say(subp.name(),
3296 "Dummy argument %d of '%s' must be a data object"_err_en_US, position,
3297 subp.name());
3298 }
3299 return false;
3300 }
3301 }
3302
3303 void CheckHelper::CheckAlreadySeenDefinedIo(const DerivedTypeSpec &derivedType,
3304 common::DefinedIo ioKind, const Symbol &proc, const Symbol &generic) {
3305 // Check for conflict between non-type-bound defined I/O and type-bound
3306 // generics. It's okay to have two or more distinct defined I/O procedures for
3307 // the same type if they're coming from distinct non-type-bound interfaces.
3308 // (The non-type-bound interfaces would have been merged into a single generic
3309 // -- with errors where indistinguishable -- when both were visible from the
3310 // same scope.)
3311 if (generic.owner().IsDerivedType()) {
3312 return;
3313 }
3314 if (const Scope * dtScope{derivedType.scope()}) {
3315 if (auto iter{dtScope->find(generic.name())}; iter != dtScope->end()) {
3316 for (auto specRef : iter->second->get<GenericDetails>().specificProcs()) {
3317 const Symbol &specific{specRef->get<ProcBindingDetails>().symbol()};
3318 if (specific == proc) { // unambiguous, accept
3319 continue;
3320 }
3321 if (const auto *specDT{GetDtvArgDerivedType(specific)};
3322 specDT && evaluate::AreSameDerivedType(derivedType, *specDT)) {
3323 SayWithDeclaration(*specRef, proc.name(),
3324 "Derived type '%s' has conflicting type-bound input/output procedure '%s'"_err_en_US,
3325 derivedType.name(), GenericKind::AsFortran(ioKind));
3326 return;
3327 }
3328 }
3329 }
3330 }
3331 }
3332
3333 void CheckHelper::CheckDioDummyIsDerived(const Symbol &subp, const Symbol &arg,
3334 common::DefinedIo ioKind, const Symbol &generic) {
3335 if (const DeclTypeSpec *type{arg.GetType()}) {
3336 if (const DerivedTypeSpec *derivedType{type->AsDerived()}) {
3337 CheckAlreadySeenDefinedIo(*derivedType, ioKind, subp, generic);
3338 bool isPolymorphic{type->IsPolymorphic()};
3339 if (isPolymorphic != IsExtensibleType(derivedType)) {
3340 messages_.Say(arg.name(),
3341 "Dummy argument '%s' of a defined input/output procedure must be %s when the derived type is %s"_err_en_US,
3342 arg.name(), isPolymorphic ? "TYPE()" : "CLASS()",
3343 isPolymorphic ? "not extensible" : "extensible");
3344 }
3345 } else {
3346 messages_.Say(arg.name(),
3347 "Dummy argument '%s' of a defined input/output procedure must have a"
3348 " derived type"_err_en_US,
3349 arg.name());
3350 }
3351 }
3352 }
3353
3354 void CheckHelper::CheckDioDummyIsDefaultInteger(
3355 const Symbol &subp, const Symbol &arg) {
3356 if (const DeclTypeSpec *type{arg.GetType()};
3357 type && type->IsNumeric(TypeCategory::Integer)) {
3358 if (const auto kind{evaluate::ToInt64(type->numericTypeSpec().kind())};
3359 kind && *kind == context_.GetDefaultKind(TypeCategory::Integer)) {
3360 return;
3361 }
3362 }
3363 messages_.Say(arg.name(),
3364 "Dummy argument '%s' of a defined input/output procedure"
3365 " must be an INTEGER of default KIND"_err_en_US,
3366 arg.name());
3367 }
3368
3369 void CheckHelper::CheckDioDummyIsScalar(const Symbol &subp, const Symbol &arg) {
3370 if (arg.Rank() > 0 || arg.Corank() > 0) {
3371 messages_.Say(arg.name(),
3372 "Dummy argument '%s' of a defined input/output procedure"
3373 " must be a scalar"_err_en_US,
3374 arg.name());
3375 }
3376 }
3377
3378 void CheckHelper::CheckDioDtvArg(const Symbol &subp, const Symbol *arg,
3379 common::DefinedIo ioKind, const Symbol &generic) {
3380 // Dtv argument looks like: dtv-type-spec, INTENT(INOUT) :: dtv
3381 if (CheckDioDummyIsData(subp, arg, 0)) {
3382 CheckDioDummyIsDerived(subp, *arg, ioKind, generic);
3383 CheckDioDummyAttrs(subp, *arg,
3384 ioKind == common::DefinedIo::ReadFormatted ||
3385 ioKind == common::DefinedIo::ReadUnformatted
3386 ? Attr::INTENT_INOUT
3387 : Attr::INTENT_IN);
3388 }
3389 }
3390
3391 // If an explicit INTRINSIC name is a function, so must all the specifics be,
3392 // and similarly for subroutines
3393 void CheckHelper::CheckGenericVsIntrinsic(
3394 const Symbol &symbol, const GenericDetails &generic) {
3395 if (symbol.attrs().test(Attr::INTRINSIC)) {
3396 const evaluate::IntrinsicProcTable &table{
3397 context_.foldingContext().intrinsics()};
3398 bool isSubroutine{table.IsIntrinsicSubroutine(symbol.name().ToString())};
3399 if (isSubroutine || table.IsIntrinsicFunction(symbol.name().ToString())) {
3400 for (const SymbolRef &ref : generic.specificProcs()) {
3401 const Symbol &ultimate{ref->GetUltimate()};
3402 bool specificFunc{ultimate.test(Symbol::Flag::Function)};
3403 bool specificSubr{ultimate.test(Symbol::Flag::Subroutine)};
3404 if (!specificFunc && !specificSubr) {
3405 if (const auto *proc{ultimate.detailsIf<SubprogramDetails>()}) {
3406 if (proc->isFunction()) {
3407 specificFunc = true;
3408 } else {
3409 specificSubr = true;
3410 }
3411 }
3412 }
3413 if ((specificFunc || specificSubr) &&
3414 isSubroutine != specificSubr) { // C848
3415 messages_.Say(symbol.name(),
3416 "Generic interface '%s' with explicit intrinsic %s of the same name may not have specific procedure '%s' that is a %s"_err_en_US,
3417 symbol.name(), isSubroutine ? "subroutine" : "function",
3418 ref->name(), isSubroutine ? "function" : "subroutine");
3419 }
3420 }
3421 }
3422 }
3423 }
3424
3425 void CheckHelper::CheckDefaultIntegerArg(
3426 const Symbol &subp, const Symbol *arg, Attr intent) {
3427 // Argument looks like: INTEGER, INTENT(intent) :: arg
3428 if (CheckDioDummyIsData(subp, arg, 1)) {
3429 CheckDioDummyIsDefaultInteger(subp, *arg);
3430 CheckDioDummyIsScalar(subp, *arg);
3431 CheckDioDummyAttrs(subp, *arg, intent);
3432 }
3433 }
3434
3435 void CheckHelper::CheckDioAssumedLenCharacterArg(const Symbol &subp,
3436 const Symbol *arg, std::size_t argPosition, Attr intent) {
3437 // Argument looks like: CHARACTER (LEN=*), INTENT(intent) :: (iotype OR iomsg)
3438 if (CheckDioDummyIsData(subp, arg, argPosition)) {
3439 CheckDioDummyAttrs(subp, *arg, intent);
3440 const DeclTypeSpec *type{arg ? arg->GetType() : nullptr};
3441 const IntrinsicTypeSpec *intrinsic{type ? type->AsIntrinsic() : nullptr};
3442 const auto kind{
3443 intrinsic ? evaluate::ToInt64(intrinsic->kind()) : std::nullopt};
3444 if (!IsAssumedLengthCharacter(*arg) ||
3445 (!kind ||
3446 *kind !=
3447 context_.defaultKinds().GetDefaultKind(
3448 TypeCategory::Character))) {
3449 messages_.Say(arg->name(),
3450 "Dummy argument '%s' of a defined input/output procedure"
3451 " must be assumed-length CHARACTER of default kind"_err_en_US,
3452 arg->name());
3453 }
3454 }
3455 }
3456
3457 void CheckHelper::CheckDioVlistArg(
3458 const Symbol &subp, const Symbol *arg, std::size_t argPosition) {
3459 // Vlist argument looks like: INTEGER, INTENT(IN) :: v_list(:)
3460 if (CheckDioDummyIsData(subp, arg, argPosition)) {
3461 CheckDioDummyIsDefaultInteger(subp, *arg);
3462 CheckDioDummyAttrs(subp, *arg, Attr::INTENT_IN);
3463 const auto *objectDetails{arg->detailsIf<ObjectEntityDetails>()};
3464 if (!objectDetails || !objectDetails->shape().CanBeDeferredShape()) {
3465 messages_.Say(arg->name(),
3466 "Dummy argument '%s' of a defined input/output procedure must be"
3467 " deferred shape"_err_en_US,
3468 arg->name());
3469 }
3470 }
3471 }
3472
3473 void CheckHelper::CheckDioArgCount(
3474 const Symbol &subp, common::DefinedIo ioKind, std::size_t argCount) {
3475 const std::size_t requiredArgCount{
3476 (std::size_t)(ioKind == common::DefinedIo::ReadFormatted ||
3477 ioKind == common::DefinedIo::WriteFormatted
3478 ? 6
3479 : 4)};
3480 if (argCount != requiredArgCount) {
3481 SayWithDeclaration(subp,
3482 "Defined input/output procedure '%s' must have"
3483 " %d dummy arguments rather than %d"_err_en_US,
3484 subp.name(), requiredArgCount, argCount);
3485 context_.SetError(subp);
3486 }
3487 }
3488
3489 void CheckHelper::CheckDioDummyAttrs(
3490 const Symbol &subp, const Symbol &arg, Attr goodIntent) {
3491 // Defined I/O procedures can't have attributes other than INTENT
3492 Attrs attrs{arg.attrs()};
3493 if (!attrs.test(goodIntent)) {
3494 messages_.Say(arg.name(),
3495 "Dummy argument '%s' of a defined input/output procedure"
3496 " must have intent '%s'"_err_en_US,
3497 arg.name(), AttrToString(goodIntent));
3498 }
3499 attrs = attrs - Attr::INTENT_IN - Attr::INTENT_OUT - Attr::INTENT_INOUT;
3500 if (!attrs.empty()) {
3501 messages_.Say(arg.name(),
3502 "Dummy argument '%s' of a defined input/output procedure may not have"
3503 " any attributes"_err_en_US,
3504 arg.name());
3505 }
3506 }
3507
3508 // Enforce semantics for defined input/output procedures (12.6.4.8.2) and C777
3509 void CheckHelper::CheckDefinedIoProc(const Symbol &symbol,
3510 const GenericDetails &details, common::DefinedIo ioKind) {
3511 for (auto ref : details.specificProcs()) {
3512 const Symbol &ultimate{ref->GetUltimate()};
3513 const auto *binding{ultimate.detailsIf<ProcBindingDetails>()};
3514 const Symbol &specific{*(binding ? &binding->symbol() : &ultimate)};
3515 if (ultimate.attrs().test(Attr::NOPASS)) { // C774
3516 messages_.Say("Defined input/output procedure '%s' may not have NOPASS "
3517 "attribute"_err_en_US,
3518 ultimate.name());
3519 context_.SetError(ultimate);
3520 }
3521 if (const auto *subpDetails{specific.detailsIf<SubprogramDetails>()}) {
3522 const std::vector<Symbol *> &dummyArgs{subpDetails->dummyArgs()};
3523 CheckDioArgCount(specific, ioKind, dummyArgs.size());
3524 int argCount{0};
3525 for (auto *arg : dummyArgs) {
3526 switch (argCount++) {
3527 case 0:
3528 // dtv-type-spec, INTENT(INOUT) :: dtv
3529 CheckDioDtvArg(specific, arg, ioKind, symbol);
3530 break;
3531 case 1:
3532 // INTEGER, INTENT(IN) :: unit
3533 CheckDefaultIntegerArg(specific, arg, Attr::INTENT_IN);
3534 break;
3535 case 2:
3536 if (ioKind == common::DefinedIo::ReadFormatted ||
3537 ioKind == common::DefinedIo::WriteFormatted) {
3538 // CHARACTER (LEN=*), INTENT(IN) :: iotype
3539 CheckDioAssumedLenCharacterArg(
3540 specific, arg, argCount, Attr::INTENT_IN);
3541 } else {
3542 // INTEGER, INTENT(OUT) :: iostat
3543 CheckDefaultIntegerArg(specific, arg, Attr::INTENT_OUT);
3544 }
3545 break;
3546 case 3:
3547 if (ioKind == common::DefinedIo::ReadFormatted ||
3548 ioKind == common::DefinedIo::WriteFormatted) {
3549 // INTEGER, INTENT(IN) :: v_list(:)
3550 CheckDioVlistArg(specific, arg, argCount);
3551 } else {
3552 // CHARACTER (LEN=*), INTENT(INOUT) :: iomsg
3553 CheckDioAssumedLenCharacterArg(
3554 specific, arg, argCount, Attr::INTENT_INOUT);
3555 }
3556 break;
3557 case 4:
3558 // INTEGER, INTENT(OUT) :: iostat
3559 CheckDefaultIntegerArg(specific, arg, Attr::INTENT_OUT);
3560 break;
3561 case 5:
3562 // CHARACTER (LEN=*), INTENT(INOUT) :: iomsg
3563 CheckDioAssumedLenCharacterArg(
3564 specific, arg, argCount, Attr::INTENT_INOUT);
3565 break;
3566 default:;
3567 }
3568 }
3569 }
3570 }
3571 }
3572
3573 void CheckHelper::CheckSymbolType(const Symbol &symbol) {
3574 const Symbol *result{FindFunctionResult(symbol)};
3575 const Symbol &relevant{result ? *result : symbol};
3576 if (IsAllocatable(relevant)) { // always ok
3577 } else if (IsProcedurePointer(symbol) && result && IsPointer(*result)) {
3578 // procedure pointer returning allocatable or pointer: ok
3579 } else if (IsPointer(relevant) && !IsProcedure(relevant)) {
3580 // object pointers are always ok
3581 } else if (auto dyType{evaluate::DynamicType::From(relevant)}) {
3582 if (dyType->IsPolymorphic() && !dyType->IsAssumedType() &&
3583 !(IsDummy(symbol) && !IsProcedure(relevant))) { // C708
3584 messages_.Say(
3585 "CLASS entity '%s' must be a dummy argument, allocatable, or object pointer"_err_en_US,
3586 symbol.name());
3587 }
3588 if (dyType->HasDeferredTypeParameter()) { // C702
3589 messages_.Say(
3590 "'%s' has a type %s with a deferred type parameter but is neither an allocatable nor an object pointer"_err_en_US,
3591 symbol.name(), dyType->AsFortran());
3592 }
3593 }
3594 }
3595
3596 void CheckHelper::CheckModuleProcedureDef(const Symbol &symbol) {
3597 auto procClass{ClassifyProcedure(symbol)};
3598 if (const auto *subprogram{symbol.detailsIf<SubprogramDetails>()};
3599 subprogram &&
3600 (procClass == ProcedureDefinitionClass::Module &&
3601 symbol.attrs().test(Attr::MODULE)) &&
3602 !subprogram->bindName() && !subprogram->isInterface()) {
3603 const Symbol &interface {
3604 subprogram->moduleInterface() ? *subprogram->moduleInterface() : symbol
3605 };
3606 if (const Symbol *
3607 module{interface.owner().kind() == Scope::Kind::Module
3608 ? interface.owner().symbol()
3609 : nullptr};
3610 module && module->has<ModuleDetails>()) {
3611 std::pair<SourceName, const Symbol *> key{symbol.name(), module};
3612 auto iter{moduleProcs_.find(key)};
3613 if (iter == moduleProcs_.end()) {
3614 moduleProcs_.emplace(std::move(key), symbol);
3615 } else if (
3616 auto *msg{messages_.Say(symbol.name(),
3617 "Module procedure '%s' in '%s' has multiple definitions"_err_en_US,
3618 symbol.name(), GetModuleOrSubmoduleName(*module))}) {
3619 msg->Attach(iter->second->name(), "Previous definition of '%s'"_en_US,
3620 symbol.name());
3621 }
3622 }
3623 }
3624 }
3625
3626 void SubprogramMatchHelper::Check(
3627 const Symbol &symbol1, const Symbol &symbol2) {
3628 const auto details1{symbol1.get<SubprogramDetails>()};
3629 const auto details2{symbol2.get<SubprogramDetails>()};
3630 if (details1.isFunction() != details2.isFunction()) {
3631 Say(symbol1, symbol2,
3632 details1.isFunction()
3633 ? "Module function '%s' was declared as a subroutine in the"
3634 " corresponding interface body"_err_en_US
3635 : "Module subroutine '%s' was declared as a function in the"
3636 " corresponding interface body"_err_en_US);
3637 return;
3638 }
3639 const auto &args1{details1.dummyArgs()};
3640 const auto &args2{details2.dummyArgs()};
3641 int nargs1{static_cast<int>(args1.size())};
3642 int nargs2{static_cast<int>(args2.size())};
3643 if (nargs1 != nargs2) {
3644 Say(symbol1, symbol2,
3645 "Module subprogram '%s' has %d args but the corresponding interface"
3646 " body has %d"_err_en_US,
3647 nargs1, nargs2);
3648 return;
3649 }
3650 bool nonRecursive1{symbol1.attrs().test(Attr::NON_RECURSIVE)};
3651 if (nonRecursive1 != symbol2.attrs().test(Attr::NON_RECURSIVE)) { // C1551
3652 Say(symbol1, symbol2,
3653 nonRecursive1
3654 ? "Module subprogram '%s' has NON_RECURSIVE prefix but"
3655 " the corresponding interface body does not"_err_en_US
3656 : "Module subprogram '%s' does not have NON_RECURSIVE prefix but "
3657 "the corresponding interface body does"_err_en_US);
3658 }
3659 const std::string *bindName1{details1.bindName()};
3660 const std::string *bindName2{details2.bindName()};
3661 if (!bindName1 && !bindName2) {
3662 // OK - neither has a binding label
3663 } else if (!bindName1) {
3664 Say(symbol1, symbol2,
3665 "Module subprogram '%s' does not have a binding label but the"
3666 " corresponding interface body does"_err_en_US);
3667 } else if (!bindName2) {
3668 Say(symbol1, symbol2,
3669 "Module subprogram '%s' has a binding label but the"
3670 " corresponding interface body does not"_err_en_US);
3671 } else if (*bindName1 != *bindName2) {
3672 Say(symbol1, symbol2,
3673 "Module subprogram '%s' has binding label '%s' but the corresponding"
3674 " interface body has '%s'"_err_en_US,
3675 *details1.bindName(), *details2.bindName());
3676 }
3677 const Procedure *proc1{checkHelper.Characterize(symbol1)};
3678 const Procedure *proc2{checkHelper.Characterize(symbol2)};
3679 if (!proc1 || !proc2) {
3680 return;
3681 }
3682 if (proc1->attrs.test(Procedure::Attr::Pure) !=
3683 proc2->attrs.test(Procedure::Attr::Pure)) {
3684 Say(symbol1, symbol2,
3685 "Module subprogram '%s' and its corresponding interface body are not both PURE"_err_en_US);
3686 }
3687 if (proc1->attrs.test(Procedure::Attr::Elemental) !=
3688 proc2->attrs.test(Procedure::Attr::Elemental)) {
3689 Say(symbol1, symbol2,
3690 "Module subprogram '%s' and its corresponding interface body are not both ELEMENTAL"_err_en_US);
3691 }
3692 if (proc1->attrs.test(Procedure::Attr::BindC) !=
3693 proc2->attrs.test(Procedure::Attr::BindC)) {
3694 Say(symbol1, symbol2,
3695 "Module subprogram '%s' and its corresponding interface body are not both BIND(C)"_err_en_US);
3696 }
3697 if (proc1->functionResult && proc2->functionResult) {
3698 std::string whyNot;
3699 if (!proc1->functionResult->IsCompatibleWith(
3700 *proc2->functionResult, &whyNot)) {
3701 Say(symbol1, symbol2,
3702 "Result of function '%s' is not compatible with the result of the corresponding interface body: %s"_err_en_US,
3703 whyNot);
3704 }
3705 }
3706 for (int i{0}; i < nargs1; ++i) {
3707 const Symbol *arg1{args1[i]};
3708 const Symbol *arg2{args2[i]};
3709 if (arg1 && !arg2) {
3710 Say(symbol1, symbol2,
3711 "Dummy argument %2$d of '%1$s' is not an alternate return indicator"
3712 " but the corresponding argument in the interface body is"_err_en_US,
3713 i + 1);
3714 } else if (!arg1 && arg2) {
3715 Say(symbol1, symbol2,
3716 "Dummy argument %2$d of '%1$s' is an alternate return indicator but"
3717 " the corresponding argument in the interface body is not"_err_en_US,
3718 i + 1);
3719 } else if (arg1 && arg2) {
3720 SourceName name1{arg1->name()};
3721 SourceName name2{arg2->name()};
3722 if (name1 != name2) {
3723 Say(*arg1, *arg2,
3724 "Dummy argument name '%s' does not match corresponding name '%s'"
3725 " in interface body"_err_en_US,
3726 name2);
3727 } else {
3728 CheckDummyArg(
3729 *arg1, *arg2, proc1->dummyArguments[i], proc2->dummyArguments[i]);
3730 }
3731 }
3732 }
3733 }
3734
3735 void SubprogramMatchHelper::CheckDummyArg(const Symbol &symbol1,
3736 const Symbol &symbol2, const DummyArgument &arg1,
3737 const DummyArgument &arg2) {
3738 common::visit(
3739 common::visitors{
3740 [&](const DummyDataObject &obj1, const DummyDataObject &obj2) {
3741 CheckDummyDataObject(symbol1, symbol2, obj1, obj2);
3742 },
3743 [&](const DummyProcedure &proc1, const DummyProcedure &proc2) {
3744 CheckDummyProcedure(symbol1, symbol2, proc1, proc2);
3745 },
3746 [&](const DummyDataObject &, const auto &) {
3747 Say(symbol1, symbol2,
3748 "Dummy argument '%s' is a data object; the corresponding"
3749 " argument in the interface body is not"_err_en_US);
3750 },
3751 [&](const DummyProcedure &, const auto &) {
3752 Say(symbol1, symbol2,
3753 "Dummy argument '%s' is a procedure; the corresponding"
3754 " argument in the interface body is not"_err_en_US);
3755 },
3756 [&](const auto &, const auto &) {
3757 llvm_unreachable("Dummy arguments are not data objects or"
3758 "procedures");
3759 },
3760 },
3761 arg1.u, arg2.u);
3762 }
3763
3764 void SubprogramMatchHelper::CheckDummyDataObject(const Symbol &symbol1,
3765 const Symbol &symbol2, const DummyDataObject &obj1,
3766 const DummyDataObject &obj2) {
3767 if (!CheckSameIntent(symbol1, symbol2, obj1.intent, obj2.intent)) {
3768 } else if (!CheckSameAttrs(symbol1, symbol2, obj1.attrs, obj2.attrs)) {
3769 } else if (!obj1.type.type().IsEquivalentTo(obj2.type.type())) {
3770 Say(symbol1, symbol2,
3771 "Dummy argument '%s' has type %s; the corresponding argument in the interface body has distinct type %s"_err_en_US,
3772 obj1.type.type().AsFortran(), obj2.type.type().AsFortran());
3773 } else if (!ShapesAreCompatible(obj1, obj2)) {
3774 Say(symbol1, symbol2,
3775 "The shape of dummy argument '%s' does not match the shape of the"
3776 " corresponding argument in the interface body"_err_en_US);
3777 }
3778 // TODO: coshape
3779 }
3780
3781 void SubprogramMatchHelper::CheckDummyProcedure(const Symbol &symbol1,
3782 const Symbol &symbol2, const DummyProcedure &proc1,
3783 const DummyProcedure &proc2) {
3784 if (!CheckSameIntent(symbol1, symbol2, proc1.intent, proc2.intent)) {
3785 } else if (!CheckSameAttrs(symbol1, symbol2, proc1.attrs, proc2.attrs)) {
3786 } else if (proc1 != proc2) {
3787 Say(symbol1, symbol2,
3788 "Dummy procedure '%s' does not match the corresponding argument in"
3789 " the interface body"_err_en_US);
3790 }
3791 }
3792
3793 bool SubprogramMatchHelper::CheckSameIntent(const Symbol &symbol1,
3794 const Symbol &symbol2, common::Intent intent1, common::Intent intent2) {
3795 if (intent1 == intent2) {
3796 return true;
3797 } else {
3798 Say(symbol1, symbol2,
3799 "The intent of dummy argument '%s' does not match the intent"
3800 " of the corresponding argument in the interface body"_err_en_US);
3801 return false;
3802 }
3803 }
3804
3805 // Report an error referring to first symbol with declaration of second symbol
3806 template <typename... A>
3807 void SubprogramMatchHelper::Say(const Symbol &symbol1, const Symbol &symbol2,
3808 parser::MessageFixedText &&text, A &&...args) {
3809 auto &message{context().Say(symbol1.name(), std::move(text), symbol1.name(),
3810 std::forward<A>(args)...)};
3811 evaluate::AttachDeclaration(message, symbol2);
3812 }
3813
3814 template <typename ATTRS>
3815 bool SubprogramMatchHelper::CheckSameAttrs(
3816 const Symbol &symbol1, const Symbol &symbol2, ATTRS attrs1, ATTRS attrs2) {
3817 if (attrs1 == attrs2) {
3818 return true;
3819 }
3820 attrs1.IterateOverMembers([&](auto attr) {
3821 if (!attrs2.test(attr)) {
3822 Say(symbol1, symbol2,
3823 "Dummy argument '%s' has the %s attribute; the corresponding"
3824 " argument in the interface body does not"_err_en_US,
3825 AsFortran(attr));
3826 }
3827 });
3828 attrs2.IterateOverMembers([&](auto attr) {
3829 if (!attrs1.test(attr)) {
3830 Say(symbol1, symbol2,
3831 "Dummy argument '%s' does not have the %s attribute; the"
3832 " corresponding argument in the interface body does"_err_en_US,
3833 AsFortran(attr));
3834 }
3835 });
3836 return false;
3837 }
3838
3839 bool SubprogramMatchHelper::ShapesAreCompatible(
3840 const DummyDataObject &obj1, const DummyDataObject &obj2) {
3841 return characteristics::ShapesAreCompatible(
3842 FoldShape(obj1.type.shape()), FoldShape(obj2.type.shape()));
3843 }
3844
3845 evaluate::Shape SubprogramMatchHelper::FoldShape(const evaluate::Shape &shape) {
3846 evaluate::Shape result;
3847 for (const auto &extent : shape) {
3848 result.emplace_back(
3849 evaluate::Fold(context().foldingContext(), common::Clone(extent)));
3850 }
3851 return result;
3852 }
3853
3854 void DistinguishabilityHelper::Add(const Symbol &generic, GenericKind kind,
3855 const Symbol &ultimateSpecific, const Procedure &procedure) {
3856 if (!context_.HasError(ultimateSpecific)) {
3857 nameToSpecifics_[generic.name()].emplace(
3858 &ultimateSpecific, ProcedureInfo{kind, procedure});
3859 }
3860 }
3861
3862 void DistinguishabilityHelper::Check(const Scope &scope) {
3863 if (FindModuleFileContaining(scope)) {
3864 // Distinguishability was checked when the module was created;
3865 // don't let optional warnings then become errors now.
3866 return;
3867 }
3868 for (const auto &[name, info] : nameToSpecifics_) {
3869 for (auto iter1{info.begin()}; iter1 != info.end(); ++iter1) {
3870 const auto &[ultimate, procInfo]{*iter1};
3871 const auto &[kind, proc]{procInfo};
3872 for (auto iter2{iter1}; ++iter2 != info.end();) {
3873 auto distinguishable{kind.IsName()
3874 ? evaluate::characteristics::Distinguishable
3875 : evaluate::characteristics::DistinguishableOpOrAssign};
3876 std::optional<bool> distinct{distinguishable(
3877 context_.languageFeatures(), proc, iter2->second.procedure)};
3878 if (!distinct.value_or(false)) {
3879 SayNotDistinguishable(GetTopLevelUnitContaining(scope), name, kind,
3880 *ultimate, *iter2->first, distinct.has_value());
3881 }
3882 }
3883 }
3884 }
3885 }
3886
3887 void DistinguishabilityHelper::SayNotDistinguishable(const Scope &scope,
3888 const SourceName &name, GenericKind kind, const Symbol &proc1,
3889 const Symbol &proc2, bool isHardConflict) {
3890 bool isUseAssociated{!scope.sourceRange().Contains(name)};
3891 // The rules for distinguishing specific procedures (F'2023 15.4.3.4.5)
3892 // are inadequate for some real-world cases like pFUnit.
3893 // When there are optional dummy arguments or unlimited polymorphic
3894 // dummy data object arguments, the best that we can do is emit an optional
3895 // portability warning. Also, named generics created by USE association
3896 // merging shouldn't receive hard errors for ambiguity.
3897 // (Non-named generics might be defined I/O procedures or defined
3898 // assignments that need to be used by the runtime.)
3899 bool isWarning{!isHardConflict || (isUseAssociated && kind.IsName())};
3900 if (isWarning &&
3901 (!context_.ShouldWarn(
3902 common::LanguageFeature::IndistinguishableSpecifics) ||
3903 FindModuleFileContaining(scope))) {
3904 return;
3905 }
3906 std::string name1{proc1.name().ToString()};
3907 std::string name2{proc2.name().ToString()};
3908 if (kind.IsOperator() || kind.IsAssignment()) {
3909 // proc1 and proc2 may come from different scopes so qualify their names
3910 if (proc1.owner().IsDerivedType()) {
3911 name1 = proc1.owner().GetName()->ToString() + '%' + name1;
3912 }
3913 if (proc2.owner().IsDerivedType()) {
3914 name2 = proc2.owner().GetName()->ToString() + '%' + name2;
3915 }
3916 }
3917 parser::Message *msg;
3918 if (!isUseAssociated) {
3919 CHECK(isWarning == !isHardConflict);
3920 msg = &context_.Say(name,
3921 isHardConflict
3922 ? "Generic '%s' may not have specific procedures '%s' and '%s' as their interfaces are not distinguishable"_err_en_US
3923 : "Generic '%s' should not have specific procedures '%s' and '%s' as their interfaces are not distinguishable by the rules in the standard"_port_en_US,
3924 MakeOpName(name), name1, name2);
3925 } else {
3926 msg = &context_.Say(*GetTopLevelUnitContaining(proc1).GetName(),
3927 isHardConflict
3928 ? (isWarning
3929 ? "USE-associated generic '%s' should not have specific procedures '%s' and '%s' as their interfaces are not distinguishable"_warn_en_US
3930 : "USE-associated generic '%s' may not have specific procedures '%s' and '%s' as their interfaces are not distinguishable"_err_en_US)
3931 : "USE-associated generic '%s' should not have specific procedures '%s' and '%s' as their interfaces are not distinguishable by the rules in the standard"_port_en_US,
3932 MakeOpName(name), name1, name2);
3933 }
3934 AttachDeclaration(*msg, scope, proc1);
3935 AttachDeclaration(*msg, scope, proc2);
3936 }
3937
3938 // `evaluate::AttachDeclaration` doesn't handle the generic case where `proc`
3939 // comes from a different module but is not necessarily use-associated.
3940 void DistinguishabilityHelper::AttachDeclaration(
3941 parser::Message &msg, const Scope &scope, const Symbol &proc) {
3942 const Scope &unit{GetTopLevelUnitContaining(proc)};
3943 if (unit == scope) {
3944 evaluate::AttachDeclaration(msg, proc);
3945 } else {
3946 msg.Attach(unit.GetName().value(),
3947 "'%s' is USE-associated from module '%s'"_en_US, proc.name(),
3948 unit.GetName().value());
3949 }
3950 }
3951
3952 void CheckDeclarations(SemanticsContext &context) {
3953 CheckHelper{context}.Check();
3954 }
3955 } // namespace Fortran::semantics