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