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