1 //===-- lib/Semantics/resolve-labels.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-labels.h" 10 #include "flang/Common/enum-set.h" 11 #include "flang/Common/template.h" 12 #include "flang/Parser/parse-tree-visitor.h" 13 #include "flang/Semantics/semantics.h" 14 #include <cctype> 15 #include <cstdarg> 16 #include <type_traits> 17 18 namespace Fortran::semantics { 19 20 using namespace parser::literals; 21 22 ENUM_CLASS( 23 TargetStatementEnum, Do, Branch, Format, CompatibleDo, CompatibleBranch) 24 using LabeledStmtClassificationSet = 25 common::EnumSet<TargetStatementEnum, TargetStatementEnum_enumSize>; 26 27 using IndexList = std::vector<std::pair<parser::CharBlock, parser::CharBlock>>; 28 // A ProxyForScope is an integral proxy for a Fortran scope. This is required 29 // because the parse tree does not actually have the scopes required. 30 using ProxyForScope = unsigned; 31 // Minimal scope information 32 struct ScopeInfo { 33 ProxyForScope parent{}; 34 bool isExteriorGotoFatal{false}; 35 int depth{0}; 36 }; 37 struct LabeledStatementInfoTuplePOD { 38 ProxyForScope proxyForScope; 39 parser::CharBlock parserCharBlock; 40 LabeledStmtClassificationSet labeledStmtClassificationSet; 41 bool isExecutableConstructEndStmt; 42 }; 43 using TargetStmtMap = std::map<parser::Label, LabeledStatementInfoTuplePOD>; 44 struct SourceStatementInfoTuplePOD { 45 SourceStatementInfoTuplePOD(const parser::Label &parserLabel, 46 const ProxyForScope &proxyForScope, 47 const parser::CharBlock &parserCharBlock) 48 : parserLabel{parserLabel}, proxyForScope{proxyForScope}, 49 parserCharBlock{parserCharBlock} {} 50 parser::Label parserLabel; 51 ProxyForScope proxyForScope; 52 parser::CharBlock parserCharBlock; 53 }; 54 using SourceStmtList = std::vector<SourceStatementInfoTuplePOD>; 55 enum class Legality { never, always, formerly }; 56 57 bool HasScope(ProxyForScope scope) { return scope != ProxyForScope{0u}; } 58 59 // F18:R1131 60 template <typename A> 61 constexpr Legality IsLegalDoTerm(const parser::Statement<A> &) { 62 if (std::is_same_v<A, common::Indirection<parser::EndDoStmt>> || 63 std::is_same_v<A, parser::EndDoStmt>) { 64 return Legality::always; 65 } else if (std::is_same_v<A, parser::EndForallStmt> || 66 std::is_same_v<A, parser::EndWhereStmt>) { 67 // Executable construct end statements are also supported as 68 // an extension but they need special care because the associated 69 // construct create their own scope. 70 return Legality::formerly; 71 } else { 72 return Legality::never; 73 } 74 } 75 76 constexpr Legality IsLegalDoTerm( 77 const parser::Statement<parser::ActionStmt> &actionStmt) { 78 if (std::holds_alternative<parser::ContinueStmt>(actionStmt.statement.u)) { 79 // See F08:C816 80 return Legality::always; 81 } else if (!(std::holds_alternative< 82 common::Indirection<parser::ArithmeticIfStmt>>( 83 actionStmt.statement.u) || 84 std::holds_alternative<common::Indirection<parser::CycleStmt>>( 85 actionStmt.statement.u) || 86 std::holds_alternative<common::Indirection<parser::ExitStmt>>( 87 actionStmt.statement.u) || 88 std::holds_alternative<common::Indirection<parser::StopStmt>>( 89 actionStmt.statement.u) || 90 std::holds_alternative<common::Indirection<parser::GotoStmt>>( 91 actionStmt.statement.u) || 92 std::holds_alternative< 93 common::Indirection<parser::ReturnStmt>>( 94 actionStmt.statement.u))) { 95 return Legality::formerly; 96 } else { 97 return Legality::never; 98 } 99 } 100 101 template <typename A> constexpr bool IsFormat(const parser::Statement<A> &) { 102 return std::is_same_v<A, common::Indirection<parser::FormatStmt>>; 103 } 104 105 template <typename A> 106 constexpr Legality IsLegalBranchTarget(const parser::Statement<A> &) { 107 if (std::is_same_v<A, parser::ActionStmt> || 108 std::is_same_v<A, parser::AssociateStmt> || 109 std::is_same_v<A, parser::EndAssociateStmt> || 110 std::is_same_v<A, parser::IfThenStmt> || 111 std::is_same_v<A, parser::EndIfStmt> || 112 std::is_same_v<A, parser::SelectCaseStmt> || 113 std::is_same_v<A, parser::EndSelectStmt> || 114 std::is_same_v<A, parser::SelectRankStmt> || 115 std::is_same_v<A, parser::SelectTypeStmt> || 116 std::is_same_v<A, common::Indirection<parser::LabelDoStmt>> || 117 std::is_same_v<A, parser::NonLabelDoStmt> || 118 std::is_same_v<A, parser::EndDoStmt> || 119 std::is_same_v<A, common::Indirection<parser::EndDoStmt>> || 120 std::is_same_v<A, parser::BlockStmt> || 121 std::is_same_v<A, parser::EndBlockStmt> || 122 std::is_same_v<A, parser::CriticalStmt> || 123 std::is_same_v<A, parser::EndCriticalStmt> || 124 std::is_same_v<A, parser::ForallConstructStmt> || 125 std::is_same_v<A, parser::WhereConstructStmt> || 126 std::is_same_v<A, parser::EndFunctionStmt> || 127 std::is_same_v<A, parser::EndMpSubprogramStmt> || 128 std::is_same_v<A, parser::EndProgramStmt> || 129 std::is_same_v<A, parser::EndSubroutineStmt>) { 130 return Legality::always; 131 } else { 132 return Legality::never; 133 } 134 } 135 136 template <typename A> 137 constexpr LabeledStmtClassificationSet ConstructBranchTargetFlags( 138 const parser::Statement<A> &statement) { 139 LabeledStmtClassificationSet labeledStmtClassificationSet{}; 140 if (IsLegalDoTerm(statement) == Legality::always) { 141 labeledStmtClassificationSet.set(TargetStatementEnum::Do); 142 } else if (IsLegalDoTerm(statement) == Legality::formerly) { 143 labeledStmtClassificationSet.set(TargetStatementEnum::CompatibleDo); 144 } 145 if (IsLegalBranchTarget(statement) == Legality::always) { 146 labeledStmtClassificationSet.set(TargetStatementEnum::Branch); 147 } else if (IsLegalBranchTarget(statement) == Legality::formerly) { 148 labeledStmtClassificationSet.set(TargetStatementEnum::CompatibleBranch); 149 } 150 if (IsFormat(statement)) { 151 labeledStmtClassificationSet.set(TargetStatementEnum::Format); 152 } 153 return labeledStmtClassificationSet; 154 } 155 156 static unsigned SayLabel(parser::Label label) { 157 return static_cast<unsigned>(label); 158 } 159 160 struct UnitAnalysis { 161 UnitAnalysis() { scopeModel.emplace_back(); } 162 163 SourceStmtList doStmtSources; 164 SourceStmtList formatStmtSources; 165 SourceStmtList otherStmtSources; 166 SourceStmtList assignStmtSources; 167 TargetStmtMap targetStmts; 168 std::vector<ScopeInfo> scopeModel; 169 }; 170 171 // Some parse tree record for statements simply wrap construct names; 172 // others include them as tuple components. Given a statement, 173 // return a pointer to its name if it has one. 174 template <typename A> 175 const parser::CharBlock *GetStmtName(const parser::Statement<A> &stmt) { 176 const std::optional<parser::Name> *name{nullptr}; 177 if constexpr (WrapperTrait<A>) { 178 if constexpr (std::is_same_v<decltype(A::v), parser::Name>) { 179 return &stmt.statement.v.source; 180 } else { 181 name = &stmt.statement.v; 182 } 183 } else if constexpr (std::is_same_v<A, parser::SelectRankStmt> || 184 std::is_same_v<A, parser::SelectTypeStmt>) { 185 name = &std::get<0>(stmt.statement.t); 186 } else if constexpr (common::HasMember<parser::Name, 187 decltype(stmt.statement.t)>) { 188 return &std::get<parser::Name>(stmt.statement.t).source; 189 } else { 190 name = &std::get<std::optional<parser::Name>>(stmt.statement.t); 191 } 192 if (name && *name) { 193 return &(*name)->source; 194 } 195 return nullptr; 196 } 197 198 class ParseTreeAnalyzer { 199 public: 200 ParseTreeAnalyzer(ParseTreeAnalyzer &&that) = default; 201 ParseTreeAnalyzer(SemanticsContext &context) : context_{context} {} 202 203 template <typename A> constexpr bool Pre(const A &x) { 204 using LabeledProgramUnitStmts = 205 std::tuple<parser::MainProgram, parser::FunctionSubprogram, 206 parser::SubroutineSubprogram, parser::SeparateModuleSubprogram>; 207 if constexpr (common::HasMember<A, LabeledProgramUnitStmts>) { 208 const auto &endStmt{std::get<std::tuple_size_v<decltype(x.t)> - 1>(x.t)}; 209 if (endStmt.label) { 210 // The END statement for a subprogram appears after any internal 211 // subprograms. Visit that statement in advance so that results 212 // are placed in the correct programUnits_ slot. 213 auto targetFlags{ConstructBranchTargetFlags(endStmt)}; 214 AddTargetLabelDefinition( 215 endStmt.label.value(), targetFlags, currentScope_); 216 } 217 } 218 return true; 219 } 220 template <typename A> constexpr void Post(const A &) {} 221 222 template <typename A> bool Pre(const parser::Statement<A> &statement) { 223 currentPosition_ = statement.source; 224 const auto &label = statement.label; 225 if (!label) { 226 return true; 227 } 228 using LabeledConstructStmts = std::tuple<parser::AssociateStmt, 229 parser::BlockStmt, parser::ChangeTeamStmt, parser::CriticalStmt, 230 parser::IfThenStmt, parser::NonLabelDoStmt, parser::SelectCaseStmt, 231 parser::SelectRankStmt, parser::SelectTypeStmt, 232 parser::ForallConstructStmt, parser::WhereConstructStmt>; 233 using LabeledConstructEndStmts = std::tuple<parser::EndAssociateStmt, 234 parser::EndBlockStmt, parser::EndChangeTeamStmt, 235 parser::EndCriticalStmt, parser::EndDoStmt, parser::EndForallStmt, 236 parser::EndIfStmt, parser::EndSelectStmt, parser::EndWhereStmt>; 237 using LabeledProgramUnitEndStmts = 238 std::tuple<parser::EndFunctionStmt, parser::EndMpSubprogramStmt, 239 parser::EndProgramStmt, parser::EndSubroutineStmt>; 240 auto targetFlags{ConstructBranchTargetFlags(statement)}; 241 if constexpr (common::HasMember<A, LabeledConstructStmts>) { 242 AddTargetLabelDefinition(label.value(), targetFlags, ParentScope()); 243 } else if constexpr (common::HasMember<A, LabeledConstructEndStmts>) { 244 constexpr bool isExecutableConstructEndStmt{true}; 245 AddTargetLabelDefinition(label.value(), targetFlags, currentScope_, 246 isExecutableConstructEndStmt); 247 } else if constexpr (!common::HasMember<A, LabeledProgramUnitEndStmts>) { 248 // Program unit END statements have already been processed. 249 AddTargetLabelDefinition(label.value(), targetFlags, currentScope_); 250 } 251 return true; 252 } 253 254 // see 11.1.1 255 bool Pre(const parser::ProgramUnit &) { return InitializeNewScopeContext(); } 256 bool Pre(const parser::InternalSubprogram &) { 257 return InitializeNewScopeContext(); 258 } 259 bool Pre(const parser::ModuleSubprogram &) { 260 return InitializeNewScopeContext(); 261 } 262 bool Pre(const parser::AssociateConstruct &associateConstruct) { 263 return PushConstructName(associateConstruct); 264 } 265 bool Pre(const parser::BlockConstruct &blockConstruct) { 266 return PushConstructName(blockConstruct); 267 } 268 bool Pre(const parser::ChangeTeamConstruct &changeTeamConstruct) { 269 return PushConstructName(changeTeamConstruct); 270 } 271 bool Pre(const parser::CriticalConstruct &criticalConstruct) { 272 return PushConstructName(criticalConstruct); 273 } 274 bool Pre(const parser::DoConstruct &doConstruct) { 275 return PushConstructName(doConstruct); 276 } 277 bool Pre(const parser::IfConstruct &ifConstruct) { 278 return PushConstructName(ifConstruct); 279 } 280 bool Pre(const parser::IfConstruct::ElseIfBlock &) { 281 return SwitchToNewScope(); 282 } 283 bool Pre(const parser::IfConstruct::ElseBlock &) { 284 return SwitchToNewScope(); 285 } 286 bool Pre(const parser::CaseConstruct &caseConstruct) { 287 return PushConstructName(caseConstruct); 288 } 289 bool Pre(const parser::CaseConstruct::Case &) { return SwitchToNewScope(); } 290 bool Pre(const parser::SelectRankConstruct &selectRankConstruct) { 291 return PushConstructName(selectRankConstruct); 292 } 293 bool Pre(const parser::SelectRankConstruct::RankCase &) { 294 return SwitchToNewScope(); 295 } 296 bool Pre(const parser::SelectTypeConstruct &selectTypeConstruct) { 297 return PushConstructName(selectTypeConstruct); 298 } 299 bool Pre(const parser::SelectTypeConstruct::TypeCase &) { 300 return SwitchToNewScope(); 301 } 302 bool Pre(const parser::WhereConstruct &whereConstruct) { 303 return PushConstructName(whereConstruct); 304 } 305 bool Pre(const parser::ForallConstruct &forallConstruct) { 306 return PushConstructName(forallConstruct); 307 } 308 309 void Post(const parser::AssociateConstruct &associateConstruct) { 310 PopConstructName(associateConstruct); 311 } 312 void Post(const parser::BlockConstruct &blockConstruct) { 313 PopConstructName(blockConstruct); 314 } 315 void Post(const parser::ChangeTeamConstruct &changeTeamConstruct) { 316 PopConstructName(changeTeamConstruct); 317 } 318 void Post(const parser::CriticalConstruct &criticalConstruct) { 319 PopConstructName(criticalConstruct); 320 } 321 void Post(const parser::DoConstruct &doConstruct) { 322 PopConstructName(doConstruct); 323 } 324 void Post(const parser::IfConstruct &ifConstruct) { 325 PopConstructName(ifConstruct); 326 } 327 void Post(const parser::CaseConstruct &caseConstruct) { 328 PopConstructName(caseConstruct); 329 } 330 void Post(const parser::SelectRankConstruct &selectRankConstruct) { 331 PopConstructName(selectRankConstruct); 332 } 333 void Post(const parser::SelectTypeConstruct &selectTypeConstruct) { 334 PopConstructName(selectTypeConstruct); 335 } 336 void Post(const parser::WhereConstruct &whereConstruct) { 337 PopConstructName(whereConstruct); 338 } 339 void Post(const parser::ForallConstruct &forallConstruct) { 340 PopConstructName(forallConstruct); 341 } 342 343 // Checks for missing or mismatching names on various constructs (e.g., IF) 344 // and their intermediate or terminal statements that allow optional 345 // construct names(e.g., ELSE). When an optional construct name is present, 346 // the construct as a whole must have a name that matches. 347 template <typename FIRST, typename CONSTRUCT, typename STMT> 348 void CheckOptionalName(const char *constructTag, const CONSTRUCT &a, 349 const parser::Statement<STMT> &stmt) { 350 if (const parser::CharBlock * name{GetStmtName(stmt)}) { 351 const auto &firstStmt{std::get<parser::Statement<FIRST>>(a.t)}; 352 if (const parser::CharBlock * firstName{GetStmtName(firstStmt)}) { 353 if (*firstName != *name) { 354 context_.Say(*name, "%s name mismatch"_err_en_US, constructTag) 355 .Attach(*firstName, "should be"_en_US); 356 } 357 } else { 358 context_.Say(*name, "%s name not allowed"_err_en_US, constructTag) 359 .Attach(firstStmt.source, "in unnamed %s"_en_US, constructTag); 360 } 361 } 362 } 363 364 // C1414 365 void Post(const parser::BlockData &blockData) { 366 CheckOptionalName<parser::BlockDataStmt>("BLOCK DATA subprogram", blockData, 367 std::get<parser::Statement<parser::EndBlockDataStmt>>(blockData.t)); 368 } 369 370 // C1564 371 void Post(const parser::InterfaceBody::Function &func) { 372 CheckOptionalName<parser::FunctionStmt>("FUNCTION", func, 373 std::get<parser::Statement<parser::EndFunctionStmt>>(func.t)); 374 } 375 376 // C1564 377 void Post(const parser::FunctionSubprogram &functionSubprogram) { 378 CheckOptionalName<parser::FunctionStmt>("FUNCTION", functionSubprogram, 379 std::get<parser::Statement<parser::EndFunctionStmt>>( 380 functionSubprogram.t)); 381 } 382 383 // C1502 384 void Post(const parser::InterfaceBlock &interfaceBlock) { 385 if (const auto &endGenericSpec{ 386 std::get<parser::Statement<parser::EndInterfaceStmt>>( 387 interfaceBlock.t) 388 .statement.v}) { 389 const auto &interfaceStmt{ 390 std::get<parser::Statement<parser::InterfaceStmt>>(interfaceBlock.t)}; 391 if (std::holds_alternative<parser::Abstract>(interfaceStmt.statement.u)) { 392 context_ 393 .Say(endGenericSpec->source, 394 "END INTERFACE generic name (%s) may not appear for ABSTRACT INTERFACE"_err_en_US, 395 endGenericSpec->source) 396 .Attach( 397 interfaceStmt.source, "corresponding ABSTRACT INTERFACE"_en_US); 398 } else if (const auto &genericSpec{ 399 std::get<std::optional<parser::GenericSpec>>( 400 interfaceStmt.statement.u)}) { 401 bool ok{genericSpec->source == endGenericSpec->source}; 402 if (!ok) { 403 // Accept variant spellings of .LT. &c. 404 const auto *endOp{ 405 std::get_if<parser::DefinedOperator>(&endGenericSpec->u)}; 406 const auto *op{std::get_if<parser::DefinedOperator>(&genericSpec->u)}; 407 if (endOp && op) { 408 const auto *endIntrin{ 409 std::get_if<parser::DefinedOperator::IntrinsicOperator>( 410 &endOp->u)}; 411 const auto *intrin{ 412 std::get_if<parser::DefinedOperator::IntrinsicOperator>( 413 &op->u)}; 414 ok = endIntrin && intrin && *endIntrin == *intrin; 415 } 416 } 417 if (!ok) { 418 context_ 419 .Say(endGenericSpec->source, 420 "END INTERFACE generic name (%s) does not match generic INTERFACE (%s)"_err_en_US, 421 endGenericSpec->source, genericSpec->source) 422 .Attach(genericSpec->source, "corresponding INTERFACE"_en_US); 423 } 424 } else { 425 context_ 426 .Say(endGenericSpec->source, 427 "END INTERFACE generic name (%s) may not appear for non-generic INTERFACE"_err_en_US, 428 endGenericSpec->source) 429 .Attach(interfaceStmt.source, "corresponding INTERFACE"_en_US); 430 } 431 } 432 } 433 434 // C1402 435 void Post(const parser::Module &module) { 436 CheckOptionalName<parser::ModuleStmt>("MODULE", module, 437 std::get<parser::Statement<parser::EndModuleStmt>>(module.t)); 438 } 439 440 // C1569 441 void Post(const parser::SeparateModuleSubprogram &separateModuleSubprogram) { 442 CheckOptionalName<parser::MpSubprogramStmt>("MODULE PROCEDURE", 443 separateModuleSubprogram, 444 std::get<parser::Statement<parser::EndMpSubprogramStmt>>( 445 separateModuleSubprogram.t)); 446 } 447 448 // C1401 449 void Post(const parser::MainProgram &mainProgram) { 450 if (const parser::CharBlock * 451 endName{GetStmtName(std::get<parser::Statement<parser::EndProgramStmt>>( 452 mainProgram.t))}) { 453 if (const auto &program{ 454 std::get<std::optional<parser::Statement<parser::ProgramStmt>>>( 455 mainProgram.t)}) { 456 if (*endName != program->statement.v.source) { 457 context_.Say(*endName, "END PROGRAM name mismatch"_err_en_US) 458 .Attach(program->statement.v.source, "should be"_en_US); 459 } 460 } else { 461 context_.Say(*endName, 462 "END PROGRAM has name without PROGRAM statement"_err_en_US); 463 } 464 } 465 } 466 467 // C1413 468 void Post(const parser::Submodule &submodule) { 469 CheckOptionalName<parser::SubmoduleStmt>("SUBMODULE", submodule, 470 std::get<parser::Statement<parser::EndSubmoduleStmt>>(submodule.t)); 471 } 472 473 // C1567 474 void Post(const parser::InterfaceBody::Subroutine &sub) { 475 CheckOptionalName<parser::SubroutineStmt>("SUBROUTINE", sub, 476 std::get<parser::Statement<parser::EndSubroutineStmt>>(sub.t)); 477 } 478 479 // C1567 480 void Post(const parser::SubroutineSubprogram &subroutineSubprogram) { 481 CheckOptionalName<parser::SubroutineStmt>("SUBROUTINE", 482 subroutineSubprogram, 483 std::get<parser::Statement<parser::EndSubroutineStmt>>( 484 subroutineSubprogram.t)); 485 } 486 487 // C739 488 void Post(const parser::DerivedTypeDef &derivedTypeDef) { 489 CheckOptionalName<parser::DerivedTypeStmt>("derived type definition", 490 derivedTypeDef, 491 std::get<parser::Statement<parser::EndTypeStmt>>(derivedTypeDef.t)); 492 } 493 494 void Post(const parser::LabelDoStmt &labelDoStmt) { 495 AddLabelReferenceFromDoStmt(std::get<parser::Label>(labelDoStmt.t)); 496 } 497 void Post(const parser::GotoStmt &gotoStmt) { AddLabelReference(gotoStmt.v); } 498 void Post(const parser::ComputedGotoStmt &computedGotoStmt) { 499 AddLabelReference(std::get<std::list<parser::Label>>(computedGotoStmt.t)); 500 } 501 void Post(const parser::ArithmeticIfStmt &arithmeticIfStmt) { 502 AddLabelReference(std::get<1>(arithmeticIfStmt.t)); 503 AddLabelReference(std::get<2>(arithmeticIfStmt.t)); 504 AddLabelReference(std::get<3>(arithmeticIfStmt.t)); 505 } 506 void Post(const parser::AssignStmt &assignStmt) { 507 AddLabelReferenceFromAssignStmt(std::get<parser::Label>(assignStmt.t)); 508 } 509 void Post(const parser::AssignedGotoStmt &assignedGotoStmt) { 510 AddLabelReference(std::get<std::list<parser::Label>>(assignedGotoStmt.t)); 511 } 512 void Post(const parser::AltReturnSpec &altReturnSpec) { 513 AddLabelReference(altReturnSpec.v); 514 } 515 516 void Post(const parser::ErrLabel &errLabel) { AddLabelReference(errLabel.v); } 517 void Post(const parser::EndLabel &endLabel) { AddLabelReference(endLabel.v); } 518 void Post(const parser::EorLabel &eorLabel) { AddLabelReference(eorLabel.v); } 519 void Post(const parser::Format &format) { 520 if (const auto *labelPointer{std::get_if<parser::Label>(&format.u)}) { 521 AddLabelReferenceToFormatStmt(*labelPointer); 522 } 523 } 524 void Post(const parser::CycleStmt &cycleStmt) { 525 if (cycleStmt.v) { 526 CheckLabelContext("CYCLE", cycleStmt.v->source); 527 } 528 } 529 void Post(const parser::ExitStmt &exitStmt) { 530 if (exitStmt.v) { 531 CheckLabelContext("EXIT", exitStmt.v->source); 532 } 533 } 534 535 const std::vector<UnitAnalysis> &ProgramUnits() const { 536 return programUnits_; 537 } 538 SemanticsContext &ErrorHandler() { return context_; } 539 540 private: 541 ScopeInfo &PushScope() { 542 auto &model{programUnits_.back().scopeModel}; 543 int newDepth{model.empty() ? 1 : model[currentScope_].depth + 1}; 544 ScopeInfo &result{model.emplace_back()}; 545 result.parent = currentScope_; 546 result.depth = newDepth; 547 currentScope_ = model.size() - 1; 548 return result; 549 } 550 bool InitializeNewScopeContext() { 551 programUnits_.emplace_back(UnitAnalysis{}); 552 currentScope_ = 0u; 553 PushScope(); 554 return true; 555 } 556 ScopeInfo &PopScope() { 557 ScopeInfo &result{programUnits_.back().scopeModel[currentScope_]}; 558 currentScope_ = result.parent; 559 return result; 560 } 561 ProxyForScope ParentScope() { 562 return programUnits_.back().scopeModel[currentScope_].parent; 563 } 564 bool SwitchToNewScope() { 565 ScopeInfo &oldScope{PopScope()}; 566 bool isExteriorGotoFatal{oldScope.isExteriorGotoFatal}; 567 PushScope().isExteriorGotoFatal = isExteriorGotoFatal; 568 return true; 569 } 570 571 template <typename A> bool PushConstructName(const A &a) { 572 const auto &optionalName{std::get<0>(std::get<0>(a.t).statement.t)}; 573 if (optionalName) { 574 constructNames_.emplace_back(optionalName->ToString()); 575 } 576 // Gotos into this construct from outside it are diagnosed, and 577 // are fatal unless the construct is a DO, IF, or SELECT CASE. 578 PushScope().isExteriorGotoFatal = 579 !(std::is_same_v<A, parser::DoConstruct> || 580 std::is_same_v<A, parser::IfConstruct> || 581 std::is_same_v<A, parser::CaseConstruct>); 582 return true; 583 } 584 bool PushConstructName(const parser::BlockConstruct &blockConstruct) { 585 const auto &optionalName{ 586 std::get<parser::Statement<parser::BlockStmt>>(blockConstruct.t) 587 .statement.v}; 588 if (optionalName) { 589 constructNames_.emplace_back(optionalName->ToString()); 590 } 591 PushScope().isExteriorGotoFatal = true; 592 return true; 593 } 594 template <typename A> void PopConstructNameIfPresent(const A &a) { 595 const auto &optionalName{std::get<0>(std::get<0>(a.t).statement.t)}; 596 if (optionalName) { 597 constructNames_.pop_back(); 598 } 599 } 600 void PopConstructNameIfPresent(const parser::BlockConstruct &blockConstruct) { 601 const auto &optionalName{ 602 std::get<parser::Statement<parser::BlockStmt>>(blockConstruct.t) 603 .statement.v}; 604 if (optionalName) { 605 constructNames_.pop_back(); 606 } 607 } 608 609 template <typename A> void PopConstructName(const A &a) { 610 CheckName(a); 611 PopScope(); 612 PopConstructNameIfPresent(a); 613 } 614 615 template <typename FIRST, typename CASEBLOCK, typename CASE, 616 typename CONSTRUCT> 617 void CheckSelectNames(const char *tag, const CONSTRUCT &construct) { 618 CheckEndName<FIRST, parser::EndSelectStmt>(tag, construct); 619 for (const auto &inner : std::get<std::list<CASEBLOCK>>(construct.t)) { 620 CheckOptionalName<FIRST>( 621 tag, construct, std::get<parser::Statement<CASE>>(inner.t)); 622 } 623 } 624 625 // C1144 626 void PopConstructName(const parser::CaseConstruct &caseConstruct) { 627 CheckSelectNames<parser::SelectCaseStmt, parser::CaseConstruct::Case, 628 parser::CaseStmt>("SELECT CASE", caseConstruct); 629 PopScope(); 630 PopConstructNameIfPresent(caseConstruct); 631 } 632 633 // C1154, C1156 634 void PopConstructName( 635 const parser::SelectRankConstruct &selectRankConstruct) { 636 CheckSelectNames<parser::SelectRankStmt, 637 parser::SelectRankConstruct::RankCase, parser::SelectRankCaseStmt>( 638 "SELECT RANK", selectRankConstruct); 639 PopScope(); 640 PopConstructNameIfPresent(selectRankConstruct); 641 } 642 643 // C1165 644 void PopConstructName( 645 const parser::SelectTypeConstruct &selectTypeConstruct) { 646 CheckSelectNames<parser::SelectTypeStmt, 647 parser::SelectTypeConstruct::TypeCase, parser::TypeGuardStmt>( 648 "SELECT TYPE", selectTypeConstruct); 649 PopScope(); 650 PopConstructNameIfPresent(selectTypeConstruct); 651 } 652 653 // Checks for missing or mismatching names on various constructs (e.g., BLOCK) 654 // and their END statements. Both names must be present if either one is. 655 template <typename FIRST, typename END, typename CONSTRUCT> 656 void CheckEndName(const char *constructTag, const CONSTRUCT &a) { 657 const auto &constructStmt{std::get<parser::Statement<FIRST>>(a.t)}; 658 const auto &endStmt{std::get<parser::Statement<END>>(a.t)}; 659 const parser::CharBlock *endName{GetStmtName(endStmt)}; 660 if (const parser::CharBlock * constructName{GetStmtName(constructStmt)}) { 661 if (endName) { 662 if (*constructName != *endName) { 663 context_ 664 .Say(*endName, "%s construct name mismatch"_err_en_US, 665 constructTag) 666 .Attach(*constructName, "should be"_en_US); 667 } 668 } else { 669 context_ 670 .Say(endStmt.source, 671 "%s construct name required but missing"_err_en_US, 672 constructTag) 673 .Attach(*constructName, "should be"_en_US); 674 } 675 } else if (endName) { 676 context_ 677 .Say(*endName, "%s construct name unexpected"_err_en_US, constructTag) 678 .Attach( 679 constructStmt.source, "unnamed %s statement"_en_US, constructTag); 680 } 681 } 682 683 // C1106 684 void CheckName(const parser::AssociateConstruct &associateConstruct) { 685 CheckEndName<parser::AssociateStmt, parser::EndAssociateStmt>( 686 "ASSOCIATE", associateConstruct); 687 } 688 // C1117 689 void CheckName(const parser::CriticalConstruct &criticalConstruct) { 690 CheckEndName<parser::CriticalStmt, parser::EndCriticalStmt>( 691 "CRITICAL", criticalConstruct); 692 } 693 // C1131 694 void CheckName(const parser::DoConstruct &doConstruct) { 695 CheckEndName<parser::NonLabelDoStmt, parser::EndDoStmt>("DO", doConstruct); 696 } 697 // C1035 698 void CheckName(const parser::ForallConstruct &forallConstruct) { 699 CheckEndName<parser::ForallConstructStmt, parser::EndForallStmt>( 700 "FORALL", forallConstruct); 701 } 702 703 // C1109 704 void CheckName(const parser::BlockConstruct &blockConstruct) { 705 CheckEndName<parser::BlockStmt, parser::EndBlockStmt>( 706 "BLOCK", blockConstruct); 707 } 708 // C1112 709 void CheckName(const parser::ChangeTeamConstruct &changeTeamConstruct) { 710 CheckEndName<parser::ChangeTeamStmt, parser::EndChangeTeamStmt>( 711 "CHANGE TEAM", changeTeamConstruct); 712 } 713 714 // C1142 715 void CheckName(const parser::IfConstruct &ifConstruct) { 716 CheckEndName<parser::IfThenStmt, parser::EndIfStmt>("IF", ifConstruct); 717 for (const auto &elseIfBlock : 718 std::get<std::list<parser::IfConstruct::ElseIfBlock>>(ifConstruct.t)) { 719 CheckOptionalName<parser::IfThenStmt>("IF construct", ifConstruct, 720 std::get<parser::Statement<parser::ElseIfStmt>>(elseIfBlock.t)); 721 } 722 if (const auto &elseBlock{ 723 std::get<std::optional<parser::IfConstruct::ElseBlock>>( 724 ifConstruct.t)}) { 725 CheckOptionalName<parser::IfThenStmt>("IF construct", ifConstruct, 726 std::get<parser::Statement<parser::ElseStmt>>(elseBlock->t)); 727 } 728 } 729 730 // C1033 731 void CheckName(const parser::WhereConstruct &whereConstruct) { 732 CheckEndName<parser::WhereConstructStmt, parser::EndWhereStmt>( 733 "WHERE", whereConstruct); 734 for (const auto &maskedElsewhere : 735 std::get<std::list<parser::WhereConstruct::MaskedElsewhere>>( 736 whereConstruct.t)) { 737 CheckOptionalName<parser::WhereConstructStmt>("WHERE construct", 738 whereConstruct, 739 std::get<parser::Statement<parser::MaskedElsewhereStmt>>( 740 maskedElsewhere.t)); 741 } 742 if (const auto &elsewhere{ 743 std::get<std::optional<parser::WhereConstruct::Elsewhere>>( 744 whereConstruct.t)}) { 745 CheckOptionalName<parser::WhereConstructStmt>("WHERE construct", 746 whereConstruct, 747 std::get<parser::Statement<parser::ElsewhereStmt>>(elsewhere->t)); 748 } 749 } 750 751 // C1134, C1166 752 void CheckLabelContext( 753 const char *const stmtString, const parser::CharBlock &constructName) { 754 const auto iter{std::find(constructNames_.crbegin(), 755 constructNames_.crend(), constructName.ToString())}; 756 if (iter == constructNames_.crend()) { 757 context_.Say(constructName, "%s construct-name is not in scope"_err_en_US, 758 stmtString); 759 } 760 } 761 762 // 6.2.5, paragraph 2 763 void CheckLabelInRange(parser::Label label) { 764 if (label < 1 || label > 99999) { 765 context_.Say(currentPosition_, "Label '%u' is out of range"_err_en_US, 766 SayLabel(label)); 767 } 768 } 769 770 // 6.2.5., paragraph 2 771 void AddTargetLabelDefinition(parser::Label label, 772 LabeledStmtClassificationSet labeledStmtClassificationSet, 773 ProxyForScope scope, bool isExecutableConstructEndStmt = false) { 774 CheckLabelInRange(label); 775 const auto pair{programUnits_.back().targetStmts.emplace(label, 776 LabeledStatementInfoTuplePOD{scope, currentPosition_, 777 labeledStmtClassificationSet, isExecutableConstructEndStmt})}; 778 if (!pair.second) { 779 context_.Say(currentPosition_, "Label '%u' is not distinct"_err_en_US, 780 SayLabel(label)); 781 } 782 } 783 784 void AddLabelReferenceFromDoStmt(parser::Label label) { 785 CheckLabelInRange(label); 786 programUnits_.back().doStmtSources.emplace_back( 787 label, currentScope_, currentPosition_); 788 } 789 790 void AddLabelReferenceToFormatStmt(parser::Label label) { 791 CheckLabelInRange(label); 792 programUnits_.back().formatStmtSources.emplace_back( 793 label, currentScope_, currentPosition_); 794 } 795 796 void AddLabelReferenceFromAssignStmt(parser::Label label) { 797 CheckLabelInRange(label); 798 programUnits_.back().assignStmtSources.emplace_back( 799 label, currentScope_, currentPosition_); 800 } 801 802 void AddLabelReference(parser::Label label) { 803 CheckLabelInRange(label); 804 programUnits_.back().otherStmtSources.emplace_back( 805 label, currentScope_, currentPosition_); 806 } 807 808 void AddLabelReference(const std::list<parser::Label> &labels) { 809 for (const parser::Label &label : labels) { 810 AddLabelReference(label); 811 } 812 } 813 814 std::vector<UnitAnalysis> programUnits_; 815 SemanticsContext &context_; 816 parser::CharBlock currentPosition_; 817 ProxyForScope currentScope_; 818 std::vector<std::string> constructNames_; 819 }; 820 821 bool InInclusiveScope(const std::vector<ScopeInfo> &scopes, ProxyForScope tail, 822 ProxyForScope head) { 823 for (; tail != head; tail = scopes[tail].parent) { 824 if (!HasScope(tail)) { 825 return false; 826 } 827 } 828 return true; 829 } 830 831 ParseTreeAnalyzer LabelAnalysis( 832 SemanticsContext &context, const parser::Program &program) { 833 ParseTreeAnalyzer analysis{context}; 834 Walk(program, analysis); 835 return analysis; 836 } 837 838 bool InBody(const parser::CharBlock &position, 839 const std::pair<parser::CharBlock, parser::CharBlock> &pair) { 840 if (position.begin() >= pair.first.begin()) { 841 if (position.begin() < pair.second.end()) { 842 return true; 843 } 844 } 845 return false; 846 } 847 848 LabeledStatementInfoTuplePOD GetLabel( 849 const TargetStmtMap &labels, const parser::Label &label) { 850 const auto iter{labels.find(label)}; 851 if (iter == labels.cend()) { 852 return {0u, nullptr, LabeledStmtClassificationSet{}, false}; 853 } else { 854 return iter->second; 855 } 856 } 857 858 // 11.1.7.3 859 void CheckBranchesIntoDoBody(const SourceStmtList &branches, 860 const TargetStmtMap &labels, const IndexList &loopBodies, 861 SemanticsContext &context) { 862 for (const auto &branch : branches) { 863 const auto &label{branch.parserLabel}; 864 auto branchTarget{GetLabel(labels, label)}; 865 if (HasScope(branchTarget.proxyForScope)) { 866 const auto &fromPosition{branch.parserCharBlock}; 867 const auto &toPosition{branchTarget.parserCharBlock}; 868 for (const auto &body : loopBodies) { 869 if (!InBody(fromPosition, body) && InBody(toPosition, body)) { 870 context 871 .Say( 872 fromPosition, "branch into loop body from outside"_warn_en_US) 873 .Attach(body.first, "the loop branched into"_en_US); 874 } 875 } 876 } 877 } 878 } 879 880 void CheckDoNesting(const IndexList &loopBodies, SemanticsContext &context) { 881 for (auto i1{loopBodies.cbegin()}; i1 != loopBodies.cend(); ++i1) { 882 const auto &v1{*i1}; 883 for (auto i2{i1 + 1}; i2 != loopBodies.cend(); ++i2) { 884 const auto &v2{*i2}; 885 if (v2.first.begin() < v1.second.end() && 886 v1.second.begin() < v2.second.begin()) { 887 context.Say(v1.first, "DO loop doesn't properly nest"_err_en_US) 888 .Attach(v2.first, "DO loop conflicts"_en_US); 889 } 890 } 891 } 892 } 893 894 parser::CharBlock SkipLabel(const parser::CharBlock &position) { 895 const std::size_t maxPosition{position.size()}; 896 if (maxPosition && parser::IsDecimalDigit(position[0])) { 897 std::size_t i{1l}; 898 for (; (i < maxPosition) && parser::IsDecimalDigit(position[i]); ++i) { 899 } 900 for (; (i < maxPosition) && std::isspace(position[i]); ++i) { 901 } 902 return parser::CharBlock{position.begin() + i, position.end()}; 903 } 904 return position; 905 } 906 907 ProxyForScope ParentScope( 908 const std::vector<ScopeInfo> &scopes, ProxyForScope scope) { 909 return scopes[scope].parent; 910 } 911 912 void CheckLabelDoConstraints(const SourceStmtList &dos, 913 const SourceStmtList &branches, const TargetStmtMap &labels, 914 const std::vector<ScopeInfo> &scopes, SemanticsContext &context) { 915 IndexList loopBodies; 916 for (const auto &stmt : dos) { 917 const auto &label{stmt.parserLabel}; 918 const auto &scope{stmt.proxyForScope}; 919 const auto &position{stmt.parserCharBlock}; 920 auto doTarget{GetLabel(labels, label)}; 921 if (!HasScope(doTarget.proxyForScope)) { 922 // C1133 923 context.Say( 924 position, "Label '%u' cannot be found"_err_en_US, SayLabel(label)); 925 } else if (doTarget.parserCharBlock.begin() < position.begin()) { 926 // R1119 927 context.Say(position, 928 "Label '%u' doesn't lexically follow DO stmt"_err_en_US, 929 SayLabel(label)); 930 931 } else if ((InInclusiveScope(scopes, scope, doTarget.proxyForScope) && 932 doTarget.labeledStmtClassificationSet.test( 933 TargetStatementEnum::CompatibleDo)) || 934 (doTarget.isExecutableConstructEndStmt && 935 ParentScope(scopes, doTarget.proxyForScope) == scope)) { 936 if (context.warnOnNonstandardUsage() || 937 context.ShouldWarn( 938 common::LanguageFeature::OldLabelDoEndStatements)) { 939 context 940 .Say(position, 941 "A DO loop should terminate with an END DO or CONTINUE"_port_en_US) 942 .Attach(doTarget.parserCharBlock, 943 "DO loop currently ends at statement:"_en_US); 944 } 945 } else if (!InInclusiveScope(scopes, scope, doTarget.proxyForScope)) { 946 context.Say(position, "Label '%u' is not in DO loop scope"_err_en_US, 947 SayLabel(label)); 948 } else if (!doTarget.labeledStmtClassificationSet.test( 949 TargetStatementEnum::Do)) { 950 context.Say(doTarget.parserCharBlock, 951 "A DO loop should terminate with an END DO or CONTINUE"_err_en_US); 952 } else { 953 loopBodies.emplace_back(SkipLabel(position), doTarget.parserCharBlock); 954 } 955 } 956 957 CheckBranchesIntoDoBody(branches, labels, loopBodies, context); 958 CheckDoNesting(loopBodies, context); 959 } 960 961 // 6.2.5 962 void CheckScopeConstraints(const SourceStmtList &stmts, 963 const TargetStmtMap &labels, const std::vector<ScopeInfo> &scopes, 964 SemanticsContext &context) { 965 for (const auto &stmt : stmts) { 966 const auto &label{stmt.parserLabel}; 967 const auto &scope{stmt.proxyForScope}; 968 const auto &position{stmt.parserCharBlock}; 969 auto target{GetLabel(labels, label)}; 970 if (!HasScope(target.proxyForScope)) { 971 context.Say( 972 position, "Label '%u' was not found"_err_en_US, SayLabel(label)); 973 } else if (!InInclusiveScope(scopes, scope, target.proxyForScope)) { 974 // Clause 11.1.2.1 prohibits transfer of control to the interior of a 975 // block from outside the block, but this does not apply to formats. 976 // C1038 and C1034 forbid statements in FORALL and WHERE constructs 977 // (resp.) from being branch targets. 978 if (target.labeledStmtClassificationSet.test( 979 TargetStatementEnum::Format)) { 980 continue; 981 } 982 bool isFatal{false}; 983 ProxyForScope fromScope{scope}; 984 for (ProxyForScope toScope{target.proxyForScope}; fromScope != toScope; 985 toScope = scopes[toScope].parent) { 986 if (scopes[toScope].isExteriorGotoFatal) { 987 isFatal = true; 988 break; 989 } 990 if (scopes[toScope].depth == scopes[fromScope].depth) { 991 fromScope = scopes[fromScope].parent; 992 } 993 } 994 context.Say(position, 995 isFatal 996 ? "Label '%u' is in a construct that prevents its use as a branch target here"_err_en_US 997 : "Label '%u' is in a construct that prevents its use as a branch target here"_en_US, 998 SayLabel(label)); 999 } 1000 } 1001 } 1002 1003 void CheckBranchTargetConstraints(const SourceStmtList &stmts, 1004 const TargetStmtMap &labels, SemanticsContext &context) { 1005 for (const auto &stmt : stmts) { 1006 const auto &label{stmt.parserLabel}; 1007 auto branchTarget{GetLabel(labels, label)}; 1008 if (HasScope(branchTarget.proxyForScope)) { 1009 if (!branchTarget.labeledStmtClassificationSet.test( 1010 TargetStatementEnum::Branch) && 1011 !branchTarget.labeledStmtClassificationSet.test( 1012 TargetStatementEnum::CompatibleBranch)) { // error 1013 context 1014 .Say(branchTarget.parserCharBlock, 1015 "Label '%u' is not a branch target"_err_en_US, SayLabel(label)) 1016 .Attach(stmt.parserCharBlock, "Control flow use of '%u'"_en_US, 1017 SayLabel(label)); 1018 } else if (!branchTarget.labeledStmtClassificationSet.test( 1019 TargetStatementEnum::Branch)) { // warning 1020 context 1021 .Say(branchTarget.parserCharBlock, 1022 "Label '%u' is not a branch target"_warn_en_US, SayLabel(label)) 1023 .Attach(stmt.parserCharBlock, "Control flow use of '%u'"_en_US, 1024 SayLabel(label)); 1025 } 1026 } 1027 } 1028 } 1029 1030 void CheckBranchConstraints(const SourceStmtList &branches, 1031 const TargetStmtMap &labels, const std::vector<ScopeInfo> &scopes, 1032 SemanticsContext &context) { 1033 CheckScopeConstraints(branches, labels, scopes, context); 1034 CheckBranchTargetConstraints(branches, labels, context); 1035 } 1036 1037 void CheckDataXferTargetConstraints(const SourceStmtList &stmts, 1038 const TargetStmtMap &labels, SemanticsContext &context) { 1039 for (const auto &stmt : stmts) { 1040 const auto &label{stmt.parserLabel}; 1041 auto ioTarget{GetLabel(labels, label)}; 1042 if (HasScope(ioTarget.proxyForScope)) { 1043 if (!ioTarget.labeledStmtClassificationSet.test( 1044 TargetStatementEnum::Format)) { 1045 context 1046 .Say(ioTarget.parserCharBlock, "'%u' not a FORMAT"_err_en_US, 1047 SayLabel(label)) 1048 .Attach(stmt.parserCharBlock, "data transfer use of '%u'"_en_US, 1049 SayLabel(label)); 1050 } 1051 } 1052 } 1053 } 1054 1055 void CheckDataTransferConstraints(const SourceStmtList &dataTransfers, 1056 const TargetStmtMap &labels, const std::vector<ScopeInfo> &scopes, 1057 SemanticsContext &context) { 1058 CheckScopeConstraints(dataTransfers, labels, scopes, context); 1059 CheckDataXferTargetConstraints(dataTransfers, labels, context); 1060 } 1061 1062 void CheckAssignTargetConstraints(const SourceStmtList &stmts, 1063 const TargetStmtMap &labels, SemanticsContext &context) { 1064 for (const auto &stmt : stmts) { 1065 const auto &label{stmt.parserLabel}; 1066 auto target{GetLabel(labels, label)}; 1067 if (HasScope(target.proxyForScope) && 1068 !target.labeledStmtClassificationSet.test( 1069 TargetStatementEnum::Branch) && 1070 !target.labeledStmtClassificationSet.test( 1071 TargetStatementEnum::Format)) { 1072 context 1073 .Say(target.parserCharBlock, 1074 target.labeledStmtClassificationSet.test( 1075 TargetStatementEnum::CompatibleBranch) 1076 ? "Label '%u' is not a branch target or FORMAT"_warn_en_US 1077 : "Label '%u' is not a branch target or FORMAT"_err_en_US, 1078 SayLabel(label)) 1079 .Attach(stmt.parserCharBlock, "ASSIGN statement use of '%u'"_en_US, 1080 SayLabel(label)); 1081 } 1082 } 1083 } 1084 1085 void CheckAssignConstraints(const SourceStmtList &assigns, 1086 const TargetStmtMap &labels, const std::vector<ScopeInfo> &scopes, 1087 SemanticsContext &context) { 1088 CheckScopeConstraints(assigns, labels, scopes, context); 1089 CheckAssignTargetConstraints(assigns, labels, context); 1090 } 1091 1092 bool CheckConstraints(ParseTreeAnalyzer &&parseTreeAnalysis) { 1093 auto &context{parseTreeAnalysis.ErrorHandler()}; 1094 for (const auto &programUnit : parseTreeAnalysis.ProgramUnits()) { 1095 const auto &dos{programUnit.doStmtSources}; 1096 const auto &branches{programUnit.otherStmtSources}; 1097 const auto &labels{programUnit.targetStmts}; 1098 const auto &scopes{programUnit.scopeModel}; 1099 CheckLabelDoConstraints(dos, branches, labels, scopes, context); 1100 CheckBranchConstraints(branches, labels, scopes, context); 1101 const auto &dataTransfers{programUnit.formatStmtSources}; 1102 CheckDataTransferConstraints(dataTransfers, labels, scopes, context); 1103 const auto &assigns{programUnit.assignStmtSources}; 1104 CheckAssignConstraints(assigns, labels, scopes, context); 1105 } 1106 return !context.AnyFatalError(); 1107 } 1108 1109 bool ValidateLabels(SemanticsContext &context, const parser::Program &program) { 1110 return CheckConstraints(LabelAnalysis(context, program)); 1111 } 1112 } // namespace Fortran::semantics 1113