1 //===-- lib/Semantics/tools.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 #include "flang/Parser/tools.h" 10 #include "flang/Common/Fortran.h" 11 #include "flang/Common/indirection.h" 12 #include "flang/Parser/dump-parse-tree.h" 13 #include "flang/Parser/message.h" 14 #include "flang/Parser/parse-tree.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 "llvm/Support/raw_ostream.h" 21 #include <algorithm> 22 #include <set> 23 #include <variant> 24 25 namespace Fortran::semantics { 26 27 // Find this or containing scope that matches predicate 28 static const Scope *FindScopeContaining( 29 const Scope &start, std::function<bool(const Scope &)> predicate) { 30 for (const Scope *scope{&start};; scope = &scope->parent()) { 31 if (predicate(*scope)) { 32 return scope; 33 } 34 if (scope->IsTopLevel()) { 35 return nullptr; 36 } 37 } 38 } 39 40 const Scope &GetTopLevelUnitContaining(const Scope &start) { 41 CHECK(!start.IsTopLevel()); 42 return DEREF(FindScopeContaining( 43 start, [](const Scope &scope) { return scope.parent().IsTopLevel(); })); 44 } 45 46 const Scope &GetTopLevelUnitContaining(const Symbol &symbol) { 47 return GetTopLevelUnitContaining(symbol.owner()); 48 } 49 50 const Scope *FindModuleContaining(const Scope &start) { 51 return FindScopeContaining( 52 start, [](const Scope &scope) { return scope.IsModule(); }); 53 } 54 55 const Scope *FindModuleFileContaining(const Scope &start) { 56 return FindScopeContaining( 57 start, [](const Scope &scope) { return scope.IsModuleFile(); }); 58 } 59 60 const Scope &GetProgramUnitContaining(const Scope &start) { 61 CHECK(!start.IsTopLevel()); 62 return DEREF(FindScopeContaining(start, [](const Scope &scope) { 63 switch (scope.kind()) { 64 case Scope::Kind::Module: 65 case Scope::Kind::MainProgram: 66 case Scope::Kind::Subprogram: 67 case Scope::Kind::BlockData: 68 return true; 69 default: 70 return false; 71 } 72 })); 73 } 74 75 const Scope &GetProgramUnitContaining(const Symbol &symbol) { 76 return GetProgramUnitContaining(symbol.owner()); 77 } 78 79 const Scope *FindPureProcedureContaining(const Scope &start) { 80 // N.B. We only need to examine the innermost containing program unit 81 // because an internal subprogram of a pure subprogram must also 82 // be pure (C1592). 83 if (start.IsTopLevel()) { 84 return nullptr; 85 } else { 86 const Scope &scope{GetProgramUnitContaining(start)}; 87 return IsPureProcedure(scope) ? &scope : nullptr; 88 } 89 } 90 91 // 7.5.2.4 "same derived type" test -- rely on IsTkCompatibleWith() and its 92 // infrastructure to detect and handle comparisons on distinct (but "same") 93 // sequence/bind(C) derived types 94 static bool MightBeSameDerivedType( 95 const std::optional<evaluate::DynamicType> &lhsType, 96 const std::optional<evaluate::DynamicType> &rhsType) { 97 return lhsType && rhsType && rhsType->IsTkCompatibleWith(*lhsType); 98 } 99 100 Tristate IsDefinedAssignment( 101 const std::optional<evaluate::DynamicType> &lhsType, int lhsRank, 102 const std::optional<evaluate::DynamicType> &rhsType, int rhsRank) { 103 if (!lhsType || !rhsType) { 104 return Tristate::No; // error or rhs is untyped 105 } 106 TypeCategory lhsCat{lhsType->category()}; 107 TypeCategory rhsCat{rhsType->category()}; 108 if (rhsRank > 0 && lhsRank != rhsRank) { 109 return Tristate::Yes; 110 } else if (lhsCat != TypeCategory::Derived) { 111 return ToTristate(lhsCat != rhsCat && 112 (!IsNumericTypeCategory(lhsCat) || !IsNumericTypeCategory(rhsCat))); 113 } else if (MightBeSameDerivedType(lhsType, rhsType)) { 114 return Tristate::Maybe; // TYPE(t) = TYPE(t) can be defined or intrinsic 115 } else { 116 return Tristate::Yes; 117 } 118 } 119 120 bool IsIntrinsicRelational(common::RelationalOperator opr, 121 const evaluate::DynamicType &type0, int rank0, 122 const evaluate::DynamicType &type1, int rank1) { 123 if (!evaluate::AreConformable(rank0, rank1)) { 124 return false; 125 } else { 126 auto cat0{type0.category()}; 127 auto cat1{type1.category()}; 128 if (IsNumericTypeCategory(cat0) && IsNumericTypeCategory(cat1)) { 129 // numeric types: EQ/NE always ok, others ok for non-complex 130 return opr == common::RelationalOperator::EQ || 131 opr == common::RelationalOperator::NE || 132 (cat0 != TypeCategory::Complex && cat1 != TypeCategory::Complex); 133 } else { 134 // not both numeric: only Character is ok 135 return cat0 == TypeCategory::Character && cat1 == TypeCategory::Character; 136 } 137 } 138 } 139 140 bool IsIntrinsicNumeric(const evaluate::DynamicType &type0) { 141 return IsNumericTypeCategory(type0.category()); 142 } 143 bool IsIntrinsicNumeric(const evaluate::DynamicType &type0, int rank0, 144 const evaluate::DynamicType &type1, int rank1) { 145 return evaluate::AreConformable(rank0, rank1) && 146 IsNumericTypeCategory(type0.category()) && 147 IsNumericTypeCategory(type1.category()); 148 } 149 150 bool IsIntrinsicLogical(const evaluate::DynamicType &type0) { 151 return type0.category() == TypeCategory::Logical; 152 } 153 bool IsIntrinsicLogical(const evaluate::DynamicType &type0, int rank0, 154 const evaluate::DynamicType &type1, int rank1) { 155 return evaluate::AreConformable(rank0, rank1) && 156 type0.category() == TypeCategory::Logical && 157 type1.category() == TypeCategory::Logical; 158 } 159 160 bool IsIntrinsicConcat(const evaluate::DynamicType &type0, int rank0, 161 const evaluate::DynamicType &type1, int rank1) { 162 return evaluate::AreConformable(rank0, rank1) && 163 type0.category() == TypeCategory::Character && 164 type1.category() == TypeCategory::Character && 165 type0.kind() == type1.kind(); 166 } 167 168 bool IsGenericDefinedOp(const Symbol &symbol) { 169 const Symbol &ultimate{symbol.GetUltimate()}; 170 if (const auto *generic{ultimate.detailsIf<GenericDetails>()}) { 171 return generic->kind().IsDefinedOperator(); 172 } else if (const auto *misc{ultimate.detailsIf<MiscDetails>()}) { 173 return misc->kind() == MiscDetails::Kind::TypeBoundDefinedOp; 174 } else { 175 return false; 176 } 177 } 178 179 bool IsDefinedOperator(SourceName name) { 180 const char *begin{name.begin()}; 181 const char *end{name.end()}; 182 return begin != end && begin[0] == '.' && end[-1] == '.'; 183 } 184 185 std::string MakeOpName(SourceName name) { 186 std::string result{name.ToString()}; 187 return IsDefinedOperator(name) ? "OPERATOR(" + result + ")" 188 : result.find("operator(", 0) == 0 ? parser::ToUpperCaseLetters(result) 189 : result; 190 } 191 192 bool IsCommonBlockContaining(const Symbol &block, const Symbol &object) { 193 const auto &objects{block.get<CommonBlockDetails>().objects()}; 194 auto found{std::find(objects.begin(), objects.end(), object)}; 195 return found != objects.end(); 196 } 197 198 bool IsUseAssociated(const Symbol &symbol, const Scope &scope) { 199 const Scope &owner{GetProgramUnitContaining(symbol.GetUltimate().owner())}; 200 return owner.kind() == Scope::Kind::Module && 201 owner != GetProgramUnitContaining(scope); 202 } 203 204 bool DoesScopeContain( 205 const Scope *maybeAncestor, const Scope &maybeDescendent) { 206 return maybeAncestor && !maybeDescendent.IsTopLevel() && 207 FindScopeContaining(maybeDescendent.parent(), 208 [&](const Scope &scope) { return &scope == maybeAncestor; }); 209 } 210 211 bool DoesScopeContain(const Scope *maybeAncestor, const Symbol &symbol) { 212 return DoesScopeContain(maybeAncestor, symbol.owner()); 213 } 214 215 static const Symbol &FollowHostAssoc(const Symbol &symbol) { 216 for (const Symbol *s{&symbol};;) { 217 const auto *details{s->detailsIf<HostAssocDetails>()}; 218 if (!details) { 219 return *s; 220 } 221 s = &details->symbol(); 222 } 223 } 224 225 bool IsHostAssociated(const Symbol &symbol, const Scope &scope) { 226 const Scope &subprogram{GetProgramUnitContaining(scope)}; 227 return DoesScopeContain( 228 &GetProgramUnitContaining(FollowHostAssoc(symbol)), subprogram); 229 } 230 231 bool IsInStmtFunction(const Symbol &symbol) { 232 if (const Symbol * function{symbol.owner().symbol()}) { 233 return IsStmtFunction(*function); 234 } 235 return false; 236 } 237 238 bool IsStmtFunctionDummy(const Symbol &symbol) { 239 return IsDummy(symbol) && IsInStmtFunction(symbol); 240 } 241 242 bool IsStmtFunctionResult(const Symbol &symbol) { 243 return IsFunctionResult(symbol) && IsInStmtFunction(symbol); 244 } 245 246 bool IsPointerDummy(const Symbol &symbol) { 247 return IsPointer(symbol) && IsDummy(symbol); 248 } 249 250 // proc-name 251 bool IsProcName(const Symbol &symbol) { 252 return symbol.GetUltimate().has<ProcEntityDetails>(); 253 } 254 255 bool IsBindCProcedure(const Symbol &symbol) { 256 if (const auto *procDetails{symbol.detailsIf<ProcEntityDetails>()}) { 257 if (const Symbol * procInterface{procDetails->interface().symbol()}) { 258 // procedure component with a BIND(C) interface 259 return IsBindCProcedure(*procInterface); 260 } 261 } 262 return symbol.attrs().test(Attr::BIND_C) && IsProcedure(symbol); 263 } 264 265 bool IsBindCProcedure(const Scope &scope) { 266 if (const Symbol * symbol{scope.GetSymbol()}) { 267 return IsBindCProcedure(*symbol); 268 } else { 269 return false; 270 } 271 } 272 273 static const Symbol *FindPointerComponent( 274 const Scope &scope, std::set<const Scope *> &visited) { 275 if (!scope.IsDerivedType()) { 276 return nullptr; 277 } 278 if (!visited.insert(&scope).second) { 279 return nullptr; 280 } 281 // If there's a top-level pointer component, return it for clearer error 282 // messaging. 283 for (const auto &pair : scope) { 284 const Symbol &symbol{*pair.second}; 285 if (IsPointer(symbol)) { 286 return &symbol; 287 } 288 } 289 for (const auto &pair : scope) { 290 const Symbol &symbol{*pair.second}; 291 if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) { 292 if (const DeclTypeSpec * type{details->type()}) { 293 if (const DerivedTypeSpec * derived{type->AsDerived()}) { 294 if (const Scope * nested{derived->scope()}) { 295 if (const Symbol * 296 pointer{FindPointerComponent(*nested, visited)}) { 297 return pointer; 298 } 299 } 300 } 301 } 302 } 303 } 304 return nullptr; 305 } 306 307 const Symbol *FindPointerComponent(const Scope &scope) { 308 std::set<const Scope *> visited; 309 return FindPointerComponent(scope, visited); 310 } 311 312 const Symbol *FindPointerComponent(const DerivedTypeSpec &derived) { 313 if (const Scope * scope{derived.scope()}) { 314 return FindPointerComponent(*scope); 315 } else { 316 return nullptr; 317 } 318 } 319 320 const Symbol *FindPointerComponent(const DeclTypeSpec &type) { 321 if (const DerivedTypeSpec * derived{type.AsDerived()}) { 322 return FindPointerComponent(*derived); 323 } else { 324 return nullptr; 325 } 326 } 327 328 const Symbol *FindPointerComponent(const DeclTypeSpec *type) { 329 return type ? FindPointerComponent(*type) : nullptr; 330 } 331 332 const Symbol *FindPointerComponent(const Symbol &symbol) { 333 return IsPointer(symbol) ? &symbol : FindPointerComponent(symbol.GetType()); 334 } 335 336 // C1594 specifies several ways by which an object might be globally visible. 337 const Symbol *FindExternallyVisibleObject( 338 const Symbol &object, const Scope &scope) { 339 // TODO: Storage association with any object for which this predicate holds, 340 // once EQUIVALENCE is supported. 341 const Symbol &ultimate{GetAssociationRoot(object)}; 342 if (IsDummy(ultimate)) { 343 if (IsIntentIn(ultimate)) { 344 return &ultimate; 345 } 346 if (IsPointer(ultimate) && IsPureProcedure(ultimate.owner()) && 347 IsFunction(ultimate.owner())) { 348 return &ultimate; 349 } 350 } else if (&GetProgramUnitContaining(ultimate) != 351 &GetProgramUnitContaining(scope)) { 352 return &object; 353 } else if (const Symbol * block{FindCommonBlockContaining(ultimate)}) { 354 return block; 355 } 356 return nullptr; 357 } 358 359 const Symbol &BypassGeneric(const Symbol &symbol) { 360 const Symbol &ultimate{symbol.GetUltimate()}; 361 if (const auto *generic{ultimate.detailsIf<GenericDetails>()}) { 362 if (const Symbol * specific{generic->specific()}) { 363 return *specific; 364 } 365 } 366 return symbol; 367 } 368 369 bool ExprHasTypeCategory( 370 const SomeExpr &expr, const common::TypeCategory &type) { 371 auto dynamicType{expr.GetType()}; 372 return dynamicType && dynamicType->category() == type; 373 } 374 375 bool ExprTypeKindIsDefault( 376 const SomeExpr &expr, const SemanticsContext &context) { 377 auto dynamicType{expr.GetType()}; 378 return dynamicType && 379 dynamicType->category() != common::TypeCategory::Derived && 380 dynamicType->kind() == context.GetDefaultKind(dynamicType->category()); 381 } 382 383 // If an analyzed expr or assignment is missing, dump the node and die. 384 template <typename T> 385 static void CheckMissingAnalysis(bool absent, const T &x) { 386 if (absent) { 387 std::string buf; 388 llvm::raw_string_ostream ss{buf}; 389 ss << "node has not been analyzed:\n"; 390 parser::DumpTree(ss, x); 391 common::die(ss.str().c_str()); 392 } 393 } 394 395 template <typename T> static const SomeExpr *GetTypedExpr(const T &x) { 396 CheckMissingAnalysis(!x.typedExpr, x); 397 return common::GetPtrFromOptional(x.typedExpr->v); 398 } 399 const SomeExpr *GetExprHelper::Get(const parser::Expr &x) { 400 return GetTypedExpr(x); 401 } 402 const SomeExpr *GetExprHelper::Get(const parser::Variable &x) { 403 return GetTypedExpr(x); 404 } 405 const SomeExpr *GetExprHelper::Get(const parser::DataStmtConstant &x) { 406 return GetTypedExpr(x); 407 } 408 const SomeExpr *GetExprHelper::Get(const parser::AllocateObject &x) { 409 return GetTypedExpr(x); 410 } 411 const SomeExpr *GetExprHelper::Get(const parser::PointerObject &x) { 412 return GetTypedExpr(x); 413 } 414 415 const evaluate::Assignment *GetAssignment(const parser::AssignmentStmt &x) { 416 CheckMissingAnalysis(!x.typedAssignment, x); 417 return common::GetPtrFromOptional(x.typedAssignment->v); 418 } 419 const evaluate::Assignment *GetAssignment( 420 const parser::PointerAssignmentStmt &x) { 421 CheckMissingAnalysis(!x.typedAssignment, x); 422 return common::GetPtrFromOptional(x.typedAssignment->v); 423 } 424 425 const Symbol *FindInterface(const Symbol &symbol) { 426 return std::visit( 427 common::visitors{ 428 [](const ProcEntityDetails &details) { 429 return details.interface().symbol(); 430 }, 431 [](const ProcBindingDetails &details) { return &details.symbol(); }, 432 [](const auto &) -> const Symbol * { return nullptr; }, 433 }, 434 symbol.details()); 435 } 436 437 const Symbol *FindSubprogram(const Symbol &symbol) { 438 return std::visit( 439 common::visitors{ 440 [&](const ProcEntityDetails &details) -> const Symbol * { 441 if (const Symbol * interface{details.interface().symbol()}) { 442 return FindSubprogram(*interface); 443 } else { 444 return &symbol; 445 } 446 }, 447 [](const ProcBindingDetails &details) { 448 return FindSubprogram(details.symbol()); 449 }, 450 [&](const SubprogramDetails &) { return &symbol; }, 451 [](const UseDetails &details) { 452 return FindSubprogram(details.symbol()); 453 }, 454 [](const HostAssocDetails &details) { 455 return FindSubprogram(details.symbol()); 456 }, 457 [](const auto &) -> const Symbol * { return nullptr; }, 458 }, 459 symbol.details()); 460 } 461 462 const Symbol *FindOverriddenBinding(const Symbol &symbol) { 463 if (symbol.has<ProcBindingDetails>()) { 464 if (const DeclTypeSpec * parentType{FindParentTypeSpec(symbol.owner())}) { 465 if (const DerivedTypeSpec * parentDerived{parentType->AsDerived()}) { 466 if (const Scope * parentScope{parentDerived->typeSymbol().scope()}) { 467 return parentScope->FindComponent(symbol.name()); 468 } 469 } 470 } 471 } 472 return nullptr; 473 } 474 475 const DeclTypeSpec *FindParentTypeSpec(const DerivedTypeSpec &derived) { 476 return FindParentTypeSpec(derived.typeSymbol()); 477 } 478 479 const DeclTypeSpec *FindParentTypeSpec(const DeclTypeSpec &decl) { 480 if (const DerivedTypeSpec * derived{decl.AsDerived()}) { 481 return FindParentTypeSpec(*derived); 482 } else { 483 return nullptr; 484 } 485 } 486 487 const DeclTypeSpec *FindParentTypeSpec(const Scope &scope) { 488 if (scope.kind() == Scope::Kind::DerivedType) { 489 if (const auto *symbol{scope.symbol()}) { 490 return FindParentTypeSpec(*symbol); 491 } 492 } 493 return nullptr; 494 } 495 496 const DeclTypeSpec *FindParentTypeSpec(const Symbol &symbol) { 497 if (const Scope * scope{symbol.scope()}) { 498 if (const auto *details{symbol.detailsIf<DerivedTypeDetails>()}) { 499 if (const Symbol * parent{details->GetParentComponent(*scope)}) { 500 return parent->GetType(); 501 } 502 } 503 } 504 return nullptr; 505 } 506 507 const EquivalenceSet *FindEquivalenceSet(const Symbol &symbol) { 508 const Symbol &ultimate{symbol.GetUltimate()}; 509 for (const EquivalenceSet &set : ultimate.owner().equivalenceSets()) { 510 for (const EquivalenceObject &object : set) { 511 if (object.symbol == ultimate) { 512 return &set; 513 } 514 } 515 } 516 return nullptr; 517 } 518 519 bool IsOrContainsEventOrLockComponent(const Symbol &original) { 520 const Symbol &symbol{ResolveAssociations(original)}; 521 if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) { 522 if (const DeclTypeSpec * type{details->type()}) { 523 if (const DerivedTypeSpec * derived{type->AsDerived()}) { 524 return IsEventTypeOrLockType(derived) || 525 FindEventOrLockPotentialComponent(*derived); 526 } 527 } 528 } 529 return false; 530 } 531 532 // Check this symbol suitable as a type-bound procedure - C769 533 bool CanBeTypeBoundProc(const Symbol *symbol) { 534 if (!symbol || IsDummy(*symbol) || IsProcedurePointer(*symbol)) { 535 return false; 536 } else if (symbol->has<SubprogramNameDetails>()) { 537 return symbol->owner().kind() == Scope::Kind::Module; 538 } else if (auto *details{symbol->detailsIf<SubprogramDetails>()}) { 539 return symbol->owner().kind() == Scope::Kind::Module || 540 details->isInterface(); 541 } else if (const auto *proc{symbol->detailsIf<ProcEntityDetails>()}) { 542 return !symbol->attrs().test(Attr::INTRINSIC) && 543 proc->HasExplicitInterface(); 544 } else { 545 return false; 546 } 547 } 548 549 bool HasDeclarationInitializer(const Symbol &symbol) { 550 if (IsNamedConstant(symbol)) { 551 return false; 552 } else if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) { 553 return object->init().has_value(); 554 } else if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}) { 555 return proc->init().has_value(); 556 } else { 557 return false; 558 } 559 } 560 561 bool IsInitialized( 562 const Symbol &symbol, bool ignoreDataStatements, bool ignoreAllocatable) { 563 if (!ignoreAllocatable && IsAllocatable(symbol)) { 564 return true; 565 } else if (!ignoreDataStatements && symbol.test(Symbol::Flag::InDataStmt)) { 566 return true; 567 } else if (HasDeclarationInitializer(symbol)) { 568 return true; 569 } else if (IsNamedConstant(symbol) || IsFunctionResult(symbol) || 570 IsPointer(symbol)) { 571 return false; 572 } else if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) { 573 if (!object->isDummy() && object->type()) { 574 if (const auto *derived{object->type()->AsDerived()}) { 575 return derived->HasDefaultInitialization(ignoreAllocatable); 576 } 577 } 578 } 579 return false; 580 } 581 582 bool IsDestructible(const Symbol &symbol, const Symbol *derivedTypeSymbol) { 583 if (IsAllocatable(symbol) || IsAutomatic(symbol)) { 584 return true; 585 } else if (IsNamedConstant(symbol) || IsFunctionResult(symbol) || 586 IsPointer(symbol)) { 587 return false; 588 } else if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) { 589 if (!object->isDummy() && object->type()) { 590 if (const auto *derived{object->type()->AsDerived()}) { 591 return &derived->typeSymbol() != derivedTypeSymbol && 592 derived->HasDestruction(); 593 } 594 } 595 } 596 return false; 597 } 598 599 bool HasIntrinsicTypeName(const Symbol &symbol) { 600 std::string name{symbol.name().ToString()}; 601 if (name == "doubleprecision") { 602 return true; 603 } else if (name == "derived") { 604 return false; 605 } else { 606 for (int i{0}; i != common::TypeCategory_enumSize; ++i) { 607 if (name == parser::ToLowerCaseLetters(EnumToString(TypeCategory{i}))) { 608 return true; 609 } 610 } 611 return false; 612 } 613 } 614 615 bool IsSeparateModuleProcedureInterface(const Symbol *symbol) { 616 if (symbol && symbol->attrs().test(Attr::MODULE)) { 617 if (auto *details{symbol->detailsIf<SubprogramDetails>()}) { 618 return details->isInterface(); 619 } 620 } 621 return false; 622 } 623 624 bool IsFinalizable( 625 const Symbol &symbol, std::set<const DerivedTypeSpec *> *inProgress) { 626 if (IsPointer(symbol)) { 627 return false; 628 } 629 if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) { 630 if (object->isDummy() && !IsIntentOut(symbol)) { 631 return false; 632 } 633 const DeclTypeSpec *type{object->type()}; 634 const DerivedTypeSpec *typeSpec{type ? type->AsDerived() : nullptr}; 635 return typeSpec && IsFinalizable(*typeSpec, inProgress); 636 } 637 return false; 638 } 639 640 bool IsFinalizable(const DerivedTypeSpec &derived, 641 std::set<const DerivedTypeSpec *> *inProgress) { 642 if (!derived.typeSymbol().get<DerivedTypeDetails>().finals().empty()) { 643 return true; 644 } 645 std::set<const DerivedTypeSpec *> basis; 646 if (inProgress) { 647 if (inProgress->find(&derived) != inProgress->end()) { 648 return false; // don't loop on recursive type 649 } 650 } else { 651 inProgress = &basis; 652 } 653 auto iterator{inProgress->insert(&derived).first}; 654 PotentialComponentIterator components{derived}; 655 bool result{bool{std::find_if( 656 components.begin(), components.end(), [=](const Symbol &component) { 657 return IsFinalizable(component, inProgress); 658 })}}; 659 inProgress->erase(iterator); 660 return result; 661 } 662 663 bool HasImpureFinal(const DerivedTypeSpec &derived) { 664 if (const auto *details{ 665 derived.typeSymbol().detailsIf<DerivedTypeDetails>()}) { 666 const auto &finals{details->finals()}; 667 return std::any_of(finals.begin(), finals.end(), 668 [](const auto &x) { return !x.second->attrs().test(Attr::PURE); }); 669 } else { 670 return false; 671 } 672 } 673 674 bool IsAssumedLengthCharacter(const Symbol &symbol) { 675 if (const DeclTypeSpec * type{symbol.GetType()}) { 676 return type->category() == DeclTypeSpec::Character && 677 type->characterTypeSpec().length().isAssumed(); 678 } else { 679 return false; 680 } 681 } 682 683 bool IsInBlankCommon(const Symbol &symbol) { 684 const Symbol *block{FindCommonBlockContaining(symbol)}; 685 return block && block->name().empty(); 686 } 687 688 // C722 and C723: For a function to be assumed length, it must be external and 689 // of CHARACTER type 690 bool IsExternal(const Symbol &symbol) { 691 return ClassifyProcedure(symbol) == ProcedureDefinitionClass::External; 692 } 693 694 // Most scopes have no EQUIVALENCE, and this function is a fast no-op for them. 695 std::list<std::list<SymbolRef>> GetStorageAssociations(const Scope &scope) { 696 UnorderedSymbolSet distinct; 697 for (const EquivalenceSet &set : scope.equivalenceSets()) { 698 for (const EquivalenceObject &object : set) { 699 distinct.emplace(object.symbol); 700 } 701 } 702 // This set is ordered by ascending offsets, with ties broken by greatest 703 // size. A multiset is used here because multiple symbols may have the 704 // same offset and size; the symbols in the set, however, are distinct. 705 std::multiset<SymbolRef, SymbolOffsetCompare> associated; 706 for (SymbolRef ref : distinct) { 707 associated.emplace(*ref); 708 } 709 std::list<std::list<SymbolRef>> result; 710 std::size_t limit{0}; 711 const Symbol *currentCommon{nullptr}; 712 for (const Symbol &symbol : associated) { 713 const Symbol *thisCommon{FindCommonBlockContaining(symbol)}; 714 if (result.empty() || symbol.offset() >= limit || 715 thisCommon != currentCommon) { 716 // Start a new group 717 result.emplace_back(std::list<SymbolRef>{}); 718 limit = 0; 719 currentCommon = thisCommon; 720 } 721 result.back().emplace_back(symbol); 722 limit = std::max(limit, symbol.offset() + symbol.size()); 723 } 724 return result; 725 } 726 727 bool IsModuleProcedure(const Symbol &symbol) { 728 return ClassifyProcedure(symbol) == ProcedureDefinitionClass::Module; 729 } 730 const Symbol *IsExternalInPureContext( 731 const Symbol &symbol, const Scope &scope) { 732 if (const auto *pureProc{FindPureProcedureContaining(scope)}) { 733 return FindExternallyVisibleObject(symbol.GetUltimate(), *pureProc); 734 } 735 return nullptr; 736 } 737 738 PotentialComponentIterator::const_iterator FindPolymorphicPotentialComponent( 739 const DerivedTypeSpec &derived) { 740 PotentialComponentIterator potentials{derived}; 741 return std::find_if( 742 potentials.begin(), potentials.end(), [](const Symbol &component) { 743 if (const auto *details{component.detailsIf<ObjectEntityDetails>()}) { 744 const DeclTypeSpec *type{details->type()}; 745 return type && type->IsPolymorphic(); 746 } 747 return false; 748 }); 749 } 750 751 bool IsOrContainsPolymorphicComponent(const Symbol &original) { 752 const Symbol &symbol{ResolveAssociations(original)}; 753 if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) { 754 if (const DeclTypeSpec * type{details->type()}) { 755 if (type->IsPolymorphic()) { 756 return true; 757 } 758 if (const DerivedTypeSpec * derived{type->AsDerived()}) { 759 return (bool)FindPolymorphicPotentialComponent(*derived); 760 } 761 } 762 } 763 return false; 764 } 765 766 bool InProtectedContext(const Symbol &symbol, const Scope ¤tScope) { 767 return IsProtected(symbol) && !IsHostAssociated(symbol, currentScope); 768 } 769 770 // C1101 and C1158 771 // Modifiability checks on the leftmost symbol ("base object") 772 // of a data-ref 773 std::optional<parser::MessageFixedText> WhyNotModifiableFirst( 774 const Symbol &symbol, const Scope &scope) { 775 if (symbol.has<AssocEntityDetails>()) { 776 return "'%s' is construct associated with an expression"_en_US; 777 } else if (IsExternalInPureContext(symbol, scope)) { 778 return "'%s' is externally visible and referenced in a pure" 779 " procedure"_en_US; 780 } else if (!IsVariableName(symbol)) { 781 return "'%s' is not a variable"_en_US; 782 } else { 783 return std::nullopt; 784 } 785 } 786 787 // Modifiability checks on the rightmost symbol of a data-ref 788 std::optional<parser::MessageFixedText> WhyNotModifiableLast( 789 const Symbol &symbol, const Scope &scope) { 790 if (IsOrContainsEventOrLockComponent(symbol)) { 791 return "'%s' is an entity with either an EVENT_TYPE or LOCK_TYPE"_en_US; 792 } else { 793 return std::nullopt; 794 } 795 } 796 797 // Modifiability checks on the leftmost (base) symbol of a data-ref 798 // that apply only when there are no pointer components or a base 799 // that is a pointer. 800 std::optional<parser::MessageFixedText> WhyNotModifiableIfNoPtr( 801 const Symbol &symbol, const Scope &scope) { 802 if (InProtectedContext(symbol, scope)) { 803 return "'%s' is protected in this scope"_en_US; 804 } else if (IsIntentIn(symbol)) { 805 return "'%s' is an INTENT(IN) dummy argument"_en_US; 806 } else { 807 return std::nullopt; 808 } 809 } 810 811 // Apply all modifiability checks to a single symbol 812 std::optional<parser::MessageFixedText> WhyNotModifiable( 813 const Symbol &original, const Scope &scope) { 814 const Symbol &symbol{GetAssociationRoot(original)}; 815 if (auto first{WhyNotModifiableFirst(symbol, scope)}) { 816 return first; 817 } else if (auto last{WhyNotModifiableLast(symbol, scope)}) { 818 return last; 819 } else if (!IsPointer(symbol)) { 820 return WhyNotModifiableIfNoPtr(symbol, scope); 821 } else { 822 return std::nullopt; 823 } 824 } 825 826 // Modifiability checks for a data-ref 827 std::optional<parser::Message> WhyNotModifiable(parser::CharBlock at, 828 const SomeExpr &expr, const Scope &scope, bool vectorSubscriptIsOk) { 829 if (auto dataRef{evaluate::ExtractDataRef(expr, true)}) { 830 if (!vectorSubscriptIsOk && evaluate::HasVectorSubscript(expr)) { 831 return parser::Message{at, "Variable has a vector subscript"_en_US}; 832 } 833 const Symbol &first{GetAssociationRoot(dataRef->GetFirstSymbol())}; 834 if (auto maybeWhyFirst{WhyNotModifiableFirst(first, scope)}) { 835 return parser::Message{first.name(), 836 parser::MessageFormattedText{ 837 std::move(*maybeWhyFirst), first.name()}}; 838 } 839 const Symbol &last{dataRef->GetLastSymbol()}; 840 if (auto maybeWhyLast{WhyNotModifiableLast(last, scope)}) { 841 return parser::Message{last.name(), 842 parser::MessageFormattedText{std::move(*maybeWhyLast), last.name()}}; 843 } 844 if (!GetLastPointerSymbol(*dataRef)) { 845 if (auto maybeWhyFirst{WhyNotModifiableIfNoPtr(first, scope)}) { 846 return parser::Message{first.name(), 847 parser::MessageFormattedText{ 848 std::move(*maybeWhyFirst), first.name()}}; 849 } 850 } 851 } else if (!evaluate::IsVariable(expr)) { 852 return parser::Message{ 853 at, "'%s' is not a variable"_en_US, expr.AsFortran()}; 854 } else { 855 // reference to function returning POINTER 856 } 857 return std::nullopt; 858 } 859 860 class ImageControlStmtHelper { 861 using ImageControlStmts = std::variant<parser::ChangeTeamConstruct, 862 parser::CriticalConstruct, parser::EventPostStmt, parser::EventWaitStmt, 863 parser::FormTeamStmt, parser::LockStmt, parser::StopStmt, 864 parser::SyncAllStmt, parser::SyncImagesStmt, parser::SyncMemoryStmt, 865 parser::SyncTeamStmt, parser::UnlockStmt>; 866 867 public: 868 template <typename T> bool operator()(const T &) { 869 return common::HasMember<T, ImageControlStmts>; 870 } 871 template <typename T> bool operator()(const common::Indirection<T> &x) { 872 return (*this)(x.value()); 873 } 874 bool operator()(const parser::AllocateStmt &stmt) { 875 const auto &allocationList{std::get<std::list<parser::Allocation>>(stmt.t)}; 876 for (const auto &allocation : allocationList) { 877 const auto &allocateObject{ 878 std::get<parser::AllocateObject>(allocation.t)}; 879 if (IsCoarrayObject(allocateObject)) { 880 return true; 881 } 882 } 883 return false; 884 } 885 bool operator()(const parser::DeallocateStmt &stmt) { 886 const auto &allocateObjectList{ 887 std::get<std::list<parser::AllocateObject>>(stmt.t)}; 888 for (const auto &allocateObject : allocateObjectList) { 889 if (IsCoarrayObject(allocateObject)) { 890 return true; 891 } 892 } 893 return false; 894 } 895 bool operator()(const parser::CallStmt &stmt) { 896 const auto &procedureDesignator{ 897 std::get<parser::ProcedureDesignator>(stmt.v.t)}; 898 if (auto *name{std::get_if<parser::Name>(&procedureDesignator.u)}) { 899 // TODO: also ensure that the procedure is, in fact, an intrinsic 900 if (name->source == "move_alloc") { 901 const auto &args{std::get<std::list<parser::ActualArgSpec>>(stmt.v.t)}; 902 if (!args.empty()) { 903 const parser::ActualArg &actualArg{ 904 std::get<parser::ActualArg>(args.front().t)}; 905 if (const auto *argExpr{ 906 std::get_if<common::Indirection<parser::Expr>>( 907 &actualArg.u)}) { 908 return HasCoarray(argExpr->value()); 909 } 910 } 911 } 912 } 913 return false; 914 } 915 bool operator()(const parser::Statement<parser::ActionStmt> &stmt) { 916 return std::visit(*this, stmt.statement.u); 917 } 918 919 private: 920 bool IsCoarrayObject(const parser::AllocateObject &allocateObject) { 921 const parser::Name &name{GetLastName(allocateObject)}; 922 return name.symbol && evaluate::IsCoarray(*name.symbol); 923 } 924 }; 925 926 bool IsImageControlStmt(const parser::ExecutableConstruct &construct) { 927 return std::visit(ImageControlStmtHelper{}, construct.u); 928 } 929 930 std::optional<parser::MessageFixedText> GetImageControlStmtCoarrayMsg( 931 const parser::ExecutableConstruct &construct) { 932 if (const auto *actionStmt{ 933 std::get_if<parser::Statement<parser::ActionStmt>>(&construct.u)}) { 934 return std::visit( 935 common::visitors{ 936 [](const common::Indirection<parser::AllocateStmt> &) 937 -> std::optional<parser::MessageFixedText> { 938 return "ALLOCATE of a coarray is an image control" 939 " statement"_en_US; 940 }, 941 [](const common::Indirection<parser::DeallocateStmt> &) 942 -> std::optional<parser::MessageFixedText> { 943 return "DEALLOCATE of a coarray is an image control" 944 " statement"_en_US; 945 }, 946 [](const common::Indirection<parser::CallStmt> &) 947 -> std::optional<parser::MessageFixedText> { 948 return "MOVE_ALLOC of a coarray is an image control" 949 " statement "_en_US; 950 }, 951 [](const auto &) -> std::optional<parser::MessageFixedText> { 952 return std::nullopt; 953 }, 954 }, 955 actionStmt->statement.u); 956 } 957 return std::nullopt; 958 } 959 960 parser::CharBlock GetImageControlStmtLocation( 961 const parser::ExecutableConstruct &executableConstruct) { 962 return std::visit( 963 common::visitors{ 964 [](const common::Indirection<parser::ChangeTeamConstruct> 965 &construct) { 966 return std::get<parser::Statement<parser::ChangeTeamStmt>>( 967 construct.value().t) 968 .source; 969 }, 970 [](const common::Indirection<parser::CriticalConstruct> &construct) { 971 return std::get<parser::Statement<parser::CriticalStmt>>( 972 construct.value().t) 973 .source; 974 }, 975 [](const parser::Statement<parser::ActionStmt> &actionStmt) { 976 return actionStmt.source; 977 }, 978 [](const auto &) { return parser::CharBlock{}; }, 979 }, 980 executableConstruct.u); 981 } 982 983 bool HasCoarray(const parser::Expr &expression) { 984 if (const auto *expr{GetExpr(expression)}) { 985 for (const Symbol &symbol : evaluate::CollectSymbols(*expr)) { 986 if (evaluate::IsCoarray(symbol)) { 987 return true; 988 } 989 } 990 } 991 return false; 992 } 993 994 bool IsPolymorphic(const Symbol &symbol) { 995 if (const DeclTypeSpec * type{symbol.GetType()}) { 996 return type->IsPolymorphic(); 997 } 998 return false; 999 } 1000 1001 bool IsPolymorphicAllocatable(const Symbol &symbol) { 1002 return IsAllocatable(symbol) && IsPolymorphic(symbol); 1003 } 1004 1005 std::optional<parser::MessageFormattedText> CheckAccessibleComponent( 1006 const Scope &scope, const Symbol &symbol) { 1007 CHECK(symbol.owner().IsDerivedType()); // symbol must be a component 1008 if (symbol.attrs().test(Attr::PRIVATE)) { 1009 if (FindModuleFileContaining(scope)) { 1010 // Don't enforce component accessibility checks in module files; 1011 // there may be forward-substituted named constants of derived type 1012 // whose structure constructors reference private components. 1013 } else if (const Scope * 1014 moduleScope{FindModuleContaining(symbol.owner())}) { 1015 if (!moduleScope->Contains(scope)) { 1016 return parser::MessageFormattedText{ 1017 "PRIVATE component '%s' is only accessible within module '%s'"_err_en_US, 1018 symbol.name(), moduleScope->GetName().value()}; 1019 } 1020 } 1021 } 1022 return std::nullopt; 1023 } 1024 1025 std::list<SourceName> OrderParameterNames(const Symbol &typeSymbol) { 1026 std::list<SourceName> result; 1027 if (const DerivedTypeSpec * spec{typeSymbol.GetParentTypeSpec()}) { 1028 result = OrderParameterNames(spec->typeSymbol()); 1029 } 1030 const auto ¶mNames{typeSymbol.get<DerivedTypeDetails>().paramNames()}; 1031 result.insert(result.end(), paramNames.begin(), paramNames.end()); 1032 return result; 1033 } 1034 1035 SymbolVector OrderParameterDeclarations(const Symbol &typeSymbol) { 1036 SymbolVector result; 1037 if (const DerivedTypeSpec * spec{typeSymbol.GetParentTypeSpec()}) { 1038 result = OrderParameterDeclarations(spec->typeSymbol()); 1039 } 1040 const auto ¶mDecls{typeSymbol.get<DerivedTypeDetails>().paramDecls()}; 1041 result.insert(result.end(), paramDecls.begin(), paramDecls.end()); 1042 return result; 1043 } 1044 1045 const DeclTypeSpec &FindOrInstantiateDerivedType( 1046 Scope &scope, DerivedTypeSpec &&spec, DeclTypeSpec::Category category) { 1047 spec.EvaluateParameters(scope.context()); 1048 if (const DeclTypeSpec * 1049 type{scope.FindInstantiatedDerivedType(spec, category)}) { 1050 return *type; 1051 } 1052 // Create a new instantiation of this parameterized derived type 1053 // for this particular distinct set of actual parameter values. 1054 DeclTypeSpec &type{scope.MakeDerivedType(category, std::move(spec))}; 1055 type.derivedTypeSpec().Instantiate(scope); 1056 return type; 1057 } 1058 1059 const Symbol *FindSeparateModuleSubprogramInterface(const Symbol *proc) { 1060 if (proc) { 1061 if (const Symbol * submodule{proc->owner().symbol()}) { 1062 if (const auto *details{submodule->detailsIf<ModuleDetails>()}) { 1063 if (const Scope * ancestor{details->ancestor()}) { 1064 const Symbol *iface{ancestor->FindSymbol(proc->name())}; 1065 if (IsSeparateModuleProcedureInterface(iface)) { 1066 return iface; 1067 } 1068 } 1069 } 1070 } 1071 } 1072 return nullptr; 1073 } 1074 1075 ProcedureDefinitionClass ClassifyProcedure(const Symbol &symbol) { // 15.2.2 1076 const Symbol &ultimate{symbol.GetUltimate()}; 1077 if (ultimate.attrs().test(Attr::INTRINSIC)) { 1078 return ProcedureDefinitionClass::Intrinsic; 1079 } else if (ultimate.attrs().test(Attr::EXTERNAL)) { 1080 return ProcedureDefinitionClass::External; 1081 } else if (const auto *procDetails{ultimate.detailsIf<ProcEntityDetails>()}) { 1082 if (procDetails->isDummy()) { 1083 return ProcedureDefinitionClass::Dummy; 1084 } else if (IsPointer(ultimate)) { 1085 return ProcedureDefinitionClass::Pointer; 1086 } 1087 } else if (const Symbol * subp{FindSubprogram(symbol)}) { 1088 if (const auto *subpDetails{subp->detailsIf<SubprogramDetails>()}) { 1089 if (subpDetails->stmtFunction()) { 1090 return ProcedureDefinitionClass::StatementFunction; 1091 } 1092 } 1093 switch (ultimate.owner().kind()) { 1094 case Scope::Kind::Global: 1095 case Scope::Kind::IntrinsicModules: 1096 return ProcedureDefinitionClass::External; 1097 case Scope::Kind::Module: 1098 return ProcedureDefinitionClass::Module; 1099 case Scope::Kind::MainProgram: 1100 case Scope::Kind::Subprogram: 1101 return ProcedureDefinitionClass::Internal; 1102 default: 1103 break; 1104 } 1105 } 1106 return ProcedureDefinitionClass::None; 1107 } 1108 1109 // ComponentIterator implementation 1110 1111 template <ComponentKind componentKind> 1112 typename ComponentIterator<componentKind>::const_iterator 1113 ComponentIterator<componentKind>::const_iterator::Create( 1114 const DerivedTypeSpec &derived) { 1115 const_iterator it{}; 1116 it.componentPath_.emplace_back(derived); 1117 it.Increment(); // cue up first relevant component, if any 1118 return it; 1119 } 1120 1121 template <ComponentKind componentKind> 1122 const DerivedTypeSpec * 1123 ComponentIterator<componentKind>::const_iterator::PlanComponentTraversal( 1124 const Symbol &component) const { 1125 if (const auto *details{component.detailsIf<ObjectEntityDetails>()}) { 1126 if (const DeclTypeSpec * type{details->type()}) { 1127 if (const auto *derived{type->AsDerived()}) { 1128 bool traverse{false}; 1129 if constexpr (componentKind == ComponentKind::Ordered) { 1130 // Order Component (only visit parents) 1131 traverse = component.test(Symbol::Flag::ParentComp); 1132 } else if constexpr (componentKind == ComponentKind::Direct) { 1133 traverse = !IsAllocatableOrPointer(component); 1134 } else if constexpr (componentKind == ComponentKind::Ultimate) { 1135 traverse = !IsAllocatableOrPointer(component); 1136 } else if constexpr (componentKind == ComponentKind::Potential) { 1137 traverse = !IsPointer(component); 1138 } else if constexpr (componentKind == ComponentKind::Scope) { 1139 traverse = !IsAllocatableOrPointer(component); 1140 } 1141 if (traverse) { 1142 const Symbol &newTypeSymbol{derived->typeSymbol()}; 1143 // Avoid infinite loop if the type is already part of the types 1144 // being visited. It is possible to have "loops in type" because 1145 // C744 does not forbid to use not yet declared type for 1146 // ALLOCATABLE or POINTER components. 1147 for (const auto &node : componentPath_) { 1148 if (&newTypeSymbol == &node.GetTypeSymbol()) { 1149 return nullptr; 1150 } 1151 } 1152 return derived; 1153 } 1154 } 1155 } // intrinsic & unlimited polymorphic not traversable 1156 } 1157 return nullptr; 1158 } 1159 1160 template <ComponentKind componentKind> 1161 static bool StopAtComponentPre(const Symbol &component) { 1162 if constexpr (componentKind == ComponentKind::Ordered) { 1163 // Parent components need to be iterated upon after their 1164 // sub-components in structure constructor analysis. 1165 return !component.test(Symbol::Flag::ParentComp); 1166 } else if constexpr (componentKind == ComponentKind::Direct) { 1167 return true; 1168 } else if constexpr (componentKind == ComponentKind::Ultimate) { 1169 return component.has<ProcEntityDetails>() || 1170 IsAllocatableOrPointer(component) || 1171 (component.get<ObjectEntityDetails>().type() && 1172 component.get<ObjectEntityDetails>().type()->AsIntrinsic()); 1173 } else if constexpr (componentKind == ComponentKind::Potential) { 1174 return !IsPointer(component); 1175 } 1176 } 1177 1178 template <ComponentKind componentKind> 1179 static bool StopAtComponentPost(const Symbol &component) { 1180 return componentKind == ComponentKind::Ordered && 1181 component.test(Symbol::Flag::ParentComp); 1182 } 1183 1184 template <ComponentKind componentKind> 1185 void ComponentIterator<componentKind>::const_iterator::Increment() { 1186 while (!componentPath_.empty()) { 1187 ComponentPathNode &deepest{componentPath_.back()}; 1188 if (deepest.component()) { 1189 if (!deepest.descended()) { 1190 deepest.set_descended(true); 1191 if (const DerivedTypeSpec * 1192 derived{PlanComponentTraversal(*deepest.component())}) { 1193 componentPath_.emplace_back(*derived); 1194 continue; 1195 } 1196 } else if (!deepest.visited()) { 1197 deepest.set_visited(true); 1198 return; // this is the next component to visit, after descending 1199 } 1200 } 1201 auto &nameIterator{deepest.nameIterator()}; 1202 if (nameIterator == deepest.nameEnd()) { 1203 componentPath_.pop_back(); 1204 } else if constexpr (componentKind == ComponentKind::Scope) { 1205 deepest.set_component(*nameIterator++->second); 1206 deepest.set_descended(false); 1207 deepest.set_visited(true); 1208 return; // this is the next component to visit, before descending 1209 } else { 1210 const Scope &scope{deepest.GetScope()}; 1211 auto scopeIter{scope.find(*nameIterator++)}; 1212 if (scopeIter != scope.cend()) { 1213 const Symbol &component{*scopeIter->second}; 1214 deepest.set_component(component); 1215 deepest.set_descended(false); 1216 if (StopAtComponentPre<componentKind>(component)) { 1217 deepest.set_visited(true); 1218 return; // this is the next component to visit, before descending 1219 } else { 1220 deepest.set_visited(!StopAtComponentPost<componentKind>(component)); 1221 } 1222 } 1223 } 1224 } 1225 } 1226 1227 template <ComponentKind componentKind> 1228 std::string 1229 ComponentIterator<componentKind>::const_iterator::BuildResultDesignatorName() 1230 const { 1231 std::string designator{""}; 1232 for (const auto &node : componentPath_) { 1233 designator += "%" + DEREF(node.component()).name().ToString(); 1234 } 1235 return designator; 1236 } 1237 1238 template class ComponentIterator<ComponentKind::Ordered>; 1239 template class ComponentIterator<ComponentKind::Direct>; 1240 template class ComponentIterator<ComponentKind::Ultimate>; 1241 template class ComponentIterator<ComponentKind::Potential>; 1242 template class ComponentIterator<ComponentKind::Scope>; 1243 1244 UltimateComponentIterator::const_iterator FindCoarrayUltimateComponent( 1245 const DerivedTypeSpec &derived) { 1246 UltimateComponentIterator ultimates{derived}; 1247 return std::find_if(ultimates.begin(), ultimates.end(), 1248 [](const Symbol &symbol) { return evaluate::IsCoarray(symbol); }); 1249 } 1250 1251 UltimateComponentIterator::const_iterator FindPointerUltimateComponent( 1252 const DerivedTypeSpec &derived) { 1253 UltimateComponentIterator ultimates{derived}; 1254 return std::find_if(ultimates.begin(), ultimates.end(), IsPointer); 1255 } 1256 1257 PotentialComponentIterator::const_iterator FindEventOrLockPotentialComponent( 1258 const DerivedTypeSpec &derived) { 1259 PotentialComponentIterator potentials{derived}; 1260 return std::find_if( 1261 potentials.begin(), potentials.end(), [](const Symbol &component) { 1262 if (const auto *details{component.detailsIf<ObjectEntityDetails>()}) { 1263 const DeclTypeSpec *type{details->type()}; 1264 return type && IsEventTypeOrLockType(type->AsDerived()); 1265 } 1266 return false; 1267 }); 1268 } 1269 1270 UltimateComponentIterator::const_iterator FindAllocatableUltimateComponent( 1271 const DerivedTypeSpec &derived) { 1272 UltimateComponentIterator ultimates{derived}; 1273 return std::find_if(ultimates.begin(), ultimates.end(), IsAllocatable); 1274 } 1275 1276 DirectComponentIterator::const_iterator FindAllocatableOrPointerDirectComponent( 1277 const DerivedTypeSpec &derived) { 1278 DirectComponentIterator directs{derived}; 1279 return std::find_if(directs.begin(), directs.end(), IsAllocatableOrPointer); 1280 } 1281 1282 UltimateComponentIterator::const_iterator 1283 FindPolymorphicAllocatableUltimateComponent(const DerivedTypeSpec &derived) { 1284 UltimateComponentIterator ultimates{derived}; 1285 return std::find_if( 1286 ultimates.begin(), ultimates.end(), IsPolymorphicAllocatable); 1287 } 1288 1289 UltimateComponentIterator::const_iterator 1290 FindPolymorphicAllocatableNonCoarrayUltimateComponent( 1291 const DerivedTypeSpec &derived) { 1292 UltimateComponentIterator ultimates{derived}; 1293 return std::find_if(ultimates.begin(), ultimates.end(), [](const Symbol &x) { 1294 return IsPolymorphicAllocatable(x) && !evaluate::IsCoarray(x); 1295 }); 1296 } 1297 1298 const Symbol *FindUltimateComponent(const DerivedTypeSpec &derived, 1299 const std::function<bool(const Symbol &)> &predicate) { 1300 UltimateComponentIterator ultimates{derived}; 1301 if (auto it{std::find_if(ultimates.begin(), ultimates.end(), 1302 [&predicate](const Symbol &component) -> bool { 1303 return predicate(component); 1304 })}) { 1305 return &*it; 1306 } 1307 return nullptr; 1308 } 1309 1310 const Symbol *FindUltimateComponent(const Symbol &symbol, 1311 const std::function<bool(const Symbol &)> &predicate) { 1312 if (predicate(symbol)) { 1313 return &symbol; 1314 } else if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) { 1315 if (const auto *type{object->type()}) { 1316 if (const auto *derived{type->AsDerived()}) { 1317 return FindUltimateComponent(*derived, predicate); 1318 } 1319 } 1320 } 1321 return nullptr; 1322 } 1323 1324 const Symbol *FindImmediateComponent(const DerivedTypeSpec &type, 1325 const std::function<bool(const Symbol &)> &predicate) { 1326 if (const Scope * scope{type.scope()}) { 1327 const Symbol *parent{nullptr}; 1328 for (const auto &pair : *scope) { 1329 const Symbol *symbol{&*pair.second}; 1330 if (predicate(*symbol)) { 1331 return symbol; 1332 } 1333 if (symbol->test(Symbol::Flag::ParentComp)) { 1334 parent = symbol; 1335 } 1336 } 1337 if (parent) { 1338 if (const auto *object{parent->detailsIf<ObjectEntityDetails>()}) { 1339 if (const auto *type{object->type()}) { 1340 if (const auto *derived{type->AsDerived()}) { 1341 return FindImmediateComponent(*derived, predicate); 1342 } 1343 } 1344 } 1345 } 1346 } 1347 return nullptr; 1348 } 1349 1350 const Symbol *IsFunctionResultWithSameNameAsFunction(const Symbol &symbol) { 1351 if (IsFunctionResult(symbol)) { 1352 if (const Symbol * function{symbol.owner().symbol()}) { 1353 if (symbol.name() == function->name()) { 1354 return function; 1355 } 1356 } 1357 } 1358 return nullptr; 1359 } 1360 1361 void LabelEnforce::Post(const parser::GotoStmt &gotoStmt) { 1362 checkLabelUse(gotoStmt.v); 1363 } 1364 void LabelEnforce::Post(const parser::ComputedGotoStmt &computedGotoStmt) { 1365 for (auto &i : std::get<std::list<parser::Label>>(computedGotoStmt.t)) { 1366 checkLabelUse(i); 1367 } 1368 } 1369 1370 void LabelEnforce::Post(const parser::ArithmeticIfStmt &arithmeticIfStmt) { 1371 checkLabelUse(std::get<1>(arithmeticIfStmt.t)); 1372 checkLabelUse(std::get<2>(arithmeticIfStmt.t)); 1373 checkLabelUse(std::get<3>(arithmeticIfStmt.t)); 1374 } 1375 1376 void LabelEnforce::Post(const parser::AssignStmt &assignStmt) { 1377 checkLabelUse(std::get<parser::Label>(assignStmt.t)); 1378 } 1379 1380 void LabelEnforce::Post(const parser::AssignedGotoStmt &assignedGotoStmt) { 1381 for (auto &i : std::get<std::list<parser::Label>>(assignedGotoStmt.t)) { 1382 checkLabelUse(i); 1383 } 1384 } 1385 1386 void LabelEnforce::Post(const parser::AltReturnSpec &altReturnSpec) { 1387 checkLabelUse(altReturnSpec.v); 1388 } 1389 1390 void LabelEnforce::Post(const parser::ErrLabel &errLabel) { 1391 checkLabelUse(errLabel.v); 1392 } 1393 void LabelEnforce::Post(const parser::EndLabel &endLabel) { 1394 checkLabelUse(endLabel.v); 1395 } 1396 void LabelEnforce::Post(const parser::EorLabel &eorLabel) { 1397 checkLabelUse(eorLabel.v); 1398 } 1399 1400 void LabelEnforce::checkLabelUse(const parser::Label &labelUsed) { 1401 if (labels_.find(labelUsed) == labels_.end()) { 1402 SayWithConstruct(context_, currentStatementSourcePosition_, 1403 parser::MessageFormattedText{ 1404 "Control flow escapes from %s"_err_en_US, construct_}, 1405 constructSourcePosition_); 1406 } 1407 } 1408 1409 parser::MessageFormattedText LabelEnforce::GetEnclosingConstructMsg() { 1410 return {"Enclosing %s statement"_en_US, construct_}; 1411 } 1412 1413 void LabelEnforce::SayWithConstruct(SemanticsContext &context, 1414 parser::CharBlock stmtLocation, parser::MessageFormattedText &&message, 1415 parser::CharBlock constructLocation) { 1416 context.Say(stmtLocation, message) 1417 .Attach(constructLocation, GetEnclosingConstructMsg()); 1418 } 1419 1420 bool HasAlternateReturns(const Symbol &subprogram) { 1421 for (const auto *dummyArg : subprogram.get<SubprogramDetails>().dummyArgs()) { 1422 if (!dummyArg) { 1423 return true; 1424 } 1425 } 1426 return false; 1427 } 1428 1429 bool InCommonBlock(const Symbol &symbol) { 1430 const auto *details{symbol.detailsIf<ObjectEntityDetails>()}; 1431 return details && details->commonBlock(); 1432 } 1433 1434 const std::optional<parser::Name> &MaybeGetNodeName( 1435 const ConstructNode &construct) { 1436 return std::visit( 1437 common::visitors{ 1438 [&](const parser::BlockConstruct *blockConstruct) 1439 -> const std::optional<parser::Name> & { 1440 return std::get<0>(blockConstruct->t).statement.v; 1441 }, 1442 [&](const auto *a) -> const std::optional<parser::Name> & { 1443 return std::get<0>(std::get<0>(a->t).statement.t); 1444 }, 1445 }, 1446 construct); 1447 } 1448 1449 std::optional<ArraySpec> ToArraySpec( 1450 evaluate::FoldingContext &context, const evaluate::Shape &shape) { 1451 if (auto extents{evaluate::AsConstantExtents(context, shape)}) { 1452 ArraySpec result; 1453 for (const auto &extent : *extents) { 1454 result.emplace_back(ShapeSpec::MakeExplicit(Bound{extent})); 1455 } 1456 return {std::move(result)}; 1457 } else { 1458 return std::nullopt; 1459 } 1460 } 1461 1462 std::optional<ArraySpec> ToArraySpec(evaluate::FoldingContext &context, 1463 const std::optional<evaluate::Shape> &shape) { 1464 return shape ? ToArraySpec(context, *shape) : std::nullopt; 1465 } 1466 1467 bool HasDefinedIo(GenericKind::DefinedIo which, const DerivedTypeSpec &derived, 1468 const Scope *scope) { 1469 if (const Scope * dtScope{derived.scope()}) { 1470 for (const auto &pair : *dtScope) { 1471 const Symbol &symbol{*pair.second}; 1472 if (const auto *generic{symbol.detailsIf<GenericDetails>()}) { 1473 GenericKind kind{generic->kind()}; 1474 if (const auto *io{std::get_if<GenericKind::DefinedIo>(&kind.u)}) { 1475 if (*io == which) { 1476 return true; // type-bound GENERIC exists 1477 } 1478 } 1479 } 1480 } 1481 } 1482 if (scope) { 1483 SourceName name{GenericKind::AsFortran(which)}; 1484 evaluate::DynamicType dyDerived{derived}; 1485 for (; scope && !scope->IsGlobal(); scope = &scope->parent()) { 1486 auto iter{scope->find(name)}; 1487 if (iter != scope->end()) { 1488 const auto &generic{iter->second->GetUltimate().get<GenericDetails>()}; 1489 for (auto ref : generic.specificProcs()) { 1490 const Symbol &procSym{ref->GetUltimate()}; 1491 if (const auto *subp{procSym.detailsIf<SubprogramDetails>()}) { 1492 if (!subp->dummyArgs().empty()) { 1493 if (const Symbol * first{subp->dummyArgs().at(0)}) { 1494 if (const DeclTypeSpec * dtSpec{first->GetType()}) { 1495 if (auto dyDummy{evaluate::DynamicType::From(*dtSpec)}) { 1496 if (dyDummy->IsTkCompatibleWith(dyDerived)) { 1497 return true; // GENERIC or INTERFACE not in type 1498 } 1499 } 1500 } 1501 } 1502 } 1503 } 1504 } 1505 } 1506 } 1507 } 1508 return false; 1509 } 1510 1511 const Symbol *FindUnsafeIoDirectComponent(GenericKind::DefinedIo which, 1512 const DerivedTypeSpec &derived, const Scope *scope) { 1513 if (HasDefinedIo(which, derived, scope)) { 1514 return nullptr; 1515 } 1516 if (const Scope * dtScope{derived.scope()}) { 1517 for (const auto &pair : *dtScope) { 1518 const Symbol &symbol{*pair.second}; 1519 if (IsAllocatableOrPointer(symbol)) { 1520 return &symbol; 1521 } 1522 if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) { 1523 if (const DeclTypeSpec * type{details->type()}) { 1524 if (type->category() == DeclTypeSpec::Category::TypeDerived) { 1525 if (const Symbol * 1526 bad{FindUnsafeIoDirectComponent( 1527 which, type->derivedTypeSpec(), scope)}) { 1528 return bad; 1529 } 1530 } 1531 } 1532 } 1533 } 1534 } 1535 return nullptr; 1536 } 1537 1538 } // namespace Fortran::semantics 1539