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