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 (const auto intrinsic{ 628 context_.intrinsics().IsSpecificIntrinsicFunction( 629 ultimate.name().ToString())}; 630 !intrinsic || intrinsic->isRestrictedSpecific) { // C1030 631 context_.Say( 632 "Intrinsic procedure '%s' is not an unrestricted specific " 633 "intrinsic permitted for use as the initializer for procedure " 634 "pointer '%s'"_err_en_US, 635 ultimate.name(), symbol.name()); 636 } 637 } else if (!ultimate.attrs().test(Attr::EXTERNAL) && 638 ultimate.owner().kind() != Scope::Kind::Module) { 639 context_.Say("Procedure pointer '%s' initializer '%s' is neither " 640 "an external nor a module procedure"_err_en_US, 641 symbol.name(), ultimate.name()); 642 } else if (ultimate.attrs().test(Attr::ELEMENTAL)) { 643 context_.Say("Procedure pointer '%s' cannot be initialized with the " 644 "elemental procedure '%s"_err_en_US, 645 symbol.name(), ultimate.name()); 646 } else { 647 // TODO: Check the "shalls" in the 15.4.3.6 paragraphs 7-10. 648 } 649 } 650 } 651 } 652 } 653 654 // The six different kinds of array-specs: 655 // array-spec -> explicit-shape-list | deferred-shape-list 656 // | assumed-shape-list | implied-shape-list 657 // | assumed-size | assumed-rank 658 // explicit-shape -> [ lb : ] ub 659 // deferred-shape -> : 660 // assumed-shape -> [ lb ] : 661 // implied-shape -> [ lb : ] * 662 // assumed-size -> [ explicit-shape-list , ] [ lb : ] * 663 // assumed-rank -> .. 664 // Note: 665 // - deferred-shape is also an assumed-shape 666 // - A single "*" or "lb:*" might be assumed-size or implied-shape-list 667 void CheckHelper::CheckArraySpec( 668 const Symbol &symbol, const ArraySpec &arraySpec) { 669 if (arraySpec.Rank() == 0) { 670 return; 671 } 672 bool isExplicit{arraySpec.IsExplicitShape()}; 673 bool isDeferred{arraySpec.IsDeferredShape()}; 674 bool isImplied{arraySpec.IsImpliedShape()}; 675 bool isAssumedShape{arraySpec.IsAssumedShape()}; 676 bool isAssumedSize{arraySpec.IsAssumedSize()}; 677 bool isAssumedRank{arraySpec.IsAssumedRank()}; 678 std::optional<parser::MessageFixedText> msg; 679 if (symbol.test(Symbol::Flag::CrayPointee) && !isExplicit && !isAssumedSize) { 680 msg = "Cray pointee '%s' must have must have explicit shape or" 681 " assumed size"_err_en_US; 682 } else if (IsAllocatableOrPointer(symbol) && !isDeferred && !isAssumedRank) { 683 if (symbol.owner().IsDerivedType()) { // C745 684 if (IsAllocatable(symbol)) { 685 msg = "Allocatable array component '%s' must have" 686 " deferred shape"_err_en_US; 687 } else { 688 msg = "Array pointer component '%s' must have deferred shape"_err_en_US; 689 } 690 } else { 691 if (IsAllocatable(symbol)) { // C832 692 msg = "Allocatable array '%s' must have deferred shape or" 693 " assumed rank"_err_en_US; 694 } else { 695 msg = "Array pointer '%s' must have deferred shape or" 696 " assumed rank"_err_en_US; 697 } 698 } 699 } else if (IsDummy(symbol)) { 700 if (isImplied && !isAssumedSize) { // C836 701 msg = "Dummy array argument '%s' may not have implied shape"_err_en_US; 702 } 703 } else if (isAssumedShape && !isDeferred) { 704 msg = "Assumed-shape array '%s' must be a dummy argument"_err_en_US; 705 } else if (isAssumedSize && !isImplied) { // C833 706 msg = "Assumed-size array '%s' must be a dummy argument"_err_en_US; 707 } else if (isAssumedRank) { // C837 708 msg = "Assumed-rank array '%s' must be a dummy argument"_err_en_US; 709 } else if (isImplied) { 710 if (!IsNamedConstant(symbol)) { // C835, C836 711 msg = "Implied-shape array '%s' must be a named constant or a " 712 "dummy argument"_err_en_US; 713 } 714 } else if (IsNamedConstant(symbol)) { 715 if (!isExplicit && !isImplied) { 716 msg = "Named constant '%s' array must have constant or" 717 " implied shape"_err_en_US; 718 } 719 } else if (!IsAllocatableOrPointer(symbol) && !isExplicit) { 720 if (symbol.owner().IsDerivedType()) { // C749 721 msg = "Component array '%s' without ALLOCATABLE or POINTER attribute must" 722 " have explicit shape"_err_en_US; 723 } else { // C816 724 msg = "Array '%s' without ALLOCATABLE or POINTER attribute must have" 725 " explicit shape"_err_en_US; 726 } 727 } 728 if (msg) { 729 context_.Say(std::move(*msg), symbol.name()); 730 } 731 } 732 733 void CheckHelper::CheckProcEntity( 734 const Symbol &symbol, const ProcEntityDetails &details) { 735 if (details.isDummy()) { 736 if (!symbol.attrs().test(Attr::POINTER) && // C843 737 (symbol.attrs().test(Attr::INTENT_IN) || 738 symbol.attrs().test(Attr::INTENT_OUT) || 739 symbol.attrs().test(Attr::INTENT_INOUT))) { 740 messages_.Say("A dummy procedure without the POINTER attribute" 741 " may not have an INTENT attribute"_err_en_US); 742 } 743 if (InElemental()) { // C15100 744 messages_.Say( 745 "An ELEMENTAL subprogram may not have a dummy procedure"_err_en_US); 746 } 747 const Symbol *interface { details.interface().symbol() }; 748 if (!symbol.attrs().test(Attr::INTRINSIC) && 749 (symbol.attrs().test(Attr::ELEMENTAL) || 750 (interface && !interface->attrs().test(Attr::INTRINSIC) && 751 interface->attrs().test(Attr::ELEMENTAL)))) { 752 // There's no explicit constraint or "shall" that we can find in the 753 // standard for this check, but it seems to be implied in multiple 754 // sites, and ELEMENTAL non-intrinsic actual arguments *are* 755 // explicitly forbidden. But we allow "PROCEDURE(SIN)::dummy" 756 // because it is explicitly legal to *pass* the specific intrinsic 757 // function SIN as an actual argument. 758 messages_.Say("A dummy procedure may not be ELEMENTAL"_err_en_US); 759 } 760 } else if (symbol.attrs().test(Attr::INTENT_IN) || 761 symbol.attrs().test(Attr::INTENT_OUT) || 762 symbol.attrs().test(Attr::INTENT_INOUT)) { 763 messages_.Say("INTENT attributes may apply only to a dummy " 764 "argument"_err_en_US); // C843 765 } else if (IsOptional(symbol)) { 766 messages_.Say("OPTIONAL attribute may apply only to a dummy " 767 "argument"_err_en_US); // C849 768 } else if (symbol.owner().IsDerivedType()) { 769 if (!symbol.attrs().test(Attr::POINTER)) { // C756 770 const auto &name{symbol.name()}; 771 messages_.Say(name, 772 "Procedure component '%s' must have POINTER attribute"_err_en_US, 773 name); 774 } 775 CheckPassArg(symbol, details.interface().symbol(), details); 776 } 777 if (symbol.attrs().test(Attr::POINTER)) { 778 CheckPointerInitialization(symbol); 779 if (const Symbol * interface{details.interface().symbol()}) { 780 if (interface->attrs().test(Attr::INTRINSIC)) { 781 if (const auto intrinsic{ 782 context_.intrinsics().IsSpecificIntrinsicFunction( 783 interface->name().ToString())}; 784 !intrinsic || intrinsic->isRestrictedSpecific) { // C1515 785 messages_.Say( 786 "Intrinsic procedure '%s' is not an unrestricted specific " 787 "intrinsic permitted for use as the definition of the interface " 788 "to procedure pointer '%s'"_err_en_US, 789 interface->name(), symbol.name()); 790 } 791 } else if (interface->attrs().test(Attr::ELEMENTAL)) { 792 messages_.Say("Procedure pointer '%s' may not be ELEMENTAL"_err_en_US, 793 symbol.name()); // C1517 794 } 795 } 796 } else if (symbol.attrs().test(Attr::SAVE)) { 797 messages_.Say( 798 "Procedure '%s' with SAVE attribute must also have POINTER attribute"_err_en_US, 799 symbol.name()); 800 } 801 } 802 803 // When a module subprogram has the MODULE prefix the following must match 804 // with the corresponding separate module procedure interface body: 805 // - C1549: characteristics and dummy argument names 806 // - C1550: binding label 807 // - C1551: NON_RECURSIVE prefix 808 class SubprogramMatchHelper { 809 public: 810 explicit SubprogramMatchHelper(CheckHelper &checkHelper) 811 : checkHelper{checkHelper} {} 812 813 void Check(const Symbol &, const Symbol &); 814 815 private: 816 SemanticsContext &context() { return checkHelper.context(); } 817 void CheckDummyArg(const Symbol &, const Symbol &, const DummyArgument &, 818 const DummyArgument &); 819 void CheckDummyDataObject(const Symbol &, const Symbol &, 820 const DummyDataObject &, const DummyDataObject &); 821 void CheckDummyProcedure(const Symbol &, const Symbol &, 822 const DummyProcedure &, const DummyProcedure &); 823 bool CheckSameIntent( 824 const Symbol &, const Symbol &, common::Intent, common::Intent); 825 template <typename... A> 826 void Say( 827 const Symbol &, const Symbol &, parser::MessageFixedText &&, A &&...); 828 template <typename ATTRS> 829 bool CheckSameAttrs(const Symbol &, const Symbol &, ATTRS, ATTRS); 830 bool ShapesAreCompatible(const DummyDataObject &, const DummyDataObject &); 831 evaluate::Shape FoldShape(const evaluate::Shape &); 832 std::string AsFortran(DummyDataObject::Attr attr) { 833 return parser::ToUpperCaseLetters(DummyDataObject::EnumToString(attr)); 834 } 835 std::string AsFortran(DummyProcedure::Attr attr) { 836 return parser::ToUpperCaseLetters(DummyProcedure::EnumToString(attr)); 837 } 838 839 CheckHelper &checkHelper; 840 }; 841 842 // 15.6.2.6 para 3 - can the result of an ENTRY differ from its function? 843 bool CheckHelper::IsResultOkToDiffer(const FunctionResult &result) { 844 if (result.attrs.test(FunctionResult::Attr::Allocatable) || 845 result.attrs.test(FunctionResult::Attr::Pointer)) { 846 return false; 847 } 848 const auto *typeAndShape{result.GetTypeAndShape()}; 849 if (!typeAndShape || typeAndShape->Rank() != 0) { 850 return false; 851 } 852 auto category{typeAndShape->type().category()}; 853 if (category == TypeCategory::Character || 854 category == TypeCategory::Derived) { 855 return false; 856 } 857 int kind{typeAndShape->type().kind()}; 858 return kind == context_.GetDefaultKind(category) || 859 (category == TypeCategory::Real && 860 kind == context_.doublePrecisionKind()); 861 } 862 863 void CheckHelper::CheckSubprogram( 864 const Symbol &symbol, const SubprogramDetails &details) { 865 if (const Symbol * iface{FindSeparateModuleSubprogramInterface(&symbol)}) { 866 SubprogramMatchHelper{*this}.Check(symbol, *iface); 867 } 868 if (const Scope * entryScope{details.entryScope()}) { 869 // ENTRY 15.6.2.6, esp. C1571 870 std::optional<parser::MessageFixedText> error; 871 const Symbol *subprogram{entryScope->symbol()}; 872 const SubprogramDetails *subprogramDetails{nullptr}; 873 if (subprogram) { 874 subprogramDetails = subprogram->detailsIf<SubprogramDetails>(); 875 } 876 if (entryScope->kind() != Scope::Kind::Subprogram) { 877 error = "ENTRY may appear only in a subroutine or function"_err_en_US; 878 } else if (!(entryScope->parent().IsGlobal() || 879 entryScope->parent().IsModule() || 880 entryScope->parent().IsSubmodule())) { 881 error = "ENTRY may not appear in an internal subprogram"_err_en_US; 882 } else if (FindSeparateModuleSubprogramInterface(subprogram)) { 883 error = "ENTRY may not appear in a separate module procedure"_err_en_US; 884 } else if (subprogramDetails && details.isFunction() && 885 subprogramDetails->isFunction() && 886 !context_.HasError(details.result()) && 887 !context_.HasError(subprogramDetails->result())) { 888 auto result{FunctionResult::Characterize( 889 details.result(), context_.foldingContext())}; 890 auto subpResult{FunctionResult::Characterize( 891 subprogramDetails->result(), context_.foldingContext())}; 892 if (result && subpResult && *result != *subpResult && 893 (!IsResultOkToDiffer(*result) || !IsResultOkToDiffer(*subpResult))) { 894 error = 895 "Result of ENTRY is not compatible with result of containing function"_err_en_US; 896 } 897 } 898 if (error) { 899 if (auto *msg{messages_.Say(symbol.name(), *error)}) { 900 if (subprogram) { 901 msg->Attach(subprogram->name(), "Containing subprogram"_en_US); 902 } 903 } 904 } 905 } 906 if (symbol.attrs().test(Attr::ELEMENTAL)) { 907 // See comment on the similar check in CheckProcEntity() 908 if (details.isDummy()) { 909 messages_.Say("A dummy procedure may not be ELEMENTAL"_err_en_US); 910 } else { 911 for (const Symbol *dummy : details.dummyArgs()) { 912 if (!dummy) { // C15100 913 messages_.Say( 914 "An ELEMENTAL subroutine may not have an alternate return dummy argument"_err_en_US); 915 } 916 } 917 } 918 } 919 } 920 921 void CheckHelper::CheckDerivedType( 922 const Symbol &derivedType, const DerivedTypeDetails &details) { 923 if (details.isForwardReferenced() && !context_.HasError(derivedType)) { 924 messages_.Say("The derived type '%s' has not been defined"_err_en_US, 925 derivedType.name()); 926 } 927 const Scope *scope{derivedType.scope()}; 928 if (!scope) { 929 CHECK(details.isForwardReferenced()); 930 return; 931 } 932 CHECK(scope->symbol() == &derivedType); 933 CHECK(scope->IsDerivedType()); 934 if (derivedType.attrs().test(Attr::ABSTRACT) && // C734 935 (derivedType.attrs().test(Attr::BIND_C) || details.sequence())) { 936 messages_.Say("An ABSTRACT derived type must be extensible"_err_en_US); 937 } 938 if (const DeclTypeSpec * parent{FindParentTypeSpec(derivedType)}) { 939 const DerivedTypeSpec *parentDerived{parent->AsDerived()}; 940 if (!IsExtensibleType(parentDerived)) { // C705 941 messages_.Say("The parent type is not extensible"_err_en_US); 942 } 943 if (!derivedType.attrs().test(Attr::ABSTRACT) && parentDerived && 944 parentDerived->typeSymbol().attrs().test(Attr::ABSTRACT)) { 945 ScopeComponentIterator components{*parentDerived}; 946 for (const Symbol &component : components) { 947 if (component.attrs().test(Attr::DEFERRED)) { 948 if (scope->FindComponent(component.name()) == &component) { 949 SayWithDeclaration(component, 950 "Non-ABSTRACT extension of ABSTRACT derived type '%s' lacks a binding for DEFERRED procedure '%s'"_err_en_US, 951 parentDerived->typeSymbol().name(), component.name()); 952 } 953 } 954 } 955 } 956 DerivedTypeSpec derived{derivedType.name(), derivedType}; 957 derived.set_scope(*scope); 958 if (FindCoarrayUltimateComponent(derived) && // C736 959 !(parentDerived && FindCoarrayUltimateComponent(*parentDerived))) { 960 messages_.Say( 961 "Type '%s' has a coarray ultimate component so the type at the base " 962 "of its type extension chain ('%s') must be a type that has a " 963 "coarray ultimate component"_err_en_US, 964 derivedType.name(), scope->GetDerivedTypeBase().GetSymbol()->name()); 965 } 966 if (FindEventOrLockPotentialComponent(derived) && // C737 967 !(FindEventOrLockPotentialComponent(*parentDerived) || 968 IsEventTypeOrLockType(parentDerived))) { 969 messages_.Say( 970 "Type '%s' has an EVENT_TYPE or LOCK_TYPE component, so the type " 971 "at the base of its type extension chain ('%s') must either have an " 972 "EVENT_TYPE or LOCK_TYPE component, or be EVENT_TYPE or " 973 "LOCK_TYPE"_err_en_US, 974 derivedType.name(), scope->GetDerivedTypeBase().GetSymbol()->name()); 975 } 976 } 977 if (HasIntrinsicTypeName(derivedType)) { // C729 978 messages_.Say("A derived type name cannot be the name of an intrinsic" 979 " type"_err_en_US); 980 } 981 std::map<SourceName, SymbolRef> previous; 982 for (const auto &pair : details.finals()) { 983 SourceName source{pair.first}; 984 const Symbol &ref{*pair.second}; 985 if (CheckFinal(ref, source, derivedType) && 986 std::all_of(previous.begin(), previous.end(), 987 [&](std::pair<SourceName, SymbolRef> prev) { 988 return CheckDistinguishableFinals( 989 ref, source, *prev.second, prev.first, derivedType); 990 })) { 991 previous.emplace(source, ref); 992 } 993 } 994 } 995 996 // C786 997 bool CheckHelper::CheckFinal( 998 const Symbol &subroutine, SourceName finalName, const Symbol &derivedType) { 999 if (!IsModuleProcedure(subroutine)) { 1000 SayWithDeclaration(subroutine, finalName, 1001 "FINAL subroutine '%s' of derived type '%s' must be a module procedure"_err_en_US, 1002 subroutine.name(), derivedType.name()); 1003 return false; 1004 } 1005 const Procedure *proc{Characterize(subroutine)}; 1006 if (!proc) { 1007 return false; // error recovery 1008 } 1009 if (!proc->IsSubroutine()) { 1010 SayWithDeclaration(subroutine, finalName, 1011 "FINAL subroutine '%s' of derived type '%s' must be a subroutine"_err_en_US, 1012 subroutine.name(), derivedType.name()); 1013 return false; 1014 } 1015 if (proc->dummyArguments.size() != 1) { 1016 SayWithDeclaration(subroutine, finalName, 1017 "FINAL subroutine '%s' of derived type '%s' must have a single dummy argument"_err_en_US, 1018 subroutine.name(), derivedType.name()); 1019 return false; 1020 } 1021 const auto &arg{proc->dummyArguments[0]}; 1022 const Symbol *errSym{&subroutine}; 1023 if (const auto *details{subroutine.detailsIf<SubprogramDetails>()}) { 1024 if (!details->dummyArgs().empty()) { 1025 if (const Symbol * argSym{details->dummyArgs()[0]}) { 1026 errSym = argSym; 1027 } 1028 } 1029 } 1030 const auto *ddo{std::get_if<DummyDataObject>(&arg.u)}; 1031 if (!ddo) { 1032 SayWithDeclaration(subroutine, finalName, 1033 "FINAL subroutine '%s' of derived type '%s' must have a single dummy argument that is a data object"_err_en_US, 1034 subroutine.name(), derivedType.name()); 1035 return false; 1036 } 1037 bool ok{true}; 1038 if (arg.IsOptional()) { 1039 SayWithDeclaration(*errSym, finalName, 1040 "FINAL subroutine '%s' of derived type '%s' must not have an OPTIONAL dummy argument"_err_en_US, 1041 subroutine.name(), derivedType.name()); 1042 ok = false; 1043 } 1044 if (ddo->attrs.test(DummyDataObject::Attr::Allocatable)) { 1045 SayWithDeclaration(*errSym, finalName, 1046 "FINAL subroutine '%s' of derived type '%s' must not have an ALLOCATABLE dummy argument"_err_en_US, 1047 subroutine.name(), derivedType.name()); 1048 ok = false; 1049 } 1050 if (ddo->attrs.test(DummyDataObject::Attr::Pointer)) { 1051 SayWithDeclaration(*errSym, finalName, 1052 "FINAL subroutine '%s' of derived type '%s' must not have a POINTER dummy argument"_err_en_US, 1053 subroutine.name(), derivedType.name()); 1054 ok = false; 1055 } 1056 if (ddo->intent == common::Intent::Out) { 1057 SayWithDeclaration(*errSym, finalName, 1058 "FINAL subroutine '%s' of derived type '%s' must not have a dummy argument with INTENT(OUT)"_err_en_US, 1059 subroutine.name(), derivedType.name()); 1060 ok = false; 1061 } 1062 if (ddo->attrs.test(DummyDataObject::Attr::Value)) { 1063 SayWithDeclaration(*errSym, finalName, 1064 "FINAL subroutine '%s' of derived type '%s' must not have a dummy argument with the VALUE attribute"_err_en_US, 1065 subroutine.name(), derivedType.name()); 1066 ok = false; 1067 } 1068 if (ddo->type.corank() > 0) { 1069 SayWithDeclaration(*errSym, finalName, 1070 "FINAL subroutine '%s' of derived type '%s' must not have a coarray dummy argument"_err_en_US, 1071 subroutine.name(), derivedType.name()); 1072 ok = false; 1073 } 1074 if (ddo->type.type().IsPolymorphic()) { 1075 SayWithDeclaration(*errSym, finalName, 1076 "FINAL subroutine '%s' of derived type '%s' must not have a polymorphic dummy argument"_err_en_US, 1077 subroutine.name(), derivedType.name()); 1078 ok = false; 1079 } else if (ddo->type.type().category() != TypeCategory::Derived || 1080 &ddo->type.type().GetDerivedTypeSpec().typeSymbol() != &derivedType) { 1081 SayWithDeclaration(*errSym, finalName, 1082 "FINAL subroutine '%s' of derived type '%s' must have a TYPE(%s) dummy argument"_err_en_US, 1083 subroutine.name(), derivedType.name(), derivedType.name()); 1084 ok = false; 1085 } else { // check that all LEN type parameters are assumed 1086 for (auto ref : OrderParameterDeclarations(derivedType)) { 1087 if (IsLenTypeParameter(*ref)) { 1088 const auto *value{ 1089 ddo->type.type().GetDerivedTypeSpec().FindParameter(ref->name())}; 1090 if (!value || !value->isAssumed()) { 1091 SayWithDeclaration(*errSym, finalName, 1092 "FINAL subroutine '%s' of derived type '%s' must have a dummy argument with an assumed LEN type parameter '%s=*'"_err_en_US, 1093 subroutine.name(), derivedType.name(), ref->name()); 1094 ok = false; 1095 } 1096 } 1097 } 1098 } 1099 return ok; 1100 } 1101 1102 bool CheckHelper::CheckDistinguishableFinals(const Symbol &f1, 1103 SourceName f1Name, const Symbol &f2, SourceName f2Name, 1104 const Symbol &derivedType) { 1105 const Procedure *p1{Characterize(f1)}; 1106 const Procedure *p2{Characterize(f2)}; 1107 if (p1 && p2) { 1108 if (characteristics::Distinguishable( 1109 context_.languageFeatures(), *p1, *p2)) { 1110 return true; 1111 } 1112 if (auto *msg{messages_.Say(f1Name, 1113 "FINAL subroutines '%s' and '%s' of derived type '%s' cannot be distinguished by rank or KIND type parameter value"_err_en_US, 1114 f1Name, f2Name, derivedType.name())}) { 1115 msg->Attach(f2Name, "FINAL declaration of '%s'"_en_US, f2.name()) 1116 .Attach(f1.name(), "Definition of '%s'"_en_US, f1Name) 1117 .Attach(f2.name(), "Definition of '%s'"_en_US, f2Name); 1118 } 1119 } 1120 return false; 1121 } 1122 1123 void CheckHelper::CheckHostAssoc( 1124 const Symbol &symbol, const HostAssocDetails &details) { 1125 const Symbol &hostSymbol{details.symbol()}; 1126 if (hostSymbol.test(Symbol::Flag::ImplicitOrError)) { 1127 if (details.implicitOrSpecExprError) { 1128 messages_.Say("Implicitly typed local entity '%s' not allowed in" 1129 " specification expression"_err_en_US, 1130 symbol.name()); 1131 } else if (details.implicitOrExplicitTypeError) { 1132 messages_.Say( 1133 "No explicit type declared for '%s'"_err_en_US, symbol.name()); 1134 } 1135 } 1136 } 1137 1138 void CheckHelper::CheckGeneric( 1139 const Symbol &symbol, const GenericDetails &details) { 1140 CheckSpecificsAreDistinguishable(symbol, details); 1141 std::visit(common::visitors{ 1142 [&](const GenericKind::DefinedIo &io) { 1143 CheckDefinedIoProc(symbol, details, io); 1144 }, 1145 [](const auto &) {}, 1146 }, 1147 details.kind().u); 1148 } 1149 1150 // Check that the specifics of this generic are distinguishable from each other 1151 void CheckHelper::CheckSpecificsAreDistinguishable( 1152 const Symbol &generic, const GenericDetails &details) { 1153 GenericKind kind{details.kind()}; 1154 const SymbolVector &specifics{details.specificProcs()}; 1155 std::size_t count{specifics.size()}; 1156 if (count < 2 || !kind.IsName()) { 1157 return; 1158 } 1159 DistinguishabilityHelper helper{context_}; 1160 for (const Symbol &specific : specifics) { 1161 if (const Procedure * procedure{Characterize(specific)}) { 1162 helper.Add(generic, kind, specific, *procedure); 1163 } 1164 } 1165 helper.Check(generic.owner()); 1166 } 1167 1168 static bool ConflictsWithIntrinsicAssignment(const Procedure &proc) { 1169 auto lhs{std::get<DummyDataObject>(proc.dummyArguments[0].u).type}; 1170 auto rhs{std::get<DummyDataObject>(proc.dummyArguments[1].u).type}; 1171 return Tristate::No == 1172 IsDefinedAssignment(lhs.type(), lhs.Rank(), rhs.type(), rhs.Rank()); 1173 } 1174 1175 static bool ConflictsWithIntrinsicOperator( 1176 const GenericKind &kind, const Procedure &proc) { 1177 if (!kind.IsIntrinsicOperator()) { 1178 return false; 1179 } 1180 auto arg0{std::get<DummyDataObject>(proc.dummyArguments[0].u).type}; 1181 auto type0{arg0.type()}; 1182 if (proc.dummyArguments.size() == 1) { // unary 1183 return std::visit( 1184 common::visitors{ 1185 [&](common::NumericOperator) { return IsIntrinsicNumeric(type0); }, 1186 [&](common::LogicalOperator) { return IsIntrinsicLogical(type0); }, 1187 [](const auto &) -> bool { DIE("bad generic kind"); }, 1188 }, 1189 kind.u); 1190 } else { // binary 1191 int rank0{arg0.Rank()}; 1192 auto arg1{std::get<DummyDataObject>(proc.dummyArguments[1].u).type}; 1193 auto type1{arg1.type()}; 1194 int rank1{arg1.Rank()}; 1195 return std::visit( 1196 common::visitors{ 1197 [&](common::NumericOperator) { 1198 return IsIntrinsicNumeric(type0, rank0, type1, rank1); 1199 }, 1200 [&](common::LogicalOperator) { 1201 return IsIntrinsicLogical(type0, rank0, type1, rank1); 1202 }, 1203 [&](common::RelationalOperator opr) { 1204 return IsIntrinsicRelational(opr, type0, rank0, type1, rank1); 1205 }, 1206 [&](GenericKind::OtherKind x) { 1207 CHECK(x == GenericKind::OtherKind::Concat); 1208 return IsIntrinsicConcat(type0, rank0, type1, rank1); 1209 }, 1210 [](const auto &) -> bool { DIE("bad generic kind"); }, 1211 }, 1212 kind.u); 1213 } 1214 } 1215 1216 // Check if this procedure can be used for defined operators (see 15.4.3.4.2). 1217 bool CheckHelper::CheckDefinedOperator(SourceName opName, GenericKind kind, 1218 const Symbol &specific, const Procedure &proc) { 1219 if (context_.HasError(specific)) { 1220 return false; 1221 } 1222 std::optional<parser::MessageFixedText> msg; 1223 auto checkDefinedOperatorArgs{ 1224 [&](SourceName opName, const Symbol &specific, const Procedure &proc) { 1225 bool arg0Defined{CheckDefinedOperatorArg(opName, specific, proc, 0)}; 1226 bool arg1Defined{CheckDefinedOperatorArg(opName, specific, proc, 1)}; 1227 return arg0Defined && arg1Defined; 1228 }}; 1229 if (specific.attrs().test(Attr::NOPASS)) { // C774 1230 msg = "%s procedure '%s' may not have NOPASS attribute"_err_en_US; 1231 } else if (!proc.functionResult.has_value()) { 1232 msg = "%s procedure '%s' must be a function"_err_en_US; 1233 } else if (proc.functionResult->IsAssumedLengthCharacter()) { 1234 msg = "%s function '%s' may not have assumed-length CHARACTER(*)" 1235 " result"_err_en_US; 1236 } else if (auto m{CheckNumberOfArgs(kind, proc.dummyArguments.size())}) { 1237 msg = std::move(m); 1238 } else if (!checkDefinedOperatorArgs(opName, specific, proc)) { 1239 return false; // error was reported 1240 } else if (ConflictsWithIntrinsicOperator(kind, proc)) { 1241 msg = "%s function '%s' conflicts with intrinsic operator"_err_en_US; 1242 } else { 1243 return true; // OK 1244 } 1245 SayWithDeclaration( 1246 specific, std::move(*msg), MakeOpName(opName), specific.name()); 1247 context_.SetError(specific); 1248 return false; 1249 } 1250 1251 // If the number of arguments is wrong for this intrinsic operator, return 1252 // false and return the error message in msg. 1253 std::optional<parser::MessageFixedText> CheckHelper::CheckNumberOfArgs( 1254 const GenericKind &kind, std::size_t nargs) { 1255 if (!kind.IsIntrinsicOperator()) { 1256 return std::nullopt; 1257 } 1258 std::size_t min{2}, max{2}; // allowed number of args; default is binary 1259 std::visit(common::visitors{ 1260 [&](const common::NumericOperator &x) { 1261 if (x == common::NumericOperator::Add || 1262 x == common::NumericOperator::Subtract) { 1263 min = 1; // + and - are unary or binary 1264 } 1265 }, 1266 [&](const common::LogicalOperator &x) { 1267 if (x == common::LogicalOperator::Not) { 1268 min = 1; // .NOT. is unary 1269 max = 1; 1270 } 1271 }, 1272 [](const common::RelationalOperator &) { 1273 // all are binary 1274 }, 1275 [](const GenericKind::OtherKind &x) { 1276 CHECK(x == GenericKind::OtherKind::Concat); 1277 }, 1278 [](const auto &) { DIE("expected intrinsic operator"); }, 1279 }, 1280 kind.u); 1281 if (nargs >= min && nargs <= max) { 1282 return std::nullopt; 1283 } else if (max == 1) { 1284 return "%s function '%s' must have one dummy argument"_err_en_US; 1285 } else if (min == 2) { 1286 return "%s function '%s' must have two dummy arguments"_err_en_US; 1287 } else { 1288 return "%s function '%s' must have one or two dummy arguments"_err_en_US; 1289 } 1290 } 1291 1292 bool CheckHelper::CheckDefinedOperatorArg(const SourceName &opName, 1293 const Symbol &symbol, const Procedure &proc, std::size_t pos) { 1294 if (pos >= proc.dummyArguments.size()) { 1295 return true; 1296 } 1297 auto &arg{proc.dummyArguments.at(pos)}; 1298 std::optional<parser::MessageFixedText> msg; 1299 if (arg.IsOptional()) { 1300 msg = "In %s function '%s', dummy argument '%s' may not be" 1301 " OPTIONAL"_err_en_US; 1302 } else if (const auto *dataObject{std::get_if<DummyDataObject>(&arg.u)}; 1303 dataObject == nullptr) { 1304 msg = "In %s function '%s', dummy argument '%s' must be a" 1305 " data object"_err_en_US; 1306 } else if (dataObject->intent != common::Intent::In && 1307 !dataObject->attrs.test(DummyDataObject::Attr::Value)) { 1308 msg = "In %s function '%s', dummy argument '%s' must have INTENT(IN)" 1309 " or VALUE attribute"_err_en_US; 1310 } 1311 if (msg) { 1312 SayWithDeclaration(symbol, std::move(*msg), 1313 parser::ToUpperCaseLetters(opName.ToString()), symbol.name(), arg.name); 1314 return false; 1315 } 1316 return true; 1317 } 1318 1319 // Check if this procedure can be used for defined assignment (see 15.4.3.4.3). 1320 bool CheckHelper::CheckDefinedAssignment( 1321 const Symbol &specific, const Procedure &proc) { 1322 if (context_.HasError(specific)) { 1323 return false; 1324 } 1325 std::optional<parser::MessageFixedText> msg; 1326 if (specific.attrs().test(Attr::NOPASS)) { // C774 1327 msg = "Defined assignment procedure '%s' may not have" 1328 " NOPASS attribute"_err_en_US; 1329 } else if (!proc.IsSubroutine()) { 1330 msg = "Defined assignment procedure '%s' must be a subroutine"_err_en_US; 1331 } else if (proc.dummyArguments.size() != 2) { 1332 msg = "Defined assignment subroutine '%s' must have" 1333 " two dummy arguments"_err_en_US; 1334 } else { 1335 // Check both arguments even if the first has an error. 1336 bool ok0{CheckDefinedAssignmentArg(specific, proc.dummyArguments[0], 0)}; 1337 bool ok1{CheckDefinedAssignmentArg(specific, proc.dummyArguments[1], 1)}; 1338 if (!(ok0 && ok1)) { 1339 return false; // error was reported 1340 } else if (ConflictsWithIntrinsicAssignment(proc)) { 1341 msg = "Defined assignment subroutine '%s' conflicts with" 1342 " intrinsic assignment"_err_en_US; 1343 } else { 1344 return true; // OK 1345 } 1346 } 1347 SayWithDeclaration(specific, std::move(msg.value()), specific.name()); 1348 context_.SetError(specific); 1349 return false; 1350 } 1351 1352 bool CheckHelper::CheckDefinedAssignmentArg( 1353 const Symbol &symbol, const DummyArgument &arg, int pos) { 1354 std::optional<parser::MessageFixedText> msg; 1355 if (arg.IsOptional()) { 1356 msg = "In defined assignment subroutine '%s', dummy argument '%s'" 1357 " may not be OPTIONAL"_err_en_US; 1358 } else if (const auto *dataObject{std::get_if<DummyDataObject>(&arg.u)}) { 1359 if (pos == 0) { 1360 if (dataObject->intent != common::Intent::Out && 1361 dataObject->intent != common::Intent::InOut) { 1362 msg = "In defined assignment subroutine '%s', first dummy argument '%s'" 1363 " must have INTENT(OUT) or INTENT(INOUT)"_err_en_US; 1364 } 1365 } else if (pos == 1) { 1366 if (dataObject->intent != common::Intent::In && 1367 !dataObject->attrs.test(DummyDataObject::Attr::Value)) { 1368 msg = 1369 "In defined assignment subroutine '%s', second dummy" 1370 " argument '%s' must have INTENT(IN) or VALUE attribute"_err_en_US; 1371 } 1372 } else { 1373 DIE("pos must be 0 or 1"); 1374 } 1375 } else { 1376 msg = "In defined assignment subroutine '%s', dummy argument '%s'" 1377 " must be a data object"_err_en_US; 1378 } 1379 if (msg) { 1380 SayWithDeclaration(symbol, std::move(*msg), symbol.name(), arg.name); 1381 context_.SetError(symbol); 1382 return false; 1383 } 1384 return true; 1385 } 1386 1387 // Report a conflicting attribute error if symbol has both of these attributes 1388 bool CheckHelper::CheckConflicting(const Symbol &symbol, Attr a1, Attr a2) { 1389 if (symbol.attrs().test(a1) && symbol.attrs().test(a2)) { 1390 messages_.Say("'%s' may not have both the %s and %s attributes"_err_en_US, 1391 symbol.name(), AttrToString(a1), AttrToString(a2)); 1392 return true; 1393 } else { 1394 return false; 1395 } 1396 } 1397 1398 void CheckHelper::WarnMissingFinal(const Symbol &symbol) { 1399 const auto *object{symbol.detailsIf<ObjectEntityDetails>()}; 1400 if (!object || IsPointer(symbol)) { 1401 return; 1402 } 1403 const DeclTypeSpec *type{object->type()}; 1404 const DerivedTypeSpec *derived{type ? type->AsDerived() : nullptr}; 1405 const Symbol *derivedSym{derived ? &derived->typeSymbol() : nullptr}; 1406 int rank{object->shape().Rank()}; 1407 const Symbol *initialDerivedSym{derivedSym}; 1408 while (const auto *derivedDetails{ 1409 derivedSym ? derivedSym->detailsIf<DerivedTypeDetails>() : nullptr}) { 1410 if (!derivedDetails->finals().empty() && 1411 !derivedDetails->GetFinalForRank(rank)) { 1412 if (auto *msg{derivedSym == initialDerivedSym 1413 ? messages_.Say(symbol.name(), 1414 "'%s' of derived type '%s' does not have a FINAL subroutine for its rank (%d)"_en_US, 1415 symbol.name(), derivedSym->name(), rank) 1416 : messages_.Say(symbol.name(), 1417 "'%s' of derived type '%s' extended from '%s' does not have a FINAL subroutine for its rank (%d)"_en_US, 1418 symbol.name(), initialDerivedSym->name(), 1419 derivedSym->name(), rank)}) { 1420 msg->Attach(derivedSym->name(), 1421 "Declaration of derived type '%s'"_en_US, derivedSym->name()); 1422 } 1423 return; 1424 } 1425 derived = derivedSym->GetParentTypeSpec(); 1426 derivedSym = derived ? &derived->typeSymbol() : nullptr; 1427 } 1428 } 1429 1430 const Procedure *CheckHelper::Characterize(const Symbol &symbol) { 1431 auto it{characterizeCache_.find(symbol)}; 1432 if (it == characterizeCache_.end()) { 1433 auto pair{characterizeCache_.emplace(SymbolRef{symbol}, 1434 Procedure::Characterize(symbol, context_.foldingContext()))}; 1435 it = pair.first; 1436 } 1437 return common::GetPtrFromOptional(it->second); 1438 } 1439 1440 void CheckHelper::CheckVolatile(const Symbol &symbol, 1441 const DerivedTypeSpec *derived) { // C866 - C868 1442 if (IsIntentIn(symbol)) { 1443 messages_.Say( 1444 "VOLATILE attribute may not apply to an INTENT(IN) argument"_err_en_US); 1445 } 1446 if (IsProcedure(symbol)) { 1447 messages_.Say("VOLATILE attribute may apply only to a variable"_err_en_US); 1448 } 1449 if (symbol.has<UseDetails>() || symbol.has<HostAssocDetails>()) { 1450 const Symbol &ultimate{symbol.GetUltimate()}; 1451 if (IsCoarray(ultimate)) { 1452 messages_.Say( 1453 "VOLATILE attribute may not apply to a coarray accessed by USE or host association"_err_en_US); 1454 } 1455 if (derived) { 1456 if (FindCoarrayUltimateComponent(*derived)) { 1457 messages_.Say( 1458 "VOLATILE attribute may not apply to a type with a coarray ultimate component accessed by USE or host association"_err_en_US); 1459 } 1460 } 1461 } 1462 } 1463 1464 void CheckHelper::CheckPointer(const Symbol &symbol) { // C852 1465 CheckConflicting(symbol, Attr::POINTER, Attr::TARGET); 1466 CheckConflicting(symbol, Attr::POINTER, Attr::ALLOCATABLE); // C751 1467 CheckConflicting(symbol, Attr::POINTER, Attr::INTRINSIC); 1468 // Prohibit constant pointers. The standard does not explicitly prohibit 1469 // them, but the PARAMETER attribute requires a entity-decl to have an 1470 // initialization that is a constant-expr, and the only form of 1471 // initialization that allows a constant-expr is the one that's not a "=>" 1472 // pointer initialization. See C811, C807, and section 8.5.13. 1473 CheckConflicting(symbol, Attr::POINTER, Attr::PARAMETER); 1474 if (symbol.Corank() > 0) { 1475 messages_.Say( 1476 "'%s' may not have the POINTER attribute because it is a coarray"_err_en_US, 1477 symbol.name()); 1478 } 1479 } 1480 1481 // C760 constraints on the passed-object dummy argument 1482 // C757 constraints on procedure pointer components 1483 void CheckHelper::CheckPassArg( 1484 const Symbol &proc, const Symbol *interface, const WithPassArg &details) { 1485 if (proc.attrs().test(Attr::NOPASS)) { 1486 return; 1487 } 1488 const auto &name{proc.name()}; 1489 if (!interface) { 1490 messages_.Say(name, 1491 "Procedure component '%s' must have NOPASS attribute or explicit interface"_err_en_US, 1492 name); 1493 return; 1494 } 1495 const auto *subprogram{interface->detailsIf<SubprogramDetails>()}; 1496 if (!subprogram) { 1497 messages_.Say(name, 1498 "Procedure component '%s' has invalid interface '%s'"_err_en_US, name, 1499 interface->name()); 1500 return; 1501 } 1502 std::optional<SourceName> passName{details.passName()}; 1503 const auto &dummyArgs{subprogram->dummyArgs()}; 1504 if (!passName) { 1505 if (dummyArgs.empty()) { 1506 messages_.Say(name, 1507 proc.has<ProcEntityDetails>() 1508 ? "Procedure component '%s' with no dummy arguments" 1509 " must have NOPASS attribute"_err_en_US 1510 : "Procedure binding '%s' with no dummy arguments" 1511 " must have NOPASS attribute"_err_en_US, 1512 name); 1513 context_.SetError(*interface); 1514 return; 1515 } 1516 Symbol *argSym{dummyArgs[0]}; 1517 if (!argSym) { 1518 messages_.Say(interface->name(), 1519 "Cannot use an alternate return as the passed-object dummy " 1520 "argument"_err_en_US); 1521 return; 1522 } 1523 passName = dummyArgs[0]->name(); 1524 } 1525 std::optional<int> passArgIndex{}; 1526 for (std::size_t i{0}; i < dummyArgs.size(); ++i) { 1527 if (dummyArgs[i] && dummyArgs[i]->name() == *passName) { 1528 passArgIndex = i; 1529 break; 1530 } 1531 } 1532 if (!passArgIndex) { // C758 1533 messages_.Say(*passName, 1534 "'%s' is not a dummy argument of procedure interface '%s'"_err_en_US, 1535 *passName, interface->name()); 1536 return; 1537 } 1538 const Symbol &passArg{*dummyArgs[*passArgIndex]}; 1539 std::optional<parser::MessageFixedText> msg; 1540 if (!passArg.has<ObjectEntityDetails>()) { 1541 msg = "Passed-object dummy argument '%s' of procedure '%s'" 1542 " must be a data object"_err_en_US; 1543 } else if (passArg.attrs().test(Attr::POINTER)) { 1544 msg = "Passed-object dummy argument '%s' of procedure '%s'" 1545 " may not have the POINTER attribute"_err_en_US; 1546 } else if (passArg.attrs().test(Attr::ALLOCATABLE)) { 1547 msg = "Passed-object dummy argument '%s' of procedure '%s'" 1548 " may not have the ALLOCATABLE attribute"_err_en_US; 1549 } else if (passArg.attrs().test(Attr::VALUE)) { 1550 msg = "Passed-object dummy argument '%s' of procedure '%s'" 1551 " may not have the VALUE attribute"_err_en_US; 1552 } else if (passArg.Rank() > 0) { 1553 msg = "Passed-object dummy argument '%s' of procedure '%s'" 1554 " must be scalar"_err_en_US; 1555 } 1556 if (msg) { 1557 messages_.Say(name, std::move(*msg), passName.value(), name); 1558 return; 1559 } 1560 const DeclTypeSpec *type{passArg.GetType()}; 1561 if (!type) { 1562 return; // an error already occurred 1563 } 1564 const Symbol &typeSymbol{*proc.owner().GetSymbol()}; 1565 const DerivedTypeSpec *derived{type->AsDerived()}; 1566 if (!derived || derived->typeSymbol() != typeSymbol) { 1567 messages_.Say(name, 1568 "Passed-object dummy argument '%s' of procedure '%s'" 1569 " must be of type '%s' but is '%s'"_err_en_US, 1570 passName.value(), name, typeSymbol.name(), type->AsFortran()); 1571 return; 1572 } 1573 if (IsExtensibleType(derived) != type->IsPolymorphic()) { 1574 messages_.Say(name, 1575 type->IsPolymorphic() 1576 ? "Passed-object dummy argument '%s' of procedure '%s'" 1577 " may not be polymorphic because '%s' is not extensible"_err_en_US 1578 : "Passed-object dummy argument '%s' of procedure '%s'" 1579 " must be polymorphic because '%s' is extensible"_err_en_US, 1580 passName.value(), name, typeSymbol.name()); 1581 return; 1582 } 1583 for (const auto &[paramName, paramValue] : derived->parameters()) { 1584 if (paramValue.isLen() && !paramValue.isAssumed()) { 1585 messages_.Say(name, 1586 "Passed-object dummy argument '%s' of procedure '%s'" 1587 " has non-assumed length parameter '%s'"_err_en_US, 1588 passName.value(), name, paramName); 1589 } 1590 } 1591 } 1592 1593 void CheckHelper::CheckProcBinding( 1594 const Symbol &symbol, const ProcBindingDetails &binding) { 1595 const Scope &dtScope{symbol.owner()}; 1596 CHECK(dtScope.kind() == Scope::Kind::DerivedType); 1597 if (symbol.attrs().test(Attr::DEFERRED)) { 1598 if (const Symbol * dtSymbol{dtScope.symbol()}) { 1599 if (!dtSymbol->attrs().test(Attr::ABSTRACT)) { // C733 1600 SayWithDeclaration(*dtSymbol, 1601 "Procedure bound to non-ABSTRACT derived type '%s' may not be DEFERRED"_err_en_US, 1602 dtSymbol->name()); 1603 } 1604 } 1605 if (symbol.attrs().test(Attr::NON_OVERRIDABLE)) { 1606 messages_.Say( 1607 "Type-bound procedure '%s' may not be both DEFERRED and NON_OVERRIDABLE"_err_en_US, 1608 symbol.name()); 1609 } 1610 } 1611 if (binding.symbol().attrs().test(Attr::INTRINSIC) && 1612 !context_.intrinsics().IsSpecificIntrinsicFunction( 1613 binding.symbol().name().ToString())) { 1614 messages_.Say( 1615 "Intrinsic procedure '%s' is not a specific intrinsic permitted for use in the definition of binding '%s'"_err_en_US, 1616 binding.symbol().name(), symbol.name()); 1617 } 1618 if (const Symbol * overridden{FindOverriddenBinding(symbol)}) { 1619 if (overridden->attrs().test(Attr::NON_OVERRIDABLE)) { 1620 SayWithDeclaration(*overridden, 1621 "Override of NON_OVERRIDABLE '%s' is not permitted"_err_en_US, 1622 symbol.name()); 1623 } 1624 if (const auto *overriddenBinding{ 1625 overridden->detailsIf<ProcBindingDetails>()}) { 1626 if (!IsPureProcedure(symbol) && IsPureProcedure(*overridden)) { 1627 SayWithDeclaration(*overridden, 1628 "An overridden pure type-bound procedure binding must also be pure"_err_en_US); 1629 return; 1630 } 1631 if (!binding.symbol().attrs().test(Attr::ELEMENTAL) && 1632 overriddenBinding->symbol().attrs().test(Attr::ELEMENTAL)) { 1633 SayWithDeclaration(*overridden, 1634 "A type-bound procedure and its override must both, or neither, be ELEMENTAL"_err_en_US); 1635 return; 1636 } 1637 bool isNopass{symbol.attrs().test(Attr::NOPASS)}; 1638 if (isNopass != overridden->attrs().test(Attr::NOPASS)) { 1639 SayWithDeclaration(*overridden, 1640 isNopass 1641 ? "A NOPASS type-bound procedure may not override a passed-argument procedure"_err_en_US 1642 : "A passed-argument type-bound procedure may not override a NOPASS procedure"_err_en_US); 1643 } else { 1644 const auto *bindingChars{Characterize(binding.symbol())}; 1645 const auto *overriddenChars{Characterize(overriddenBinding->symbol())}; 1646 if (bindingChars && overriddenChars) { 1647 if (isNopass) { 1648 if (!bindingChars->CanOverride(*overriddenChars, std::nullopt)) { 1649 SayWithDeclaration(*overridden, 1650 "A type-bound procedure and its override must have compatible interfaces"_err_en_US); 1651 } 1652 } else if (!context_.HasError(binding.symbol())) { 1653 int passIndex{bindingChars->FindPassIndex(binding.passName())}; 1654 int overriddenPassIndex{ 1655 overriddenChars->FindPassIndex(overriddenBinding->passName())}; 1656 if (passIndex != overriddenPassIndex) { 1657 SayWithDeclaration(*overridden, 1658 "A type-bound procedure and its override must use the same PASS argument"_err_en_US); 1659 } else if (!bindingChars->CanOverride( 1660 *overriddenChars, passIndex)) { 1661 SayWithDeclaration(*overridden, 1662 "A type-bound procedure and its override must have compatible interfaces apart from their passed argument"_err_en_US); 1663 } 1664 } 1665 } 1666 } 1667 if (symbol.attrs().test(Attr::PRIVATE) && 1668 overridden->attrs().test(Attr::PUBLIC)) { 1669 SayWithDeclaration(*overridden, 1670 "A PRIVATE procedure may not override a PUBLIC procedure"_err_en_US); 1671 } 1672 } else { 1673 SayWithDeclaration(*overridden, 1674 "A type-bound procedure binding may not have the same name as a parent component"_err_en_US); 1675 } 1676 } 1677 CheckPassArg(symbol, &binding.symbol(), binding); 1678 } 1679 1680 void CheckHelper::Check(const Scope &scope) { 1681 scope_ = &scope; 1682 common::Restorer<const Symbol *> restorer{innermostSymbol_, innermostSymbol_}; 1683 if (const Symbol * symbol{scope.symbol()}) { 1684 innermostSymbol_ = symbol; 1685 } 1686 if (scope.IsParameterizedDerivedTypeInstantiation()) { 1687 auto restorer{common::ScopedSet(scopeIsUninstantiatedPDT_, false)}; 1688 auto restorer2{context_.foldingContext().messages().SetContext( 1689 scope.instantiationContext().get())}; 1690 for (const auto &pair : scope) { 1691 CheckPointerInitialization(*pair.second); 1692 } 1693 } else { 1694 auto restorer{common::ScopedSet( 1695 scopeIsUninstantiatedPDT_, scope.IsParameterizedDerivedType())}; 1696 for (const auto &set : scope.equivalenceSets()) { 1697 CheckEquivalenceSet(set); 1698 } 1699 for (const auto &pair : scope) { 1700 Check(*pair.second); 1701 } 1702 for (const Scope &child : scope.children()) { 1703 Check(child); 1704 } 1705 if (scope.kind() == Scope::Kind::BlockData) { 1706 CheckBlockData(scope); 1707 } 1708 CheckGenericOps(scope); 1709 } 1710 } 1711 1712 void CheckHelper::CheckEquivalenceSet(const EquivalenceSet &set) { 1713 auto iter{ 1714 std::find_if(set.begin(), set.end(), [](const EquivalenceObject &object) { 1715 return FindCommonBlockContaining(object.symbol) != nullptr; 1716 })}; 1717 if (iter != set.end()) { 1718 const Symbol &commonBlock{DEREF(FindCommonBlockContaining(iter->symbol))}; 1719 for (auto &object : set) { 1720 if (&object != &*iter) { 1721 if (auto *details{object.symbol.detailsIf<ObjectEntityDetails>()}) { 1722 if (details->commonBlock()) { 1723 if (details->commonBlock() != &commonBlock) { // 8.10.3 paragraph 1 1724 if (auto *msg{messages_.Say(object.symbol.name(), 1725 "Two objects in the same EQUIVALENCE set may not be members of distinct COMMON blocks"_err_en_US)}) { 1726 msg->Attach(iter->symbol.name(), 1727 "Other object in EQUIVALENCE set"_en_US) 1728 .Attach(details->commonBlock()->name(), 1729 "COMMON block containing '%s'"_en_US, 1730 object.symbol.name()) 1731 .Attach(commonBlock.name(), 1732 "COMMON block containing '%s'"_en_US, 1733 iter->symbol.name()); 1734 } 1735 } 1736 } else { 1737 // Mark all symbols in the equivalence set with the same COMMON 1738 // block to prevent spurious error messages about initialization 1739 // in BLOCK DATA outside COMMON 1740 details->set_commonBlock(commonBlock); 1741 } 1742 } 1743 } 1744 } 1745 } 1746 // TODO: Move C8106 (&al.) checks here from resolve-names-utils.cpp 1747 } 1748 1749 void CheckHelper::CheckBlockData(const Scope &scope) { 1750 // BLOCK DATA subprograms should contain only named common blocks. 1751 // C1415 presents a list of statements that shouldn't appear in 1752 // BLOCK DATA, but so long as the subprogram contains no executable 1753 // code and allocates no storage outside named COMMON, we're happy 1754 // (e.g., an ENUM is strictly not allowed). 1755 for (const auto &pair : scope) { 1756 const Symbol &symbol{*pair.second}; 1757 if (!(symbol.has<CommonBlockDetails>() || symbol.has<UseDetails>() || 1758 symbol.has<UseErrorDetails>() || symbol.has<DerivedTypeDetails>() || 1759 symbol.has<SubprogramDetails>() || 1760 symbol.has<ObjectEntityDetails>() || 1761 (symbol.has<ProcEntityDetails>() && 1762 !symbol.attrs().test(Attr::POINTER)))) { 1763 messages_.Say(symbol.name(), 1764 "'%s' may not appear in a BLOCK DATA subprogram"_err_en_US, 1765 symbol.name()); 1766 } 1767 } 1768 } 1769 1770 // Check distinguishability of generic assignment and operators. 1771 // For these, generics and generic bindings must be considered together. 1772 void CheckHelper::CheckGenericOps(const Scope &scope) { 1773 DistinguishabilityHelper helper{context_}; 1774 auto addSpecifics{[&](const Symbol &generic) { 1775 const auto *details{generic.GetUltimate().detailsIf<GenericDetails>()}; 1776 if (!details) { 1777 return; 1778 } 1779 GenericKind kind{details->kind()}; 1780 if (!kind.IsAssignment() && !kind.IsOperator()) { 1781 return; 1782 } 1783 const SymbolVector &specifics{details->specificProcs()}; 1784 const std::vector<SourceName> &bindingNames{details->bindingNames()}; 1785 for (std::size_t i{0}; i < specifics.size(); ++i) { 1786 const Symbol &specific{*specifics[i]}; 1787 if (const Procedure * proc{Characterize(specific)}) { 1788 auto restorer{messages_.SetLocation(bindingNames[i])}; 1789 if (kind.IsAssignment()) { 1790 if (!CheckDefinedAssignment(specific, *proc)) { 1791 continue; 1792 } 1793 } else { 1794 if (!CheckDefinedOperator(generic.name(), kind, specific, *proc)) { 1795 continue; 1796 } 1797 } 1798 helper.Add(generic, kind, specific, *proc); 1799 } 1800 } 1801 }}; 1802 for (const auto &pair : scope) { 1803 const Symbol &symbol{*pair.second}; 1804 addSpecifics(symbol); 1805 const Symbol &ultimate{symbol.GetUltimate()}; 1806 if (ultimate.has<DerivedTypeDetails>()) { 1807 if (const Scope * typeScope{ultimate.scope()}) { 1808 for (const auto &pair2 : *typeScope) { 1809 addSpecifics(*pair2.second); 1810 } 1811 } 1812 } 1813 } 1814 helper.Check(scope); 1815 } 1816 1817 static const std::string *DefinesBindCName(const Symbol &symbol) { 1818 const auto *subp{symbol.detailsIf<SubprogramDetails>()}; 1819 if ((subp && !subp->isInterface()) || symbol.has<ObjectEntityDetails>()) { 1820 // Symbol defines data or entry point 1821 return symbol.GetBindName(); 1822 } else { 1823 return nullptr; 1824 } 1825 } 1826 1827 // Check that BIND(C) names are distinct 1828 void CheckHelper::CheckBindCName(const Symbol &symbol) { 1829 if (const std::string * name{DefinesBindCName(symbol)}) { 1830 auto pair{bindC_.emplace(*name, symbol)}; 1831 if (!pair.second) { 1832 const Symbol &other{*pair.first->second}; 1833 if (DefinesBindCName(other) && !context_.HasError(other)) { 1834 if (auto *msg{messages_.Say( 1835 "Two symbols have the same BIND(C) name '%s'"_err_en_US, 1836 *name)}) { 1837 msg->Attach(other.name(), "Conflicting symbol"_en_US); 1838 } 1839 context_.SetError(symbol); 1840 context_.SetError(other); 1841 } 1842 } 1843 } 1844 } 1845 1846 bool CheckHelper::CheckDioDummyIsData( 1847 const Symbol &subp, const Symbol *arg, std::size_t position) { 1848 if (arg && arg->detailsIf<ObjectEntityDetails>()) { 1849 return true; 1850 } else { 1851 if (arg) { 1852 messages_.Say(arg->name(), 1853 "Dummy argument '%s' must be a data object"_err_en_US, arg->name()); 1854 } else { 1855 messages_.Say(subp.name(), 1856 "Dummy argument %d of '%s' must be a data object"_err_en_US, position, 1857 subp.name()); 1858 } 1859 return false; 1860 } 1861 } 1862 1863 void CheckHelper::CheckAlreadySeenDefinedIo(const DerivedTypeSpec *derivedType, 1864 GenericKind::DefinedIo ioKind, const Symbol &proc) { 1865 for (TypeWithDefinedIo definedIoType : seenDefinedIoTypes_) { 1866 if (*derivedType == *definedIoType.type && ioKind == definedIoType.ioKind && 1867 proc != definedIoType.proc) { 1868 SayWithDeclaration(proc, definedIoType.proc.name(), 1869 "Derived type '%s' already has defined input/output procedure" 1870 " '%s'"_err_en_US, 1871 derivedType->name(), 1872 parser::ToUpperCaseLetters(GenericKind::EnumToString(ioKind))); 1873 return; 1874 } 1875 } 1876 seenDefinedIoTypes_.emplace_back( 1877 TypeWithDefinedIo{derivedType, ioKind, proc}); 1878 } 1879 1880 void CheckHelper::CheckDioDummyIsDerived( 1881 const Symbol &subp, const Symbol &arg, GenericKind::DefinedIo ioKind) { 1882 if (const DeclTypeSpec * type{arg.GetType()}) { 1883 if (const DerivedTypeSpec * derivedType{type->AsDerived()}) { 1884 CheckAlreadySeenDefinedIo(derivedType, ioKind, subp); 1885 bool isPolymorphic{type->IsPolymorphic()}; 1886 if (isPolymorphic != IsExtensibleType(derivedType)) { 1887 messages_.Say(arg.name(), 1888 "Dummy argument '%s' of a defined input/output procedure must be %s when the derived type is %s"_err_en_US, 1889 arg.name(), isPolymorphic ? "TYPE()" : "CLASS()", 1890 isPolymorphic ? "not extensible" : "extensible"); 1891 } 1892 } else { 1893 messages_.Say(arg.name(), 1894 "Dummy argument '%s' of a defined input/output procedure must have a" 1895 " derived type"_err_en_US, 1896 arg.name()); 1897 } 1898 } 1899 } 1900 1901 void CheckHelper::CheckDioDummyIsDefaultInteger( 1902 const Symbol &subp, const Symbol &arg) { 1903 if (const DeclTypeSpec * type{arg.GetType()}; 1904 type && type->IsNumeric(TypeCategory::Integer)) { 1905 if (const auto kind{evaluate::ToInt64(type->numericTypeSpec().kind())}; 1906 kind && *kind == context_.GetDefaultKind(TypeCategory::Integer)) { 1907 return; 1908 } 1909 } 1910 messages_.Say(arg.name(), 1911 "Dummy argument '%s' of a defined input/output procedure" 1912 " must be an INTEGER of default KIND"_err_en_US, 1913 arg.name()); 1914 } 1915 1916 void CheckHelper::CheckDioDummyIsScalar(const Symbol &subp, const Symbol &arg) { 1917 if (arg.Rank() > 0 || arg.Corank() > 0) { 1918 messages_.Say(arg.name(), 1919 "Dummy argument '%s' of a defined input/output procedure" 1920 " must be a scalar"_err_en_US, 1921 arg.name()); 1922 } 1923 } 1924 1925 void CheckHelper::CheckDioDtvArg( 1926 const Symbol &subp, const Symbol *arg, GenericKind::DefinedIo ioKind) { 1927 // Dtv argument looks like: dtv-type-spec, INTENT(INOUT) :: dtv 1928 if (CheckDioDummyIsData(subp, arg, 0)) { 1929 CheckDioDummyIsDerived(subp, *arg, ioKind); 1930 CheckDioDummyAttrs(subp, *arg, 1931 ioKind == GenericKind::DefinedIo::ReadFormatted || 1932 ioKind == GenericKind::DefinedIo::ReadUnformatted 1933 ? Attr::INTENT_INOUT 1934 : Attr::INTENT_IN); 1935 } 1936 } 1937 1938 void CheckHelper::CheckDefaultIntegerArg( 1939 const Symbol &subp, const Symbol *arg, Attr intent) { 1940 // Argument looks like: INTEGER, INTENT(intent) :: arg 1941 if (CheckDioDummyIsData(subp, arg, 1)) { 1942 CheckDioDummyIsDefaultInteger(subp, *arg); 1943 CheckDioDummyIsScalar(subp, *arg); 1944 CheckDioDummyAttrs(subp, *arg, intent); 1945 } 1946 } 1947 1948 void CheckHelper::CheckDioAssumedLenCharacterArg(const Symbol &subp, 1949 const Symbol *arg, std::size_t argPosition, Attr intent) { 1950 // Argument looks like: CHARACTER (LEN=*), INTENT(intent) :: (iotype OR iomsg) 1951 if (CheckDioDummyIsData(subp, arg, argPosition)) { 1952 CheckDioDummyAttrs(subp, *arg, intent); 1953 if (!IsAssumedLengthCharacter(*arg)) { 1954 messages_.Say(arg->name(), 1955 "Dummy argument '%s' of a defined input/output procedure" 1956 " must be assumed-length CHARACTER"_err_en_US, 1957 arg->name()); 1958 } 1959 } 1960 } 1961 1962 void CheckHelper::CheckDioVlistArg( 1963 const Symbol &subp, const Symbol *arg, std::size_t argPosition) { 1964 // Vlist argument looks like: INTEGER, INTENT(IN) :: v_list(:) 1965 if (CheckDioDummyIsData(subp, arg, argPosition)) { 1966 CheckDioDummyIsDefaultInteger(subp, *arg); 1967 CheckDioDummyAttrs(subp, *arg, Attr::INTENT_IN); 1968 if (const auto *objectDetails{arg->detailsIf<ObjectEntityDetails>()}) { 1969 if (objectDetails->shape().IsDeferredShape()) { 1970 return; 1971 } 1972 } 1973 messages_.Say(arg->name(), 1974 "Dummy argument '%s' of a defined input/output procedure must be" 1975 " deferred shape"_err_en_US, 1976 arg->name()); 1977 } 1978 } 1979 1980 void CheckHelper::CheckDioArgCount( 1981 const Symbol &subp, GenericKind::DefinedIo ioKind, std::size_t argCount) { 1982 const std::size_t requiredArgCount{ 1983 (std::size_t)(ioKind == GenericKind::DefinedIo::ReadFormatted || 1984 ioKind == GenericKind::DefinedIo::WriteFormatted 1985 ? 6 1986 : 4)}; 1987 if (argCount != requiredArgCount) { 1988 SayWithDeclaration(subp, 1989 "Defined input/output procedure '%s' must have" 1990 " %d dummy arguments rather than %d"_err_en_US, 1991 subp.name(), requiredArgCount, argCount); 1992 context_.SetError(subp); 1993 } 1994 } 1995 1996 void CheckHelper::CheckDioDummyAttrs( 1997 const Symbol &subp, const Symbol &arg, Attr goodIntent) { 1998 // Defined I/O procedures can't have attributes other than INTENT 1999 Attrs attrs{arg.attrs()}; 2000 if (!attrs.test(goodIntent)) { 2001 messages_.Say(arg.name(), 2002 "Dummy argument '%s' of a defined input/output procedure" 2003 " must have intent '%s'"_err_en_US, 2004 arg.name(), AttrToString(goodIntent)); 2005 } 2006 attrs = attrs - Attr::INTENT_IN - Attr::INTENT_OUT - Attr::INTENT_INOUT; 2007 if (!attrs.empty()) { 2008 messages_.Say(arg.name(), 2009 "Dummy argument '%s' of a defined input/output procedure may not have" 2010 " any attributes"_err_en_US, 2011 arg.name()); 2012 } 2013 } 2014 2015 // Enforce semantics for defined input/output procedures (12.6.4.8.2) and C777 2016 void CheckHelper::CheckDefinedIoProc(const Symbol &symbol, 2017 const GenericDetails &details, GenericKind::DefinedIo ioKind) { 2018 for (auto ref : details.specificProcs()) { 2019 const auto *binding{ref->detailsIf<ProcBindingDetails>()}; 2020 const Symbol &specific{*(binding ? &binding->symbol() : &*ref)}; 2021 if (ref->attrs().test(Attr::NOPASS)) { // C774 2022 messages_.Say("Defined input/output procedure '%s' may not have NOPASS " 2023 "attribute"_err_en_US, 2024 ref->name()); 2025 context_.SetError(*ref); 2026 } 2027 if (const auto *subpDetails{specific.detailsIf<SubprogramDetails>()}) { 2028 const std::vector<Symbol *> &dummyArgs{subpDetails->dummyArgs()}; 2029 CheckDioArgCount(specific, ioKind, dummyArgs.size()); 2030 int argCount{0}; 2031 for (auto *arg : dummyArgs) { 2032 switch (argCount++) { 2033 case 0: 2034 // dtv-type-spec, INTENT(INOUT) :: dtv 2035 CheckDioDtvArg(specific, arg, ioKind); 2036 break; 2037 case 1: 2038 // INTEGER, INTENT(IN) :: unit 2039 CheckDefaultIntegerArg(specific, arg, Attr::INTENT_IN); 2040 break; 2041 case 2: 2042 if (ioKind == GenericKind::DefinedIo::ReadFormatted || 2043 ioKind == GenericKind::DefinedIo::WriteFormatted) { 2044 // CHARACTER (LEN=*), INTENT(IN) :: iotype 2045 CheckDioAssumedLenCharacterArg( 2046 specific, arg, argCount, Attr::INTENT_IN); 2047 } else { 2048 // INTEGER, INTENT(OUT) :: iostat 2049 CheckDefaultIntegerArg(specific, arg, Attr::INTENT_OUT); 2050 } 2051 break; 2052 case 3: 2053 if (ioKind == GenericKind::DefinedIo::ReadFormatted || 2054 ioKind == GenericKind::DefinedIo::WriteFormatted) { 2055 // INTEGER, INTENT(IN) :: v_list(:) 2056 CheckDioVlistArg(specific, arg, argCount); 2057 } else { 2058 // CHARACTER (LEN=*), INTENT(INOUT) :: iomsg 2059 CheckDioAssumedLenCharacterArg( 2060 specific, arg, argCount, Attr::INTENT_INOUT); 2061 } 2062 break; 2063 case 4: 2064 // INTEGER, INTENT(OUT) :: iostat 2065 CheckDefaultIntegerArg(specific, arg, Attr::INTENT_OUT); 2066 break; 2067 case 5: 2068 // CHARACTER (LEN=*), INTENT(INOUT) :: iomsg 2069 CheckDioAssumedLenCharacterArg( 2070 specific, arg, argCount, Attr::INTENT_INOUT); 2071 break; 2072 default:; 2073 } 2074 } 2075 } 2076 } 2077 } 2078 2079 void SubprogramMatchHelper::Check( 2080 const Symbol &symbol1, const Symbol &symbol2) { 2081 const auto details1{symbol1.get<SubprogramDetails>()}; 2082 const auto details2{symbol2.get<SubprogramDetails>()}; 2083 if (details1.isFunction() != details2.isFunction()) { 2084 Say(symbol1, symbol2, 2085 details1.isFunction() 2086 ? "Module function '%s' was declared as a subroutine in the" 2087 " corresponding interface body"_err_en_US 2088 : "Module subroutine '%s' was declared as a function in the" 2089 " corresponding interface body"_err_en_US); 2090 return; 2091 } 2092 const auto &args1{details1.dummyArgs()}; 2093 const auto &args2{details2.dummyArgs()}; 2094 int nargs1{static_cast<int>(args1.size())}; 2095 int nargs2{static_cast<int>(args2.size())}; 2096 if (nargs1 != nargs2) { 2097 Say(symbol1, symbol2, 2098 "Module subprogram '%s' has %d args but the corresponding interface" 2099 " body has %d"_err_en_US, 2100 nargs1, nargs2); 2101 return; 2102 } 2103 bool nonRecursive1{symbol1.attrs().test(Attr::NON_RECURSIVE)}; 2104 if (nonRecursive1 != symbol2.attrs().test(Attr::NON_RECURSIVE)) { // C1551 2105 Say(symbol1, symbol2, 2106 nonRecursive1 2107 ? "Module subprogram '%s' has NON_RECURSIVE prefix but" 2108 " the corresponding interface body does not"_err_en_US 2109 : "Module subprogram '%s' does not have NON_RECURSIVE prefix but " 2110 "the corresponding interface body does"_err_en_US); 2111 } 2112 const std::string *bindName1{details1.bindName()}; 2113 const std::string *bindName2{details2.bindName()}; 2114 if (!bindName1 && !bindName2) { 2115 // OK - neither has a binding label 2116 } else if (!bindName1) { 2117 Say(symbol1, symbol2, 2118 "Module subprogram '%s' does not have a binding label but the" 2119 " corresponding interface body does"_err_en_US); 2120 } else if (!bindName2) { 2121 Say(symbol1, symbol2, 2122 "Module subprogram '%s' has a binding label but the" 2123 " corresponding interface body does not"_err_en_US); 2124 } else if (*bindName1 != *bindName2) { 2125 Say(symbol1, symbol2, 2126 "Module subprogram '%s' has binding label '%s' but the corresponding" 2127 " interface body has '%s'"_err_en_US, 2128 *details1.bindName(), *details2.bindName()); 2129 } 2130 const Procedure *proc1{checkHelper.Characterize(symbol1)}; 2131 const Procedure *proc2{checkHelper.Characterize(symbol2)}; 2132 if (!proc1 || !proc2) { 2133 return; 2134 } 2135 if (proc1->functionResult && proc2->functionResult && 2136 *proc1->functionResult != *proc2->functionResult) { 2137 Say(symbol1, symbol2, 2138 "Return type of function '%s' does not match return type of" 2139 " the corresponding interface body"_err_en_US); 2140 } 2141 for (int i{0}; i < nargs1; ++i) { 2142 const Symbol *arg1{args1[i]}; 2143 const Symbol *arg2{args2[i]}; 2144 if (arg1 && !arg2) { 2145 Say(symbol1, symbol2, 2146 "Dummy argument %2$d of '%1$s' is not an alternate return indicator" 2147 " but the corresponding argument in the interface body is"_err_en_US, 2148 i + 1); 2149 } else if (!arg1 && arg2) { 2150 Say(symbol1, symbol2, 2151 "Dummy argument %2$d of '%1$s' is an alternate return indicator but" 2152 " the corresponding argument in the interface body is not"_err_en_US, 2153 i + 1); 2154 } else if (arg1 && arg2) { 2155 SourceName name1{arg1->name()}; 2156 SourceName name2{arg2->name()}; 2157 if (name1 != name2) { 2158 Say(*arg1, *arg2, 2159 "Dummy argument name '%s' does not match corresponding name '%s'" 2160 " in interface body"_err_en_US, 2161 name2); 2162 } else { 2163 CheckDummyArg( 2164 *arg1, *arg2, proc1->dummyArguments[i], proc2->dummyArguments[i]); 2165 } 2166 } 2167 } 2168 } 2169 2170 void SubprogramMatchHelper::CheckDummyArg(const Symbol &symbol1, 2171 const Symbol &symbol2, const DummyArgument &arg1, 2172 const DummyArgument &arg2) { 2173 std::visit(common::visitors{ 2174 [&](const DummyDataObject &obj1, const DummyDataObject &obj2) { 2175 CheckDummyDataObject(symbol1, symbol2, obj1, obj2); 2176 }, 2177 [&](const DummyProcedure &proc1, const DummyProcedure &proc2) { 2178 CheckDummyProcedure(symbol1, symbol2, proc1, proc2); 2179 }, 2180 [&](const DummyDataObject &, const auto &) { 2181 Say(symbol1, symbol2, 2182 "Dummy argument '%s' is a data object; the corresponding" 2183 " argument in the interface body is not"_err_en_US); 2184 }, 2185 [&](const DummyProcedure &, const auto &) { 2186 Say(symbol1, symbol2, 2187 "Dummy argument '%s' is a procedure; the corresponding" 2188 " argument in the interface body is not"_err_en_US); 2189 }, 2190 [&](const auto &, const auto &) { 2191 llvm_unreachable("Dummy arguments are not data objects or" 2192 "procedures"); 2193 }, 2194 }, 2195 arg1.u, arg2.u); 2196 } 2197 2198 void SubprogramMatchHelper::CheckDummyDataObject(const Symbol &symbol1, 2199 const Symbol &symbol2, const DummyDataObject &obj1, 2200 const DummyDataObject &obj2) { 2201 if (!CheckSameIntent(symbol1, symbol2, obj1.intent, obj2.intent)) { 2202 } else if (!CheckSameAttrs(symbol1, symbol2, obj1.attrs, obj2.attrs)) { 2203 } else if (obj1.type.type() != obj2.type.type()) { 2204 Say(symbol1, symbol2, 2205 "Dummy argument '%s' has type %s; the corresponding argument in the" 2206 " interface body has type %s"_err_en_US, 2207 obj1.type.type().AsFortran(), obj2.type.type().AsFortran()); 2208 } else if (!ShapesAreCompatible(obj1, obj2)) { 2209 Say(symbol1, symbol2, 2210 "The shape of dummy argument '%s' does not match the shape of the" 2211 " corresponding argument in the interface body"_err_en_US); 2212 } 2213 // TODO: coshape 2214 } 2215 2216 void SubprogramMatchHelper::CheckDummyProcedure(const Symbol &symbol1, 2217 const Symbol &symbol2, const DummyProcedure &proc1, 2218 const DummyProcedure &proc2) { 2219 if (!CheckSameIntent(symbol1, symbol2, proc1.intent, proc2.intent)) { 2220 } else if (!CheckSameAttrs(symbol1, symbol2, proc1.attrs, proc2.attrs)) { 2221 } else if (proc1 != proc2) { 2222 Say(symbol1, symbol2, 2223 "Dummy procedure '%s' does not match the corresponding argument in" 2224 " the interface body"_err_en_US); 2225 } 2226 } 2227 2228 bool SubprogramMatchHelper::CheckSameIntent(const Symbol &symbol1, 2229 const Symbol &symbol2, common::Intent intent1, common::Intent intent2) { 2230 if (intent1 == intent2) { 2231 return true; 2232 } else { 2233 Say(symbol1, symbol2, 2234 "The intent of dummy argument '%s' does not match the intent" 2235 " of the corresponding argument in the interface body"_err_en_US); 2236 return false; 2237 } 2238 } 2239 2240 // Report an error referring to first symbol with declaration of second symbol 2241 template <typename... A> 2242 void SubprogramMatchHelper::Say(const Symbol &symbol1, const Symbol &symbol2, 2243 parser::MessageFixedText &&text, A &&...args) { 2244 auto &message{context().Say(symbol1.name(), std::move(text), symbol1.name(), 2245 std::forward<A>(args)...)}; 2246 evaluate::AttachDeclaration(message, symbol2); 2247 } 2248 2249 template <typename ATTRS> 2250 bool SubprogramMatchHelper::CheckSameAttrs( 2251 const Symbol &symbol1, const Symbol &symbol2, ATTRS attrs1, ATTRS attrs2) { 2252 if (attrs1 == attrs2) { 2253 return true; 2254 } 2255 attrs1.IterateOverMembers([&](auto attr) { 2256 if (!attrs2.test(attr)) { 2257 Say(symbol1, symbol2, 2258 "Dummy argument '%s' has the %s attribute; the corresponding" 2259 " argument in the interface body does not"_err_en_US, 2260 AsFortran(attr)); 2261 } 2262 }); 2263 attrs2.IterateOverMembers([&](auto attr) { 2264 if (!attrs1.test(attr)) { 2265 Say(symbol1, symbol2, 2266 "Dummy argument '%s' does not have the %s attribute; the" 2267 " corresponding argument in the interface body does"_err_en_US, 2268 AsFortran(attr)); 2269 } 2270 }); 2271 return false; 2272 } 2273 2274 bool SubprogramMatchHelper::ShapesAreCompatible( 2275 const DummyDataObject &obj1, const DummyDataObject &obj2) { 2276 return characteristics::ShapesAreCompatible( 2277 FoldShape(obj1.type.shape()), FoldShape(obj2.type.shape())); 2278 } 2279 2280 evaluate::Shape SubprogramMatchHelper::FoldShape(const evaluate::Shape &shape) { 2281 evaluate::Shape result; 2282 for (const auto &extent : shape) { 2283 result.emplace_back( 2284 evaluate::Fold(context().foldingContext(), common::Clone(extent))); 2285 } 2286 return result; 2287 } 2288 2289 void DistinguishabilityHelper::Add(const Symbol &generic, GenericKind kind, 2290 const Symbol &specific, const Procedure &procedure) { 2291 if (!context_.HasError(specific)) { 2292 nameToInfo_[generic.name()].emplace_back( 2293 ProcedureInfo{kind, specific, procedure}); 2294 } 2295 } 2296 2297 void DistinguishabilityHelper::Check(const Scope &scope) { 2298 for (const auto &[name, info] : nameToInfo_) { 2299 auto count{info.size()}; 2300 for (std::size_t i1{0}; i1 < count - 1; ++i1) { 2301 const auto &[kind, symbol, proc]{info[i1]}; 2302 for (std::size_t i2{i1 + 1}; i2 < count; ++i2) { 2303 auto distinguishable{kind.IsName() 2304 ? evaluate::characteristics::Distinguishable 2305 : evaluate::characteristics::DistinguishableOpOrAssign}; 2306 if (!distinguishable( 2307 context_.languageFeatures(), proc, info[i2].procedure)) { 2308 SayNotDistinguishable(GetTopLevelUnitContaining(scope), name, kind, 2309 symbol, info[i2].symbol); 2310 } 2311 } 2312 } 2313 } 2314 } 2315 2316 void DistinguishabilityHelper::SayNotDistinguishable(const Scope &scope, 2317 const SourceName &name, GenericKind kind, const Symbol &proc1, 2318 const Symbol &proc2) { 2319 std::string name1{proc1.name().ToString()}; 2320 std::string name2{proc2.name().ToString()}; 2321 if (kind.IsOperator() || kind.IsAssignment()) { 2322 // proc1 and proc2 may come from different scopes so qualify their names 2323 if (proc1.owner().IsDerivedType()) { 2324 name1 = proc1.owner().GetName()->ToString() + '%' + name1; 2325 } 2326 if (proc2.owner().IsDerivedType()) { 2327 name2 = proc2.owner().GetName()->ToString() + '%' + name2; 2328 } 2329 } 2330 parser::Message *msg; 2331 if (scope.sourceRange().Contains(name)) { 2332 msg = &context_.Say(name, 2333 "Generic '%s' may not have specific procedures '%s' and '%s' as their interfaces are not distinguishable"_err_en_US, 2334 MakeOpName(name), name1, name2); 2335 } else { 2336 msg = &context_.Say(*GetTopLevelUnitContaining(proc1).GetName(), 2337 "USE-associated generic '%s' may not have specific procedures '%s' and '%s' as their interfaces are not distinguishable"_err_en_US, 2338 MakeOpName(name), name1, name2); 2339 } 2340 AttachDeclaration(*msg, scope, proc1); 2341 AttachDeclaration(*msg, scope, proc2); 2342 } 2343 2344 // `evaluate::AttachDeclaration` doesn't handle the generic case where `proc` 2345 // comes from a different module but is not necessarily use-associated. 2346 void DistinguishabilityHelper::AttachDeclaration( 2347 parser::Message &msg, const Scope &scope, const Symbol &proc) { 2348 const Scope &unit{GetTopLevelUnitContaining(proc)}; 2349 if (unit == scope) { 2350 evaluate::AttachDeclaration(msg, proc); 2351 } else { 2352 msg.Attach(unit.GetName().value(), 2353 "'%s' is USE-associated from module '%s'"_en_US, proc.name(), 2354 unit.GetName().value()); 2355 } 2356 } 2357 2358 void CheckDeclarations(SemanticsContext &context) { 2359 CheckHelper{context}.Check(); 2360 } 2361 } // namespace Fortran::semantics 2362