1 //===-- lib/Semantics/resolve-names-utils.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 "resolve-names-utils.h" 10 #include "flang/Common/Fortran-features.h" 11 #include "flang/Common/Fortran.h" 12 #include "flang/Common/idioms.h" 13 #include "flang/Common/indirection.h" 14 #include "flang/Evaluate/fold.h" 15 #include "flang/Evaluate/tools.h" 16 #include "flang/Evaluate/traverse.h" 17 #include "flang/Evaluate/type.h" 18 #include "flang/Parser/char-block.h" 19 #include "flang/Parser/parse-tree.h" 20 #include "flang/Semantics/expression.h" 21 #include "flang/Semantics/semantics.h" 22 #include "flang/Semantics/tools.h" 23 #include <initializer_list> 24 #include <variant> 25 26 namespace Fortran::semantics { 27 28 using common::LanguageFeature; 29 using common::LogicalOperator; 30 using common::NumericOperator; 31 using common::RelationalOperator; 32 using IntrinsicOperator = parser::DefinedOperator::IntrinsicOperator; 33 34 static constexpr const char *operatorPrefix{"operator("}; 35 36 static GenericKind MapIntrinsicOperator(IntrinsicOperator); 37 38 Symbol *Resolve(const parser::Name &name, Symbol *symbol) { 39 if (symbol && !name.symbol) { 40 name.symbol = symbol; 41 } 42 return symbol; 43 } 44 Symbol &Resolve(const parser::Name &name, Symbol &symbol) { 45 return *Resolve(name, &symbol); 46 } 47 48 parser::MessageFixedText WithSeverity( 49 const parser::MessageFixedText &msg, parser::Severity severity) { 50 return parser::MessageFixedText{ 51 msg.text().begin(), msg.text().size(), severity}; 52 } 53 54 bool IsIntrinsicOperator( 55 const SemanticsContext &context, const SourceName &name) { 56 std::string str{name.ToString()}; 57 for (int i{0}; i != common::LogicalOperator_enumSize; ++i) { 58 auto names{context.languageFeatures().GetNames(LogicalOperator{i})}; 59 if (llvm::is_contained(names, str)) { 60 return true; 61 } 62 } 63 for (int i{0}; i != common::RelationalOperator_enumSize; ++i) { 64 auto names{context.languageFeatures().GetNames(RelationalOperator{i})}; 65 if (llvm::is_contained(names, str)) { 66 return true; 67 } 68 } 69 return false; 70 } 71 72 template <typename E> 73 std::forward_list<std::string> GetOperatorNames( 74 const SemanticsContext &context, E opr) { 75 std::forward_list<std::string> result; 76 for (const char *name : context.languageFeatures().GetNames(opr)) { 77 result.emplace_front(std::string{operatorPrefix} + name + ')'); 78 } 79 return result; 80 } 81 82 std::forward_list<std::string> GetAllNames( 83 const SemanticsContext &context, const SourceName &name) { 84 std::string str{name.ToString()}; 85 if (!name.empty() && name.end()[-1] == ')' && 86 name.ToString().rfind(std::string{operatorPrefix}, 0) == 0) { 87 for (int i{0}; i != common::LogicalOperator_enumSize; ++i) { 88 auto names{GetOperatorNames(context, LogicalOperator{i})}; 89 if (llvm::is_contained(names, str)) { 90 return names; 91 } 92 } 93 for (int i{0}; i != common::RelationalOperator_enumSize; ++i) { 94 auto names{GetOperatorNames(context, RelationalOperator{i})}; 95 if (llvm::is_contained(names, str)) { 96 return names; 97 } 98 } 99 } 100 return {str}; 101 } 102 103 bool IsLogicalConstant( 104 const SemanticsContext &context, const SourceName &name) { 105 std::string str{name.ToString()}; 106 return str == ".true." || str == ".false." || 107 (context.IsEnabled(LanguageFeature::LogicalAbbreviations) && 108 (str == ".t" || str == ".f.")); 109 } 110 111 void GenericSpecInfo::Resolve(Symbol *symbol) const { 112 if (symbol) { 113 if (auto *details{symbol->detailsIf<GenericDetails>()}) { 114 details->set_kind(kind_); 115 } 116 if (parseName_) { 117 semantics::Resolve(*parseName_, symbol); 118 } 119 } 120 } 121 122 void GenericSpecInfo::Analyze(const parser::DefinedOpName &name) { 123 kind_ = GenericKind::OtherKind::DefinedOp; 124 parseName_ = &name.v; 125 symbolName_ = name.v.source; 126 } 127 128 void GenericSpecInfo::Analyze(const parser::GenericSpec &x) { 129 symbolName_ = x.source; 130 kind_ = common::visit( 131 common::visitors{ 132 [&](const parser::Name &y) -> GenericKind { 133 parseName_ = &y; 134 symbolName_ = y.source; 135 return GenericKind::OtherKind::Name; 136 }, 137 [&](const parser::DefinedOperator &y) { 138 return common::visit( 139 common::visitors{ 140 [&](const parser::DefinedOpName &z) -> GenericKind { 141 Analyze(z); 142 return GenericKind::OtherKind::DefinedOp; 143 }, 144 [&](const IntrinsicOperator &z) { 145 return MapIntrinsicOperator(z); 146 }, 147 }, 148 y.u); 149 }, 150 [&](const parser::GenericSpec::Assignment &) -> GenericKind { 151 return GenericKind::OtherKind::Assignment; 152 }, 153 [&](const parser::GenericSpec::ReadFormatted &) -> GenericKind { 154 return common::DefinedIo::ReadFormatted; 155 }, 156 [&](const parser::GenericSpec::ReadUnformatted &) -> GenericKind { 157 return common::DefinedIo::ReadUnformatted; 158 }, 159 [&](const parser::GenericSpec::WriteFormatted &) -> GenericKind { 160 return common::DefinedIo::WriteFormatted; 161 }, 162 [&](const parser::GenericSpec::WriteUnformatted &) -> GenericKind { 163 return common::DefinedIo::WriteUnformatted; 164 }, 165 }, 166 x.u); 167 } 168 169 llvm::raw_ostream &operator<<( 170 llvm::raw_ostream &os, const GenericSpecInfo &info) { 171 os << "GenericSpecInfo: kind=" << info.kind_.ToString(); 172 os << " parseName=" 173 << (info.parseName_ ? info.parseName_->ToString() : "null"); 174 os << " symbolName=" 175 << (info.symbolName_ ? info.symbolName_->ToString() : "null"); 176 return os; 177 } 178 179 // parser::DefinedOperator::IntrinsicOperator -> GenericKind 180 static GenericKind MapIntrinsicOperator(IntrinsicOperator op) { 181 switch (op) { 182 SWITCH_COVERS_ALL_CASES 183 case IntrinsicOperator::Concat: 184 return GenericKind::OtherKind::Concat; 185 case IntrinsicOperator::Power: 186 return NumericOperator::Power; 187 case IntrinsicOperator::Multiply: 188 return NumericOperator::Multiply; 189 case IntrinsicOperator::Divide: 190 return NumericOperator::Divide; 191 case IntrinsicOperator::Add: 192 return NumericOperator::Add; 193 case IntrinsicOperator::Subtract: 194 return NumericOperator::Subtract; 195 case IntrinsicOperator::AND: 196 return LogicalOperator::And; 197 case IntrinsicOperator::OR: 198 return LogicalOperator::Or; 199 case IntrinsicOperator::EQV: 200 return LogicalOperator::Eqv; 201 case IntrinsicOperator::NEQV: 202 return LogicalOperator::Neqv; 203 case IntrinsicOperator::NOT: 204 return LogicalOperator::Not; 205 case IntrinsicOperator::LT: 206 return RelationalOperator::LT; 207 case IntrinsicOperator::LE: 208 return RelationalOperator::LE; 209 case IntrinsicOperator::EQ: 210 return RelationalOperator::EQ; 211 case IntrinsicOperator::NE: 212 return RelationalOperator::NE; 213 case IntrinsicOperator::GE: 214 return RelationalOperator::GE; 215 case IntrinsicOperator::GT: 216 return RelationalOperator::GT; 217 } 218 } 219 220 class ArraySpecAnalyzer { 221 public: 222 ArraySpecAnalyzer(SemanticsContext &context) : context_{context} {} 223 ArraySpec Analyze(const parser::ArraySpec &); 224 ArraySpec AnalyzeDeferredShapeSpecList(const parser::DeferredShapeSpecList &); 225 ArraySpec Analyze(const parser::ComponentArraySpec &); 226 ArraySpec Analyze(const parser::CoarraySpec &); 227 228 private: 229 SemanticsContext &context_; 230 ArraySpec arraySpec_; 231 232 template <typename T> void Analyze(const std::list<T> &list) { 233 for (const auto &elem : list) { 234 Analyze(elem); 235 } 236 } 237 void Analyze(const parser::AssumedShapeSpec &); 238 void Analyze(const parser::ExplicitShapeSpec &); 239 void Analyze(const parser::AssumedImpliedSpec &); 240 void Analyze(const parser::DeferredShapeSpecList &); 241 void Analyze(const parser::AssumedRankSpec &); 242 void MakeExplicit(const std::optional<parser::SpecificationExpr> &, 243 const parser::SpecificationExpr &); 244 void MakeImplied(const std::optional<parser::SpecificationExpr> &); 245 void MakeDeferred(int); 246 Bound GetBound(const std::optional<parser::SpecificationExpr> &); 247 Bound GetBound(const parser::SpecificationExpr &); 248 }; 249 250 ArraySpec AnalyzeArraySpec( 251 SemanticsContext &context, const parser::ArraySpec &arraySpec) { 252 return ArraySpecAnalyzer{context}.Analyze(arraySpec); 253 } 254 ArraySpec AnalyzeArraySpec( 255 SemanticsContext &context, const parser::ComponentArraySpec &arraySpec) { 256 return ArraySpecAnalyzer{context}.Analyze(arraySpec); 257 } 258 ArraySpec AnalyzeDeferredShapeSpecList(SemanticsContext &context, 259 const parser::DeferredShapeSpecList &deferredShapeSpecs) { 260 return ArraySpecAnalyzer{context}.AnalyzeDeferredShapeSpecList( 261 deferredShapeSpecs); 262 } 263 ArraySpec AnalyzeCoarraySpec( 264 SemanticsContext &context, const parser::CoarraySpec &coarraySpec) { 265 return ArraySpecAnalyzer{context}.Analyze(coarraySpec); 266 } 267 268 ArraySpec ArraySpecAnalyzer::Analyze(const parser::ComponentArraySpec &x) { 269 common::visit([this](const auto &y) { Analyze(y); }, x.u); 270 CHECK(!arraySpec_.empty()); 271 return arraySpec_; 272 } 273 ArraySpec ArraySpecAnalyzer::Analyze(const parser::ArraySpec &x) { 274 common::visit(common::visitors{ 275 [&](const parser::AssumedSizeSpec &y) { 276 Analyze( 277 std::get<std::list<parser::ExplicitShapeSpec>>(y.t)); 278 Analyze(std::get<parser::AssumedImpliedSpec>(y.t)); 279 }, 280 [&](const parser::ImpliedShapeSpec &y) { Analyze(y.v); }, 281 [&](const auto &y) { Analyze(y); }, 282 }, 283 x.u); 284 CHECK(!arraySpec_.empty()); 285 return arraySpec_; 286 } 287 ArraySpec ArraySpecAnalyzer::AnalyzeDeferredShapeSpecList( 288 const parser::DeferredShapeSpecList &x) { 289 Analyze(x); 290 CHECK(!arraySpec_.empty()); 291 return arraySpec_; 292 } 293 ArraySpec ArraySpecAnalyzer::Analyze(const parser::CoarraySpec &x) { 294 common::visit( 295 common::visitors{ 296 [&](const parser::DeferredCoshapeSpecList &y) { MakeDeferred(y.v); }, 297 [&](const parser::ExplicitCoshapeSpec &y) { 298 Analyze(std::get<std::list<parser::ExplicitShapeSpec>>(y.t)); 299 MakeImplied( 300 std::get<std::optional<parser::SpecificationExpr>>(y.t)); 301 }, 302 }, 303 x.u); 304 CHECK(!arraySpec_.empty()); 305 return arraySpec_; 306 } 307 308 void ArraySpecAnalyzer::Analyze(const parser::AssumedShapeSpec &x) { 309 arraySpec_.push_back(ShapeSpec::MakeAssumedShape(GetBound(x.v))); 310 } 311 void ArraySpecAnalyzer::Analyze(const parser::ExplicitShapeSpec &x) { 312 MakeExplicit(std::get<std::optional<parser::SpecificationExpr>>(x.t), 313 std::get<parser::SpecificationExpr>(x.t)); 314 } 315 void ArraySpecAnalyzer::Analyze(const parser::AssumedImpliedSpec &x) { 316 MakeImplied(x.v); 317 } 318 void ArraySpecAnalyzer::Analyze(const parser::DeferredShapeSpecList &x) { 319 MakeDeferred(x.v); 320 } 321 void ArraySpecAnalyzer::Analyze(const parser::AssumedRankSpec &) { 322 arraySpec_.push_back(ShapeSpec::MakeAssumedRank()); 323 } 324 325 void ArraySpecAnalyzer::MakeExplicit( 326 const std::optional<parser::SpecificationExpr> &lb, 327 const parser::SpecificationExpr &ub) { 328 arraySpec_.push_back(ShapeSpec::MakeExplicit(GetBound(lb), GetBound(ub))); 329 } 330 void ArraySpecAnalyzer::MakeImplied( 331 const std::optional<parser::SpecificationExpr> &lb) { 332 arraySpec_.push_back(ShapeSpec::MakeImplied(GetBound(lb))); 333 } 334 void ArraySpecAnalyzer::MakeDeferred(int n) { 335 for (int i = 0; i < n; ++i) { 336 arraySpec_.push_back(ShapeSpec::MakeDeferred()); 337 } 338 } 339 340 Bound ArraySpecAnalyzer::GetBound( 341 const std::optional<parser::SpecificationExpr> &x) { 342 return x ? GetBound(*x) : Bound{1}; 343 } 344 Bound ArraySpecAnalyzer::GetBound(const parser::SpecificationExpr &x) { 345 MaybeSubscriptIntExpr expr; 346 if (MaybeExpr maybeExpr{AnalyzeExpr(context_, x.v)}) { 347 if (auto *intExpr{evaluate::UnwrapExpr<SomeIntExpr>(*maybeExpr)}) { 348 expr = evaluate::Fold(context_.foldingContext(), 349 evaluate::ConvertToType<evaluate::SubscriptInteger>( 350 std::move(*intExpr))); 351 } 352 } 353 return Bound{std::move(expr)}; 354 } 355 356 // If src is SAVE (explicitly or implicitly), 357 // set SAVE attribute on all members of dst. 358 static void PropagateSaveAttr( 359 const EquivalenceObject &src, EquivalenceSet &dst) { 360 if (IsSaved(src.symbol)) { 361 for (auto &obj : dst) { 362 if (!obj.symbol.attrs().test(Attr::SAVE)) { 363 obj.symbol.attrs().set(Attr::SAVE); 364 // If the other equivalenced symbol itself is not SAVE, 365 // then adding SAVE here implies that it has to be implicit. 366 obj.symbol.implicitAttrs().set(Attr::SAVE); 367 } 368 } 369 } 370 } 371 static void PropagateSaveAttr(const EquivalenceSet &src, EquivalenceSet &dst) { 372 if (!src.empty()) { 373 PropagateSaveAttr(src.front(), dst); 374 } 375 } 376 377 void EquivalenceSets::AddToSet(const parser::Designator &designator) { 378 if (CheckDesignator(designator)) { 379 if (Symbol * symbol{currObject_.symbol}) { 380 if (!currSet_.empty()) { 381 // check this symbol against first of set for compatibility 382 Symbol &first{currSet_.front().symbol}; 383 CheckCanEquivalence(designator.source, first, *symbol) && 384 CheckCanEquivalence(designator.source, *symbol, first); 385 } 386 auto subscripts{currObject_.subscripts}; 387 if (subscripts.empty()) { 388 if (const ArraySpec * shape{symbol->GetShape()}; 389 shape && shape->IsExplicitShape()) { 390 // record a whole array as its first element 391 for (const ShapeSpec &spec : *shape) { 392 if (auto lbound{spec.lbound().GetExplicit()}) { 393 if (auto lbValue{evaluate::ToInt64(*lbound)}) { 394 subscripts.push_back(*lbValue); 395 continue; 396 } 397 } 398 subscripts.clear(); // error recovery 399 break; 400 } 401 } 402 } 403 auto substringStart{currObject_.substringStart}; 404 currSet_.emplace_back( 405 *symbol, subscripts, substringStart, designator.source); 406 PropagateSaveAttr(currSet_.back(), currSet_); 407 } 408 } 409 currObject_ = {}; 410 } 411 412 void EquivalenceSets::FinishSet(const parser::CharBlock &source) { 413 std::set<std::size_t> existing; // indices of sets intersecting this one 414 for (auto &obj : currSet_) { 415 auto it{objectToSet_.find(obj)}; 416 if (it != objectToSet_.end()) { 417 existing.insert(it->second); // symbol already in this set 418 } 419 } 420 if (existing.empty()) { 421 sets_.push_back({}); // create a new equivalence set 422 MergeInto(source, currSet_, sets_.size() - 1); 423 } else { 424 auto it{existing.begin()}; 425 std::size_t dstIndex{*it}; 426 MergeInto(source, currSet_, dstIndex); 427 while (++it != existing.end()) { 428 MergeInto(source, sets_[*it], dstIndex); 429 } 430 } 431 currSet_.clear(); 432 } 433 434 // Report an error or warning if sym1 and sym2 cannot be in the same equivalence 435 // set. 436 bool EquivalenceSets::CheckCanEquivalence( 437 const parser::CharBlock &source, const Symbol &sym1, const Symbol &sym2) { 438 std::optional<common::LanguageFeature> feature; 439 std::optional<parser::MessageFixedText> msg; 440 const DeclTypeSpec *type1{sym1.GetType()}; 441 const DeclTypeSpec *type2{sym2.GetType()}; 442 bool isDefaultNum1{IsDefaultNumericSequenceType(type1)}; 443 bool isAnyNum1{IsAnyNumericSequenceType(type1)}; 444 bool isDefaultNum2{IsDefaultNumericSequenceType(type2)}; 445 bool isAnyNum2{IsAnyNumericSequenceType(type2)}; 446 bool isChar1{IsCharacterSequenceType(type1)}; 447 bool isChar2{IsCharacterSequenceType(type2)}; 448 if (sym1.attrs().test(Attr::PROTECTED) && 449 !sym2.attrs().test(Attr::PROTECTED)) { // C8114 450 msg = "Equivalence set cannot contain '%s'" 451 " with PROTECTED attribute and '%s' without"_err_en_US; 452 } else if ((isDefaultNum1 && isDefaultNum2) || (isChar1 && isChar2)) { 453 // ok & standard conforming 454 } else if (!(isAnyNum1 || isChar1) && 455 !(isAnyNum2 || isChar2)) { // C8110 - C8113 456 if (AreTkCompatibleTypes(type1, type2)) { 457 msg = 458 "nonstandard: Equivalence set contains '%s' and '%s' with same type that is neither numeric nor character sequence type"_port_en_US; 459 feature = LanguageFeature::EquivalenceSameNonSequence; 460 } else { 461 msg = "Equivalence set cannot contain '%s' and '%s' with distinct types " 462 "that are not both numeric or character sequence types"_err_en_US; 463 } 464 } else if (isAnyNum1) { 465 if (isChar2) { 466 msg = 467 "nonstandard: Equivalence set contains '%s' that is numeric sequence type and '%s' that is character"_port_en_US; 468 feature = LanguageFeature::EquivalenceNumericWithCharacter; 469 } else if (isAnyNum2) { 470 if (isDefaultNum1) { 471 msg = 472 "nonstandard: Equivalence set contains '%s' that is a default " 473 "numeric sequence type and '%s' that is numeric with non-default kind"_port_en_US; 474 } else if (!isDefaultNum2) { 475 msg = "nonstandard: Equivalence set contains '%s' and '%s' that are " 476 "numeric sequence types with non-default kinds"_port_en_US; 477 } 478 feature = LanguageFeature::EquivalenceNonDefaultNumeric; 479 } 480 } 481 if (msg) { 482 if (feature) { 483 context_.Warn( 484 *feature, source, std::move(*msg), sym1.name(), sym2.name()); 485 } else { 486 context_.Say(source, std::move(*msg), sym1.name(), sym2.name()); 487 } 488 return false; 489 } 490 return true; 491 } 492 493 // Move objects from src to sets_[dstIndex] 494 void EquivalenceSets::MergeInto(const parser::CharBlock &source, 495 EquivalenceSet &src, std::size_t dstIndex) { 496 EquivalenceSet &dst{sets_[dstIndex]}; 497 PropagateSaveAttr(dst, src); 498 for (const auto &obj : src) { 499 dst.push_back(obj); 500 objectToSet_[obj] = dstIndex; 501 } 502 PropagateSaveAttr(src, dst); 503 src.clear(); 504 } 505 506 // If set has an object with this symbol, return it. 507 const EquivalenceObject *EquivalenceSets::Find( 508 const EquivalenceSet &set, const Symbol &symbol) { 509 for (const auto &obj : set) { 510 if (obj.symbol == symbol) { 511 return &obj; 512 } 513 } 514 return nullptr; 515 } 516 517 bool EquivalenceSets::CheckDesignator(const parser::Designator &designator) { 518 return common::visit( 519 common::visitors{ 520 [&](const parser::DataRef &x) { 521 return CheckDataRef(designator.source, x); 522 }, 523 [&](const parser::Substring &x) { 524 const auto &dataRef{std::get<parser::DataRef>(x.t)}; 525 const auto &range{std::get<parser::SubstringRange>(x.t)}; 526 bool ok{CheckDataRef(designator.source, dataRef)}; 527 if (const auto &lb{std::get<0>(range.t)}) { 528 ok &= CheckSubstringBound(lb->thing.thing.value(), true); 529 } else { 530 currObject_.substringStart = 1; 531 } 532 if (const auto &ub{std::get<1>(range.t)}) { 533 ok &= CheckSubstringBound(ub->thing.thing.value(), false); 534 } 535 return ok; 536 }, 537 }, 538 designator.u); 539 } 540 541 bool EquivalenceSets::CheckDataRef( 542 const parser::CharBlock &source, const parser::DataRef &x) { 543 return common::visit( 544 common::visitors{ 545 [&](const parser::Name &name) { return CheckObject(name); }, 546 [&](const common::Indirection<parser::StructureComponent> &) { 547 context_.Say(source, // C8107 548 "Derived type component '%s' is not allowed in an equivalence set"_err_en_US, 549 source); 550 return false; 551 }, 552 [&](const common::Indirection<parser::ArrayElement> &elem) { 553 bool ok{CheckDataRef(source, elem.value().base)}; 554 for (const auto &subscript : elem.value().subscripts) { 555 ok &= common::visit( 556 common::visitors{ 557 [&](const parser::SubscriptTriplet &) { 558 context_.Say(source, // C924, R872 559 "Array section '%s' is not allowed in an equivalence set"_err_en_US, 560 source); 561 return false; 562 }, 563 [&](const parser::IntExpr &y) { 564 return CheckArrayBound(y.thing.value()); 565 }, 566 }, 567 subscript.u); 568 } 569 return ok; 570 }, 571 [&](const common::Indirection<parser::CoindexedNamedObject> &) { 572 context_.Say(source, // C924 (R872) 573 "Coindexed object '%s' is not allowed in an equivalence set"_err_en_US, 574 source); 575 return false; 576 }, 577 }, 578 x.u); 579 } 580 581 bool EquivalenceSets::CheckObject(const parser::Name &name) { 582 currObject_.symbol = name.symbol; 583 return currObject_.symbol != nullptr; 584 } 585 586 bool EquivalenceSets::CheckArrayBound(const parser::Expr &bound) { 587 MaybeExpr expr{ 588 evaluate::Fold(context_.foldingContext(), AnalyzeExpr(context_, bound))}; 589 if (!expr) { 590 return false; 591 } 592 if (expr->Rank() > 0) { 593 context_.Say(bound.source, // C924, R872 594 "Array with vector subscript '%s' is not allowed in an equivalence set"_err_en_US, 595 bound.source); 596 return false; 597 } 598 auto subscript{evaluate::ToInt64(*expr)}; 599 if (!subscript) { 600 context_.Say(bound.source, // C8109 601 "Array with nonconstant subscript '%s' is not allowed in an equivalence set"_err_en_US, 602 bound.source); 603 return false; 604 } 605 currObject_.subscripts.push_back(*subscript); 606 return true; 607 } 608 609 bool EquivalenceSets::CheckSubstringBound( 610 const parser::Expr &bound, bool isStart) { 611 MaybeExpr expr{ 612 evaluate::Fold(context_.foldingContext(), AnalyzeExpr(context_, bound))}; 613 if (!expr) { 614 return false; 615 } 616 auto subscript{evaluate::ToInt64(*expr)}; 617 if (!subscript) { 618 context_.Say(bound.source, // C8109 619 "Substring with nonconstant bound '%s' is not allowed in an equivalence set"_err_en_US, 620 bound.source); 621 return false; 622 } 623 if (!isStart) { 624 auto start{currObject_.substringStart}; 625 if (*subscript < (start ? *start : 1)) { 626 context_.Say(bound.source, // C8116 627 "Substring with zero length is not allowed in an equivalence set"_err_en_US); 628 return false; 629 } 630 } else if (*subscript != 1) { 631 currObject_.substringStart = *subscript; 632 } 633 return true; 634 } 635 636 bool EquivalenceSets::IsCharacterSequenceType(const DeclTypeSpec *type) { 637 return IsSequenceType(type, [&](const IntrinsicTypeSpec &type) { 638 auto kind{evaluate::ToInt64(type.kind())}; 639 return type.category() == TypeCategory::Character && kind && 640 kind.value() == context_.GetDefaultKind(TypeCategory::Character); 641 }); 642 } 643 644 // Numeric or logical type of default kind or DOUBLE PRECISION or DOUBLE COMPLEX 645 bool EquivalenceSets::IsDefaultKindNumericType(const IntrinsicTypeSpec &type) { 646 if (auto kind{evaluate::ToInt64(type.kind())}) { 647 switch (type.category()) { 648 case TypeCategory::Integer: 649 case TypeCategory::Logical: 650 return *kind == context_.GetDefaultKind(TypeCategory::Integer); 651 case TypeCategory::Real: 652 case TypeCategory::Complex: 653 return *kind == context_.GetDefaultKind(TypeCategory::Real) || 654 *kind == context_.doublePrecisionKind(); 655 default: 656 return false; 657 } 658 } 659 return false; 660 } 661 662 bool EquivalenceSets::IsDefaultNumericSequenceType(const DeclTypeSpec *type) { 663 return IsSequenceType(type, [&](const IntrinsicTypeSpec &type) { 664 return IsDefaultKindNumericType(type); 665 }); 666 } 667 668 bool EquivalenceSets::IsAnyNumericSequenceType(const DeclTypeSpec *type) { 669 return IsSequenceType(type, [&](const IntrinsicTypeSpec &type) { 670 return type.category() == TypeCategory::Logical || 671 common::IsNumericTypeCategory(type.category()); 672 }); 673 } 674 675 // Is type an intrinsic type that satisfies predicate or a sequence type 676 // whose components do. 677 bool EquivalenceSets::IsSequenceType(const DeclTypeSpec *type, 678 std::function<bool(const IntrinsicTypeSpec &)> predicate) { 679 if (!type) { 680 return false; 681 } else if (const IntrinsicTypeSpec * intrinsic{type->AsIntrinsic()}) { 682 return predicate(*intrinsic); 683 } else if (const DerivedTypeSpec * derived{type->AsDerived()}) { 684 for (const auto &pair : *derived->typeSymbol().scope()) { 685 const Symbol &component{*pair.second}; 686 if (IsAllocatableOrPointer(component) || 687 !IsSequenceType(component.GetType(), predicate)) { 688 return false; 689 } 690 } 691 return true; 692 } else { 693 return false; 694 } 695 } 696 697 // MapSubprogramToNewSymbols() relies on the following recursive symbol/scope 698 // copying infrastructure to duplicate an interface's symbols and map all 699 // of the symbol references in their contained expressions and interfaces 700 // to the new symbols. 701 702 struct SymbolAndTypeMappings { 703 std::map<const Symbol *, const Symbol *> symbolMap; 704 std::map<const DeclTypeSpec *, const DeclTypeSpec *> typeMap; 705 }; 706 707 class SymbolMapper : public evaluate::AnyTraverse<SymbolMapper, bool> { 708 public: 709 using Base = evaluate::AnyTraverse<SymbolMapper, bool>; 710 SymbolMapper(Scope &scope, SymbolAndTypeMappings &map) 711 : Base{*this}, scope_{scope}, map_{map} {} 712 using Base::operator(); 713 bool operator()(const SymbolRef &ref) { 714 if (const Symbol *mapped{MapSymbol(*ref)}) { 715 const_cast<SymbolRef &>(ref) = *mapped; 716 } else if (ref->has<UseDetails>()) { 717 CopySymbol(&*ref); 718 } 719 return false; 720 } 721 bool operator()(const Symbol &x) { 722 if (MapSymbol(x)) { 723 DIE("SymbolMapper hit symbol outside SymbolRef"); 724 } 725 return false; 726 } 727 void MapSymbolExprs(Symbol &); 728 Symbol *CopySymbol(const Symbol *); 729 730 private: 731 void MapParamValue(ParamValue ¶m) { (*this)(param.GetExplicit()); } 732 void MapBound(Bound &bound) { (*this)(bound.GetExplicit()); } 733 void MapShapeSpec(ShapeSpec &spec) { 734 MapBound(spec.lbound()); 735 MapBound(spec.ubound()); 736 } 737 const Symbol *MapSymbol(const Symbol &) const; 738 const Symbol *MapSymbol(const Symbol *) const; 739 const DeclTypeSpec *MapType(const DeclTypeSpec &); 740 const DeclTypeSpec *MapType(const DeclTypeSpec *); 741 const Symbol *MapInterface(const Symbol *); 742 743 Scope &scope_; 744 SymbolAndTypeMappings &map_; 745 }; 746 747 Symbol *SymbolMapper::CopySymbol(const Symbol *symbol) { 748 if (symbol) { 749 if (auto *subp{symbol->detailsIf<SubprogramDetails>()}) { 750 if (subp->isInterface()) { 751 if (auto pair{scope_.try_emplace(symbol->name(), symbol->attrs())}; 752 pair.second) { 753 Symbol ©{*pair.first->second}; 754 map_.symbolMap[symbol] = © 755 copy.set(symbol->test(Symbol::Flag::Subroutine) 756 ? Symbol::Flag::Subroutine 757 : Symbol::Flag::Function); 758 Scope &newScope{scope_.MakeScope(Scope::Kind::Subprogram, ©)}; 759 copy.set_scope(&newScope); 760 copy.set_details(SubprogramDetails{}); 761 auto &newSubp{copy.get<SubprogramDetails>()}; 762 newSubp.set_isInterface(true); 763 newSubp.set_isDummy(subp->isDummy()); 764 newSubp.set_defaultIgnoreTKR(subp->defaultIgnoreTKR()); 765 MapSubprogramToNewSymbols(*symbol, copy, newScope, &map_); 766 return © 767 } 768 } 769 } else if (Symbol * copy{scope_.CopySymbol(*symbol)}) { 770 map_.symbolMap[symbol] = copy; 771 return copy; 772 } 773 } 774 return nullptr; 775 } 776 777 void SymbolMapper::MapSymbolExprs(Symbol &symbol) { 778 common::visit( 779 common::visitors{[&](ObjectEntityDetails &object) { 780 if (const DeclTypeSpec * type{object.type()}) { 781 if (const DeclTypeSpec * newType{MapType(*type)}) { 782 object.ReplaceType(*newType); 783 } 784 } 785 for (ShapeSpec &spec : object.shape()) { 786 MapShapeSpec(spec); 787 } 788 for (ShapeSpec &spec : object.coshape()) { 789 MapShapeSpec(spec); 790 } 791 }, 792 [&](ProcEntityDetails &proc) { 793 if (const Symbol * 794 mappedSymbol{MapInterface(proc.rawProcInterface())}) { 795 proc.set_procInterfaces( 796 *mappedSymbol, BypassGeneric(mappedSymbol->GetUltimate())); 797 } else if (const DeclTypeSpec * mappedType{MapType(proc.type())}) { 798 proc.set_type(*mappedType); 799 } 800 if (proc.init()) { 801 if (const Symbol * mapped{MapSymbol(*proc.init())}) { 802 proc.set_init(*mapped); 803 } 804 } 805 }, 806 [&](const HostAssocDetails &hostAssoc) { 807 if (const Symbol * mapped{MapSymbol(hostAssoc.symbol())}) { 808 symbol.set_details(HostAssocDetails{*mapped}); 809 } 810 }, 811 [](const auto &) {}}, 812 symbol.details()); 813 } 814 815 const Symbol *SymbolMapper::MapSymbol(const Symbol &symbol) const { 816 if (auto iter{map_.symbolMap.find(&symbol)}; iter != map_.symbolMap.end()) { 817 return iter->second; 818 } 819 return nullptr; 820 } 821 822 const Symbol *SymbolMapper::MapSymbol(const Symbol *symbol) const { 823 return symbol ? MapSymbol(*symbol) : nullptr; 824 } 825 826 const DeclTypeSpec *SymbolMapper::MapType(const DeclTypeSpec &type) { 827 if (auto iter{map_.typeMap.find(&type)}; iter != map_.typeMap.end()) { 828 return iter->second; 829 } 830 const DeclTypeSpec *newType{nullptr}; 831 if (type.category() == DeclTypeSpec::Category::Character) { 832 const CharacterTypeSpec &charType{type.characterTypeSpec()}; 833 if (charType.length().GetExplicit()) { 834 ParamValue newLen{charType.length()}; 835 (*this)(newLen.GetExplicit()); 836 newType = &scope_.MakeCharacterType( 837 std::move(newLen), KindExpr{charType.kind()}); 838 } 839 } else if (const DerivedTypeSpec *derived{type.AsDerived()}) { 840 if (!derived->parameters().empty()) { 841 DerivedTypeSpec newDerived{derived->name(), derived->typeSymbol()}; 842 newDerived.CookParameters(scope_.context().foldingContext()); 843 for (const auto &[paramName, paramValue] : derived->parameters()) { 844 ParamValue newParamValue{paramValue}; 845 MapParamValue(newParamValue); 846 newDerived.AddParamValue(paramName, std::move(newParamValue)); 847 } 848 // Scope::InstantiateDerivedTypes() instantiates it later. 849 newType = &scope_.MakeDerivedType(type.category(), std::move(newDerived)); 850 } 851 } 852 if (newType) { 853 map_.typeMap[&type] = newType; 854 } 855 return newType; 856 } 857 858 const DeclTypeSpec *SymbolMapper::MapType(const DeclTypeSpec *type) { 859 return type ? MapType(*type) : nullptr; 860 } 861 862 const Symbol *SymbolMapper::MapInterface(const Symbol *interface) { 863 if (const Symbol *mapped{MapSymbol(interface)}) { 864 return mapped; 865 } 866 if (interface) { 867 if (&interface->owner() != &scope_) { 868 return interface; 869 } else if (const auto *subp{interface->detailsIf<SubprogramDetails>()}; 870 subp && subp->isInterface()) { 871 return CopySymbol(interface); 872 } 873 } 874 return nullptr; 875 } 876 877 void MapSubprogramToNewSymbols(const Symbol &oldSymbol, Symbol &newSymbol, 878 Scope &newScope, SymbolAndTypeMappings *mappings) { 879 SymbolAndTypeMappings newMappings; 880 if (!mappings) { 881 mappings = &newMappings; 882 } 883 mappings->symbolMap[&oldSymbol] = &newSymbol; 884 const auto &oldDetails{oldSymbol.get<SubprogramDetails>()}; 885 auto &newDetails{newSymbol.get<SubprogramDetails>()}; 886 SymbolMapper mapper{newScope, *mappings}; 887 for (const Symbol *dummyArg : oldDetails.dummyArgs()) { 888 if (!dummyArg) { 889 newDetails.add_alternateReturn(); 890 } else if (Symbol * copy{mapper.CopySymbol(dummyArg)}) { 891 copy->set(Symbol::Flag::Implicit, false); 892 newDetails.add_dummyArg(*copy); 893 mappings->symbolMap[dummyArg] = copy; 894 } 895 } 896 if (oldDetails.isFunction()) { 897 newScope.erase(newSymbol.name()); 898 const Symbol &result{oldDetails.result()}; 899 if (Symbol * copy{mapper.CopySymbol(&result)}) { 900 newDetails.set_result(*copy); 901 mappings->symbolMap[&result] = copy; 902 } 903 } 904 for (auto &[_, ref] : newScope) { 905 mapper.MapSymbolExprs(*ref); 906 } 907 newScope.InstantiateDerivedTypes(); 908 } 909 910 } // namespace Fortran::semantics 911