1 //===-- lib/Semantics/check-declarations.cpp ------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 // Static declaration checking 10 11 #include "check-declarations.h" 12 #include "pointer-assignment.h" 13 #include "flang/Evaluate/check-expression.h" 14 #include "flang/Evaluate/fold.h" 15 #include "flang/Evaluate/tools.h" 16 #include "flang/Semantics/scope.h" 17 #include "flang/Semantics/semantics.h" 18 #include "flang/Semantics/symbol.h" 19 #include "flang/Semantics/tools.h" 20 #include "flang/Semantics/type.h" 21 #include <algorithm> 22 #include <map> 23 #include <string> 24 25 namespace Fortran::semantics { 26 27 namespace characteristics = evaluate::characteristics; 28 using characteristics::DummyArgument; 29 using characteristics::DummyDataObject; 30 using characteristics::DummyProcedure; 31 using characteristics::FunctionResult; 32 using characteristics::Procedure; 33 34 class CheckHelper { 35 public: 36 explicit CheckHelper(SemanticsContext &c) : context_{c} {} 37 CheckHelper(SemanticsContext &c, const Scope &s) : context_{c}, scope_{&s} {} 38 39 SemanticsContext &context() { return context_; } 40 void Check() { Check(context_.globalScope()); } 41 void Check(const ParamValue &, bool canBeAssumed); 42 void Check(const Bound &bound) { CheckSpecExpr(bound.GetExplicit()); } 43 void Check(const ShapeSpec &spec) { 44 Check(spec.lbound()); 45 Check(spec.ubound()); 46 } 47 void Check(const ArraySpec &); 48 void Check(const DeclTypeSpec &, bool canHaveAssumedTypeParameters); 49 void Check(const Symbol &); 50 void Check(const Scope &); 51 const Procedure *Characterize(const Symbol &); 52 53 private: 54 template <typename A> void CheckSpecExpr(const A &x) { 55 evaluate::CheckSpecificationExpr(x, DEREF(scope_), foldingContext_); 56 } 57 void CheckValue(const Symbol &, const DerivedTypeSpec *); 58 void CheckVolatile(const Symbol &, const DerivedTypeSpec *); 59 void CheckPointer(const Symbol &); 60 void CheckPassArg( 61 const Symbol &proc, const Symbol *interface, const WithPassArg &); 62 void CheckProcBinding(const Symbol &, const ProcBindingDetails &); 63 void CheckObjectEntity(const Symbol &, const ObjectEntityDetails &); 64 void CheckPointerInitialization(const Symbol &); 65 void CheckArraySpec(const Symbol &, const ArraySpec &); 66 void CheckProcEntity(const Symbol &, const ProcEntityDetails &); 67 void CheckSubprogram(const Symbol &, const SubprogramDetails &); 68 void CheckAssumedTypeEntity(const Symbol &, const ObjectEntityDetails &); 69 void CheckDerivedType(const Symbol &, const DerivedTypeDetails &); 70 bool CheckFinal( 71 const Symbol &subroutine, SourceName, const Symbol &derivedType); 72 bool CheckDistinguishableFinals(const Symbol &f1, SourceName f1name, 73 const Symbol &f2, SourceName f2name, const Symbol &derivedType); 74 void CheckGeneric(const Symbol &, const GenericDetails &); 75 void CheckHostAssoc(const Symbol &, const HostAssocDetails &); 76 bool CheckDefinedOperator( 77 SourceName, GenericKind, const Symbol &, const Procedure &); 78 std::optional<parser::MessageFixedText> CheckNumberOfArgs( 79 const GenericKind &, std::size_t); 80 bool CheckDefinedOperatorArg( 81 const SourceName &, const Symbol &, const Procedure &, std::size_t); 82 bool CheckDefinedAssignment(const Symbol &, const Procedure &); 83 bool CheckDefinedAssignmentArg(const Symbol &, const DummyArgument &, int); 84 void CheckSpecificsAreDistinguishable(const Symbol &, const GenericDetails &); 85 void CheckEquivalenceSet(const EquivalenceSet &); 86 void CheckBlockData(const Scope &); 87 void CheckGenericOps(const Scope &); 88 bool CheckConflicting(const Symbol &, Attr, Attr); 89 void WarnMissingFinal(const Symbol &); 90 bool InPure() const { 91 return innermostSymbol_ && IsPureProcedure(*innermostSymbol_); 92 } 93 bool InElemental() const { 94 return innermostSymbol_ && innermostSymbol_->attrs().test(Attr::ELEMENTAL); 95 } 96 bool InFunction() const { 97 return innermostSymbol_ && IsFunction(*innermostSymbol_); 98 } 99 template <typename... A> 100 void SayWithDeclaration(const Symbol &symbol, A &&...x) { 101 if (parser::Message * msg{messages_.Say(std::forward<A>(x)...)}) { 102 if (messages_.at().begin() != symbol.name().begin()) { 103 evaluate::AttachDeclaration(*msg, symbol); 104 } 105 } 106 } 107 bool IsResultOkToDiffer(const FunctionResult &); 108 void CheckBindCName(const Symbol &); 109 // Check functions for defined I/O procedures 110 void CheckDefinedIoProc( 111 const Symbol &, const GenericDetails &, GenericKind::DefinedIo); 112 bool CheckDioDummyIsData(const Symbol &, const Symbol *, std::size_t); 113 void CheckDioDummyIsDerived( 114 const Symbol &, const Symbol &, GenericKind::DefinedIo ioKind); 115 void CheckDioDummyIsDefaultInteger(const Symbol &, const Symbol &); 116 void CheckDioDummyIsScalar(const Symbol &, const Symbol &); 117 void CheckDioDummyAttrs(const Symbol &, const Symbol &, Attr); 118 void CheckDioDtvArg(const Symbol &, const Symbol *, GenericKind::DefinedIo); 119 void CheckDefaultIntegerArg(const Symbol &, const Symbol *, Attr); 120 void CheckDioAssumedLenCharacterArg( 121 const Symbol &, const Symbol *, std::size_t, Attr); 122 void CheckDioVlistArg(const Symbol &, const Symbol *, std::size_t); 123 void CheckDioArgCount( 124 const Symbol &, GenericKind::DefinedIo ioKind, std::size_t); 125 struct TypeWithDefinedIo { 126 const DerivedTypeSpec *type; 127 GenericKind::DefinedIo ioKind; 128 const Symbol &proc; 129 }; 130 void CheckAlreadySeenDefinedIo( 131 const DerivedTypeSpec *, GenericKind::DefinedIo, const Symbol &); 132 133 SemanticsContext &context_; 134 evaluate::FoldingContext &foldingContext_{context_.foldingContext()}; 135 parser::ContextualMessages &messages_{foldingContext_.messages()}; 136 const Scope *scope_{nullptr}; 137 bool scopeIsUninstantiatedPDT_{false}; 138 // This symbol is the one attached to the innermost enclosing scope 139 // that has a symbol. 140 const Symbol *innermostSymbol_{nullptr}; 141 // Cache of calls to Procedure::Characterize(Symbol) 142 std::map<SymbolRef, std::optional<Procedure>, SymbolAddressCompare> 143 characterizeCache_; 144 // Collection of symbols with BIND(C) names 145 std::map<std::string, SymbolRef> bindC_; 146 // Derived types that have defined input/output procedures 147 std::vector<TypeWithDefinedIo> seenDefinedIoTypes_; 148 }; 149 150 class DistinguishabilityHelper { 151 public: 152 DistinguishabilityHelper(SemanticsContext &context) : context_{context} {} 153 void Add(const Symbol &, GenericKind, const Symbol &, const Procedure &); 154 void Check(const Scope &); 155 156 private: 157 void SayNotDistinguishable(const Scope &, const SourceName &, GenericKind, 158 const Symbol &, const Symbol &); 159 void AttachDeclaration(parser::Message &, const Scope &, const Symbol &); 160 161 SemanticsContext &context_; 162 struct ProcedureInfo { 163 GenericKind kind; 164 const Symbol &symbol; 165 const Procedure &procedure; 166 }; 167 std::map<SourceName, std::vector<ProcedureInfo>> nameToInfo_; 168 }; 169 170 void CheckHelper::Check(const ParamValue &value, bool canBeAssumed) { 171 if (value.isAssumed()) { 172 if (!canBeAssumed) { // C795, C721, C726 173 messages_.Say( 174 "An assumed (*) type parameter may be used only for a (non-statement" 175 " function) dummy argument, associate name, named constant, or" 176 " external function result"_err_en_US); 177 } 178 } else { 179 CheckSpecExpr(value.GetExplicit()); 180 } 181 } 182 183 void CheckHelper::Check(const ArraySpec &shape) { 184 for (const auto &spec : shape) { 185 Check(spec); 186 } 187 } 188 189 void CheckHelper::Check( 190 const DeclTypeSpec &type, bool canHaveAssumedTypeParameters) { 191 if (type.category() == DeclTypeSpec::Character) { 192 Check(type.characterTypeSpec().length(), canHaveAssumedTypeParameters); 193 } else if (const DerivedTypeSpec * derived{type.AsDerived()}) { 194 for (auto &parm : derived->parameters()) { 195 Check(parm.second, canHaveAssumedTypeParameters); 196 } 197 } 198 } 199 200 void CheckHelper::Check(const Symbol &symbol) { 201 if (context_.HasError(symbol)) { 202 return; 203 } 204 auto restorer{messages_.SetLocation(symbol.name())}; 205 context_.set_location(symbol.name()); 206 const DeclTypeSpec *type{symbol.GetType()}; 207 const DerivedTypeSpec *derived{type ? type->AsDerived() : nullptr}; 208 bool isDone{false}; 209 std::visit( 210 common::visitors{ 211 [&](const UseDetails &x) { isDone = true; }, 212 [&](const HostAssocDetails &x) { 213 CheckHostAssoc(symbol, x); 214 isDone = true; 215 }, 216 [&](const ProcBindingDetails &x) { 217 CheckProcBinding(symbol, x); 218 isDone = true; 219 }, 220 [&](const ObjectEntityDetails &x) { CheckObjectEntity(symbol, x); }, 221 [&](const ProcEntityDetails &x) { CheckProcEntity(symbol, x); }, 222 [&](const SubprogramDetails &x) { CheckSubprogram(symbol, x); }, 223 [&](const DerivedTypeDetails &x) { CheckDerivedType(symbol, x); }, 224 [&](const GenericDetails &x) { CheckGeneric(symbol, x); }, 225 [](const auto &) {}, 226 }, 227 symbol.details()); 228 if (symbol.attrs().test(Attr::VOLATILE)) { 229 CheckVolatile(symbol, derived); 230 } 231 CheckBindCName(symbol); 232 if (isDone) { 233 return; // following checks do not apply 234 } 235 if (IsPointer(symbol)) { 236 CheckPointer(symbol); 237 } 238 if (InPure()) { 239 if (IsSaved(symbol)) { 240 messages_.Say( 241 "A pure subprogram may not have a variable with the SAVE attribute"_err_en_US); 242 } 243 if (symbol.attrs().test(Attr::VOLATILE)) { 244 messages_.Say( 245 "A pure subprogram may not have a variable with the VOLATILE attribute"_err_en_US); 246 } 247 if (IsProcedure(symbol) && !IsPureProcedure(symbol) && IsDummy(symbol)) { 248 messages_.Say( 249 "A dummy procedure of a pure subprogram must be pure"_err_en_US); 250 } 251 if (!IsDummy(symbol) && !IsFunctionResult(symbol)) { 252 if (IsPolymorphicAllocatable(symbol)) { 253 SayWithDeclaration(symbol, 254 "Deallocation of polymorphic object '%s' is not permitted in a pure subprogram"_err_en_US, 255 symbol.name()); 256 } else if (derived) { 257 if (auto bad{FindPolymorphicAllocatableUltimateComponent(*derived)}) { 258 SayWithDeclaration(*bad, 259 "Deallocation of polymorphic object '%s%s' is not permitted in a pure subprogram"_err_en_US, 260 symbol.name(), bad.BuildResultDesignatorName()); 261 } 262 } 263 } 264 } 265 if (type) { // Section 7.2, paragraph 7 266 bool canHaveAssumedParameter{IsNamedConstant(symbol) || 267 (IsAssumedLengthCharacter(symbol) && // C722 268 IsExternal(symbol)) || 269 symbol.test(Symbol::Flag::ParentComp)}; 270 if (!IsStmtFunctionDummy(symbol)) { // C726 271 if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) { 272 canHaveAssumedParameter |= object->isDummy() || 273 (object->isFuncResult() && 274 type->category() == DeclTypeSpec::Character) || 275 IsStmtFunctionResult(symbol); // Avoids multiple messages 276 } else { 277 canHaveAssumedParameter |= symbol.has<AssocEntityDetails>(); 278 } 279 } 280 Check(*type, canHaveAssumedParameter); 281 if (InPure() && InFunction() && IsFunctionResult(symbol)) { 282 if (derived && HasImpureFinal(*derived)) { // C1584 283 messages_.Say( 284 "Result of pure function may not have an impure FINAL subroutine"_err_en_US); 285 } 286 if (type->IsPolymorphic() && IsAllocatable(symbol)) { // C1585 287 messages_.Say( 288 "Result of pure function may not be both polymorphic and ALLOCATABLE"_err_en_US); 289 } 290 if (derived) { 291 if (auto bad{FindPolymorphicAllocatableUltimateComponent(*derived)}) { 292 SayWithDeclaration(*bad, 293 "Result of pure function may not have polymorphic ALLOCATABLE ultimate component '%s'"_err_en_US, 294 bad.BuildResultDesignatorName()); 295 } 296 } 297 } 298 } 299 if (IsAssumedLengthCharacter(symbol) && IsExternal(symbol)) { // C723 300 if (symbol.attrs().test(Attr::RECURSIVE)) { 301 messages_.Say( 302 "An assumed-length CHARACTER(*) function cannot be RECURSIVE"_err_en_US); 303 } 304 if (symbol.Rank() > 0) { 305 messages_.Say( 306 "An assumed-length CHARACTER(*) function cannot return an array"_err_en_US); 307 } 308 if (symbol.attrs().test(Attr::PURE)) { 309 messages_.Say( 310 "An assumed-length CHARACTER(*) function cannot be PURE"_err_en_US); 311 } 312 if (symbol.attrs().test(Attr::ELEMENTAL)) { 313 messages_.Say( 314 "An assumed-length CHARACTER(*) function cannot be ELEMENTAL"_err_en_US); 315 } 316 if (const Symbol * result{FindFunctionResult(symbol)}) { 317 if (IsPointer(*result)) { 318 messages_.Say( 319 "An assumed-length CHARACTER(*) function cannot return a POINTER"_err_en_US); 320 } 321 } 322 } 323 if (symbol.attrs().test(Attr::VALUE)) { 324 CheckValue(symbol, derived); 325 } 326 if (symbol.attrs().test(Attr::CONTIGUOUS) && IsPointer(symbol) && 327 symbol.Rank() == 0) { // C830 328 messages_.Say("CONTIGUOUS POINTER must be an array"_err_en_US); 329 } 330 if (IsDummy(symbol)) { 331 if (IsNamedConstant(symbol)) { 332 messages_.Say( 333 "A dummy argument may not also be a named constant"_err_en_US); 334 } 335 if (!symbol.test(Symbol::Flag::InDataStmt) /*caught elsewhere*/ && 336 IsSaved(symbol)) { 337 messages_.Say( 338 "A dummy argument may not have the SAVE attribute"_err_en_US); 339 } 340 } else if (IsFunctionResult(symbol)) { 341 if (!symbol.test(Symbol::Flag::InDataStmt) /*caught elsewhere*/ && 342 IsSaved(symbol)) { 343 messages_.Say( 344 "A function result may not have the SAVE attribute"_err_en_US); 345 } 346 } 347 if (symbol.owner().IsDerivedType() && 348 (symbol.attrs().test(Attr::CONTIGUOUS) && 349 !(IsPointer(symbol) && symbol.Rank() > 0))) { // C752 350 messages_.Say( 351 "A CONTIGUOUS component must be an array with the POINTER attribute"_err_en_US); 352 } 353 if (symbol.owner().IsModule() && IsAutomatic(symbol)) { 354 messages_.Say( 355 "Automatic data object '%s' may not appear in the specification part" 356 " of a module"_err_en_US, 357 symbol.name()); 358 } 359 } 360 361 void CheckHelper::CheckValue( 362 const Symbol &symbol, const DerivedTypeSpec *derived) { // C863 - C865 363 if (!IsDummy(symbol)) { 364 messages_.Say( 365 "VALUE attribute may apply only to a dummy argument"_err_en_US); 366 } 367 if (IsProcedure(symbol)) { 368 messages_.Say( 369 "VALUE attribute may apply only to a dummy data object"_err_en_US); 370 } 371 if (IsAssumedSizeArray(symbol)) { 372 messages_.Say( 373 "VALUE attribute may not apply to an assumed-size array"_err_en_US); 374 } 375 if (IsCoarray(symbol)) { 376 messages_.Say("VALUE attribute may not apply to a coarray"_err_en_US); 377 } 378 if (IsAllocatable(symbol)) { 379 messages_.Say("VALUE attribute may not apply to an ALLOCATABLE"_err_en_US); 380 } else if (IsPointer(symbol)) { 381 messages_.Say("VALUE attribute may not apply to a POINTER"_err_en_US); 382 } 383 if (IsIntentInOut(symbol)) { 384 messages_.Say( 385 "VALUE attribute may not apply to an INTENT(IN OUT) argument"_err_en_US); 386 } else if (IsIntentOut(symbol)) { 387 messages_.Say( 388 "VALUE attribute may not apply to an INTENT(OUT) argument"_err_en_US); 389 } 390 if (symbol.attrs().test(Attr::VOLATILE)) { 391 messages_.Say("VALUE attribute may not apply to a VOLATILE"_err_en_US); 392 } 393 if (innermostSymbol_ && IsBindCProcedure(*innermostSymbol_) && 394 IsOptional(symbol)) { 395 messages_.Say( 396 "VALUE attribute may not apply to an OPTIONAL in a BIND(C) procedure"_err_en_US); 397 } 398 if (derived) { 399 if (FindCoarrayUltimateComponent(*derived)) { 400 messages_.Say( 401 "VALUE attribute may not apply to a type with a coarray ultimate component"_err_en_US); 402 } 403 } 404 } 405 406 void CheckHelper::CheckAssumedTypeEntity( // C709 407 const Symbol &symbol, const ObjectEntityDetails &details) { 408 if (const DeclTypeSpec * type{symbol.GetType()}; 409 type && type->category() == DeclTypeSpec::TypeStar) { 410 if (!IsDummy(symbol)) { 411 messages_.Say( 412 "Assumed-type entity '%s' must be a dummy argument"_err_en_US, 413 symbol.name()); 414 } else { 415 if (symbol.attrs().test(Attr::ALLOCATABLE)) { 416 messages_.Say("Assumed-type argument '%s' cannot have the ALLOCATABLE" 417 " attribute"_err_en_US, 418 symbol.name()); 419 } 420 if (symbol.attrs().test(Attr::POINTER)) { 421 messages_.Say("Assumed-type argument '%s' cannot have the POINTER" 422 " attribute"_err_en_US, 423 symbol.name()); 424 } 425 if (symbol.attrs().test(Attr::VALUE)) { 426 messages_.Say("Assumed-type argument '%s' cannot have the VALUE" 427 " attribute"_err_en_US, 428 symbol.name()); 429 } 430 if (symbol.attrs().test(Attr::INTENT_OUT)) { 431 messages_.Say( 432 "Assumed-type argument '%s' cannot be INTENT(OUT)"_err_en_US, 433 symbol.name()); 434 } 435 if (IsCoarray(symbol)) { 436 messages_.Say( 437 "Assumed-type argument '%s' cannot be a coarray"_err_en_US, 438 symbol.name()); 439 } 440 if (details.IsArray() && details.shape().IsExplicitShape()) { 441 messages_.Say( 442 "Assumed-type array argument 'arg8' must be assumed shape," 443 " assumed size, or assumed rank"_err_en_US, 444 symbol.name()); 445 } 446 } 447 } 448 } 449 450 void CheckHelper::CheckObjectEntity( 451 const Symbol &symbol, const ObjectEntityDetails &details) { 452 CheckArraySpec(symbol, details.shape()); 453 Check(details.shape()); 454 Check(details.coshape()); 455 CheckAssumedTypeEntity(symbol, details); 456 WarnMissingFinal(symbol); 457 if (!details.coshape().empty()) { 458 bool isDeferredCoshape{details.coshape().IsDeferredShape()}; 459 if (IsAllocatable(symbol)) { 460 if (!isDeferredCoshape) { // C827 461 messages_.Say("'%s' is an ALLOCATABLE coarray and must have a deferred" 462 " coshape"_err_en_US, 463 symbol.name()); 464 } 465 } else if (symbol.owner().IsDerivedType()) { // C746 466 std::string deferredMsg{ 467 isDeferredCoshape ? "" : " and have a deferred coshape"}; 468 messages_.Say("Component '%s' is a coarray and must have the ALLOCATABLE" 469 " attribute%s"_err_en_US, 470 symbol.name(), deferredMsg); 471 } else { 472 if (!details.coshape().IsAssumedSize()) { // C828 473 messages_.Say( 474 "'%s' is a non-ALLOCATABLE coarray and must have an explicit coshape"_err_en_US, 475 symbol.name()); 476 } 477 } 478 if (const DeclTypeSpec * type{details.type()}) { 479 if (IsBadCoarrayType(type->AsDerived())) { // C747 & C824 480 messages_.Say( 481 "Coarray '%s' may not have type TEAM_TYPE, C_PTR, or C_FUNPTR"_err_en_US, 482 symbol.name()); 483 } 484 } 485 } 486 if (details.isDummy()) { 487 if (symbol.attrs().test(Attr::INTENT_OUT)) { 488 if (FindUltimateComponent(symbol, [](const Symbol &x) { 489 return IsCoarray(x) && IsAllocatable(x); 490 })) { // C846 491 messages_.Say( 492 "An INTENT(OUT) dummy argument may not be, or contain, an ALLOCATABLE coarray"_err_en_US); 493 } 494 if (IsOrContainsEventOrLockComponent(symbol)) { // C847 495 messages_.Say( 496 "An INTENT(OUT) dummy argument may not be, or contain, EVENT_TYPE or LOCK_TYPE"_err_en_US); 497 } 498 } 499 if (InPure() && !IsStmtFunction(DEREF(innermostSymbol_)) && 500 !IsPointer(symbol) && !IsIntentIn(symbol) && 501 !symbol.attrs().test(Attr::VALUE)) { 502 if (InFunction()) { // C1583 503 messages_.Say( 504 "non-POINTER dummy argument of pure function must be INTENT(IN) or VALUE"_err_en_US); 505 } else if (IsIntentOut(symbol)) { 506 if (const DeclTypeSpec * type{details.type()}) { 507 if (type && type->IsPolymorphic()) { // C1588 508 messages_.Say( 509 "An INTENT(OUT) dummy argument of a pure subroutine may not be polymorphic"_err_en_US); 510 } else if (const DerivedTypeSpec * derived{type->AsDerived()}) { 511 if (FindUltimateComponent(*derived, [](const Symbol &x) { 512 const DeclTypeSpec *type{x.GetType()}; 513 return type && type->IsPolymorphic(); 514 })) { // C1588 515 messages_.Say( 516 "An INTENT(OUT) dummy argument of a pure subroutine may not have a polymorphic ultimate component"_err_en_US); 517 } 518 if (HasImpureFinal(*derived)) { // C1587 519 messages_.Say( 520 "An INTENT(OUT) dummy argument of a pure subroutine may not have an impure FINAL subroutine"_err_en_US); 521 } 522 } 523 } 524 } else if (!IsIntentInOut(symbol)) { // C1586 525 messages_.Say( 526 "non-POINTER dummy argument of pure subroutine must have INTENT() or VALUE attribute"_err_en_US); 527 } 528 } 529 } else if (symbol.attrs().test(Attr::INTENT_IN) || 530 symbol.attrs().test(Attr::INTENT_OUT) || 531 symbol.attrs().test(Attr::INTENT_INOUT)) { 532 messages_.Say("INTENT attributes may apply only to a dummy " 533 "argument"_err_en_US); // C843 534 } else if (IsOptional(symbol)) { 535 messages_.Say("OPTIONAL attribute may apply only to a dummy " 536 "argument"_err_en_US); // C849 537 } 538 if (InElemental()) { 539 if (details.isDummy()) { // C15100 540 if (details.shape().Rank() > 0) { 541 messages_.Say( 542 "A dummy argument of an ELEMENTAL procedure must be scalar"_err_en_US); 543 } 544 if (IsAllocatable(symbol)) { 545 messages_.Say( 546 "A dummy argument of an ELEMENTAL procedure may not be ALLOCATABLE"_err_en_US); 547 } 548 if (IsCoarray(symbol)) { 549 messages_.Say( 550 "A dummy argument of an ELEMENTAL procedure may not be a coarray"_err_en_US); 551 } 552 if (IsPointer(symbol)) { 553 messages_.Say( 554 "A dummy argument of an ELEMENTAL procedure may not be a POINTER"_err_en_US); 555 } 556 if (!symbol.attrs().HasAny(Attrs{Attr::VALUE, Attr::INTENT_IN, 557 Attr::INTENT_INOUT, Attr::INTENT_OUT})) { // C15102 558 messages_.Say( 559 "A dummy argument of an ELEMENTAL procedure must have an INTENT() or VALUE attribute"_err_en_US); 560 } 561 } else if (IsFunctionResult(symbol)) { // C15101 562 if (details.shape().Rank() > 0) { 563 messages_.Say( 564 "The result of an ELEMENTAL function must be scalar"_err_en_US); 565 } 566 if (IsAllocatable(symbol)) { 567 messages_.Say( 568 "The result of an ELEMENTAL function may not be ALLOCATABLE"_err_en_US); 569 } 570 if (IsPointer(symbol)) { 571 messages_.Say( 572 "The result of an ELEMENTAL function may not be a POINTER"_err_en_US); 573 } 574 } 575 } 576 if (HasDeclarationInitializer(symbol)) { // C808; ignore DATA initialization 577 CheckPointerInitialization(symbol); 578 if (IsAutomatic(symbol)) { 579 messages_.Say( 580 "An automatic variable or component must not be initialized"_err_en_US); 581 } else if (IsDummy(symbol)) { 582 messages_.Say("A dummy argument must not be initialized"_err_en_US); 583 } else if (IsFunctionResult(symbol)) { 584 messages_.Say("A function result must not be initialized"_err_en_US); 585 } else if (IsInBlankCommon(symbol)) { 586 messages_.Say( 587 "A variable in blank COMMON should not be initialized"_en_US); 588 } 589 } 590 if (symbol.owner().kind() == Scope::Kind::BlockData) { 591 if (IsAllocatable(symbol)) { 592 messages_.Say( 593 "An ALLOCATABLE variable may not appear in a BLOCK DATA subprogram"_err_en_US); 594 } else if (IsInitialized(symbol) && !FindCommonBlockContaining(symbol)) { 595 messages_.Say( 596 "An initialized variable in BLOCK DATA must be in a COMMON block"_err_en_US); 597 } 598 } 599 if (const DeclTypeSpec * type{details.type()}) { // C708 600 if (type->IsPolymorphic() && 601 !(type->IsAssumedType() || IsAllocatableOrPointer(symbol) || 602 IsDummy(symbol))) { 603 messages_.Say("CLASS entity '%s' must be a dummy argument or have " 604 "ALLOCATABLE or POINTER attribute"_err_en_US, 605 symbol.name()); 606 } 607 } 608 } 609 610 void CheckHelper::CheckPointerInitialization(const Symbol &symbol) { 611 if (IsPointer(symbol) && !context_.HasError(symbol) && 612 !scopeIsUninstantiatedPDT_) { 613 if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) { 614 if (object->init()) { // C764, C765; C808 615 if (auto designator{evaluate::AsGenericExpr(symbol)}) { 616 auto restorer{messages_.SetLocation(symbol.name())}; 617 context_.set_location(symbol.name()); 618 CheckInitialTarget(foldingContext_, *designator, *object->init()); 619 } 620 } 621 } else if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}) { 622 if (proc->init() && *proc->init()) { 623 // C1519 - must be nonelemental external or module procedure, 624 // or an unrestricted specific intrinsic function. 625 const Symbol &ultimate{(*proc->init())->GetUltimate()}; 626 if (ultimate.attrs().test(Attr::INTRINSIC)) { 627 if (!context_.intrinsics().IsSpecificIntrinsicFunction( 628 ultimate.name().ToString())) { // C1030 629 context_.Say( 630 "Intrinsic procedure '%s' is not a specific intrinsic permitted for use as the initializer for procedure pointer '%s'"_err_en_US, 631 ultimate.name(), symbol.name()); 632 } 633 } else if (!ultimate.attrs().test(Attr::EXTERNAL) && 634 ultimate.owner().kind() != Scope::Kind::Module) { 635 context_.Say("Procedure pointer '%s' initializer '%s' is neither " 636 "an external nor a module procedure"_err_en_US, 637 symbol.name(), ultimate.name()); 638 } else if (ultimate.attrs().test(Attr::ELEMENTAL)) { 639 context_.Say("Procedure pointer '%s' cannot be initialized with the " 640 "elemental procedure '%s"_err_en_US, 641 symbol.name(), ultimate.name()); 642 } else { 643 // TODO: Check the "shalls" in the 15.4.3.6 paragraphs 7-10. 644 } 645 } 646 } 647 } 648 } 649 650 // The six different kinds of array-specs: 651 // array-spec -> explicit-shape-list | deferred-shape-list 652 // | assumed-shape-list | implied-shape-list 653 // | assumed-size | assumed-rank 654 // explicit-shape -> [ lb : ] ub 655 // deferred-shape -> : 656 // assumed-shape -> [ lb ] : 657 // implied-shape -> [ lb : ] * 658 // assumed-size -> [ explicit-shape-list , ] [ lb : ] * 659 // assumed-rank -> .. 660 // Note: 661 // - deferred-shape is also an assumed-shape 662 // - A single "*" or "lb:*" might be assumed-size or implied-shape-list 663 void CheckHelper::CheckArraySpec( 664 const Symbol &symbol, const ArraySpec &arraySpec) { 665 if (arraySpec.Rank() == 0) { 666 return; 667 } 668 bool isExplicit{arraySpec.IsExplicitShape()}; 669 bool isDeferred{arraySpec.IsDeferredShape()}; 670 bool isImplied{arraySpec.IsImpliedShape()}; 671 bool isAssumedShape{arraySpec.IsAssumedShape()}; 672 bool isAssumedSize{arraySpec.IsAssumedSize()}; 673 bool isAssumedRank{arraySpec.IsAssumedRank()}; 674 std::optional<parser::MessageFixedText> msg; 675 if (symbol.test(Symbol::Flag::CrayPointee) && !isExplicit && !isAssumedSize) { 676 msg = "Cray pointee '%s' must have must have explicit shape or" 677 " assumed size"_err_en_US; 678 } else if (IsAllocatableOrPointer(symbol) && !isDeferred && !isAssumedRank) { 679 if (symbol.owner().IsDerivedType()) { // C745 680 if (IsAllocatable(symbol)) { 681 msg = "Allocatable array component '%s' must have" 682 " deferred shape"_err_en_US; 683 } else { 684 msg = "Array pointer component '%s' must have deferred shape"_err_en_US; 685 } 686 } else { 687 if (IsAllocatable(symbol)) { // C832 688 msg = "Allocatable array '%s' must have deferred shape or" 689 " assumed rank"_err_en_US; 690 } else { 691 msg = "Array pointer '%s' must have deferred shape or" 692 " assumed rank"_err_en_US; 693 } 694 } 695 } else if (IsDummy(symbol)) { 696 if (isImplied && !isAssumedSize) { // C836 697 msg = "Dummy array argument '%s' may not have implied shape"_err_en_US; 698 } 699 } else if (isAssumedShape && !isDeferred) { 700 msg = "Assumed-shape array '%s' must be a dummy argument"_err_en_US; 701 } else if (isAssumedSize && !isImplied) { // C833 702 msg = "Assumed-size array '%s' must be a dummy argument"_err_en_US; 703 } else if (isAssumedRank) { // C837 704 msg = "Assumed-rank array '%s' must be a dummy argument"_err_en_US; 705 } else if (isImplied) { 706 if (!IsNamedConstant(symbol)) { // C835, C836 707 msg = "Implied-shape array '%s' must be a named constant or a " 708 "dummy argument"_err_en_US; 709 } 710 } else if (IsNamedConstant(symbol)) { 711 if (!isExplicit && !isImplied) { 712 msg = "Named constant '%s' array must have constant or" 713 " implied shape"_err_en_US; 714 } 715 } else if (!IsAllocatableOrPointer(symbol) && !isExplicit) { 716 if (symbol.owner().IsDerivedType()) { // C749 717 msg = "Component array '%s' without ALLOCATABLE or POINTER attribute must" 718 " have explicit shape"_err_en_US; 719 } else { // C816 720 msg = "Array '%s' without ALLOCATABLE or POINTER attribute must have" 721 " explicit shape"_err_en_US; 722 } 723 } 724 if (msg) { 725 context_.Say(std::move(*msg), symbol.name()); 726 } 727 } 728 729 void CheckHelper::CheckProcEntity( 730 const Symbol &symbol, const ProcEntityDetails &details) { 731 if (details.isDummy()) { 732 if (!symbol.attrs().test(Attr::POINTER) && // C843 733 (symbol.attrs().test(Attr::INTENT_IN) || 734 symbol.attrs().test(Attr::INTENT_OUT) || 735 symbol.attrs().test(Attr::INTENT_INOUT))) { 736 messages_.Say("A dummy procedure without the POINTER attribute" 737 " may not have an INTENT attribute"_err_en_US); 738 } 739 if (InElemental()) { // C15100 740 messages_.Say( 741 "An ELEMENTAL subprogram may not have a dummy procedure"_err_en_US); 742 } 743 const Symbol *interface { details.interface().symbol() }; 744 if (!symbol.attrs().test(Attr::INTRINSIC) && 745 (symbol.attrs().test(Attr::ELEMENTAL) || 746 (interface && !interface->attrs().test(Attr::INTRINSIC) && 747 interface->attrs().test(Attr::ELEMENTAL)))) { 748 // There's no explicit constraint or "shall" that we can find in the 749 // standard for this check, but it seems to be implied in multiple 750 // sites, and ELEMENTAL non-intrinsic actual arguments *are* 751 // explicitly forbidden. But we allow "PROCEDURE(SIN)::dummy" 752 // because it is explicitly legal to *pass* the specific intrinsic 753 // function SIN as an actual argument. 754 messages_.Say("A dummy procedure may not be ELEMENTAL"_err_en_US); 755 } 756 } else if (symbol.attrs().test(Attr::INTENT_IN) || 757 symbol.attrs().test(Attr::INTENT_OUT) || 758 symbol.attrs().test(Attr::INTENT_INOUT)) { 759 messages_.Say("INTENT attributes may apply only to a dummy " 760 "argument"_err_en_US); // C843 761 } else if (IsOptional(symbol)) { 762 messages_.Say("OPTIONAL attribute may apply only to a dummy " 763 "argument"_err_en_US); // C849 764 } else if (symbol.owner().IsDerivedType()) { 765 if (!symbol.attrs().test(Attr::POINTER)) { // C756 766 const auto &name{symbol.name()}; 767 messages_.Say(name, 768 "Procedure component '%s' must have POINTER attribute"_err_en_US, 769 name); 770 } 771 CheckPassArg(symbol, details.interface().symbol(), details); 772 } 773 if (symbol.attrs().test(Attr::POINTER)) { 774 CheckPointerInitialization(symbol); 775 if (const Symbol * interface{details.interface().symbol()}) { 776 if (interface->attrs().test(Attr::INTRINSIC)) { 777 if (!context_.intrinsics().IsSpecificIntrinsicFunction( 778 interface->name().ToString())) { // C1515 779 messages_.Say( 780 "Intrinsic procedure '%s' is not a specific intrinsic permitted for use as the definition of the interface to procedure pointer '%s'"_err_en_US, 781 interface->name(), symbol.name()); 782 } 783 } else if (interface->attrs().test(Attr::ELEMENTAL)) { 784 messages_.Say("Procedure pointer '%s' may not be ELEMENTAL"_err_en_US, 785 symbol.name()); // C1517 786 } 787 } 788 } else if (symbol.attrs().test(Attr::SAVE)) { 789 messages_.Say( 790 "Procedure '%s' with SAVE attribute must also have POINTER attribute"_err_en_US, 791 symbol.name()); 792 } 793 } 794 795 // When a module subprogram has the MODULE prefix the following must match 796 // with the corresponding separate module procedure interface body: 797 // - C1549: characteristics and dummy argument names 798 // - C1550: binding label 799 // - C1551: NON_RECURSIVE prefix 800 class SubprogramMatchHelper { 801 public: 802 explicit SubprogramMatchHelper(CheckHelper &checkHelper) 803 : checkHelper{checkHelper} {} 804 805 void Check(const Symbol &, const Symbol &); 806 807 private: 808 SemanticsContext &context() { return checkHelper.context(); } 809 void CheckDummyArg(const Symbol &, const Symbol &, const DummyArgument &, 810 const DummyArgument &); 811 void CheckDummyDataObject(const Symbol &, const Symbol &, 812 const DummyDataObject &, const DummyDataObject &); 813 void CheckDummyProcedure(const Symbol &, const Symbol &, 814 const DummyProcedure &, const DummyProcedure &); 815 bool CheckSameIntent( 816 const Symbol &, const Symbol &, common::Intent, common::Intent); 817 template <typename... A> 818 void Say( 819 const Symbol &, const Symbol &, parser::MessageFixedText &&, A &&...); 820 template <typename ATTRS> 821 bool CheckSameAttrs(const Symbol &, const Symbol &, ATTRS, ATTRS); 822 bool ShapesAreCompatible(const DummyDataObject &, const DummyDataObject &); 823 evaluate::Shape FoldShape(const evaluate::Shape &); 824 std::string AsFortran(DummyDataObject::Attr attr) { 825 return parser::ToUpperCaseLetters(DummyDataObject::EnumToString(attr)); 826 } 827 std::string AsFortran(DummyProcedure::Attr attr) { 828 return parser::ToUpperCaseLetters(DummyProcedure::EnumToString(attr)); 829 } 830 831 CheckHelper &checkHelper; 832 }; 833 834 // 15.6.2.6 para 3 - can the result of an ENTRY differ from its function? 835 bool CheckHelper::IsResultOkToDiffer(const FunctionResult &result) { 836 if (result.attrs.test(FunctionResult::Attr::Allocatable) || 837 result.attrs.test(FunctionResult::Attr::Pointer)) { 838 return false; 839 } 840 const auto *typeAndShape{result.GetTypeAndShape()}; 841 if (!typeAndShape || typeAndShape->Rank() != 0) { 842 return false; 843 } 844 auto category{typeAndShape->type().category()}; 845 if (category == TypeCategory::Character || 846 category == TypeCategory::Derived) { 847 return false; 848 } 849 int kind{typeAndShape->type().kind()}; 850 return kind == context_.GetDefaultKind(category) || 851 (category == TypeCategory::Real && 852 kind == context_.doublePrecisionKind()); 853 } 854 855 void CheckHelper::CheckSubprogram( 856 const Symbol &symbol, const SubprogramDetails &details) { 857 if (const Symbol * iface{FindSeparateModuleSubprogramInterface(&symbol)}) { 858 SubprogramMatchHelper{*this}.Check(symbol, *iface); 859 } 860 if (const Scope * entryScope{details.entryScope()}) { 861 // ENTRY 15.6.2.6, esp. C1571 862 std::optional<parser::MessageFixedText> error; 863 const Symbol *subprogram{entryScope->symbol()}; 864 const SubprogramDetails *subprogramDetails{nullptr}; 865 if (subprogram) { 866 subprogramDetails = subprogram->detailsIf<SubprogramDetails>(); 867 } 868 if (entryScope->kind() != Scope::Kind::Subprogram) { 869 error = "ENTRY may appear only in a subroutine or function"_err_en_US; 870 } else if (!(entryScope->parent().IsGlobal() || 871 entryScope->parent().IsModule() || 872 entryScope->parent().IsSubmodule())) { 873 error = "ENTRY may not appear in an internal subprogram"_err_en_US; 874 } else if (FindSeparateModuleSubprogramInterface(subprogram)) { 875 error = "ENTRY may not appear in a separate module procedure"_err_en_US; 876 } else if (subprogramDetails && details.isFunction() && 877 subprogramDetails->isFunction() && 878 !context_.HasError(details.result()) && 879 !context_.HasError(subprogramDetails->result())) { 880 auto result{FunctionResult::Characterize( 881 details.result(), context_.foldingContext())}; 882 auto subpResult{FunctionResult::Characterize( 883 subprogramDetails->result(), context_.foldingContext())}; 884 if (result && subpResult && *result != *subpResult && 885 (!IsResultOkToDiffer(*result) || !IsResultOkToDiffer(*subpResult))) { 886 error = 887 "Result of ENTRY is not compatible with result of containing function"_err_en_US; 888 } 889 } 890 if (error) { 891 if (auto *msg{messages_.Say(symbol.name(), *error)}) { 892 if (subprogram) { 893 msg->Attach(subprogram->name(), "Containing subprogram"_en_US); 894 } 895 } 896 } 897 } 898 if (symbol.attrs().test(Attr::ELEMENTAL)) { 899 // See comment on the similar check in CheckProcEntity() 900 if (details.isDummy()) { 901 messages_.Say("A dummy procedure may not be ELEMENTAL"_err_en_US); 902 } else { 903 for (const Symbol *dummy : details.dummyArgs()) { 904 if (!dummy) { // C15100 905 messages_.Say( 906 "An ELEMENTAL subroutine may not have an alternate return dummy argument"_err_en_US); 907 } 908 } 909 } 910 } 911 } 912 913 void CheckHelper::CheckDerivedType( 914 const Symbol &derivedType, const DerivedTypeDetails &details) { 915 if (details.isForwardReferenced() && !context_.HasError(derivedType)) { 916 messages_.Say("The derived type '%s' has not been defined"_err_en_US, 917 derivedType.name()); 918 } 919 const Scope *scope{derivedType.scope()}; 920 if (!scope) { 921 CHECK(details.isForwardReferenced()); 922 return; 923 } 924 CHECK(scope->symbol() == &derivedType); 925 CHECK(scope->IsDerivedType()); 926 if (derivedType.attrs().test(Attr::ABSTRACT) && // C734 927 (derivedType.attrs().test(Attr::BIND_C) || details.sequence())) { 928 messages_.Say("An ABSTRACT derived type must be extensible"_err_en_US); 929 } 930 if (const DeclTypeSpec * parent{FindParentTypeSpec(derivedType)}) { 931 const DerivedTypeSpec *parentDerived{parent->AsDerived()}; 932 if (!IsExtensibleType(parentDerived)) { // C705 933 messages_.Say("The parent type is not extensible"_err_en_US); 934 } 935 if (!derivedType.attrs().test(Attr::ABSTRACT) && parentDerived && 936 parentDerived->typeSymbol().attrs().test(Attr::ABSTRACT)) { 937 ScopeComponentIterator components{*parentDerived}; 938 for (const Symbol &component : components) { 939 if (component.attrs().test(Attr::DEFERRED)) { 940 if (scope->FindComponent(component.name()) == &component) { 941 SayWithDeclaration(component, 942 "Non-ABSTRACT extension of ABSTRACT derived type '%s' lacks a binding for DEFERRED procedure '%s'"_err_en_US, 943 parentDerived->typeSymbol().name(), component.name()); 944 } 945 } 946 } 947 } 948 DerivedTypeSpec derived{derivedType.name(), derivedType}; 949 derived.set_scope(*scope); 950 if (FindCoarrayUltimateComponent(derived) && // C736 951 !(parentDerived && FindCoarrayUltimateComponent(*parentDerived))) { 952 messages_.Say( 953 "Type '%s' has a coarray ultimate component so the type at the base " 954 "of its type extension chain ('%s') must be a type that has a " 955 "coarray ultimate component"_err_en_US, 956 derivedType.name(), scope->GetDerivedTypeBase().GetSymbol()->name()); 957 } 958 if (FindEventOrLockPotentialComponent(derived) && // C737 959 !(FindEventOrLockPotentialComponent(*parentDerived) || 960 IsEventTypeOrLockType(parentDerived))) { 961 messages_.Say( 962 "Type '%s' has an EVENT_TYPE or LOCK_TYPE component, so the type " 963 "at the base of its type extension chain ('%s') must either have an " 964 "EVENT_TYPE or LOCK_TYPE component, or be EVENT_TYPE or " 965 "LOCK_TYPE"_err_en_US, 966 derivedType.name(), scope->GetDerivedTypeBase().GetSymbol()->name()); 967 } 968 } 969 if (HasIntrinsicTypeName(derivedType)) { // C729 970 messages_.Say("A derived type name cannot be the name of an intrinsic" 971 " type"_err_en_US); 972 } 973 std::map<SourceName, SymbolRef> previous; 974 for (const auto &pair : details.finals()) { 975 SourceName source{pair.first}; 976 const Symbol &ref{*pair.second}; 977 if (CheckFinal(ref, source, derivedType) && 978 std::all_of(previous.begin(), previous.end(), 979 [&](std::pair<SourceName, SymbolRef> prev) { 980 return CheckDistinguishableFinals( 981 ref, source, *prev.second, prev.first, derivedType); 982 })) { 983 previous.emplace(source, ref); 984 } 985 } 986 } 987 988 // C786 989 bool CheckHelper::CheckFinal( 990 const Symbol &subroutine, SourceName finalName, const Symbol &derivedType) { 991 if (!IsModuleProcedure(subroutine)) { 992 SayWithDeclaration(subroutine, finalName, 993 "FINAL subroutine '%s' of derived type '%s' must be a module procedure"_err_en_US, 994 subroutine.name(), derivedType.name()); 995 return false; 996 } 997 const Procedure *proc{Characterize(subroutine)}; 998 if (!proc) { 999 return false; // error recovery 1000 } 1001 if (!proc->IsSubroutine()) { 1002 SayWithDeclaration(subroutine, finalName, 1003 "FINAL subroutine '%s' of derived type '%s' must be a subroutine"_err_en_US, 1004 subroutine.name(), derivedType.name()); 1005 return false; 1006 } 1007 if (proc->dummyArguments.size() != 1) { 1008 SayWithDeclaration(subroutine, finalName, 1009 "FINAL subroutine '%s' of derived type '%s' must have a single dummy argument"_err_en_US, 1010 subroutine.name(), derivedType.name()); 1011 return false; 1012 } 1013 const auto &arg{proc->dummyArguments[0]}; 1014 const Symbol *errSym{&subroutine}; 1015 if (const auto *details{subroutine.detailsIf<SubprogramDetails>()}) { 1016 if (!details->dummyArgs().empty()) { 1017 if (const Symbol * argSym{details->dummyArgs()[0]}) { 1018 errSym = argSym; 1019 } 1020 } 1021 } 1022 const auto *ddo{std::get_if<DummyDataObject>(&arg.u)}; 1023 if (!ddo) { 1024 SayWithDeclaration(subroutine, finalName, 1025 "FINAL subroutine '%s' of derived type '%s' must have a single dummy argument that is a data object"_err_en_US, 1026 subroutine.name(), derivedType.name()); 1027 return false; 1028 } 1029 bool ok{true}; 1030 if (arg.IsOptional()) { 1031 SayWithDeclaration(*errSym, finalName, 1032 "FINAL subroutine '%s' of derived type '%s' must not have an OPTIONAL dummy argument"_err_en_US, 1033 subroutine.name(), derivedType.name()); 1034 ok = false; 1035 } 1036 if (ddo->attrs.test(DummyDataObject::Attr::Allocatable)) { 1037 SayWithDeclaration(*errSym, finalName, 1038 "FINAL subroutine '%s' of derived type '%s' must not have an ALLOCATABLE dummy argument"_err_en_US, 1039 subroutine.name(), derivedType.name()); 1040 ok = false; 1041 } 1042 if (ddo->attrs.test(DummyDataObject::Attr::Pointer)) { 1043 SayWithDeclaration(*errSym, finalName, 1044 "FINAL subroutine '%s' of derived type '%s' must not have a POINTER dummy argument"_err_en_US, 1045 subroutine.name(), derivedType.name()); 1046 ok = false; 1047 } 1048 if (ddo->intent == common::Intent::Out) { 1049 SayWithDeclaration(*errSym, finalName, 1050 "FINAL subroutine '%s' of derived type '%s' must not have a dummy argument with INTENT(OUT)"_err_en_US, 1051 subroutine.name(), derivedType.name()); 1052 ok = false; 1053 } 1054 if (ddo->attrs.test(DummyDataObject::Attr::Value)) { 1055 SayWithDeclaration(*errSym, finalName, 1056 "FINAL subroutine '%s' of derived type '%s' must not have a dummy argument with the VALUE attribute"_err_en_US, 1057 subroutine.name(), derivedType.name()); 1058 ok = false; 1059 } 1060 if (ddo->type.corank() > 0) { 1061 SayWithDeclaration(*errSym, finalName, 1062 "FINAL subroutine '%s' of derived type '%s' must not have a coarray dummy argument"_err_en_US, 1063 subroutine.name(), derivedType.name()); 1064 ok = false; 1065 } 1066 if (ddo->type.type().IsPolymorphic()) { 1067 SayWithDeclaration(*errSym, finalName, 1068 "FINAL subroutine '%s' of derived type '%s' must not have a polymorphic dummy argument"_err_en_US, 1069 subroutine.name(), derivedType.name()); 1070 ok = false; 1071 } else if (ddo->type.type().category() != TypeCategory::Derived || 1072 &ddo->type.type().GetDerivedTypeSpec().typeSymbol() != &derivedType) { 1073 SayWithDeclaration(*errSym, finalName, 1074 "FINAL subroutine '%s' of derived type '%s' must have a TYPE(%s) dummy argument"_err_en_US, 1075 subroutine.name(), derivedType.name(), derivedType.name()); 1076 ok = false; 1077 } else { // check that all LEN type parameters are assumed 1078 for (auto ref : OrderParameterDeclarations(derivedType)) { 1079 if (IsLenTypeParameter(*ref)) { 1080 const auto *value{ 1081 ddo->type.type().GetDerivedTypeSpec().FindParameter(ref->name())}; 1082 if (!value || !value->isAssumed()) { 1083 SayWithDeclaration(*errSym, finalName, 1084 "FINAL subroutine '%s' of derived type '%s' must have a dummy argument with an assumed LEN type parameter '%s=*'"_err_en_US, 1085 subroutine.name(), derivedType.name(), ref->name()); 1086 ok = false; 1087 } 1088 } 1089 } 1090 } 1091 return ok; 1092 } 1093 1094 bool CheckHelper::CheckDistinguishableFinals(const Symbol &f1, 1095 SourceName f1Name, const Symbol &f2, SourceName f2Name, 1096 const Symbol &derivedType) { 1097 const Procedure *p1{Characterize(f1)}; 1098 const Procedure *p2{Characterize(f2)}; 1099 if (p1 && p2) { 1100 if (characteristics::Distinguishable(*p1, *p2)) { 1101 return true; 1102 } 1103 if (auto *msg{messages_.Say(f1Name, 1104 "FINAL subroutines '%s' and '%s' of derived type '%s' cannot be distinguished by rank or KIND type parameter value"_err_en_US, 1105 f1Name, f2Name, derivedType.name())}) { 1106 msg->Attach(f2Name, "FINAL declaration of '%s'"_en_US, f2.name()) 1107 .Attach(f1.name(), "Definition of '%s'"_en_US, f1Name) 1108 .Attach(f2.name(), "Definition of '%s'"_en_US, f2Name); 1109 } 1110 } 1111 return false; 1112 } 1113 1114 void CheckHelper::CheckHostAssoc( 1115 const Symbol &symbol, const HostAssocDetails &details) { 1116 const Symbol &hostSymbol{details.symbol()}; 1117 if (hostSymbol.test(Symbol::Flag::ImplicitOrError)) { 1118 if (details.implicitOrSpecExprError) { 1119 messages_.Say("Implicitly typed local entity '%s' not allowed in" 1120 " specification expression"_err_en_US, 1121 symbol.name()); 1122 } else if (details.implicitOrExplicitTypeError) { 1123 messages_.Say( 1124 "No explicit type declared for '%s'"_err_en_US, symbol.name()); 1125 } 1126 } 1127 } 1128 1129 void CheckHelper::CheckGeneric( 1130 const Symbol &symbol, const GenericDetails &details) { 1131 CheckSpecificsAreDistinguishable(symbol, details); 1132 std::visit(common::visitors{ 1133 [&](const GenericKind::DefinedIo &io) { 1134 CheckDefinedIoProc(symbol, details, io); 1135 }, 1136 [](const auto &) {}, 1137 }, 1138 details.kind().u); 1139 } 1140 1141 // Check that the specifics of this generic are distinguishable from each other 1142 void CheckHelper::CheckSpecificsAreDistinguishable( 1143 const Symbol &generic, const GenericDetails &details) { 1144 GenericKind kind{details.kind()}; 1145 const SymbolVector &specifics{details.specificProcs()}; 1146 std::size_t count{specifics.size()}; 1147 if (count < 2 || !kind.IsName()) { 1148 return; 1149 } 1150 DistinguishabilityHelper helper{context_}; 1151 for (const Symbol &specific : specifics) { 1152 if (const Procedure * procedure{Characterize(specific)}) { 1153 helper.Add(generic, kind, specific, *procedure); 1154 } 1155 } 1156 helper.Check(generic.owner()); 1157 } 1158 1159 static bool ConflictsWithIntrinsicAssignment(const Procedure &proc) { 1160 auto lhs{std::get<DummyDataObject>(proc.dummyArguments[0].u).type}; 1161 auto rhs{std::get<DummyDataObject>(proc.dummyArguments[1].u).type}; 1162 return Tristate::No == 1163 IsDefinedAssignment(lhs.type(), lhs.Rank(), rhs.type(), rhs.Rank()); 1164 } 1165 1166 static bool ConflictsWithIntrinsicOperator( 1167 const GenericKind &kind, const Procedure &proc) { 1168 if (!kind.IsIntrinsicOperator()) { 1169 return false; 1170 } 1171 auto arg0{std::get<DummyDataObject>(proc.dummyArguments[0].u).type}; 1172 auto type0{arg0.type()}; 1173 if (proc.dummyArguments.size() == 1) { // unary 1174 return std::visit( 1175 common::visitors{ 1176 [&](common::NumericOperator) { return IsIntrinsicNumeric(type0); }, 1177 [&](common::LogicalOperator) { return IsIntrinsicLogical(type0); }, 1178 [](const auto &) -> bool { DIE("bad generic kind"); }, 1179 }, 1180 kind.u); 1181 } else { // binary 1182 int rank0{arg0.Rank()}; 1183 auto arg1{std::get<DummyDataObject>(proc.dummyArguments[1].u).type}; 1184 auto type1{arg1.type()}; 1185 int rank1{arg1.Rank()}; 1186 return std::visit( 1187 common::visitors{ 1188 [&](common::NumericOperator) { 1189 return IsIntrinsicNumeric(type0, rank0, type1, rank1); 1190 }, 1191 [&](common::LogicalOperator) { 1192 return IsIntrinsicLogical(type0, rank0, type1, rank1); 1193 }, 1194 [&](common::RelationalOperator opr) { 1195 return IsIntrinsicRelational(opr, type0, rank0, type1, rank1); 1196 }, 1197 [&](GenericKind::OtherKind x) { 1198 CHECK(x == GenericKind::OtherKind::Concat); 1199 return IsIntrinsicConcat(type0, rank0, type1, rank1); 1200 }, 1201 [](const auto &) -> bool { DIE("bad generic kind"); }, 1202 }, 1203 kind.u); 1204 } 1205 } 1206 1207 // Check if this procedure can be used for defined operators (see 15.4.3.4.2). 1208 bool CheckHelper::CheckDefinedOperator(SourceName opName, GenericKind kind, 1209 const Symbol &specific, const Procedure &proc) { 1210 if (context_.HasError(specific)) { 1211 return false; 1212 } 1213 std::optional<parser::MessageFixedText> msg; 1214 auto checkDefinedOperatorArgs{ 1215 [&](SourceName opName, const Symbol &specific, const Procedure &proc) { 1216 bool arg0Defined{CheckDefinedOperatorArg(opName, specific, proc, 0)}; 1217 bool arg1Defined{CheckDefinedOperatorArg(opName, specific, proc, 1)}; 1218 return arg0Defined && arg1Defined; 1219 }}; 1220 if (specific.attrs().test(Attr::NOPASS)) { // C774 1221 msg = "%s procedure '%s' may not have NOPASS attribute"_err_en_US; 1222 } else if (!proc.functionResult.has_value()) { 1223 msg = "%s procedure '%s' must be a function"_err_en_US; 1224 } else if (proc.functionResult->IsAssumedLengthCharacter()) { 1225 msg = "%s function '%s' may not have assumed-length CHARACTER(*)" 1226 " result"_err_en_US; 1227 } else if (auto m{CheckNumberOfArgs(kind, proc.dummyArguments.size())}) { 1228 msg = std::move(m); 1229 } else if (!checkDefinedOperatorArgs(opName, specific, proc)) { 1230 return false; // error was reported 1231 } else if (ConflictsWithIntrinsicOperator(kind, proc)) { 1232 msg = "%s function '%s' conflicts with intrinsic operator"_err_en_US; 1233 } else { 1234 return true; // OK 1235 } 1236 SayWithDeclaration( 1237 specific, std::move(*msg), MakeOpName(opName), specific.name()); 1238 context_.SetError(specific); 1239 return false; 1240 } 1241 1242 // If the number of arguments is wrong for this intrinsic operator, return 1243 // false and return the error message in msg. 1244 std::optional<parser::MessageFixedText> CheckHelper::CheckNumberOfArgs( 1245 const GenericKind &kind, std::size_t nargs) { 1246 if (!kind.IsIntrinsicOperator()) { 1247 return std::nullopt; 1248 } 1249 std::size_t min{2}, max{2}; // allowed number of args; default is binary 1250 std::visit(common::visitors{ 1251 [&](const common::NumericOperator &x) { 1252 if (x == common::NumericOperator::Add || 1253 x == common::NumericOperator::Subtract) { 1254 min = 1; // + and - are unary or binary 1255 } 1256 }, 1257 [&](const common::LogicalOperator &x) { 1258 if (x == common::LogicalOperator::Not) { 1259 min = 1; // .NOT. is unary 1260 max = 1; 1261 } 1262 }, 1263 [](const common::RelationalOperator &) { 1264 // all are binary 1265 }, 1266 [](const GenericKind::OtherKind &x) { 1267 CHECK(x == GenericKind::OtherKind::Concat); 1268 }, 1269 [](const auto &) { DIE("expected intrinsic operator"); }, 1270 }, 1271 kind.u); 1272 if (nargs >= min && nargs <= max) { 1273 return std::nullopt; 1274 } else if (max == 1) { 1275 return "%s function '%s' must have one dummy argument"_err_en_US; 1276 } else if (min == 2) { 1277 return "%s function '%s' must have two dummy arguments"_err_en_US; 1278 } else { 1279 return "%s function '%s' must have one or two dummy arguments"_err_en_US; 1280 } 1281 } 1282 1283 bool CheckHelper::CheckDefinedOperatorArg(const SourceName &opName, 1284 const Symbol &symbol, const Procedure &proc, std::size_t pos) { 1285 if (pos >= proc.dummyArguments.size()) { 1286 return true; 1287 } 1288 auto &arg{proc.dummyArguments.at(pos)}; 1289 std::optional<parser::MessageFixedText> msg; 1290 if (arg.IsOptional()) { 1291 msg = "In %s function '%s', dummy argument '%s' may not be" 1292 " OPTIONAL"_err_en_US; 1293 } else if (const auto *dataObject{std::get_if<DummyDataObject>(&arg.u)}; 1294 dataObject == nullptr) { 1295 msg = "In %s function '%s', dummy argument '%s' must be a" 1296 " data object"_err_en_US; 1297 } else if (dataObject->intent != common::Intent::In && 1298 !dataObject->attrs.test(DummyDataObject::Attr::Value)) { 1299 msg = "In %s function '%s', dummy argument '%s' must have INTENT(IN)" 1300 " or VALUE attribute"_err_en_US; 1301 } 1302 if (msg) { 1303 SayWithDeclaration(symbol, std::move(*msg), 1304 parser::ToUpperCaseLetters(opName.ToString()), symbol.name(), arg.name); 1305 return false; 1306 } 1307 return true; 1308 } 1309 1310 // Check if this procedure can be used for defined assignment (see 15.4.3.4.3). 1311 bool CheckHelper::CheckDefinedAssignment( 1312 const Symbol &specific, const Procedure &proc) { 1313 if (context_.HasError(specific)) { 1314 return false; 1315 } 1316 std::optional<parser::MessageFixedText> msg; 1317 if (specific.attrs().test(Attr::NOPASS)) { // C774 1318 msg = "Defined assignment procedure '%s' may not have" 1319 " NOPASS attribute"_err_en_US; 1320 } else if (!proc.IsSubroutine()) { 1321 msg = "Defined assignment procedure '%s' must be a subroutine"_err_en_US; 1322 } else if (proc.dummyArguments.size() != 2) { 1323 msg = "Defined assignment subroutine '%s' must have" 1324 " two dummy arguments"_err_en_US; 1325 } else if (!CheckDefinedAssignmentArg(specific, proc.dummyArguments[0], 0) | 1326 !CheckDefinedAssignmentArg(specific, proc.dummyArguments[1], 1)) { 1327 return false; // error was reported 1328 } else if (ConflictsWithIntrinsicAssignment(proc)) { 1329 msg = "Defined assignment subroutine '%s' conflicts with" 1330 " intrinsic assignment"_err_en_US; 1331 } else { 1332 return true; // OK 1333 } 1334 SayWithDeclaration(specific, std::move(msg.value()), specific.name()); 1335 context_.SetError(specific); 1336 return false; 1337 } 1338 1339 bool CheckHelper::CheckDefinedAssignmentArg( 1340 const Symbol &symbol, const DummyArgument &arg, int pos) { 1341 std::optional<parser::MessageFixedText> msg; 1342 if (arg.IsOptional()) { 1343 msg = "In defined assignment subroutine '%s', dummy argument '%s'" 1344 " may not be OPTIONAL"_err_en_US; 1345 } else if (const auto *dataObject{std::get_if<DummyDataObject>(&arg.u)}) { 1346 if (pos == 0) { 1347 if (dataObject->intent != common::Intent::Out && 1348 dataObject->intent != common::Intent::InOut) { 1349 msg = "In defined assignment subroutine '%s', first dummy argument '%s'" 1350 " must have INTENT(OUT) or INTENT(INOUT)"_err_en_US; 1351 } 1352 } else if (pos == 1) { 1353 if (dataObject->intent != common::Intent::In && 1354 !dataObject->attrs.test(DummyDataObject::Attr::Value)) { 1355 msg = 1356 "In defined assignment subroutine '%s', second dummy" 1357 " argument '%s' must have INTENT(IN) or VALUE attribute"_err_en_US; 1358 } 1359 } else { 1360 DIE("pos must be 0 or 1"); 1361 } 1362 } else { 1363 msg = "In defined assignment subroutine '%s', dummy argument '%s'" 1364 " must be a data object"_err_en_US; 1365 } 1366 if (msg) { 1367 SayWithDeclaration(symbol, std::move(*msg), symbol.name(), arg.name); 1368 context_.SetError(symbol); 1369 return false; 1370 } 1371 return true; 1372 } 1373 1374 // Report a conflicting attribute error if symbol has both of these attributes 1375 bool CheckHelper::CheckConflicting(const Symbol &symbol, Attr a1, Attr a2) { 1376 if (symbol.attrs().test(a1) && symbol.attrs().test(a2)) { 1377 messages_.Say("'%s' may not have both the %s and %s attributes"_err_en_US, 1378 symbol.name(), AttrToString(a1), AttrToString(a2)); 1379 return true; 1380 } else { 1381 return false; 1382 } 1383 } 1384 1385 void CheckHelper::WarnMissingFinal(const Symbol &symbol) { 1386 const auto *object{symbol.detailsIf<ObjectEntityDetails>()}; 1387 if (!object || IsPointer(symbol)) { 1388 return; 1389 } 1390 const DeclTypeSpec *type{object->type()}; 1391 const DerivedTypeSpec *derived{type ? type->AsDerived() : nullptr}; 1392 const Symbol *derivedSym{derived ? &derived->typeSymbol() : nullptr}; 1393 int rank{object->shape().Rank()}; 1394 const Symbol *initialDerivedSym{derivedSym}; 1395 while (const auto *derivedDetails{ 1396 derivedSym ? derivedSym->detailsIf<DerivedTypeDetails>() : nullptr}) { 1397 if (!derivedDetails->finals().empty() && 1398 !derivedDetails->GetFinalForRank(rank)) { 1399 if (auto *msg{derivedSym == initialDerivedSym 1400 ? messages_.Say(symbol.name(), 1401 "'%s' of derived type '%s' does not have a FINAL subroutine for its rank (%d)"_en_US, 1402 symbol.name(), derivedSym->name(), rank) 1403 : messages_.Say(symbol.name(), 1404 "'%s' of derived type '%s' extended from '%s' does not have a FINAL subroutine for its rank (%d)"_en_US, 1405 symbol.name(), initialDerivedSym->name(), 1406 derivedSym->name(), rank)}) { 1407 msg->Attach(derivedSym->name(), 1408 "Declaration of derived type '%s'"_en_US, derivedSym->name()); 1409 } 1410 return; 1411 } 1412 derived = derivedSym->GetParentTypeSpec(); 1413 derivedSym = derived ? &derived->typeSymbol() : nullptr; 1414 } 1415 } 1416 1417 const Procedure *CheckHelper::Characterize(const Symbol &symbol) { 1418 auto it{characterizeCache_.find(symbol)}; 1419 if (it == characterizeCache_.end()) { 1420 auto pair{characterizeCache_.emplace(SymbolRef{symbol}, 1421 Procedure::Characterize(symbol, context_.foldingContext()))}; 1422 it = pair.first; 1423 } 1424 return common::GetPtrFromOptional(it->second); 1425 } 1426 1427 void CheckHelper::CheckVolatile(const Symbol &symbol, 1428 const DerivedTypeSpec *derived) { // C866 - C868 1429 if (IsIntentIn(symbol)) { 1430 messages_.Say( 1431 "VOLATILE attribute may not apply to an INTENT(IN) argument"_err_en_US); 1432 } 1433 if (IsProcedure(symbol)) { 1434 messages_.Say("VOLATILE attribute may apply only to a variable"_err_en_US); 1435 } 1436 if (symbol.has<UseDetails>() || symbol.has<HostAssocDetails>()) { 1437 const Symbol &ultimate{symbol.GetUltimate()}; 1438 if (IsCoarray(ultimate)) { 1439 messages_.Say( 1440 "VOLATILE attribute may not apply to a coarray accessed by USE or host association"_err_en_US); 1441 } 1442 if (derived) { 1443 if (FindCoarrayUltimateComponent(*derived)) { 1444 messages_.Say( 1445 "VOLATILE attribute may not apply to a type with a coarray ultimate component accessed by USE or host association"_err_en_US); 1446 } 1447 } 1448 } 1449 } 1450 1451 void CheckHelper::CheckPointer(const Symbol &symbol) { // C852 1452 CheckConflicting(symbol, Attr::POINTER, Attr::TARGET); 1453 CheckConflicting(symbol, Attr::POINTER, Attr::ALLOCATABLE); // C751 1454 CheckConflicting(symbol, Attr::POINTER, Attr::INTRINSIC); 1455 // Prohibit constant pointers. The standard does not explicitly prohibit 1456 // them, but the PARAMETER attribute requires a entity-decl to have an 1457 // initialization that is a constant-expr, and the only form of 1458 // initialization that allows a constant-expr is the one that's not a "=>" 1459 // pointer initialization. See C811, C807, and section 8.5.13. 1460 CheckConflicting(symbol, Attr::POINTER, Attr::PARAMETER); 1461 if (symbol.Corank() > 0) { 1462 messages_.Say( 1463 "'%s' may not have the POINTER attribute because it is a coarray"_err_en_US, 1464 symbol.name()); 1465 } 1466 } 1467 1468 // C760 constraints on the passed-object dummy argument 1469 // C757 constraints on procedure pointer components 1470 void CheckHelper::CheckPassArg( 1471 const Symbol &proc, const Symbol *interface, const WithPassArg &details) { 1472 if (proc.attrs().test(Attr::NOPASS)) { 1473 return; 1474 } 1475 const auto &name{proc.name()}; 1476 if (!interface) { 1477 messages_.Say(name, 1478 "Procedure component '%s' must have NOPASS attribute or explicit interface"_err_en_US, 1479 name); 1480 return; 1481 } 1482 const auto *subprogram{interface->detailsIf<SubprogramDetails>()}; 1483 if (!subprogram) { 1484 messages_.Say(name, 1485 "Procedure component '%s' has invalid interface '%s'"_err_en_US, name, 1486 interface->name()); 1487 return; 1488 } 1489 std::optional<SourceName> passName{details.passName()}; 1490 const auto &dummyArgs{subprogram->dummyArgs()}; 1491 if (!passName) { 1492 if (dummyArgs.empty()) { 1493 messages_.Say(name, 1494 proc.has<ProcEntityDetails>() 1495 ? "Procedure component '%s' with no dummy arguments" 1496 " must have NOPASS attribute"_err_en_US 1497 : "Procedure binding '%s' with no dummy arguments" 1498 " must have NOPASS attribute"_err_en_US, 1499 name); 1500 context_.SetError(*interface); 1501 return; 1502 } 1503 Symbol *argSym{dummyArgs[0]}; 1504 if (!argSym) { 1505 messages_.Say(interface->name(), 1506 "Cannot use an alternate return as the passed-object dummy " 1507 "argument"_err_en_US); 1508 return; 1509 } 1510 passName = dummyArgs[0]->name(); 1511 } 1512 std::optional<int> passArgIndex{}; 1513 for (std::size_t i{0}; i < dummyArgs.size(); ++i) { 1514 if (dummyArgs[i] && dummyArgs[i]->name() == *passName) { 1515 passArgIndex = i; 1516 break; 1517 } 1518 } 1519 if (!passArgIndex) { // C758 1520 messages_.Say(*passName, 1521 "'%s' is not a dummy argument of procedure interface '%s'"_err_en_US, 1522 *passName, interface->name()); 1523 return; 1524 } 1525 const Symbol &passArg{*dummyArgs[*passArgIndex]}; 1526 std::optional<parser::MessageFixedText> msg; 1527 if (!passArg.has<ObjectEntityDetails>()) { 1528 msg = "Passed-object dummy argument '%s' of procedure '%s'" 1529 " must be a data object"_err_en_US; 1530 } else if (passArg.attrs().test(Attr::POINTER)) { 1531 msg = "Passed-object dummy argument '%s' of procedure '%s'" 1532 " may not have the POINTER attribute"_err_en_US; 1533 } else if (passArg.attrs().test(Attr::ALLOCATABLE)) { 1534 msg = "Passed-object dummy argument '%s' of procedure '%s'" 1535 " may not have the ALLOCATABLE attribute"_err_en_US; 1536 } else if (passArg.attrs().test(Attr::VALUE)) { 1537 msg = "Passed-object dummy argument '%s' of procedure '%s'" 1538 " may not have the VALUE attribute"_err_en_US; 1539 } else if (passArg.Rank() > 0) { 1540 msg = "Passed-object dummy argument '%s' of procedure '%s'" 1541 " must be scalar"_err_en_US; 1542 } 1543 if (msg) { 1544 messages_.Say(name, std::move(*msg), passName.value(), name); 1545 return; 1546 } 1547 const DeclTypeSpec *type{passArg.GetType()}; 1548 if (!type) { 1549 return; // an error already occurred 1550 } 1551 const Symbol &typeSymbol{*proc.owner().GetSymbol()}; 1552 const DerivedTypeSpec *derived{type->AsDerived()}; 1553 if (!derived || derived->typeSymbol() != typeSymbol) { 1554 messages_.Say(name, 1555 "Passed-object dummy argument '%s' of procedure '%s'" 1556 " must be of type '%s' but is '%s'"_err_en_US, 1557 passName.value(), name, typeSymbol.name(), type->AsFortran()); 1558 return; 1559 } 1560 if (IsExtensibleType(derived) != type->IsPolymorphic()) { 1561 messages_.Say(name, 1562 type->IsPolymorphic() 1563 ? "Passed-object dummy argument '%s' of procedure '%s'" 1564 " may not be polymorphic because '%s' is not extensible"_err_en_US 1565 : "Passed-object dummy argument '%s' of procedure '%s'" 1566 " must be polymorphic because '%s' is extensible"_err_en_US, 1567 passName.value(), name, typeSymbol.name()); 1568 return; 1569 } 1570 for (const auto &[paramName, paramValue] : derived->parameters()) { 1571 if (paramValue.isLen() && !paramValue.isAssumed()) { 1572 messages_.Say(name, 1573 "Passed-object dummy argument '%s' of procedure '%s'" 1574 " has non-assumed length parameter '%s'"_err_en_US, 1575 passName.value(), name, paramName); 1576 } 1577 } 1578 } 1579 1580 void CheckHelper::CheckProcBinding( 1581 const Symbol &symbol, const ProcBindingDetails &binding) { 1582 const Scope &dtScope{symbol.owner()}; 1583 CHECK(dtScope.kind() == Scope::Kind::DerivedType); 1584 if (symbol.attrs().test(Attr::DEFERRED)) { 1585 if (const Symbol * dtSymbol{dtScope.symbol()}) { 1586 if (!dtSymbol->attrs().test(Attr::ABSTRACT)) { // C733 1587 SayWithDeclaration(*dtSymbol, 1588 "Procedure bound to non-ABSTRACT derived type '%s' may not be DEFERRED"_err_en_US, 1589 dtSymbol->name()); 1590 } 1591 } 1592 if (symbol.attrs().test(Attr::NON_OVERRIDABLE)) { 1593 messages_.Say( 1594 "Type-bound procedure '%s' may not be both DEFERRED and NON_OVERRIDABLE"_err_en_US, 1595 symbol.name()); 1596 } 1597 } 1598 if (binding.symbol().attrs().test(Attr::INTRINSIC) && 1599 !context_.intrinsics().IsSpecificIntrinsicFunction( 1600 binding.symbol().name().ToString())) { 1601 messages_.Say( 1602 "Intrinsic procedure '%s' is not a specific intrinsic permitted for use in the definition of binding '%s'"_err_en_US, 1603 binding.symbol().name(), symbol.name()); 1604 } 1605 if (const Symbol * overridden{FindOverriddenBinding(symbol)}) { 1606 if (overridden->attrs().test(Attr::NON_OVERRIDABLE)) { 1607 SayWithDeclaration(*overridden, 1608 "Override of NON_OVERRIDABLE '%s' is not permitted"_err_en_US, 1609 symbol.name()); 1610 } 1611 if (const auto *overriddenBinding{ 1612 overridden->detailsIf<ProcBindingDetails>()}) { 1613 if (!IsPureProcedure(symbol) && IsPureProcedure(*overridden)) { 1614 SayWithDeclaration(*overridden, 1615 "An overridden pure type-bound procedure binding must also be pure"_err_en_US); 1616 return; 1617 } 1618 if (!binding.symbol().attrs().test(Attr::ELEMENTAL) && 1619 overriddenBinding->symbol().attrs().test(Attr::ELEMENTAL)) { 1620 SayWithDeclaration(*overridden, 1621 "A type-bound procedure and its override must both, or neither, be ELEMENTAL"_err_en_US); 1622 return; 1623 } 1624 bool isNopass{symbol.attrs().test(Attr::NOPASS)}; 1625 if (isNopass != overridden->attrs().test(Attr::NOPASS)) { 1626 SayWithDeclaration(*overridden, 1627 isNopass 1628 ? "A NOPASS type-bound procedure may not override a passed-argument procedure"_err_en_US 1629 : "A passed-argument type-bound procedure may not override a NOPASS procedure"_err_en_US); 1630 } else { 1631 const auto *bindingChars{Characterize(binding.symbol())}; 1632 const auto *overriddenChars{Characterize(overriddenBinding->symbol())}; 1633 if (bindingChars && overriddenChars) { 1634 if (isNopass) { 1635 if (!bindingChars->CanOverride(*overriddenChars, std::nullopt)) { 1636 SayWithDeclaration(*overridden, 1637 "A type-bound procedure and its override must have compatible interfaces"_err_en_US); 1638 } 1639 } else if (!context_.HasError(binding.symbol())) { 1640 int passIndex{bindingChars->FindPassIndex(binding.passName())}; 1641 int overriddenPassIndex{ 1642 overriddenChars->FindPassIndex(overriddenBinding->passName())}; 1643 if (passIndex != overriddenPassIndex) { 1644 SayWithDeclaration(*overridden, 1645 "A type-bound procedure and its override must use the same PASS argument"_err_en_US); 1646 } else if (!bindingChars->CanOverride( 1647 *overriddenChars, passIndex)) { 1648 SayWithDeclaration(*overridden, 1649 "A type-bound procedure and its override must have compatible interfaces apart from their passed argument"_err_en_US); 1650 } 1651 } 1652 } 1653 } 1654 if (symbol.attrs().test(Attr::PRIVATE) && 1655 overridden->attrs().test(Attr::PUBLIC)) { 1656 SayWithDeclaration(*overridden, 1657 "A PRIVATE procedure may not override a PUBLIC procedure"_err_en_US); 1658 } 1659 } else { 1660 SayWithDeclaration(*overridden, 1661 "A type-bound procedure binding may not have the same name as a parent component"_err_en_US); 1662 } 1663 } 1664 CheckPassArg(symbol, &binding.symbol(), binding); 1665 } 1666 1667 void CheckHelper::Check(const Scope &scope) { 1668 scope_ = &scope; 1669 common::Restorer<const Symbol *> restorer{innermostSymbol_, innermostSymbol_}; 1670 if (const Symbol * symbol{scope.symbol()}) { 1671 innermostSymbol_ = symbol; 1672 } 1673 if (scope.IsParameterizedDerivedTypeInstantiation()) { 1674 auto restorer{common::ScopedSet(scopeIsUninstantiatedPDT_, false)}; 1675 auto restorer2{context_.foldingContext().messages().SetContext( 1676 scope.instantiationContext().get())}; 1677 for (const auto &pair : scope) { 1678 CheckPointerInitialization(*pair.second); 1679 } 1680 } else { 1681 auto restorer{common::ScopedSet( 1682 scopeIsUninstantiatedPDT_, scope.IsParameterizedDerivedType())}; 1683 for (const auto &set : scope.equivalenceSets()) { 1684 CheckEquivalenceSet(set); 1685 } 1686 for (const auto &pair : scope) { 1687 Check(*pair.second); 1688 } 1689 for (const Scope &child : scope.children()) { 1690 Check(child); 1691 } 1692 if (scope.kind() == Scope::Kind::BlockData) { 1693 CheckBlockData(scope); 1694 } 1695 CheckGenericOps(scope); 1696 } 1697 } 1698 1699 void CheckHelper::CheckEquivalenceSet(const EquivalenceSet &set) { 1700 auto iter{ 1701 std::find_if(set.begin(), set.end(), [](const EquivalenceObject &object) { 1702 return FindCommonBlockContaining(object.symbol) != nullptr; 1703 })}; 1704 if (iter != set.end()) { 1705 const Symbol &commonBlock{DEREF(FindCommonBlockContaining(iter->symbol))}; 1706 for (auto &object : set) { 1707 if (&object != &*iter) { 1708 if (auto *details{object.symbol.detailsIf<ObjectEntityDetails>()}) { 1709 if (details->commonBlock()) { 1710 if (details->commonBlock() != &commonBlock) { // 8.10.3 paragraph 1 1711 if (auto *msg{messages_.Say(object.symbol.name(), 1712 "Two objects in the same EQUIVALENCE set may not be members of distinct COMMON blocks"_err_en_US)}) { 1713 msg->Attach(iter->symbol.name(), 1714 "Other object in EQUIVALENCE set"_en_US) 1715 .Attach(details->commonBlock()->name(), 1716 "COMMON block containing '%s'"_en_US, 1717 object.symbol.name()) 1718 .Attach(commonBlock.name(), 1719 "COMMON block containing '%s'"_en_US, 1720 iter->symbol.name()); 1721 } 1722 } 1723 } else { 1724 // Mark all symbols in the equivalence set with the same COMMON 1725 // block to prevent spurious error messages about initialization 1726 // in BLOCK DATA outside COMMON 1727 details->set_commonBlock(commonBlock); 1728 } 1729 } 1730 } 1731 } 1732 } 1733 // TODO: Move C8106 (&al.) checks here from resolve-names-utils.cpp 1734 } 1735 1736 void CheckHelper::CheckBlockData(const Scope &scope) { 1737 // BLOCK DATA subprograms should contain only named common blocks. 1738 // C1415 presents a list of statements that shouldn't appear in 1739 // BLOCK DATA, but so long as the subprogram contains no executable 1740 // code and allocates no storage outside named COMMON, we're happy 1741 // (e.g., an ENUM is strictly not allowed). 1742 for (const auto &pair : scope) { 1743 const Symbol &symbol{*pair.second}; 1744 if (!(symbol.has<CommonBlockDetails>() || symbol.has<UseDetails>() || 1745 symbol.has<UseErrorDetails>() || symbol.has<DerivedTypeDetails>() || 1746 symbol.has<SubprogramDetails>() || 1747 symbol.has<ObjectEntityDetails>() || 1748 (symbol.has<ProcEntityDetails>() && 1749 !symbol.attrs().test(Attr::POINTER)))) { 1750 messages_.Say(symbol.name(), 1751 "'%s' may not appear in a BLOCK DATA subprogram"_err_en_US, 1752 symbol.name()); 1753 } 1754 } 1755 } 1756 1757 // Check distinguishability of generic assignment and operators. 1758 // For these, generics and generic bindings must be considered together. 1759 void CheckHelper::CheckGenericOps(const Scope &scope) { 1760 DistinguishabilityHelper helper{context_}; 1761 auto addSpecifics{[&](const Symbol &generic) { 1762 const auto *details{generic.GetUltimate().detailsIf<GenericDetails>()}; 1763 if (!details) { 1764 return; 1765 } 1766 GenericKind kind{details->kind()}; 1767 if (!kind.IsAssignment() && !kind.IsOperator()) { 1768 return; 1769 } 1770 const SymbolVector &specifics{details->specificProcs()}; 1771 const std::vector<SourceName> &bindingNames{details->bindingNames()}; 1772 for (std::size_t i{0}; i < specifics.size(); ++i) { 1773 const Symbol &specific{*specifics[i]}; 1774 if (const Procedure * proc{Characterize(specific)}) { 1775 auto restorer{messages_.SetLocation(bindingNames[i])}; 1776 if (kind.IsAssignment()) { 1777 if (!CheckDefinedAssignment(specific, *proc)) { 1778 continue; 1779 } 1780 } else { 1781 if (!CheckDefinedOperator(generic.name(), kind, specific, *proc)) { 1782 continue; 1783 } 1784 } 1785 helper.Add(generic, kind, specific, *proc); 1786 } 1787 } 1788 }}; 1789 for (const auto &pair : scope) { 1790 const Symbol &symbol{*pair.second}; 1791 addSpecifics(symbol); 1792 const Symbol &ultimate{symbol.GetUltimate()}; 1793 if (ultimate.has<DerivedTypeDetails>()) { 1794 if (const Scope * typeScope{ultimate.scope()}) { 1795 for (const auto &pair2 : *typeScope) { 1796 addSpecifics(*pair2.second); 1797 } 1798 } 1799 } 1800 } 1801 helper.Check(scope); 1802 } 1803 1804 static const std::string *DefinesBindCName(const Symbol &symbol) { 1805 const auto *subp{symbol.detailsIf<SubprogramDetails>()}; 1806 if ((subp && !subp->isInterface()) || symbol.has<ObjectEntityDetails>()) { 1807 // Symbol defines data or entry point 1808 return symbol.GetBindName(); 1809 } else { 1810 return nullptr; 1811 } 1812 } 1813 1814 // Check that BIND(C) names are distinct 1815 void CheckHelper::CheckBindCName(const Symbol &symbol) { 1816 if (const std::string * name{DefinesBindCName(symbol)}) { 1817 auto pair{bindC_.emplace(*name, symbol)}; 1818 if (!pair.second) { 1819 const Symbol &other{*pair.first->second}; 1820 if (DefinesBindCName(other) && !context_.HasError(other)) { 1821 if (auto *msg{messages_.Say( 1822 "Two symbols have the same BIND(C) name '%s'"_err_en_US, 1823 *name)}) { 1824 msg->Attach(other.name(), "Conflicting symbol"_en_US); 1825 } 1826 context_.SetError(symbol); 1827 context_.SetError(other); 1828 } 1829 } 1830 } 1831 } 1832 1833 bool CheckHelper::CheckDioDummyIsData( 1834 const Symbol &subp, const Symbol *arg, std::size_t position) { 1835 if (arg && arg->detailsIf<ObjectEntityDetails>()) { 1836 return true; 1837 } else { 1838 if (arg) { 1839 messages_.Say(arg->name(), 1840 "Dummy argument '%s' must be a data object"_err_en_US, arg->name()); 1841 } else { 1842 messages_.Say(subp.name(), 1843 "Dummy argument %d of '%s' must be a data object"_err_en_US, position, 1844 subp.name()); 1845 } 1846 return false; 1847 } 1848 } 1849 1850 void CheckHelper::CheckAlreadySeenDefinedIo(const DerivedTypeSpec *derivedType, 1851 GenericKind::DefinedIo ioKind, const Symbol &proc) { 1852 for (TypeWithDefinedIo definedIoType : seenDefinedIoTypes_) { 1853 if (*derivedType == *definedIoType.type && ioKind == definedIoType.ioKind && 1854 proc != definedIoType.proc) { 1855 SayWithDeclaration(proc, definedIoType.proc.name(), 1856 "Derived type '%s' already has defined input/output procedure" 1857 " '%s'"_err_en_US, 1858 derivedType->name(), 1859 parser::ToUpperCaseLetters(GenericKind::EnumToString(ioKind))); 1860 return; 1861 } 1862 } 1863 seenDefinedIoTypes_.emplace_back( 1864 TypeWithDefinedIo{derivedType, ioKind, proc}); 1865 } 1866 1867 void CheckHelper::CheckDioDummyIsDerived( 1868 const Symbol &subp, const Symbol &arg, GenericKind::DefinedIo ioKind) { 1869 if (const DeclTypeSpec * type{arg.GetType()}) { 1870 if (const DerivedTypeSpec * derivedType{type->AsDerived()}) { 1871 CheckAlreadySeenDefinedIo(derivedType, ioKind, subp); 1872 bool isPolymorphic{type->IsPolymorphic()}; 1873 if (isPolymorphic != IsExtensibleType(derivedType)) { 1874 messages_.Say(arg.name(), 1875 "Dummy argument '%s' of a defined input/output procedure must be %s when the derived type is %s"_err_en_US, 1876 arg.name(), isPolymorphic ? "TYPE()" : "CLASS()", 1877 isPolymorphic ? "not extensible" : "extensible"); 1878 } 1879 } else { 1880 messages_.Say(arg.name(), 1881 "Dummy argument '%s' of a defined input/output procedure must have a" 1882 " derived type"_err_en_US, 1883 arg.name()); 1884 } 1885 } 1886 } 1887 1888 void CheckHelper::CheckDioDummyIsDefaultInteger( 1889 const Symbol &subp, const Symbol &arg) { 1890 if (const DeclTypeSpec * type{arg.GetType()}; 1891 type && type->IsNumeric(TypeCategory::Integer)) { 1892 if (const auto kind{evaluate::ToInt64(type->numericTypeSpec().kind())}; 1893 kind && *kind == context_.GetDefaultKind(TypeCategory::Integer)) { 1894 return; 1895 } 1896 } 1897 messages_.Say(arg.name(), 1898 "Dummy argument '%s' of a defined input/output procedure" 1899 " must be an INTEGER of default KIND"_err_en_US, 1900 arg.name()); 1901 } 1902 1903 void CheckHelper::CheckDioDummyIsScalar(const Symbol &subp, const Symbol &arg) { 1904 if (arg.Rank() > 0 || arg.Corank() > 0) { 1905 messages_.Say(arg.name(), 1906 "Dummy argument '%s' of a defined input/output procedure" 1907 " must be a scalar"_err_en_US, 1908 arg.name()); 1909 } 1910 } 1911 1912 void CheckHelper::CheckDioDtvArg( 1913 const Symbol &subp, const Symbol *arg, GenericKind::DefinedIo ioKind) { 1914 // Dtv argument looks like: dtv-type-spec, INTENT(INOUT) :: dtv 1915 if (CheckDioDummyIsData(subp, arg, 0)) { 1916 CheckDioDummyIsDerived(subp, *arg, ioKind); 1917 CheckDioDummyAttrs(subp, *arg, 1918 ioKind == GenericKind::DefinedIo::ReadFormatted || 1919 ioKind == GenericKind::DefinedIo::ReadUnformatted 1920 ? Attr::INTENT_INOUT 1921 : Attr::INTENT_IN); 1922 } 1923 } 1924 1925 void CheckHelper::CheckDefaultIntegerArg( 1926 const Symbol &subp, const Symbol *arg, Attr intent) { 1927 // Argument looks like: INTEGER, INTENT(intent) :: arg 1928 if (CheckDioDummyIsData(subp, arg, 1)) { 1929 CheckDioDummyIsDefaultInteger(subp, *arg); 1930 CheckDioDummyIsScalar(subp, *arg); 1931 CheckDioDummyAttrs(subp, *arg, intent); 1932 } 1933 } 1934 1935 void CheckHelper::CheckDioAssumedLenCharacterArg(const Symbol &subp, 1936 const Symbol *arg, std::size_t argPosition, Attr intent) { 1937 // Argument looks like: CHARACTER (LEN=*), INTENT(intent) :: (iotype OR iomsg) 1938 if (CheckDioDummyIsData(subp, arg, argPosition)) { 1939 CheckDioDummyAttrs(subp, *arg, intent); 1940 if (!IsAssumedLengthCharacter(*arg)) { 1941 messages_.Say(arg->name(), 1942 "Dummy argument '%s' of a defined input/output procedure" 1943 " must be assumed-length CHARACTER"_err_en_US, 1944 arg->name()); 1945 } 1946 } 1947 } 1948 1949 void CheckHelper::CheckDioVlistArg( 1950 const Symbol &subp, const Symbol *arg, std::size_t argPosition) { 1951 // Vlist argument looks like: INTEGER, INTENT(IN) :: v_list(:) 1952 if (CheckDioDummyIsData(subp, arg, argPosition)) { 1953 CheckDioDummyIsDefaultInteger(subp, *arg); 1954 CheckDioDummyAttrs(subp, *arg, Attr::INTENT_IN); 1955 if (const auto *objectDetails{arg->detailsIf<ObjectEntityDetails>()}) { 1956 if (objectDetails->shape().IsDeferredShape()) { 1957 return; 1958 } 1959 } 1960 messages_.Say(arg->name(), 1961 "Dummy argument '%s' of a defined input/output procedure must be" 1962 " deferred shape"_err_en_US, 1963 arg->name()); 1964 } 1965 } 1966 1967 void CheckHelper::CheckDioArgCount( 1968 const Symbol &subp, GenericKind::DefinedIo ioKind, std::size_t argCount) { 1969 const std::size_t requiredArgCount{ 1970 (std::size_t)(ioKind == GenericKind::DefinedIo::ReadFormatted || 1971 ioKind == GenericKind::DefinedIo::WriteFormatted 1972 ? 6 1973 : 4)}; 1974 if (argCount != requiredArgCount) { 1975 SayWithDeclaration(subp, 1976 "Defined input/output procedure '%s' must have" 1977 " %d dummy arguments rather than %d"_err_en_US, 1978 subp.name(), requiredArgCount, argCount); 1979 context_.SetError(subp); 1980 } 1981 } 1982 1983 void CheckHelper::CheckDioDummyAttrs( 1984 const Symbol &subp, const Symbol &arg, Attr goodIntent) { 1985 // Defined I/O procedures can't have attributes other than INTENT 1986 Attrs attrs{arg.attrs()}; 1987 if (!attrs.test(goodIntent)) { 1988 messages_.Say(arg.name(), 1989 "Dummy argument '%s' of a defined input/output procedure" 1990 " must have intent '%s'"_err_en_US, 1991 arg.name(), AttrToString(goodIntent)); 1992 } 1993 attrs = attrs - Attr::INTENT_IN - Attr::INTENT_OUT - Attr::INTENT_INOUT; 1994 if (!attrs.empty()) { 1995 messages_.Say(arg.name(), 1996 "Dummy argument '%s' of a defined input/output procedure may not have" 1997 " any attributes"_err_en_US, 1998 arg.name()); 1999 } 2000 } 2001 2002 // Enforce semantics for defined input/output procedures (12.6.4.8.2) and C777 2003 void CheckHelper::CheckDefinedIoProc(const Symbol &symbol, 2004 const GenericDetails &details, GenericKind::DefinedIo ioKind) { 2005 for (auto ref : details.specificProcs()) { 2006 const auto *binding{ref->detailsIf<ProcBindingDetails>()}; 2007 const Symbol &specific{*(binding ? &binding->symbol() : &*ref)}; 2008 if (ref->attrs().test(Attr::NOPASS)) { // C774 2009 messages_.Say("Defined input/output procedure '%s' may not have NOPASS " 2010 "attribute"_err_en_US, 2011 ref->name()); 2012 context_.SetError(*ref); 2013 } 2014 if (const auto *subpDetails{specific.detailsIf<SubprogramDetails>()}) { 2015 const std::vector<Symbol *> &dummyArgs{subpDetails->dummyArgs()}; 2016 CheckDioArgCount(specific, ioKind, dummyArgs.size()); 2017 int argCount{0}; 2018 for (auto *arg : dummyArgs) { 2019 switch (argCount++) { 2020 case 0: 2021 // dtv-type-spec, INTENT(INOUT) :: dtv 2022 CheckDioDtvArg(specific, arg, ioKind); 2023 break; 2024 case 1: 2025 // INTEGER, INTENT(IN) :: unit 2026 CheckDefaultIntegerArg(specific, arg, Attr::INTENT_IN); 2027 break; 2028 case 2: 2029 if (ioKind == GenericKind::DefinedIo::ReadFormatted || 2030 ioKind == GenericKind::DefinedIo::WriteFormatted) { 2031 // CHARACTER (LEN=*), INTENT(IN) :: iotype 2032 CheckDioAssumedLenCharacterArg( 2033 specific, arg, argCount, Attr::INTENT_IN); 2034 } else { 2035 // INTEGER, INTENT(OUT) :: iostat 2036 CheckDefaultIntegerArg(specific, arg, Attr::INTENT_OUT); 2037 } 2038 break; 2039 case 3: 2040 if (ioKind == GenericKind::DefinedIo::ReadFormatted || 2041 ioKind == GenericKind::DefinedIo::WriteFormatted) { 2042 // INTEGER, INTENT(IN) :: v_list(:) 2043 CheckDioVlistArg(specific, arg, argCount); 2044 } else { 2045 // CHARACTER (LEN=*), INTENT(INOUT) :: iomsg 2046 CheckDioAssumedLenCharacterArg( 2047 specific, arg, argCount, Attr::INTENT_INOUT); 2048 } 2049 break; 2050 case 4: 2051 // INTEGER, INTENT(OUT) :: iostat 2052 CheckDefaultIntegerArg(specific, arg, Attr::INTENT_OUT); 2053 break; 2054 case 5: 2055 // CHARACTER (LEN=*), INTENT(INOUT) :: iomsg 2056 CheckDioAssumedLenCharacterArg( 2057 specific, arg, argCount, Attr::INTENT_INOUT); 2058 break; 2059 default:; 2060 } 2061 } 2062 } 2063 } 2064 } 2065 2066 void SubprogramMatchHelper::Check( 2067 const Symbol &symbol1, const Symbol &symbol2) { 2068 const auto details1{symbol1.get<SubprogramDetails>()}; 2069 const auto details2{symbol2.get<SubprogramDetails>()}; 2070 if (details1.isFunction() != details2.isFunction()) { 2071 Say(symbol1, symbol2, 2072 details1.isFunction() 2073 ? "Module function '%s' was declared as a subroutine in the" 2074 " corresponding interface body"_err_en_US 2075 : "Module subroutine '%s' was declared as a function in the" 2076 " corresponding interface body"_err_en_US); 2077 return; 2078 } 2079 const auto &args1{details1.dummyArgs()}; 2080 const auto &args2{details2.dummyArgs()}; 2081 int nargs1{static_cast<int>(args1.size())}; 2082 int nargs2{static_cast<int>(args2.size())}; 2083 if (nargs1 != nargs2) { 2084 Say(symbol1, symbol2, 2085 "Module subprogram '%s' has %d args but the corresponding interface" 2086 " body has %d"_err_en_US, 2087 nargs1, nargs2); 2088 return; 2089 } 2090 bool nonRecursive1{symbol1.attrs().test(Attr::NON_RECURSIVE)}; 2091 if (nonRecursive1 != symbol2.attrs().test(Attr::NON_RECURSIVE)) { // C1551 2092 Say(symbol1, symbol2, 2093 nonRecursive1 2094 ? "Module subprogram '%s' has NON_RECURSIVE prefix but" 2095 " the corresponding interface body does not"_err_en_US 2096 : "Module subprogram '%s' does not have NON_RECURSIVE prefix but " 2097 "the corresponding interface body does"_err_en_US); 2098 } 2099 const std::string *bindName1{details1.bindName()}; 2100 const std::string *bindName2{details2.bindName()}; 2101 if (!bindName1 && !bindName2) { 2102 // OK - neither has a binding label 2103 } else if (!bindName1) { 2104 Say(symbol1, symbol2, 2105 "Module subprogram '%s' does not have a binding label but the" 2106 " corresponding interface body does"_err_en_US); 2107 } else if (!bindName2) { 2108 Say(symbol1, symbol2, 2109 "Module subprogram '%s' has a binding label but the" 2110 " corresponding interface body does not"_err_en_US); 2111 } else if (*bindName1 != *bindName2) { 2112 Say(symbol1, symbol2, 2113 "Module subprogram '%s' has binding label '%s' but the corresponding" 2114 " interface body has '%s'"_err_en_US, 2115 *details1.bindName(), *details2.bindName()); 2116 } 2117 const Procedure *proc1{checkHelper.Characterize(symbol1)}; 2118 const Procedure *proc2{checkHelper.Characterize(symbol2)}; 2119 if (!proc1 || !proc2) { 2120 return; 2121 } 2122 if (proc1->functionResult && proc2->functionResult && 2123 *proc1->functionResult != *proc2->functionResult) { 2124 Say(symbol1, symbol2, 2125 "Return type of function '%s' does not match return type of" 2126 " the corresponding interface body"_err_en_US); 2127 } 2128 for (int i{0}; i < nargs1; ++i) { 2129 const Symbol *arg1{args1[i]}; 2130 const Symbol *arg2{args2[i]}; 2131 if (arg1 && !arg2) { 2132 Say(symbol1, symbol2, 2133 "Dummy argument %2$d of '%1$s' is not an alternate return indicator" 2134 " but the corresponding argument in the interface body is"_err_en_US, 2135 i + 1); 2136 } else if (!arg1 && arg2) { 2137 Say(symbol1, symbol2, 2138 "Dummy argument %2$d of '%1$s' is an alternate return indicator but" 2139 " the corresponding argument in the interface body is not"_err_en_US, 2140 i + 1); 2141 } else if (arg1 && arg2) { 2142 SourceName name1{arg1->name()}; 2143 SourceName name2{arg2->name()}; 2144 if (name1 != name2) { 2145 Say(*arg1, *arg2, 2146 "Dummy argument name '%s' does not match corresponding name '%s'" 2147 " in interface body"_err_en_US, 2148 name2); 2149 } else { 2150 CheckDummyArg( 2151 *arg1, *arg2, proc1->dummyArguments[i], proc2->dummyArguments[i]); 2152 } 2153 } 2154 } 2155 } 2156 2157 void SubprogramMatchHelper::CheckDummyArg(const Symbol &symbol1, 2158 const Symbol &symbol2, const DummyArgument &arg1, 2159 const DummyArgument &arg2) { 2160 std::visit(common::visitors{ 2161 [&](const DummyDataObject &obj1, const DummyDataObject &obj2) { 2162 CheckDummyDataObject(symbol1, symbol2, obj1, obj2); 2163 }, 2164 [&](const DummyProcedure &proc1, const DummyProcedure &proc2) { 2165 CheckDummyProcedure(symbol1, symbol2, proc1, proc2); 2166 }, 2167 [&](const DummyDataObject &, const auto &) { 2168 Say(symbol1, symbol2, 2169 "Dummy argument '%s' is a data object; the corresponding" 2170 " argument in the interface body is not"_err_en_US); 2171 }, 2172 [&](const DummyProcedure &, const auto &) { 2173 Say(symbol1, symbol2, 2174 "Dummy argument '%s' is a procedure; the corresponding" 2175 " argument in the interface body is not"_err_en_US); 2176 }, 2177 [&](const auto &, const auto &) { 2178 llvm_unreachable("Dummy arguments are not data objects or" 2179 "procedures"); 2180 }, 2181 }, 2182 arg1.u, arg2.u); 2183 } 2184 2185 void SubprogramMatchHelper::CheckDummyDataObject(const Symbol &symbol1, 2186 const Symbol &symbol2, const DummyDataObject &obj1, 2187 const DummyDataObject &obj2) { 2188 if (!CheckSameIntent(symbol1, symbol2, obj1.intent, obj2.intent)) { 2189 } else if (!CheckSameAttrs(symbol1, symbol2, obj1.attrs, obj2.attrs)) { 2190 } else if (obj1.type.type() != obj2.type.type()) { 2191 Say(symbol1, symbol2, 2192 "Dummy argument '%s' has type %s; the corresponding argument in the" 2193 " interface body has type %s"_err_en_US, 2194 obj1.type.type().AsFortran(), obj2.type.type().AsFortran()); 2195 } else if (!ShapesAreCompatible(obj1, obj2)) { 2196 Say(symbol1, symbol2, 2197 "The shape of dummy argument '%s' does not match the shape of the" 2198 " corresponding argument in the interface body"_err_en_US); 2199 } 2200 // TODO: coshape 2201 } 2202 2203 void SubprogramMatchHelper::CheckDummyProcedure(const Symbol &symbol1, 2204 const Symbol &symbol2, const DummyProcedure &proc1, 2205 const DummyProcedure &proc2) { 2206 if (!CheckSameIntent(symbol1, symbol2, proc1.intent, proc2.intent)) { 2207 } else if (!CheckSameAttrs(symbol1, symbol2, proc1.attrs, proc2.attrs)) { 2208 } else if (proc1 != proc2) { 2209 Say(symbol1, symbol2, 2210 "Dummy procedure '%s' does not match the corresponding argument in" 2211 " the interface body"_err_en_US); 2212 } 2213 } 2214 2215 bool SubprogramMatchHelper::CheckSameIntent(const Symbol &symbol1, 2216 const Symbol &symbol2, common::Intent intent1, common::Intent intent2) { 2217 if (intent1 == intent2) { 2218 return true; 2219 } else { 2220 Say(symbol1, symbol2, 2221 "The intent of dummy argument '%s' does not match the intent" 2222 " of the corresponding argument in the interface body"_err_en_US); 2223 return false; 2224 } 2225 } 2226 2227 // Report an error referring to first symbol with declaration of second symbol 2228 template <typename... A> 2229 void SubprogramMatchHelper::Say(const Symbol &symbol1, const Symbol &symbol2, 2230 parser::MessageFixedText &&text, A &&...args) { 2231 auto &message{context().Say(symbol1.name(), std::move(text), symbol1.name(), 2232 std::forward<A>(args)...)}; 2233 evaluate::AttachDeclaration(message, symbol2); 2234 } 2235 2236 template <typename ATTRS> 2237 bool SubprogramMatchHelper::CheckSameAttrs( 2238 const Symbol &symbol1, const Symbol &symbol2, ATTRS attrs1, ATTRS attrs2) { 2239 if (attrs1 == attrs2) { 2240 return true; 2241 } 2242 attrs1.IterateOverMembers([&](auto attr) { 2243 if (!attrs2.test(attr)) { 2244 Say(symbol1, symbol2, 2245 "Dummy argument '%s' has the %s attribute; the corresponding" 2246 " argument in the interface body does not"_err_en_US, 2247 AsFortran(attr)); 2248 } 2249 }); 2250 attrs2.IterateOverMembers([&](auto attr) { 2251 if (!attrs1.test(attr)) { 2252 Say(symbol1, symbol2, 2253 "Dummy argument '%s' does not have the %s attribute; the" 2254 " corresponding argument in the interface body does"_err_en_US, 2255 AsFortran(attr)); 2256 } 2257 }); 2258 return false; 2259 } 2260 2261 bool SubprogramMatchHelper::ShapesAreCompatible( 2262 const DummyDataObject &obj1, const DummyDataObject &obj2) { 2263 return characteristics::ShapesAreCompatible( 2264 FoldShape(obj1.type.shape()), FoldShape(obj2.type.shape())); 2265 } 2266 2267 evaluate::Shape SubprogramMatchHelper::FoldShape(const evaluate::Shape &shape) { 2268 evaluate::Shape result; 2269 for (const auto &extent : shape) { 2270 result.emplace_back( 2271 evaluate::Fold(context().foldingContext(), common::Clone(extent))); 2272 } 2273 return result; 2274 } 2275 2276 void DistinguishabilityHelper::Add(const Symbol &generic, GenericKind kind, 2277 const Symbol &specific, const Procedure &procedure) { 2278 if (!context_.HasError(specific)) { 2279 nameToInfo_[generic.name()].emplace_back( 2280 ProcedureInfo{kind, specific, procedure}); 2281 } 2282 } 2283 2284 void DistinguishabilityHelper::Check(const Scope &scope) { 2285 for (const auto &[name, info] : nameToInfo_) { 2286 auto count{info.size()}; 2287 for (std::size_t i1{0}; i1 < count - 1; ++i1) { 2288 const auto &[kind, symbol, proc]{info[i1]}; 2289 for (std::size_t i2{i1 + 1}; i2 < count; ++i2) { 2290 auto distinguishable{kind.IsName() 2291 ? evaluate::characteristics::Distinguishable 2292 : evaluate::characteristics::DistinguishableOpOrAssign}; 2293 if (!distinguishable(proc, info[i2].procedure)) { 2294 SayNotDistinguishable(GetTopLevelUnitContaining(scope), name, kind, 2295 symbol, info[i2].symbol); 2296 } 2297 } 2298 } 2299 } 2300 } 2301 2302 void DistinguishabilityHelper::SayNotDistinguishable(const Scope &scope, 2303 const SourceName &name, GenericKind kind, const Symbol &proc1, 2304 const Symbol &proc2) { 2305 std::string name1{proc1.name().ToString()}; 2306 std::string name2{proc2.name().ToString()}; 2307 if (kind.IsOperator() || kind.IsAssignment()) { 2308 // proc1 and proc2 may come from different scopes so qualify their names 2309 if (proc1.owner().IsDerivedType()) { 2310 name1 = proc1.owner().GetName()->ToString() + '%' + name1; 2311 } 2312 if (proc2.owner().IsDerivedType()) { 2313 name2 = proc2.owner().GetName()->ToString() + '%' + name2; 2314 } 2315 } 2316 parser::Message *msg; 2317 if (scope.sourceRange().Contains(name)) { 2318 msg = &context_.Say(name, 2319 "Generic '%s' may not have specific procedures '%s' and '%s' as their interfaces are not distinguishable"_err_en_US, 2320 MakeOpName(name), name1, name2); 2321 } else { 2322 msg = &context_.Say(*GetTopLevelUnitContaining(proc1).GetName(), 2323 "USE-associated generic '%s' may not have specific procedures '%s' and '%s' as their interfaces are not distinguishable"_err_en_US, 2324 MakeOpName(name), name1, name2); 2325 } 2326 AttachDeclaration(*msg, scope, proc1); 2327 AttachDeclaration(*msg, scope, proc2); 2328 } 2329 2330 // `evaluate::AttachDeclaration` doesn't handle the generic case where `proc` 2331 // comes from a different module but is not necessarily use-associated. 2332 void DistinguishabilityHelper::AttachDeclaration( 2333 parser::Message &msg, const Scope &scope, const Symbol &proc) { 2334 const Scope &unit{GetTopLevelUnitContaining(proc)}; 2335 if (unit == scope) { 2336 evaluate::AttachDeclaration(msg, proc); 2337 } else { 2338 msg.Attach(unit.GetName().value(), 2339 "'%s' is USE-associated from module '%s'"_en_US, proc.name(), 2340 unit.GetName().value()); 2341 } 2342 } 2343 2344 void CheckDeclarations(SemanticsContext &context) { 2345 CheckHelper{context}.Check(); 2346 } 2347 } // namespace Fortran::semantics 2348