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