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