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