1 //===-- lib/Semantics/resolve-names.cpp -----------------------------------===// 2 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 3 // See https://llvm.org/LICENSE.txt for license information. 4 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 5 // 6 //===----------------------------------------------------------------------===// 7 8 #include "resolve-names.h" 9 #include "assignment.h" 10 #include "mod-file.h" 11 #include "pointer-assignment.h" 12 #include "program-tree.h" 13 #include "resolve-directives.h" 14 #include "resolve-names-utils.h" 15 #include "rewrite-parse-tree.h" 16 #include "flang/Common/Fortran.h" 17 #include "flang/Common/default-kinds.h" 18 #include "flang/Common/indirection.h" 19 #include "flang/Common/restorer.h" 20 #include "flang/Evaluate/characteristics.h" 21 #include "flang/Evaluate/check-expression.h" 22 #include "flang/Evaluate/common.h" 23 #include "flang/Evaluate/fold-designator.h" 24 #include "flang/Evaluate/fold.h" 25 #include "flang/Evaluate/intrinsics.h" 26 #include "flang/Evaluate/tools.h" 27 #include "flang/Evaluate/type.h" 28 #include "flang/Parser/parse-tree-visitor.h" 29 #include "flang/Parser/parse-tree.h" 30 #include "flang/Parser/tools.h" 31 #include "flang/Semantics/attr.h" 32 #include "flang/Semantics/expression.h" 33 #include "flang/Semantics/scope.h" 34 #include "flang/Semantics/semantics.h" 35 #include "flang/Semantics/symbol.h" 36 #include "flang/Semantics/tools.h" 37 #include "flang/Semantics/type.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include <list> 40 #include <map> 41 #include <set> 42 #include <stack> 43 44 namespace Fortran::semantics { 45 46 using namespace parser::literals; 47 48 template <typename T> using Indirection = common::Indirection<T>; 49 using Message = parser::Message; 50 using Messages = parser::Messages; 51 using MessageFixedText = parser::MessageFixedText; 52 using MessageFormattedText = parser::MessageFormattedText; 53 54 class ResolveNamesVisitor; 55 56 // ImplicitRules maps initial character of identifier to the DeclTypeSpec 57 // representing the implicit type; std::nullopt if none. 58 // It also records the presence of IMPLICIT NONE statements. 59 // When inheritFromParent is set, defaults come from the parent rules. 60 class ImplicitRules { 61 public: 62 ImplicitRules(SemanticsContext &context, ImplicitRules *parent) 63 : parent_{parent}, context_{context} { 64 inheritFromParent_ = parent != nullptr; 65 } 66 bool isImplicitNoneType() const; 67 bool isImplicitNoneExternal() const; 68 void set_isImplicitNoneType(bool x) { isImplicitNoneType_ = x; } 69 void set_isImplicitNoneExternal(bool x) { isImplicitNoneExternal_ = x; } 70 void set_inheritFromParent(bool x) { inheritFromParent_ = x; } 71 // Get the implicit type for this name. May be null. 72 const DeclTypeSpec *GetType(SourceName) const; 73 // Record the implicit type for the range of characters [fromLetter, 74 // toLetter]. 75 void SetTypeMapping(const DeclTypeSpec &type, parser::Location fromLetter, 76 parser::Location toLetter); 77 78 private: 79 static char Incr(char ch); 80 81 ImplicitRules *parent_; 82 SemanticsContext &context_; 83 bool inheritFromParent_{false}; // look in parent if not specified here 84 bool isImplicitNoneType_{ 85 context_.IsEnabled(common::LanguageFeature::ImplicitNoneTypeAlways)}; 86 bool isImplicitNoneExternal_{false}; 87 // map_ contains the mapping between letters and types that were defined 88 // by the IMPLICIT statements of the related scope. It does not contain 89 // the default Fortran mappings nor the mapping defined in parents. 90 std::map<char, common::Reference<const DeclTypeSpec>> map_; 91 92 friend llvm::raw_ostream &operator<<( 93 llvm::raw_ostream &, const ImplicitRules &); 94 friend void ShowImplicitRule( 95 llvm::raw_ostream &, const ImplicitRules &, char); 96 }; 97 98 // scope -> implicit rules for that scope 99 using ImplicitRulesMap = std::map<const Scope *, ImplicitRules>; 100 101 // Track statement source locations and save messages. 102 class MessageHandler { 103 public: 104 MessageHandler() { DIE("MessageHandler: default-constructed"); } 105 explicit MessageHandler(SemanticsContext &c) : context_{&c} {} 106 Messages &messages() { return context_->messages(); }; 107 const std::optional<SourceName> &currStmtSource() { 108 return context_->location(); 109 } 110 void set_currStmtSource(const std::optional<SourceName> &source) { 111 context_->set_location(source); 112 } 113 114 // Emit a message associated with the current statement source. 115 Message &Say(MessageFixedText &&); 116 Message &Say(MessageFormattedText &&); 117 // Emit a message about a SourceName 118 Message &Say(const SourceName &, MessageFixedText &&); 119 // Emit a formatted message associated with a source location. 120 template <typename... A> 121 Message &Say(const SourceName &source, MessageFixedText &&msg, A &&...args) { 122 return context_->Say(source, std::move(msg), std::forward<A>(args)...); 123 } 124 125 private: 126 SemanticsContext *context_; 127 }; 128 129 // Inheritance graph for the parse tree visitation classes that follow: 130 // BaseVisitor 131 // + AttrsVisitor 132 // | + DeclTypeSpecVisitor 133 // | + ImplicitRulesVisitor 134 // | + ScopeHandler -----------+--+ 135 // | + ModuleVisitor ========|==+ 136 // | + InterfaceVisitor | | 137 // | +-+ SubprogramVisitor ==|==+ 138 // + ArraySpecVisitor | | 139 // + DeclarationVisitor <--------+ | 140 // + ConstructVisitor | 141 // + ResolveNamesVisitor <------+ 142 143 class BaseVisitor { 144 public: 145 BaseVisitor() { DIE("BaseVisitor: default-constructed"); } 146 BaseVisitor( 147 SemanticsContext &c, ResolveNamesVisitor &v, ImplicitRulesMap &rules) 148 : implicitRulesMap_{&rules}, this_{&v}, context_{&c}, messageHandler_{c} { 149 } 150 template <typename T> void Walk(const T &); 151 152 MessageHandler &messageHandler() { return messageHandler_; } 153 const std::optional<SourceName> &currStmtSource() { 154 return context_->location(); 155 } 156 SemanticsContext &context() const { return *context_; } 157 evaluate::FoldingContext &GetFoldingContext() const { 158 return context_->foldingContext(); 159 } 160 bool IsIntrinsic( 161 const SourceName &name, std::optional<Symbol::Flag> flag) const { 162 if (!flag) { 163 return context_->intrinsics().IsIntrinsic(name.ToString()); 164 } else if (flag == Symbol::Flag::Function) { 165 return context_->intrinsics().IsIntrinsicFunction(name.ToString()); 166 } else if (flag == Symbol::Flag::Subroutine) { 167 return context_->intrinsics().IsIntrinsicSubroutine(name.ToString()); 168 } else { 169 DIE("expected Subroutine or Function flag"); 170 } 171 } 172 173 // Make a placeholder symbol for a Name that otherwise wouldn't have one. 174 // It is not in any scope and always has MiscDetails. 175 void MakePlaceholder(const parser::Name &, MiscDetails::Kind); 176 177 template <typename T> common::IfNoLvalue<T, T> FoldExpr(T &&expr) { 178 return evaluate::Fold(GetFoldingContext(), std::move(expr)); 179 } 180 181 template <typename T> MaybeExpr EvaluateExpr(const T &expr) { 182 return FoldExpr(AnalyzeExpr(*context_, expr)); 183 } 184 185 template <typename T> 186 MaybeExpr EvaluateNonPointerInitializer( 187 const Symbol &symbol, const T &expr, parser::CharBlock source) { 188 if (!context().HasError(symbol)) { 189 if (auto maybeExpr{AnalyzeExpr(*context_, expr)}) { 190 auto restorer{GetFoldingContext().messages().SetLocation(source)}; 191 return evaluate::NonPointerInitializationExpr( 192 symbol, std::move(*maybeExpr), GetFoldingContext()); 193 } 194 } 195 return std::nullopt; 196 } 197 198 template <typename T> MaybeIntExpr EvaluateIntExpr(const T &expr) { 199 return semantics::EvaluateIntExpr(*context_, expr); 200 } 201 202 template <typename T> 203 MaybeSubscriptIntExpr EvaluateSubscriptIntExpr(const T &expr) { 204 if (MaybeIntExpr maybeIntExpr{EvaluateIntExpr(expr)}) { 205 return FoldExpr(evaluate::ConvertToType<evaluate::SubscriptInteger>( 206 std::move(*maybeIntExpr))); 207 } else { 208 return std::nullopt; 209 } 210 } 211 212 template <typename... A> Message &Say(A &&...args) { 213 return messageHandler_.Say(std::forward<A>(args)...); 214 } 215 template <typename... A> 216 Message &Say( 217 const parser::Name &name, MessageFixedText &&text, const A &...args) { 218 return messageHandler_.Say(name.source, std::move(text), args...); 219 } 220 221 protected: 222 ImplicitRulesMap *implicitRulesMap_{nullptr}; 223 224 private: 225 ResolveNamesVisitor *this_; 226 SemanticsContext *context_; 227 MessageHandler messageHandler_; 228 }; 229 230 // Provide Post methods to collect attributes into a member variable. 231 class AttrsVisitor : public virtual BaseVisitor { 232 public: 233 bool BeginAttrs(); // always returns true 234 Attrs GetAttrs(); 235 Attrs EndAttrs(); 236 bool SetPassNameOn(Symbol &); 237 bool SetBindNameOn(Symbol &); 238 void Post(const parser::LanguageBindingSpec &); 239 bool Pre(const parser::IntentSpec &); 240 bool Pre(const parser::Pass &); 241 242 bool CheckAndSet(Attr); 243 244 // Simple case: encountering CLASSNAME causes ATTRNAME to be set. 245 #define HANDLE_ATTR_CLASS(CLASSNAME, ATTRNAME) \ 246 bool Pre(const parser::CLASSNAME &) { \ 247 CheckAndSet(Attr::ATTRNAME); \ 248 return false; \ 249 } 250 HANDLE_ATTR_CLASS(PrefixSpec::Elemental, ELEMENTAL) 251 HANDLE_ATTR_CLASS(PrefixSpec::Impure, IMPURE) 252 HANDLE_ATTR_CLASS(PrefixSpec::Module, MODULE) 253 HANDLE_ATTR_CLASS(PrefixSpec::Non_Recursive, NON_RECURSIVE) 254 HANDLE_ATTR_CLASS(PrefixSpec::Pure, PURE) 255 HANDLE_ATTR_CLASS(PrefixSpec::Recursive, RECURSIVE) 256 HANDLE_ATTR_CLASS(TypeAttrSpec::BindC, BIND_C) 257 HANDLE_ATTR_CLASS(BindAttr::Deferred, DEFERRED) 258 HANDLE_ATTR_CLASS(BindAttr::Non_Overridable, NON_OVERRIDABLE) 259 HANDLE_ATTR_CLASS(Abstract, ABSTRACT) 260 HANDLE_ATTR_CLASS(Allocatable, ALLOCATABLE) 261 HANDLE_ATTR_CLASS(Asynchronous, ASYNCHRONOUS) 262 HANDLE_ATTR_CLASS(Contiguous, CONTIGUOUS) 263 HANDLE_ATTR_CLASS(External, EXTERNAL) 264 HANDLE_ATTR_CLASS(Intrinsic, INTRINSIC) 265 HANDLE_ATTR_CLASS(NoPass, NOPASS) 266 HANDLE_ATTR_CLASS(Optional, OPTIONAL) 267 HANDLE_ATTR_CLASS(Parameter, PARAMETER) 268 HANDLE_ATTR_CLASS(Pointer, POINTER) 269 HANDLE_ATTR_CLASS(Protected, PROTECTED) 270 HANDLE_ATTR_CLASS(Save, SAVE) 271 HANDLE_ATTR_CLASS(Target, TARGET) 272 HANDLE_ATTR_CLASS(Value, VALUE) 273 HANDLE_ATTR_CLASS(Volatile, VOLATILE) 274 #undef HANDLE_ATTR_CLASS 275 276 protected: 277 std::optional<Attrs> attrs_; 278 279 Attr AccessSpecToAttr(const parser::AccessSpec &x) { 280 switch (x.v) { 281 case parser::AccessSpec::Kind::Public: 282 return Attr::PUBLIC; 283 case parser::AccessSpec::Kind::Private: 284 return Attr::PRIVATE; 285 } 286 llvm_unreachable("Switch covers all cases"); // suppress g++ warning 287 } 288 Attr IntentSpecToAttr(const parser::IntentSpec &x) { 289 switch (x.v) { 290 case parser::IntentSpec::Intent::In: 291 return Attr::INTENT_IN; 292 case parser::IntentSpec::Intent::Out: 293 return Attr::INTENT_OUT; 294 case parser::IntentSpec::Intent::InOut: 295 return Attr::INTENT_INOUT; 296 } 297 llvm_unreachable("Switch covers all cases"); // suppress g++ warning 298 } 299 300 private: 301 bool IsDuplicateAttr(Attr); 302 bool HaveAttrConflict(Attr, Attr, Attr); 303 bool IsConflictingAttr(Attr); 304 305 MaybeExpr bindName_; // from BIND(C, NAME="...") 306 std::optional<SourceName> passName_; // from PASS(...) 307 }; 308 309 // Find and create types from declaration-type-spec nodes. 310 class DeclTypeSpecVisitor : public AttrsVisitor { 311 public: 312 using AttrsVisitor::Post; 313 using AttrsVisitor::Pre; 314 void Post(const parser::IntrinsicTypeSpec::DoublePrecision &); 315 void Post(const parser::IntrinsicTypeSpec::DoubleComplex &); 316 void Post(const parser::DeclarationTypeSpec::ClassStar &); 317 void Post(const parser::DeclarationTypeSpec::TypeStar &); 318 bool Pre(const parser::TypeGuardStmt &); 319 void Post(const parser::TypeGuardStmt &); 320 void Post(const parser::TypeSpec &); 321 322 protected: 323 struct State { 324 bool expectDeclTypeSpec{false}; // should see decl-type-spec only when true 325 const DeclTypeSpec *declTypeSpec{nullptr}; 326 struct { 327 DerivedTypeSpec *type{nullptr}; 328 DeclTypeSpec::Category category{DeclTypeSpec::TypeDerived}; 329 } derived; 330 bool allowForwardReferenceToDerivedType{false}; 331 }; 332 333 bool allowForwardReferenceToDerivedType() const { 334 return state_.allowForwardReferenceToDerivedType; 335 } 336 void set_allowForwardReferenceToDerivedType(bool yes) { 337 state_.allowForwardReferenceToDerivedType = yes; 338 } 339 340 // Walk the parse tree of a type spec and return the DeclTypeSpec for it. 341 template <typename T> 342 const DeclTypeSpec *ProcessTypeSpec(const T &x, bool allowForward = false) { 343 auto restorer{common::ScopedSet(state_, State{})}; 344 set_allowForwardReferenceToDerivedType(allowForward); 345 BeginDeclTypeSpec(); 346 Walk(x); 347 const auto *type{GetDeclTypeSpec()}; 348 EndDeclTypeSpec(); 349 return type; 350 } 351 352 const DeclTypeSpec *GetDeclTypeSpec(); 353 void BeginDeclTypeSpec(); 354 void EndDeclTypeSpec(); 355 void SetDeclTypeSpec(const DeclTypeSpec &); 356 void SetDeclTypeSpecCategory(DeclTypeSpec::Category); 357 DeclTypeSpec::Category GetDeclTypeSpecCategory() const { 358 return state_.derived.category; 359 } 360 KindExpr GetKindParamExpr( 361 TypeCategory, const std::optional<parser::KindSelector> &); 362 void CheckForAbstractType(const Symbol &typeSymbol); 363 364 private: 365 State state_; 366 367 void MakeNumericType(TypeCategory, int kind); 368 }; 369 370 // Visit ImplicitStmt and related parse tree nodes and updates implicit rules. 371 class ImplicitRulesVisitor : public DeclTypeSpecVisitor { 372 public: 373 using DeclTypeSpecVisitor::Post; 374 using DeclTypeSpecVisitor::Pre; 375 using ImplicitNoneNameSpec = parser::ImplicitStmt::ImplicitNoneNameSpec; 376 377 void Post(const parser::ParameterStmt &); 378 bool Pre(const parser::ImplicitStmt &); 379 bool Pre(const parser::LetterSpec &); 380 bool Pre(const parser::ImplicitSpec &); 381 void Post(const parser::ImplicitSpec &); 382 383 const DeclTypeSpec *GetType(SourceName name) { 384 return implicitRules_->GetType(name); 385 } 386 bool isImplicitNoneType() const { 387 return implicitRules_->isImplicitNoneType(); 388 } 389 bool isImplicitNoneType(const Scope &scope) const { 390 return implicitRulesMap_->at(&scope).isImplicitNoneType(); 391 } 392 bool isImplicitNoneExternal() const { 393 return implicitRules_->isImplicitNoneExternal(); 394 } 395 void set_inheritFromParent(bool x) { 396 implicitRules_->set_inheritFromParent(x); 397 } 398 399 protected: 400 void BeginScope(const Scope &); 401 void SetScope(const Scope &); 402 403 private: 404 // implicit rules in effect for current scope 405 ImplicitRules *implicitRules_{nullptr}; 406 std::optional<SourceName> prevImplicit_; 407 std::optional<SourceName> prevImplicitNone_; 408 std::optional<SourceName> prevImplicitNoneType_; 409 std::optional<SourceName> prevParameterStmt_; 410 411 bool HandleImplicitNone(const std::list<ImplicitNoneNameSpec> &nameSpecs); 412 }; 413 414 // Track array specifications. They can occur in AttrSpec, EntityDecl, 415 // ObjectDecl, DimensionStmt, CommonBlockObject, or BasedPointerStmt. 416 // 1. INTEGER, DIMENSION(10) :: x 417 // 2. INTEGER :: x(10) 418 // 3. ALLOCATABLE :: x(:) 419 // 4. DIMENSION :: x(10) 420 // 5. COMMON x(10) 421 // 6. BasedPointerStmt 422 class ArraySpecVisitor : public virtual BaseVisitor { 423 public: 424 void Post(const parser::ArraySpec &); 425 void Post(const parser::ComponentArraySpec &); 426 void Post(const parser::CoarraySpec &); 427 void Post(const parser::AttrSpec &) { PostAttrSpec(); } 428 void Post(const parser::ComponentAttrSpec &) { PostAttrSpec(); } 429 430 protected: 431 const ArraySpec &arraySpec(); 432 const ArraySpec &coarraySpec(); 433 void BeginArraySpec(); 434 void EndArraySpec(); 435 void ClearArraySpec() { arraySpec_.clear(); } 436 void ClearCoarraySpec() { coarraySpec_.clear(); } 437 438 private: 439 // arraySpec_/coarraySpec_ are populated from any ArraySpec/CoarraySpec 440 ArraySpec arraySpec_; 441 ArraySpec coarraySpec_; 442 // When an ArraySpec is under an AttrSpec or ComponentAttrSpec, it is moved 443 // into attrArraySpec_ 444 ArraySpec attrArraySpec_; 445 ArraySpec attrCoarraySpec_; 446 447 void PostAttrSpec(); 448 }; 449 450 // Manage a stack of Scopes 451 class ScopeHandler : public ImplicitRulesVisitor { 452 public: 453 using ImplicitRulesVisitor::Post; 454 using ImplicitRulesVisitor::Pre; 455 456 Scope &currScope() { return DEREF(currScope_); } 457 // The enclosing host procedure if current scope is in an internal procedure 458 Scope *GetHostProcedure(); 459 // The enclosing scope, skipping blocks and derived types. 460 // TODO: Will return the scope of a FORALL or implied DO loop; is this ok? 461 // If not, should call FindProgramUnitContaining() instead. 462 Scope &InclusiveScope(); 463 // The enclosing scope, skipping derived types. 464 Scope &NonDerivedTypeScope(); 465 466 // Create a new scope and push it on the scope stack. 467 void PushScope(Scope::Kind kind, Symbol *symbol); 468 void PushScope(Scope &scope); 469 void PopScope(); 470 void SetScope(Scope &); 471 472 template <typename T> bool Pre(const parser::Statement<T> &x) { 473 messageHandler().set_currStmtSource(x.source); 474 currScope_->AddSourceRange(x.source); 475 return true; 476 } 477 template <typename T> void Post(const parser::Statement<T> &) { 478 messageHandler().set_currStmtSource(std::nullopt); 479 } 480 481 // Special messages: already declared; referencing symbol's declaration; 482 // about a type; two names & locations 483 void SayAlreadyDeclared(const parser::Name &, Symbol &); 484 void SayAlreadyDeclared(const SourceName &, Symbol &); 485 void SayAlreadyDeclared(const SourceName &, const SourceName &); 486 void SayWithReason( 487 const parser::Name &, Symbol &, MessageFixedText &&, MessageFixedText &&); 488 void SayWithDecl(const parser::Name &, Symbol &, MessageFixedText &&); 489 void SayLocalMustBeVariable(const parser::Name &, Symbol &); 490 void SayDerivedType(const SourceName &, MessageFixedText &&, const Scope &); 491 void Say2(const SourceName &, MessageFixedText &&, const SourceName &, 492 MessageFixedText &&); 493 void Say2( 494 const SourceName &, MessageFixedText &&, Symbol &, MessageFixedText &&); 495 void Say2( 496 const parser::Name &, MessageFixedText &&, Symbol &, MessageFixedText &&); 497 498 // Search for symbol by name in current, parent derived type, and 499 // containing scopes 500 Symbol *FindSymbol(const parser::Name &); 501 Symbol *FindSymbol(const Scope &, const parser::Name &); 502 // Search for name only in scope, not in enclosing scopes. 503 Symbol *FindInScope(const Scope &, const parser::Name &); 504 Symbol *FindInScope(const Scope &, const SourceName &); 505 template <typename T> Symbol *FindInScope(const T &name) { 506 return FindInScope(currScope(), name); 507 } 508 // Search for name in a derived type scope and its parents. 509 Symbol *FindInTypeOrParents(const Scope &, const parser::Name &); 510 Symbol *FindInTypeOrParents(const parser::Name &); 511 void EraseSymbol(const parser::Name &); 512 void EraseSymbol(const Symbol &symbol) { currScope().erase(symbol.name()); } 513 // Make a new symbol with the name and attrs of an existing one 514 Symbol &CopySymbol(const SourceName &, const Symbol &); 515 516 // Make symbols in the current or named scope 517 Symbol &MakeSymbol(Scope &, const SourceName &, Attrs); 518 Symbol &MakeSymbol(const SourceName &, Attrs = Attrs{}); 519 Symbol &MakeSymbol(const parser::Name &, Attrs = Attrs{}); 520 Symbol &MakeHostAssocSymbol(const parser::Name &, const Symbol &); 521 522 template <typename D> 523 common::IfNoLvalue<Symbol &, D> MakeSymbol( 524 const parser::Name &name, D &&details) { 525 return MakeSymbol(name, Attrs{}, std::move(details)); 526 } 527 528 template <typename D> 529 common::IfNoLvalue<Symbol &, D> MakeSymbol( 530 const parser::Name &name, const Attrs &attrs, D &&details) { 531 return Resolve(name, MakeSymbol(name.source, attrs, std::move(details))); 532 } 533 534 template <typename D> 535 common::IfNoLvalue<Symbol &, D> MakeSymbol( 536 const SourceName &name, const Attrs &attrs, D &&details) { 537 // Note: don't use FindSymbol here. If this is a derived type scope, 538 // we want to detect whether the name is already declared as a component. 539 auto *symbol{FindInScope(name)}; 540 if (!symbol) { 541 symbol = &MakeSymbol(name, attrs); 542 symbol->set_details(std::move(details)); 543 return *symbol; 544 } 545 if constexpr (std::is_same_v<DerivedTypeDetails, D>) { 546 if (auto *d{symbol->detailsIf<GenericDetails>()}) { 547 if (!d->specific()) { 548 // derived type with same name as a generic 549 auto *derivedType{d->derivedType()}; 550 if (!derivedType) { 551 derivedType = 552 &currScope().MakeSymbol(name, attrs, std::move(details)); 553 d->set_derivedType(*derivedType); 554 } else { 555 SayAlreadyDeclared(name, *derivedType); 556 } 557 return *derivedType; 558 } 559 } 560 } 561 if (symbol->CanReplaceDetails(details)) { 562 // update the existing symbol 563 symbol->attrs() |= attrs; 564 symbol->set_details(std::move(details)); 565 return *symbol; 566 } else if constexpr (std::is_same_v<UnknownDetails, D>) { 567 symbol->attrs() |= attrs; 568 return *symbol; 569 } else { 570 if (!CheckPossibleBadForwardRef(*symbol)) { 571 SayAlreadyDeclared(name, *symbol); 572 } 573 // replace the old symbol with a new one with correct details 574 EraseSymbol(*symbol); 575 auto &result{MakeSymbol(name, attrs, std::move(details))}; 576 context().SetError(result); 577 return result; 578 } 579 } 580 581 void MakeExternal(Symbol &); 582 583 protected: 584 // Apply the implicit type rules to this symbol. 585 void ApplyImplicitRules(Symbol &); 586 const DeclTypeSpec *GetImplicitType(Symbol &, const Scope &); 587 bool ConvertToObjectEntity(Symbol &); 588 bool ConvertToProcEntity(Symbol &); 589 590 const DeclTypeSpec &MakeNumericType( 591 TypeCategory, const std::optional<parser::KindSelector> &); 592 const DeclTypeSpec &MakeLogicalType( 593 const std::optional<parser::KindSelector> &); 594 void NotePossibleBadForwardRef(const parser::Name &); 595 std::optional<SourceName> HadForwardRef(const Symbol &) const; 596 bool CheckPossibleBadForwardRef(const Symbol &); 597 598 bool inExecutionPart_{false}; 599 bool inSpecificationPart_{false}; 600 bool inEquivalenceStmt_{false}; 601 std::set<SourceName> specPartForwardRefs_; 602 603 private: 604 Scope *currScope_{nullptr}; 605 }; 606 607 class ModuleVisitor : public virtual ScopeHandler { 608 public: 609 bool Pre(const parser::AccessStmt &); 610 bool Pre(const parser::Only &); 611 bool Pre(const parser::Rename::Names &); 612 bool Pre(const parser::Rename::Operators &); 613 bool Pre(const parser::UseStmt &); 614 void Post(const parser::UseStmt &); 615 616 void BeginModule(const parser::Name &, bool isSubmodule); 617 bool BeginSubmodule(const parser::Name &, const parser::ParentIdentifier &); 618 void ApplyDefaultAccess(); 619 void AddGenericUse(GenericDetails &, const SourceName &, const Symbol &); 620 621 private: 622 // The default access spec for this module. 623 Attr defaultAccess_{Attr::PUBLIC}; 624 // The location of the last AccessStmt without access-ids, if any. 625 std::optional<SourceName> prevAccessStmt_; 626 // The scope of the module during a UseStmt 627 Scope *useModuleScope_{nullptr}; 628 629 Symbol &SetAccess(const SourceName &, Attr attr, Symbol * = nullptr); 630 // A rename in a USE statement: local => use 631 struct SymbolRename { 632 Symbol *local{nullptr}; 633 Symbol *use{nullptr}; 634 }; 635 // Record a use from useModuleScope_ of use Name/Symbol as local Name/Symbol 636 SymbolRename AddUse(const SourceName &localName, const SourceName &useName); 637 SymbolRename AddUse(const SourceName &, const SourceName &, Symbol *); 638 void DoAddUse(const SourceName &, const SourceName &, Symbol &localSymbol, 639 const Symbol &useSymbol); 640 void AddUse(const GenericSpecInfo &); 641 Scope *FindModule(const parser::Name &, Scope *ancestor = nullptr); 642 }; 643 644 class InterfaceVisitor : public virtual ScopeHandler { 645 public: 646 bool Pre(const parser::InterfaceStmt &); 647 void Post(const parser::InterfaceStmt &); 648 void Post(const parser::EndInterfaceStmt &); 649 bool Pre(const parser::GenericSpec &); 650 bool Pre(const parser::ProcedureStmt &); 651 bool Pre(const parser::GenericStmt &); 652 void Post(const parser::GenericStmt &); 653 654 bool inInterfaceBlock() const; 655 bool isGeneric() const; 656 bool isAbstract() const; 657 658 protected: 659 GenericDetails &GetGenericDetails(); 660 // Add to generic the symbol for the subprogram with the same name 661 void CheckGenericProcedures(Symbol &); 662 663 private: 664 // A new GenericInfo is pushed for each interface block and generic stmt 665 struct GenericInfo { 666 GenericInfo(bool isInterface, bool isAbstract = false) 667 : isInterface{isInterface}, isAbstract{isAbstract} {} 668 bool isInterface; // in interface block 669 bool isAbstract; // in abstract interface block 670 Symbol *symbol{nullptr}; // the generic symbol being defined 671 }; 672 std::stack<GenericInfo> genericInfo_; 673 const GenericInfo &GetGenericInfo() const { return genericInfo_.top(); } 674 void SetGenericSymbol(Symbol &symbol) { genericInfo_.top().symbol = &symbol; } 675 676 using ProcedureKind = parser::ProcedureStmt::Kind; 677 // mapping of generic to its specific proc names and kinds 678 std::multimap<Symbol *, std::pair<const parser::Name *, ProcedureKind>> 679 specificProcs_; 680 681 void AddSpecificProcs(const std::list<parser::Name> &, ProcedureKind); 682 void ResolveSpecificsInGeneric(Symbol &generic); 683 }; 684 685 class SubprogramVisitor : public virtual ScopeHandler, public InterfaceVisitor { 686 public: 687 bool HandleStmtFunction(const parser::StmtFunctionStmt &); 688 bool Pre(const parser::SubroutineStmt &); 689 void Post(const parser::SubroutineStmt &); 690 bool Pre(const parser::FunctionStmt &); 691 void Post(const parser::FunctionStmt &); 692 bool Pre(const parser::EntryStmt &); 693 void Post(const parser::EntryStmt &); 694 bool Pre(const parser::InterfaceBody::Subroutine &); 695 void Post(const parser::InterfaceBody::Subroutine &); 696 bool Pre(const parser::InterfaceBody::Function &); 697 void Post(const parser::InterfaceBody::Function &); 698 bool Pre(const parser::Suffix &); 699 bool Pre(const parser::PrefixSpec &); 700 void Post(const parser::ImplicitPart &); 701 702 bool BeginSubprogram( 703 const parser::Name &, Symbol::Flag, bool hasModulePrefix = false); 704 bool BeginMpSubprogram(const parser::Name &); 705 void PushBlockDataScope(const parser::Name &); 706 void EndSubprogram(); 707 708 protected: 709 // Set when we see a stmt function that is really an array element assignment 710 bool badStmtFuncFound_{false}; 711 712 private: 713 // Info about the current function: parse tree of the type in the PrefixSpec; 714 // name and symbol of the function result from the Suffix; source location. 715 struct { 716 const parser::DeclarationTypeSpec *parsedType{nullptr}; 717 const parser::Name *resultName{nullptr}; 718 Symbol *resultSymbol{nullptr}; 719 std::optional<SourceName> source; 720 } funcInfo_; 721 722 // Create a subprogram symbol in the current scope and push a new scope. 723 void CheckExtantExternal(const parser::Name &, Symbol::Flag); 724 Symbol &PushSubprogramScope(const parser::Name &, Symbol::Flag); 725 Symbol *GetSpecificFromGeneric(const parser::Name &); 726 SubprogramDetails &PostSubprogramStmt(const parser::Name &); 727 }; 728 729 class DeclarationVisitor : public ArraySpecVisitor, 730 public virtual ScopeHandler { 731 public: 732 using ArraySpecVisitor::Post; 733 using ScopeHandler::Post; 734 using ScopeHandler::Pre; 735 736 bool Pre(const parser::Initialization &); 737 void Post(const parser::EntityDecl &); 738 void Post(const parser::ObjectDecl &); 739 void Post(const parser::PointerDecl &); 740 bool Pre(const parser::BindStmt &) { return BeginAttrs(); } 741 void Post(const parser::BindStmt &) { EndAttrs(); } 742 bool Pre(const parser::BindEntity &); 743 bool Pre(const parser::NamedConstantDef &); 744 bool Pre(const parser::NamedConstant &); 745 void Post(const parser::EnumDef &); 746 bool Pre(const parser::Enumerator &); 747 bool Pre(const parser::AccessSpec &); 748 bool Pre(const parser::AsynchronousStmt &); 749 bool Pre(const parser::ContiguousStmt &); 750 bool Pre(const parser::ExternalStmt &); 751 bool Pre(const parser::IntentStmt &); 752 bool Pre(const parser::IntrinsicStmt &); 753 bool Pre(const parser::OptionalStmt &); 754 bool Pre(const parser::ProtectedStmt &); 755 bool Pre(const parser::ValueStmt &); 756 bool Pre(const parser::VolatileStmt &); 757 bool Pre(const parser::AllocatableStmt &) { 758 objectDeclAttr_ = Attr::ALLOCATABLE; 759 return true; 760 } 761 void Post(const parser::AllocatableStmt &) { objectDeclAttr_ = std::nullopt; } 762 bool Pre(const parser::TargetStmt &) { 763 objectDeclAttr_ = Attr::TARGET; 764 return true; 765 } 766 void Post(const parser::TargetStmt &) { objectDeclAttr_ = std::nullopt; } 767 void Post(const parser::DimensionStmt::Declaration &); 768 void Post(const parser::CodimensionDecl &); 769 bool Pre(const parser::TypeDeclarationStmt &) { return BeginDecl(); } 770 void Post(const parser::TypeDeclarationStmt &); 771 void Post(const parser::IntegerTypeSpec &); 772 void Post(const parser::IntrinsicTypeSpec::Real &); 773 void Post(const parser::IntrinsicTypeSpec::Complex &); 774 void Post(const parser::IntrinsicTypeSpec::Logical &); 775 void Post(const parser::IntrinsicTypeSpec::Character &); 776 void Post(const parser::CharSelector::LengthAndKind &); 777 void Post(const parser::CharLength &); 778 void Post(const parser::LengthSelector &); 779 bool Pre(const parser::KindParam &); 780 bool Pre(const parser::DeclarationTypeSpec::Type &); 781 void Post(const parser::DeclarationTypeSpec::Type &); 782 bool Pre(const parser::DeclarationTypeSpec::Class &); 783 void Post(const parser::DeclarationTypeSpec::Class &); 784 bool Pre(const parser::DeclarationTypeSpec::Record &); 785 void Post(const parser::DerivedTypeSpec &); 786 bool Pre(const parser::DerivedTypeDef &); 787 bool Pre(const parser::DerivedTypeStmt &); 788 void Post(const parser::DerivedTypeStmt &); 789 bool Pre(const parser::TypeParamDefStmt &) { return BeginDecl(); } 790 void Post(const parser::TypeParamDefStmt &); 791 bool Pre(const parser::TypeAttrSpec::Extends &); 792 bool Pre(const parser::PrivateStmt &); 793 bool Pre(const parser::SequenceStmt &); 794 bool Pre(const parser::ComponentDefStmt &) { return BeginDecl(); } 795 void Post(const parser::ComponentDefStmt &) { EndDecl(); } 796 void Post(const parser::ComponentDecl &); 797 bool Pre(const parser::ProcedureDeclarationStmt &); 798 void Post(const parser::ProcedureDeclarationStmt &); 799 bool Pre(const parser::DataComponentDefStmt &); // returns false 800 bool Pre(const parser::ProcComponentDefStmt &); 801 void Post(const parser::ProcComponentDefStmt &); 802 bool Pre(const parser::ProcPointerInit &); 803 void Post(const parser::ProcInterface &); 804 void Post(const parser::ProcDecl &); 805 bool Pre(const parser::TypeBoundProcedurePart &); 806 void Post(const parser::TypeBoundProcedurePart &); 807 void Post(const parser::ContainsStmt &); 808 bool Pre(const parser::TypeBoundProcBinding &) { return BeginAttrs(); } 809 void Post(const parser::TypeBoundProcBinding &) { EndAttrs(); } 810 void Post(const parser::TypeBoundProcedureStmt::WithoutInterface &); 811 void Post(const parser::TypeBoundProcedureStmt::WithInterface &); 812 void Post(const parser::FinalProcedureStmt &); 813 bool Pre(const parser::TypeBoundGenericStmt &); 814 bool Pre(const parser::AllocateStmt &); 815 void Post(const parser::AllocateStmt &); 816 bool Pre(const parser::StructureConstructor &); 817 bool Pre(const parser::NamelistStmt::Group &); 818 bool Pre(const parser::IoControlSpec &); 819 bool Pre(const parser::CommonStmt::Block &); 820 bool Pre(const parser::CommonBlockObject &); 821 void Post(const parser::CommonBlockObject &); 822 bool Pre(const parser::EquivalenceStmt &); 823 bool Pre(const parser::SaveStmt &); 824 bool Pre(const parser::BasedPointerStmt &); 825 826 void PointerInitialization( 827 const parser::Name &, const parser::InitialDataTarget &); 828 void PointerInitialization( 829 const parser::Name &, const parser::ProcPointerInit &); 830 void NonPointerInitialization( 831 const parser::Name &, const parser::ConstantExpr &); 832 void CheckExplicitInterface(const parser::Name &); 833 void CheckBindings(const parser::TypeBoundProcedureStmt::WithoutInterface &); 834 835 const parser::Name *ResolveDesignator(const parser::Designator &); 836 837 protected: 838 bool BeginDecl(); 839 void EndDecl(); 840 Symbol &DeclareObjectEntity(const parser::Name &, Attrs = Attrs{}); 841 // Make sure that there's an entity in an enclosing scope called Name 842 Symbol &FindOrDeclareEnclosingEntity(const parser::Name &); 843 // Declare a LOCAL/LOCAL_INIT entity. If there isn't a type specified 844 // it comes from the entity in the containing scope, or implicit rules. 845 // Return pointer to the new symbol, or nullptr on error. 846 Symbol *DeclareLocalEntity(const parser::Name &); 847 // Declare a statement entity (e.g., an implied DO loop index). 848 // If there isn't a type specified, implicit rules apply. 849 // Return pointer to the new symbol, or nullptr on error. 850 Symbol *DeclareStatementEntity( 851 const parser::Name &, const std::optional<parser::IntegerTypeSpec> &); 852 Symbol &MakeCommonBlockSymbol(const parser::Name &); 853 Symbol &MakeCommonBlockSymbol(const std::optional<parser::Name> &); 854 bool CheckUseError(const parser::Name &); 855 void CheckAccessibility(const SourceName &, bool, Symbol &); 856 void CheckCommonBlocks(); 857 void CheckSaveStmts(); 858 void CheckEquivalenceSets(); 859 bool CheckNotInBlock(const char *); 860 bool NameIsKnownOrIntrinsic(const parser::Name &); 861 862 // Each of these returns a pointer to a resolved Name (i.e. with symbol) 863 // or nullptr in case of error. 864 const parser::Name *ResolveStructureComponent( 865 const parser::StructureComponent &); 866 const parser::Name *ResolveDataRef(const parser::DataRef &); 867 const parser::Name *ResolveName(const parser::Name &); 868 bool PassesSharedLocalityChecks(const parser::Name &name, Symbol &symbol); 869 Symbol *NoteInterfaceName(const parser::Name &); 870 871 private: 872 // The attribute corresponding to the statement containing an ObjectDecl 873 std::optional<Attr> objectDeclAttr_; 874 // Info about current character type while walking DeclTypeSpec. 875 // Also captures any "*length" specifier on an individual declaration. 876 struct { 877 std::optional<ParamValue> length; 878 std::optional<KindExpr> kind; 879 } charInfo_; 880 // Info about current derived type while walking DerivedTypeDef 881 struct { 882 const parser::Name *extends{nullptr}; // EXTENDS(name) 883 bool privateComps{false}; // components are private by default 884 bool privateBindings{false}; // bindings are private by default 885 bool sawContains{false}; // currently processing bindings 886 bool sequence{false}; // is a sequence type 887 const Symbol *type{nullptr}; // derived type being defined 888 } derivedTypeInfo_; 889 // Collect equivalence sets and process at end of specification part 890 std::vector<const std::list<parser::EquivalenceObject> *> equivalenceSets_; 891 // Names of all common block objects in the scope 892 std::set<SourceName> commonBlockObjects_; 893 // Info about about SAVE statements and attributes in current scope 894 struct { 895 std::optional<SourceName> saveAll; // "SAVE" without entity list 896 std::set<SourceName> entities; // names of entities with save attr 897 std::set<SourceName> commons; // names of common blocks with save attr 898 } saveInfo_; 899 // In a ProcedureDeclarationStmt or ProcComponentDefStmt, this is 900 // the interface name, if any. 901 const parser::Name *interfaceName_{nullptr}; 902 // Map type-bound generic to binding names of its specific bindings 903 std::multimap<Symbol *, const parser::Name *> genericBindings_; 904 // Info about current ENUM 905 struct EnumeratorState { 906 // Enum value must hold inside a C_INT (7.6.2). 907 std::optional<int> value{0}; 908 } enumerationState_; 909 910 bool HandleAttributeStmt(Attr, const std::list<parser::Name> &); 911 Symbol &HandleAttributeStmt(Attr, const parser::Name &); 912 Symbol &DeclareUnknownEntity(const parser::Name &, Attrs); 913 Symbol &DeclareProcEntity(const parser::Name &, Attrs, const ProcInterface &); 914 void SetType(const parser::Name &, const DeclTypeSpec &); 915 std::optional<DerivedTypeSpec> ResolveDerivedType(const parser::Name &); 916 std::optional<DerivedTypeSpec> ResolveExtendsType( 917 const parser::Name &, const parser::Name *); 918 Symbol *MakeTypeSymbol(const SourceName &, Details &&); 919 Symbol *MakeTypeSymbol(const parser::Name &, Details &&); 920 bool OkToAddComponent(const parser::Name &, const Symbol * = nullptr); 921 ParamValue GetParamValue( 922 const parser::TypeParamValue &, common::TypeParamAttr attr); 923 void CheckCommonBlockDerivedType(const SourceName &, const Symbol &); 924 std::optional<MessageFixedText> CheckSaveAttr(const Symbol &); 925 Attrs HandleSaveName(const SourceName &, Attrs); 926 void AddSaveName(std::set<SourceName> &, const SourceName &); 927 void SetSaveAttr(Symbol &); 928 bool HandleUnrestrictedSpecificIntrinsicFunction(const parser::Name &); 929 bool IsUplevelReference(const Symbol &); 930 const parser::Name *FindComponent(const parser::Name *, const parser::Name &); 931 void Initialization(const parser::Name &, const parser::Initialization &, 932 bool inComponentDecl); 933 bool PassesLocalityChecks(const parser::Name &name, Symbol &symbol); 934 bool CheckForHostAssociatedImplicit(const parser::Name &); 935 936 // Declare an object or procedure entity. 937 // T is one of: EntityDetails, ObjectEntityDetails, ProcEntityDetails 938 template <typename T> 939 Symbol &DeclareEntity(const parser::Name &name, Attrs attrs) { 940 Symbol &symbol{MakeSymbol(name, attrs)}; 941 if (context().HasError(symbol) || symbol.has<T>()) { 942 return symbol; // OK or error already reported 943 } else if (symbol.has<UnknownDetails>()) { 944 symbol.set_details(T{}); 945 return symbol; 946 } else if (auto *details{symbol.detailsIf<EntityDetails>()}) { 947 symbol.set_details(T{std::move(*details)}); 948 return symbol; 949 } else if (std::is_same_v<EntityDetails, T> && 950 (symbol.has<ObjectEntityDetails>() || 951 symbol.has<ProcEntityDetails>())) { 952 return symbol; // OK 953 } else if (auto *details{symbol.detailsIf<UseDetails>()}) { 954 Say(name.source, 955 "'%s' is use-associated from module '%s' and cannot be re-declared"_err_en_US, 956 name.source, GetUsedModule(*details).name()); 957 } else if (auto *details{symbol.detailsIf<SubprogramNameDetails>()}) { 958 if (details->kind() == SubprogramKind::Module) { 959 Say2(name, 960 "Declaration of '%s' conflicts with its use as module procedure"_err_en_US, 961 symbol, "Module procedure definition"_en_US); 962 } else if (details->kind() == SubprogramKind::Internal) { 963 Say2(name, 964 "Declaration of '%s' conflicts with its use as internal procedure"_err_en_US, 965 symbol, "Internal procedure definition"_en_US); 966 } else { 967 DIE("unexpected kind"); 968 } 969 } else if (std::is_same_v<ObjectEntityDetails, T> && 970 symbol.has<ProcEntityDetails>()) { 971 SayWithDecl( 972 name, symbol, "'%s' is already declared as a procedure"_err_en_US); 973 } else if (std::is_same_v<ProcEntityDetails, T> && 974 symbol.has<ObjectEntityDetails>()) { 975 if (InCommonBlock(symbol)) { 976 SayWithDecl(name, symbol, 977 "'%s' may not be a procedure as it is in a COMMON block"_err_en_US); 978 } else { 979 SayWithDecl( 980 name, symbol, "'%s' is already declared as an object"_err_en_US); 981 } 982 } else if (!CheckPossibleBadForwardRef(symbol)) { 983 SayAlreadyDeclared(name, symbol); 984 } 985 context().SetError(symbol); 986 return symbol; 987 } 988 }; 989 990 // Resolve construct entities and statement entities. 991 // Check that construct names don't conflict with other names. 992 class ConstructVisitor : public virtual DeclarationVisitor { 993 public: 994 bool Pre(const parser::ConcurrentHeader &); 995 bool Pre(const parser::LocalitySpec::Local &); 996 bool Pre(const parser::LocalitySpec::LocalInit &); 997 bool Pre(const parser::LocalitySpec::Shared &); 998 bool Pre(const parser::AcSpec &); 999 bool Pre(const parser::AcImpliedDo &); 1000 bool Pre(const parser::DataImpliedDo &); 1001 bool Pre(const parser::DataIDoObject &); 1002 bool Pre(const parser::DataStmtObject &); 1003 bool Pre(const parser::DataStmtValue &); 1004 bool Pre(const parser::DoConstruct &); 1005 void Post(const parser::DoConstruct &); 1006 bool Pre(const parser::ForallConstruct &); 1007 void Post(const parser::ForallConstruct &); 1008 bool Pre(const parser::ForallStmt &); 1009 void Post(const parser::ForallStmt &); 1010 bool Pre(const parser::BlockStmt &); 1011 bool Pre(const parser::EndBlockStmt &); 1012 void Post(const parser::Selector &); 1013 bool Pre(const parser::AssociateStmt &); 1014 void Post(const parser::EndAssociateStmt &); 1015 void Post(const parser::Association &); 1016 void Post(const parser::SelectTypeStmt &); 1017 void Post(const parser::SelectRankStmt &); 1018 bool Pre(const parser::SelectTypeConstruct &); 1019 void Post(const parser::SelectTypeConstruct &); 1020 bool Pre(const parser::SelectTypeConstruct::TypeCase &); 1021 void Post(const parser::SelectTypeConstruct::TypeCase &); 1022 // Creates Block scopes with neither symbol name nor symbol details. 1023 bool Pre(const parser::SelectRankConstruct::RankCase &); 1024 void Post(const parser::SelectRankConstruct::RankCase &); 1025 void Post(const parser::TypeGuardStmt::Guard &); 1026 void Post(const parser::SelectRankCaseStmt::Rank &); 1027 bool Pre(const parser::ChangeTeamStmt &); 1028 void Post(const parser::EndChangeTeamStmt &); 1029 void Post(const parser::CoarrayAssociation &); 1030 1031 // Definitions of construct names 1032 bool Pre(const parser::WhereConstructStmt &x) { return CheckDef(x.t); } 1033 bool Pre(const parser::ForallConstructStmt &x) { return CheckDef(x.t); } 1034 bool Pre(const parser::CriticalStmt &x) { return CheckDef(x.t); } 1035 bool Pre(const parser::LabelDoStmt &) { 1036 return false; // error recovery 1037 } 1038 bool Pre(const parser::NonLabelDoStmt &x) { return CheckDef(x.t); } 1039 bool Pre(const parser::IfThenStmt &x) { return CheckDef(x.t); } 1040 bool Pre(const parser::SelectCaseStmt &x) { return CheckDef(x.t); } 1041 bool Pre(const parser::SelectRankConstruct &); 1042 void Post(const parser::SelectRankConstruct &); 1043 bool Pre(const parser::SelectRankStmt &x) { 1044 return CheckDef(std::get<0>(x.t)); 1045 } 1046 bool Pre(const parser::SelectTypeStmt &x) { 1047 return CheckDef(std::get<0>(x.t)); 1048 } 1049 1050 // References to construct names 1051 void Post(const parser::MaskedElsewhereStmt &x) { CheckRef(x.t); } 1052 void Post(const parser::ElsewhereStmt &x) { CheckRef(x.v); } 1053 void Post(const parser::EndWhereStmt &x) { CheckRef(x.v); } 1054 void Post(const parser::EndForallStmt &x) { CheckRef(x.v); } 1055 void Post(const parser::EndCriticalStmt &x) { CheckRef(x.v); } 1056 void Post(const parser::EndDoStmt &x) { CheckRef(x.v); } 1057 void Post(const parser::ElseIfStmt &x) { CheckRef(x.t); } 1058 void Post(const parser::ElseStmt &x) { CheckRef(x.v); } 1059 void Post(const parser::EndIfStmt &x) { CheckRef(x.v); } 1060 void Post(const parser::CaseStmt &x) { CheckRef(x.t); } 1061 void Post(const parser::EndSelectStmt &x) { CheckRef(x.v); } 1062 void Post(const parser::SelectRankCaseStmt &x) { CheckRef(x.t); } 1063 void Post(const parser::TypeGuardStmt &x) { CheckRef(x.t); } 1064 void Post(const parser::CycleStmt &x) { CheckRef(x.v); } 1065 void Post(const parser::ExitStmt &x) { CheckRef(x.v); } 1066 1067 private: 1068 // R1105 selector -> expr | variable 1069 // expr is set in either case unless there were errors 1070 struct Selector { 1071 Selector() {} 1072 Selector(const SourceName &source, MaybeExpr &&expr) 1073 : source{source}, expr{std::move(expr)} {} 1074 operator bool() const { return expr.has_value(); } 1075 parser::CharBlock source; 1076 MaybeExpr expr; 1077 }; 1078 // association -> [associate-name =>] selector 1079 struct Association { 1080 const parser::Name *name{nullptr}; 1081 Selector selector; 1082 }; 1083 std::vector<Association> associationStack_; 1084 1085 template <typename T> bool CheckDef(const T &t) { 1086 return CheckDef(std::get<std::optional<parser::Name>>(t)); 1087 } 1088 template <typename T> void CheckRef(const T &t) { 1089 CheckRef(std::get<std::optional<parser::Name>>(t)); 1090 } 1091 bool CheckDef(const std::optional<parser::Name> &); 1092 void CheckRef(const std::optional<parser::Name> &); 1093 const DeclTypeSpec &ToDeclTypeSpec(evaluate::DynamicType &&); 1094 const DeclTypeSpec &ToDeclTypeSpec( 1095 evaluate::DynamicType &&, MaybeSubscriptIntExpr &&length); 1096 Symbol *MakeAssocEntity(); 1097 void SetTypeFromAssociation(Symbol &); 1098 void SetAttrsFromAssociation(Symbol &); 1099 Selector ResolveSelector(const parser::Selector &); 1100 void ResolveIndexName(const parser::ConcurrentControl &control); 1101 Association &GetCurrentAssociation(); 1102 void PushAssociation(); 1103 void PopAssociation(); 1104 }; 1105 1106 // Create scopes for OpenACC constructs 1107 class AccVisitor : public virtual DeclarationVisitor { 1108 public: 1109 void AddAccSourceRange(const parser::CharBlock &); 1110 1111 static bool NeedsScope(const parser::OpenACCBlockConstruct &); 1112 1113 bool Pre(const parser::OpenACCBlockConstruct &); 1114 void Post(const parser::OpenACCBlockConstruct &); 1115 bool Pre(const parser::AccBeginBlockDirective &x) { 1116 AddAccSourceRange(x.source); 1117 return true; 1118 } 1119 void Post(const parser::AccBeginBlockDirective &) { 1120 messageHandler().set_currStmtSource(std::nullopt); 1121 } 1122 bool Pre(const parser::AccEndBlockDirective &x) { 1123 AddAccSourceRange(x.source); 1124 return true; 1125 } 1126 void Post(const parser::AccEndBlockDirective &) { 1127 messageHandler().set_currStmtSource(std::nullopt); 1128 } 1129 bool Pre(const parser::AccBeginLoopDirective &x) { 1130 AddAccSourceRange(x.source); 1131 return true; 1132 } 1133 void Post(const parser::AccBeginLoopDirective &x) { 1134 messageHandler().set_currStmtSource(std::nullopt); 1135 } 1136 }; 1137 1138 bool AccVisitor::NeedsScope(const parser::OpenACCBlockConstruct &x) { 1139 const auto &beginBlockDir{std::get<parser::AccBeginBlockDirective>(x.t)}; 1140 const auto &beginDir{std::get<parser::AccBlockDirective>(beginBlockDir.t)}; 1141 switch (beginDir.v) { 1142 case llvm::acc::Directive::ACCD_data: 1143 case llvm::acc::Directive::ACCD_host_data: 1144 case llvm::acc::Directive::ACCD_kernels: 1145 case llvm::acc::Directive::ACCD_parallel: 1146 case llvm::acc::Directive::ACCD_serial: 1147 return true; 1148 default: 1149 return false; 1150 } 1151 } 1152 1153 void AccVisitor::AddAccSourceRange(const parser::CharBlock &source) { 1154 messageHandler().set_currStmtSource(source); 1155 currScope().AddSourceRange(source); 1156 } 1157 1158 bool AccVisitor::Pre(const parser::OpenACCBlockConstruct &x) { 1159 if (NeedsScope(x)) { 1160 PushScope(Scope::Kind::Block, nullptr); 1161 } 1162 return true; 1163 } 1164 1165 void AccVisitor::Post(const parser::OpenACCBlockConstruct &x) { 1166 if (NeedsScope(x)) { 1167 PopScope(); 1168 } 1169 } 1170 1171 // Create scopes for OpenMP constructs 1172 class OmpVisitor : public virtual DeclarationVisitor { 1173 public: 1174 void AddOmpSourceRange(const parser::CharBlock &); 1175 1176 static bool NeedsScope(const parser::OpenMPBlockConstruct &); 1177 1178 bool Pre(const parser::OpenMPBlockConstruct &); 1179 void Post(const parser::OpenMPBlockConstruct &); 1180 bool Pre(const parser::OmpBeginBlockDirective &x) { 1181 AddOmpSourceRange(x.source); 1182 return true; 1183 } 1184 void Post(const parser::OmpBeginBlockDirective &) { 1185 messageHandler().set_currStmtSource(std::nullopt); 1186 } 1187 bool Pre(const parser::OmpEndBlockDirective &x) { 1188 AddOmpSourceRange(x.source); 1189 return true; 1190 } 1191 void Post(const parser::OmpEndBlockDirective &) { 1192 messageHandler().set_currStmtSource(std::nullopt); 1193 } 1194 1195 bool Pre(const parser::OpenMPLoopConstruct &) { 1196 PushScope(Scope::Kind::Block, nullptr); 1197 return true; 1198 } 1199 void Post(const parser::OpenMPLoopConstruct &) { PopScope(); } 1200 bool Pre(const parser::OmpBeginLoopDirective &x) { 1201 AddOmpSourceRange(x.source); 1202 return true; 1203 } 1204 void Post(const parser::OmpBeginLoopDirective &) { 1205 messageHandler().set_currStmtSource(std::nullopt); 1206 } 1207 bool Pre(const parser::OmpEndLoopDirective &x) { 1208 AddOmpSourceRange(x.source); 1209 return true; 1210 } 1211 void Post(const parser::OmpEndLoopDirective &) { 1212 messageHandler().set_currStmtSource(std::nullopt); 1213 } 1214 1215 bool Pre(const parser::OpenMPSectionsConstruct &) { 1216 PushScope(Scope::Kind::Block, nullptr); 1217 return true; 1218 } 1219 void Post(const parser::OpenMPSectionsConstruct &) { PopScope(); } 1220 bool Pre(const parser::OmpBeginSectionsDirective &x) { 1221 AddOmpSourceRange(x.source); 1222 return true; 1223 } 1224 void Post(const parser::OmpBeginSectionsDirective &) { 1225 messageHandler().set_currStmtSource(std::nullopt); 1226 } 1227 bool Pre(const parser::OmpEndSectionsDirective &x) { 1228 AddOmpSourceRange(x.source); 1229 return true; 1230 } 1231 void Post(const parser::OmpEndSectionsDirective &) { 1232 messageHandler().set_currStmtSource(std::nullopt); 1233 } 1234 }; 1235 1236 bool OmpVisitor::NeedsScope(const parser::OpenMPBlockConstruct &x) { 1237 const auto &beginBlockDir{std::get<parser::OmpBeginBlockDirective>(x.t)}; 1238 const auto &beginDir{std::get<parser::OmpBlockDirective>(beginBlockDir.t)}; 1239 switch (beginDir.v) { 1240 case llvm::omp::Directive::OMPD_target_data: 1241 case llvm::omp::Directive::OMPD_master: 1242 case llvm::omp::Directive::OMPD_ordered: 1243 return false; 1244 default: 1245 return true; 1246 } 1247 } 1248 1249 void OmpVisitor::AddOmpSourceRange(const parser::CharBlock &source) { 1250 messageHandler().set_currStmtSource(source); 1251 currScope().AddSourceRange(source); 1252 } 1253 1254 bool OmpVisitor::Pre(const parser::OpenMPBlockConstruct &x) { 1255 if (NeedsScope(x)) { 1256 PushScope(Scope::Kind::Block, nullptr); 1257 } 1258 return true; 1259 } 1260 1261 void OmpVisitor::Post(const parser::OpenMPBlockConstruct &x) { 1262 if (NeedsScope(x)) { 1263 PopScope(); 1264 } 1265 } 1266 1267 // Walk the parse tree and resolve names to symbols. 1268 class ResolveNamesVisitor : public virtual ScopeHandler, 1269 public ModuleVisitor, 1270 public SubprogramVisitor, 1271 public ConstructVisitor, 1272 public OmpVisitor, 1273 public AccVisitor { 1274 public: 1275 using AccVisitor::Post; 1276 using AccVisitor::Pre; 1277 using ArraySpecVisitor::Post; 1278 using ConstructVisitor::Post; 1279 using ConstructVisitor::Pre; 1280 using DeclarationVisitor::Post; 1281 using DeclarationVisitor::Pre; 1282 using ImplicitRulesVisitor::Post; 1283 using ImplicitRulesVisitor::Pre; 1284 using InterfaceVisitor::Post; 1285 using InterfaceVisitor::Pre; 1286 using ModuleVisitor::Post; 1287 using ModuleVisitor::Pre; 1288 using OmpVisitor::Post; 1289 using OmpVisitor::Pre; 1290 using ScopeHandler::Post; 1291 using ScopeHandler::Pre; 1292 using SubprogramVisitor::Post; 1293 using SubprogramVisitor::Pre; 1294 1295 ResolveNamesVisitor(SemanticsContext &context, ImplicitRulesMap &rules) 1296 : BaseVisitor{context, *this, rules} { 1297 PushScope(context.globalScope()); 1298 } 1299 1300 // Default action for a parse tree node is to visit children. 1301 template <typename T> bool Pre(const T &) { return true; } 1302 template <typename T> void Post(const T &) {} 1303 1304 bool Pre(const parser::SpecificationPart &); 1305 void Post(const parser::Program &); 1306 bool Pre(const parser::ImplicitStmt &); 1307 void Post(const parser::PointerObject &); 1308 void Post(const parser::AllocateObject &); 1309 bool Pre(const parser::PointerAssignmentStmt &); 1310 void Post(const parser::Designator &); 1311 template <typename A, typename B> 1312 void Post(const parser::LoopBounds<A, B> &x) { 1313 ResolveName(*parser::Unwrap<parser::Name>(x.name)); 1314 } 1315 void Post(const parser::ProcComponentRef &); 1316 bool Pre(const parser::FunctionReference &); 1317 bool Pre(const parser::CallStmt &); 1318 bool Pre(const parser::ImportStmt &); 1319 void Post(const parser::TypeGuardStmt &); 1320 bool Pre(const parser::StmtFunctionStmt &); 1321 bool Pre(const parser::DefinedOpName &); 1322 bool Pre(const parser::ProgramUnit &); 1323 void Post(const parser::AssignStmt &); 1324 void Post(const parser::AssignedGotoStmt &); 1325 1326 // These nodes should never be reached: they are handled in ProgramUnit 1327 bool Pre(const parser::MainProgram &) { 1328 llvm_unreachable("This node is handled in ProgramUnit"); 1329 } 1330 bool Pre(const parser::FunctionSubprogram &) { 1331 llvm_unreachable("This node is handled in ProgramUnit"); 1332 } 1333 bool Pre(const parser::SubroutineSubprogram &) { 1334 llvm_unreachable("This node is handled in ProgramUnit"); 1335 } 1336 bool Pre(const parser::SeparateModuleSubprogram &) { 1337 llvm_unreachable("This node is handled in ProgramUnit"); 1338 } 1339 bool Pre(const parser::Module &) { 1340 llvm_unreachable("This node is handled in ProgramUnit"); 1341 } 1342 bool Pre(const parser::Submodule &) { 1343 llvm_unreachable("This node is handled in ProgramUnit"); 1344 } 1345 bool Pre(const parser::BlockData &) { 1346 llvm_unreachable("This node is handled in ProgramUnit"); 1347 } 1348 1349 void NoteExecutablePartCall(Symbol::Flag, const parser::Call &); 1350 1351 friend void ResolveSpecificationParts(SemanticsContext &, const Symbol &); 1352 1353 private: 1354 // Kind of procedure we are expecting to see in a ProcedureDesignator 1355 std::optional<Symbol::Flag> expectedProcFlag_; 1356 std::optional<SourceName> prevImportStmt_; 1357 1358 void PreSpecificationConstruct(const parser::SpecificationConstruct &); 1359 void CreateCommonBlockSymbols(const parser::CommonStmt &); 1360 void CreateGeneric(const parser::GenericSpec &); 1361 void FinishSpecificationPart(const std::list<parser::DeclarationConstruct> &); 1362 void AnalyzeStmtFunctionStmt(const parser::StmtFunctionStmt &); 1363 void CheckImports(); 1364 void CheckImport(const SourceName &, const SourceName &); 1365 void HandleCall(Symbol::Flag, const parser::Call &); 1366 void HandleProcedureName(Symbol::Flag, const parser::Name &); 1367 bool CheckImplicitNoneExternal(const SourceName &, const Symbol &); 1368 bool SetProcFlag(const parser::Name &, Symbol &, Symbol::Flag); 1369 void ResolveSpecificationParts(ProgramTree &); 1370 void AddSubpNames(ProgramTree &); 1371 bool BeginScopeForNode(const ProgramTree &); 1372 void FinishSpecificationParts(const ProgramTree &); 1373 void FinishDerivedTypeInstantiation(Scope &); 1374 void ResolveExecutionParts(const ProgramTree &); 1375 }; 1376 1377 // ImplicitRules implementation 1378 1379 bool ImplicitRules::isImplicitNoneType() const { 1380 if (isImplicitNoneType_) { 1381 return true; 1382 } else if (map_.empty() && inheritFromParent_) { 1383 return parent_->isImplicitNoneType(); 1384 } else { 1385 return false; // default if not specified 1386 } 1387 } 1388 1389 bool ImplicitRules::isImplicitNoneExternal() const { 1390 if (isImplicitNoneExternal_) { 1391 return true; 1392 } else if (inheritFromParent_) { 1393 return parent_->isImplicitNoneExternal(); 1394 } else { 1395 return false; // default if not specified 1396 } 1397 } 1398 1399 const DeclTypeSpec *ImplicitRules::GetType(SourceName name) const { 1400 char ch{name.begin()[0]}; 1401 if (isImplicitNoneType_) { 1402 return nullptr; 1403 } else if (auto it{map_.find(ch)}; it != map_.end()) { 1404 return &*it->second; 1405 } else if (inheritFromParent_) { 1406 return parent_->GetType(name); 1407 } else if (ch >= 'i' && ch <= 'n') { 1408 return &context_.MakeNumericType(TypeCategory::Integer); 1409 } else if (ch >= 'a' && ch <= 'z') { 1410 return &context_.MakeNumericType(TypeCategory::Real); 1411 } else { 1412 return nullptr; 1413 } 1414 } 1415 1416 void ImplicitRules::SetTypeMapping(const DeclTypeSpec &type, 1417 parser::Location fromLetter, parser::Location toLetter) { 1418 for (char ch = *fromLetter; ch; ch = ImplicitRules::Incr(ch)) { 1419 auto res{map_.emplace(ch, type)}; 1420 if (!res.second) { 1421 context_.Say(parser::CharBlock{fromLetter}, 1422 "More than one implicit type specified for '%c'"_err_en_US, ch); 1423 } 1424 if (ch == *toLetter) { 1425 break; 1426 } 1427 } 1428 } 1429 1430 // Return the next char after ch in a way that works for ASCII or EBCDIC. 1431 // Return '\0' for the char after 'z'. 1432 char ImplicitRules::Incr(char ch) { 1433 switch (ch) { 1434 case 'i': 1435 return 'j'; 1436 case 'r': 1437 return 's'; 1438 case 'z': 1439 return '\0'; 1440 default: 1441 return ch + 1; 1442 } 1443 } 1444 1445 llvm::raw_ostream &operator<<( 1446 llvm::raw_ostream &o, const ImplicitRules &implicitRules) { 1447 o << "ImplicitRules:\n"; 1448 for (char ch = 'a'; ch; ch = ImplicitRules::Incr(ch)) { 1449 ShowImplicitRule(o, implicitRules, ch); 1450 } 1451 ShowImplicitRule(o, implicitRules, '_'); 1452 ShowImplicitRule(o, implicitRules, '$'); 1453 ShowImplicitRule(o, implicitRules, '@'); 1454 return o; 1455 } 1456 void ShowImplicitRule( 1457 llvm::raw_ostream &o, const ImplicitRules &implicitRules, char ch) { 1458 auto it{implicitRules.map_.find(ch)}; 1459 if (it != implicitRules.map_.end()) { 1460 o << " " << ch << ": " << *it->second << '\n'; 1461 } 1462 } 1463 1464 template <typename T> void BaseVisitor::Walk(const T &x) { 1465 parser::Walk(x, *this_); 1466 } 1467 1468 void BaseVisitor::MakePlaceholder( 1469 const parser::Name &name, MiscDetails::Kind kind) { 1470 if (!name.symbol) { 1471 name.symbol = &context_->globalScope().MakeSymbol( 1472 name.source, Attrs{}, MiscDetails{kind}); 1473 } 1474 } 1475 1476 // AttrsVisitor implementation 1477 1478 bool AttrsVisitor::BeginAttrs() { 1479 CHECK(!attrs_); 1480 attrs_ = std::make_optional<Attrs>(); 1481 return true; 1482 } 1483 Attrs AttrsVisitor::GetAttrs() { 1484 CHECK(attrs_); 1485 return *attrs_; 1486 } 1487 Attrs AttrsVisitor::EndAttrs() { 1488 Attrs result{GetAttrs()}; 1489 attrs_.reset(); 1490 passName_ = std::nullopt; 1491 bindName_.reset(); 1492 return result; 1493 } 1494 1495 bool AttrsVisitor::SetPassNameOn(Symbol &symbol) { 1496 if (!passName_) { 1497 return false; 1498 } 1499 std::visit(common::visitors{ 1500 [&](ProcEntityDetails &x) { x.set_passName(*passName_); }, 1501 [&](ProcBindingDetails &x) { x.set_passName(*passName_); }, 1502 [](auto &) { common::die("unexpected pass name"); }, 1503 }, 1504 symbol.details()); 1505 return true; 1506 } 1507 1508 bool AttrsVisitor::SetBindNameOn(Symbol &symbol) { 1509 if (!bindName_) { 1510 return false; 1511 } 1512 std::visit( 1513 common::visitors{ 1514 [&](EntityDetails &x) { x.set_bindName(std::move(bindName_)); }, 1515 [&](ObjectEntityDetails &x) { x.set_bindName(std::move(bindName_)); }, 1516 [&](ProcEntityDetails &x) { x.set_bindName(std::move(bindName_)); }, 1517 [&](SubprogramDetails &x) { x.set_bindName(std::move(bindName_)); }, 1518 [&](CommonBlockDetails &x) { x.set_bindName(std::move(bindName_)); }, 1519 [](auto &) { common::die("unexpected bind name"); }, 1520 }, 1521 symbol.details()); 1522 return true; 1523 } 1524 1525 void AttrsVisitor::Post(const parser::LanguageBindingSpec &x) { 1526 CHECK(attrs_); 1527 if (CheckAndSet(Attr::BIND_C)) { 1528 if (x.v) { 1529 bindName_ = EvaluateExpr(*x.v); 1530 } 1531 } 1532 } 1533 bool AttrsVisitor::Pre(const parser::IntentSpec &x) { 1534 CHECK(attrs_); 1535 CheckAndSet(IntentSpecToAttr(x)); 1536 return false; 1537 } 1538 bool AttrsVisitor::Pre(const parser::Pass &x) { 1539 if (CheckAndSet(Attr::PASS)) { 1540 if (x.v) { 1541 passName_ = x.v->source; 1542 MakePlaceholder(*x.v, MiscDetails::Kind::PassName); 1543 } 1544 } 1545 return false; 1546 } 1547 1548 // C730, C743, C755, C778, C1543 say no attribute or prefix repetitions 1549 bool AttrsVisitor::IsDuplicateAttr(Attr attrName) { 1550 if (attrs_->test(attrName)) { 1551 Say(currStmtSource().value(), 1552 "Attribute '%s' cannot be used more than once"_en_US, 1553 AttrToString(attrName)); 1554 return true; 1555 } 1556 return false; 1557 } 1558 1559 // See if attrName violates a constraint cause by a conflict. attr1 and attr2 1560 // name attributes that cannot be used on the same declaration 1561 bool AttrsVisitor::HaveAttrConflict(Attr attrName, Attr attr1, Attr attr2) { 1562 if ((attrName == attr1 && attrs_->test(attr2)) || 1563 (attrName == attr2 && attrs_->test(attr1))) { 1564 Say(currStmtSource().value(), 1565 "Attributes '%s' and '%s' conflict with each other"_err_en_US, 1566 AttrToString(attr1), AttrToString(attr2)); 1567 return true; 1568 } 1569 return false; 1570 } 1571 // C759, C1543 1572 bool AttrsVisitor::IsConflictingAttr(Attr attrName) { 1573 return HaveAttrConflict(attrName, Attr::INTENT_IN, Attr::INTENT_INOUT) || 1574 HaveAttrConflict(attrName, Attr::INTENT_IN, Attr::INTENT_OUT) || 1575 HaveAttrConflict(attrName, Attr::INTENT_INOUT, Attr::INTENT_OUT) || 1576 HaveAttrConflict(attrName, Attr::PASS, Attr::NOPASS) || // C781 1577 HaveAttrConflict(attrName, Attr::PURE, Attr::IMPURE) || 1578 HaveAttrConflict(attrName, Attr::PUBLIC, Attr::PRIVATE) || 1579 HaveAttrConflict(attrName, Attr::RECURSIVE, Attr::NON_RECURSIVE); 1580 } 1581 bool AttrsVisitor::CheckAndSet(Attr attrName) { 1582 CHECK(attrs_); 1583 if (IsConflictingAttr(attrName) || IsDuplicateAttr(attrName)) { 1584 return false; 1585 } 1586 attrs_->set(attrName); 1587 return true; 1588 } 1589 1590 // DeclTypeSpecVisitor implementation 1591 1592 const DeclTypeSpec *DeclTypeSpecVisitor::GetDeclTypeSpec() { 1593 return state_.declTypeSpec; 1594 } 1595 1596 void DeclTypeSpecVisitor::BeginDeclTypeSpec() { 1597 CHECK(!state_.expectDeclTypeSpec); 1598 CHECK(!state_.declTypeSpec); 1599 state_.expectDeclTypeSpec = true; 1600 } 1601 void DeclTypeSpecVisitor::EndDeclTypeSpec() { 1602 CHECK(state_.expectDeclTypeSpec); 1603 state_ = {}; 1604 } 1605 1606 void DeclTypeSpecVisitor::SetDeclTypeSpecCategory( 1607 DeclTypeSpec::Category category) { 1608 CHECK(state_.expectDeclTypeSpec); 1609 state_.derived.category = category; 1610 } 1611 1612 bool DeclTypeSpecVisitor::Pre(const parser::TypeGuardStmt &) { 1613 BeginDeclTypeSpec(); 1614 return true; 1615 } 1616 void DeclTypeSpecVisitor::Post(const parser::TypeGuardStmt &) { 1617 EndDeclTypeSpec(); 1618 } 1619 1620 void DeclTypeSpecVisitor::Post(const parser::TypeSpec &typeSpec) { 1621 // Record the resolved DeclTypeSpec in the parse tree for use by 1622 // expression semantics if the DeclTypeSpec is a valid TypeSpec. 1623 // The grammar ensures that it's an intrinsic or derived type spec, 1624 // not TYPE(*) or CLASS(*) or CLASS(T). 1625 if (const DeclTypeSpec * spec{state_.declTypeSpec}) { 1626 switch (spec->category()) { 1627 case DeclTypeSpec::Numeric: 1628 case DeclTypeSpec::Logical: 1629 case DeclTypeSpec::Character: 1630 typeSpec.declTypeSpec = spec; 1631 break; 1632 case DeclTypeSpec::TypeDerived: 1633 if (const DerivedTypeSpec * derived{spec->AsDerived()}) { 1634 CheckForAbstractType(derived->typeSymbol()); // C703 1635 typeSpec.declTypeSpec = spec; 1636 } 1637 break; 1638 default: 1639 CRASH_NO_CASE; 1640 } 1641 } 1642 } 1643 1644 void DeclTypeSpecVisitor::Post( 1645 const parser::IntrinsicTypeSpec::DoublePrecision &) { 1646 MakeNumericType(TypeCategory::Real, context().doublePrecisionKind()); 1647 } 1648 void DeclTypeSpecVisitor::Post( 1649 const parser::IntrinsicTypeSpec::DoubleComplex &) { 1650 MakeNumericType(TypeCategory::Complex, context().doublePrecisionKind()); 1651 } 1652 void DeclTypeSpecVisitor::MakeNumericType(TypeCategory category, int kind) { 1653 SetDeclTypeSpec(context().MakeNumericType(category, kind)); 1654 } 1655 1656 void DeclTypeSpecVisitor::CheckForAbstractType(const Symbol &typeSymbol) { 1657 if (typeSymbol.attrs().test(Attr::ABSTRACT)) { 1658 Say("ABSTRACT derived type may not be used here"_err_en_US); 1659 } 1660 } 1661 1662 void DeclTypeSpecVisitor::Post(const parser::DeclarationTypeSpec::ClassStar &) { 1663 SetDeclTypeSpec(context().globalScope().MakeClassStarType()); 1664 } 1665 void DeclTypeSpecVisitor::Post(const parser::DeclarationTypeSpec::TypeStar &) { 1666 SetDeclTypeSpec(context().globalScope().MakeTypeStarType()); 1667 } 1668 1669 // Check that we're expecting to see a DeclTypeSpec (and haven't seen one yet) 1670 // and save it in state_.declTypeSpec. 1671 void DeclTypeSpecVisitor::SetDeclTypeSpec(const DeclTypeSpec &declTypeSpec) { 1672 CHECK(state_.expectDeclTypeSpec); 1673 CHECK(!state_.declTypeSpec); 1674 state_.declTypeSpec = &declTypeSpec; 1675 } 1676 1677 KindExpr DeclTypeSpecVisitor::GetKindParamExpr( 1678 TypeCategory category, const std::optional<parser::KindSelector> &kind) { 1679 return AnalyzeKindSelector(context(), category, kind); 1680 } 1681 1682 // MessageHandler implementation 1683 1684 Message &MessageHandler::Say(MessageFixedText &&msg) { 1685 return context_->Say(currStmtSource().value(), std::move(msg)); 1686 } 1687 Message &MessageHandler::Say(MessageFormattedText &&msg) { 1688 return context_->Say(currStmtSource().value(), std::move(msg)); 1689 } 1690 Message &MessageHandler::Say(const SourceName &name, MessageFixedText &&msg) { 1691 return Say(name, std::move(msg), name); 1692 } 1693 1694 // ImplicitRulesVisitor implementation 1695 1696 void ImplicitRulesVisitor::Post(const parser::ParameterStmt &) { 1697 prevParameterStmt_ = currStmtSource(); 1698 } 1699 1700 bool ImplicitRulesVisitor::Pre(const parser::ImplicitStmt &x) { 1701 bool result{ 1702 std::visit(common::visitors{ 1703 [&](const std::list<ImplicitNoneNameSpec> &y) { 1704 return HandleImplicitNone(y); 1705 }, 1706 [&](const std::list<parser::ImplicitSpec> &) { 1707 if (prevImplicitNoneType_) { 1708 Say("IMPLICIT statement after IMPLICIT NONE or " 1709 "IMPLICIT NONE(TYPE) statement"_err_en_US); 1710 return false; 1711 } 1712 implicitRules_->set_isImplicitNoneType(false); 1713 return true; 1714 }, 1715 }, 1716 x.u)}; 1717 prevImplicit_ = currStmtSource(); 1718 return result; 1719 } 1720 1721 bool ImplicitRulesVisitor::Pre(const parser::LetterSpec &x) { 1722 auto loLoc{std::get<parser::Location>(x.t)}; 1723 auto hiLoc{loLoc}; 1724 if (auto hiLocOpt{std::get<std::optional<parser::Location>>(x.t)}) { 1725 hiLoc = *hiLocOpt; 1726 if (*hiLoc < *loLoc) { 1727 Say(hiLoc, "'%s' does not follow '%s' alphabetically"_err_en_US, 1728 std::string(hiLoc, 1), std::string(loLoc, 1)); 1729 return false; 1730 } 1731 } 1732 implicitRules_->SetTypeMapping(*GetDeclTypeSpec(), loLoc, hiLoc); 1733 return false; 1734 } 1735 1736 bool ImplicitRulesVisitor::Pre(const parser::ImplicitSpec &) { 1737 BeginDeclTypeSpec(); 1738 set_allowForwardReferenceToDerivedType(true); 1739 return true; 1740 } 1741 1742 void ImplicitRulesVisitor::Post(const parser::ImplicitSpec &) { 1743 EndDeclTypeSpec(); 1744 } 1745 1746 void ImplicitRulesVisitor::SetScope(const Scope &scope) { 1747 implicitRules_ = &DEREF(implicitRulesMap_).at(&scope); 1748 prevImplicit_ = std::nullopt; 1749 prevImplicitNone_ = std::nullopt; 1750 prevImplicitNoneType_ = std::nullopt; 1751 prevParameterStmt_ = std::nullopt; 1752 } 1753 void ImplicitRulesVisitor::BeginScope(const Scope &scope) { 1754 // find or create implicit rules for this scope 1755 DEREF(implicitRulesMap_).try_emplace(&scope, context(), implicitRules_); 1756 SetScope(scope); 1757 } 1758 1759 // TODO: for all of these errors, reference previous statement too 1760 bool ImplicitRulesVisitor::HandleImplicitNone( 1761 const std::list<ImplicitNoneNameSpec> &nameSpecs) { 1762 if (prevImplicitNone_) { 1763 Say("More than one IMPLICIT NONE statement"_err_en_US); 1764 Say(*prevImplicitNone_, "Previous IMPLICIT NONE statement"_en_US); 1765 return false; 1766 } 1767 if (prevParameterStmt_) { 1768 Say("IMPLICIT NONE statement after PARAMETER statement"_err_en_US); 1769 return false; 1770 } 1771 prevImplicitNone_ = currStmtSource(); 1772 bool implicitNoneTypeNever{ 1773 context().IsEnabled(common::LanguageFeature::ImplicitNoneTypeNever)}; 1774 if (nameSpecs.empty()) { 1775 if (!implicitNoneTypeNever) { 1776 prevImplicitNoneType_ = currStmtSource(); 1777 implicitRules_->set_isImplicitNoneType(true); 1778 if (prevImplicit_) { 1779 Say("IMPLICIT NONE statement after IMPLICIT statement"_err_en_US); 1780 return false; 1781 } 1782 } 1783 } else { 1784 int sawType{0}; 1785 int sawExternal{0}; 1786 for (const auto noneSpec : nameSpecs) { 1787 switch (noneSpec) { 1788 case ImplicitNoneNameSpec::External: 1789 implicitRules_->set_isImplicitNoneExternal(true); 1790 ++sawExternal; 1791 break; 1792 case ImplicitNoneNameSpec::Type: 1793 if (!implicitNoneTypeNever) { 1794 prevImplicitNoneType_ = currStmtSource(); 1795 implicitRules_->set_isImplicitNoneType(true); 1796 if (prevImplicit_) { 1797 Say("IMPLICIT NONE(TYPE) after IMPLICIT statement"_err_en_US); 1798 return false; 1799 } 1800 ++sawType; 1801 } 1802 break; 1803 } 1804 } 1805 if (sawType > 1) { 1806 Say("TYPE specified more than once in IMPLICIT NONE statement"_err_en_US); 1807 return false; 1808 } 1809 if (sawExternal > 1) { 1810 Say("EXTERNAL specified more than once in IMPLICIT NONE statement"_err_en_US); 1811 return false; 1812 } 1813 } 1814 return true; 1815 } 1816 1817 // ArraySpecVisitor implementation 1818 1819 void ArraySpecVisitor::Post(const parser::ArraySpec &x) { 1820 CHECK(arraySpec_.empty()); 1821 arraySpec_ = AnalyzeArraySpec(context(), x); 1822 } 1823 void ArraySpecVisitor::Post(const parser::ComponentArraySpec &x) { 1824 CHECK(arraySpec_.empty()); 1825 arraySpec_ = AnalyzeArraySpec(context(), x); 1826 } 1827 void ArraySpecVisitor::Post(const parser::CoarraySpec &x) { 1828 CHECK(coarraySpec_.empty()); 1829 coarraySpec_ = AnalyzeCoarraySpec(context(), x); 1830 } 1831 1832 const ArraySpec &ArraySpecVisitor::arraySpec() { 1833 return !arraySpec_.empty() ? arraySpec_ : attrArraySpec_; 1834 } 1835 const ArraySpec &ArraySpecVisitor::coarraySpec() { 1836 return !coarraySpec_.empty() ? coarraySpec_ : attrCoarraySpec_; 1837 } 1838 void ArraySpecVisitor::BeginArraySpec() { 1839 CHECK(arraySpec_.empty()); 1840 CHECK(coarraySpec_.empty()); 1841 CHECK(attrArraySpec_.empty()); 1842 CHECK(attrCoarraySpec_.empty()); 1843 } 1844 void ArraySpecVisitor::EndArraySpec() { 1845 CHECK(arraySpec_.empty()); 1846 CHECK(coarraySpec_.empty()); 1847 attrArraySpec_.clear(); 1848 attrCoarraySpec_.clear(); 1849 } 1850 void ArraySpecVisitor::PostAttrSpec() { 1851 // Save dimension/codimension from attrs so we can process array/coarray-spec 1852 // on the entity-decl 1853 if (!arraySpec_.empty()) { 1854 if (attrArraySpec_.empty()) { 1855 attrArraySpec_ = arraySpec_; 1856 arraySpec_.clear(); 1857 } else { 1858 Say(currStmtSource().value(), 1859 "Attribute 'DIMENSION' cannot be used more than once"_err_en_US); 1860 } 1861 } 1862 if (!coarraySpec_.empty()) { 1863 if (attrCoarraySpec_.empty()) { 1864 attrCoarraySpec_ = coarraySpec_; 1865 coarraySpec_.clear(); 1866 } else { 1867 Say(currStmtSource().value(), 1868 "Attribute 'CODIMENSION' cannot be used more than once"_err_en_US); 1869 } 1870 } 1871 } 1872 1873 // ScopeHandler implementation 1874 1875 void ScopeHandler::SayAlreadyDeclared(const parser::Name &name, Symbol &prev) { 1876 SayAlreadyDeclared(name.source, prev); 1877 } 1878 void ScopeHandler::SayAlreadyDeclared(const SourceName &name, Symbol &prev) { 1879 if (context().HasError(prev)) { 1880 // don't report another error about prev 1881 } else { 1882 if (const auto *details{prev.detailsIf<UseDetails>()}) { 1883 Say(name, "'%s' is already declared in this scoping unit"_err_en_US) 1884 .Attach(details->location(), 1885 "It is use-associated with '%s' in module '%s'"_err_en_US, 1886 details->symbol().name(), GetUsedModule(*details).name()); 1887 } else { 1888 SayAlreadyDeclared(name, prev.name()); 1889 } 1890 context().SetError(prev); 1891 } 1892 } 1893 void ScopeHandler::SayAlreadyDeclared( 1894 const SourceName &name1, const SourceName &name2) { 1895 if (name1.begin() < name2.begin()) { 1896 SayAlreadyDeclared(name2, name1); 1897 } else { 1898 Say(name1, "'%s' is already declared in this scoping unit"_err_en_US) 1899 .Attach(name2, "Previous declaration of '%s'"_en_US, name2); 1900 } 1901 } 1902 1903 void ScopeHandler::SayWithReason(const parser::Name &name, Symbol &symbol, 1904 MessageFixedText &&msg1, MessageFixedText &&msg2) { 1905 Say2(name, std::move(msg1), symbol, std::move(msg2)); 1906 context().SetError(symbol, msg1.isFatal()); 1907 } 1908 1909 void ScopeHandler::SayWithDecl( 1910 const parser::Name &name, Symbol &symbol, MessageFixedText &&msg) { 1911 SayWithReason(name, symbol, std::move(msg), 1912 symbol.test(Symbol::Flag::Implicit) ? "Implicit declaration of '%s'"_en_US 1913 : "Declaration of '%s'"_en_US); 1914 } 1915 1916 void ScopeHandler::SayLocalMustBeVariable( 1917 const parser::Name &name, Symbol &symbol) { 1918 SayWithDecl(name, symbol, 1919 "The name '%s' must be a variable to appear" 1920 " in a locality-spec"_err_en_US); 1921 } 1922 1923 void ScopeHandler::SayDerivedType( 1924 const SourceName &name, MessageFixedText &&msg, const Scope &type) { 1925 const Symbol &typeSymbol{DEREF(type.GetSymbol())}; 1926 Say(name, std::move(msg), name, typeSymbol.name()) 1927 .Attach(typeSymbol.name(), "Declaration of derived type '%s'"_en_US, 1928 typeSymbol.name()); 1929 } 1930 void ScopeHandler::Say2(const SourceName &name1, MessageFixedText &&msg1, 1931 const SourceName &name2, MessageFixedText &&msg2) { 1932 Say(name1, std::move(msg1)).Attach(name2, std::move(msg2), name2); 1933 } 1934 void ScopeHandler::Say2(const SourceName &name, MessageFixedText &&msg1, 1935 Symbol &symbol, MessageFixedText &&msg2) { 1936 Say2(name, std::move(msg1), symbol.name(), std::move(msg2)); 1937 context().SetError(symbol, msg1.isFatal()); 1938 } 1939 void ScopeHandler::Say2(const parser::Name &name, MessageFixedText &&msg1, 1940 Symbol &symbol, MessageFixedText &&msg2) { 1941 Say2(name.source, std::move(msg1), symbol.name(), std::move(msg2)); 1942 context().SetError(symbol, msg1.isFatal()); 1943 } 1944 1945 // T may be `Scope` or `const Scope` 1946 template <typename T> static T &GetInclusiveScope(T &scope) { 1947 for (T *s{&scope}; !s->IsGlobal(); s = &s->parent()) { 1948 if (s->kind() != Scope::Kind::Block && !s->IsDerivedType() && 1949 !s->IsStmtFunction()) { 1950 return *s; 1951 } 1952 } 1953 return scope; 1954 } 1955 1956 Scope &ScopeHandler::InclusiveScope() { return GetInclusiveScope(currScope()); } 1957 1958 Scope *ScopeHandler::GetHostProcedure() { 1959 Scope &parent{InclusiveScope().parent()}; 1960 return parent.kind() == Scope::Kind::Subprogram ? &parent : nullptr; 1961 } 1962 1963 Scope &ScopeHandler::NonDerivedTypeScope() { 1964 return currScope_->IsDerivedType() ? currScope_->parent() : *currScope_; 1965 } 1966 1967 void ScopeHandler::PushScope(Scope::Kind kind, Symbol *symbol) { 1968 PushScope(currScope().MakeScope(kind, symbol)); 1969 } 1970 void ScopeHandler::PushScope(Scope &scope) { 1971 currScope_ = &scope; 1972 auto kind{currScope_->kind()}; 1973 if (kind != Scope::Kind::Block) { 1974 BeginScope(scope); 1975 } 1976 // The name of a module or submodule cannot be "used" in its scope, 1977 // as we read 19.3.1(2), so we allow the name to be used as a local 1978 // identifier in the module or submodule too. Same with programs 1979 // (14.1(3)) and BLOCK DATA. 1980 if (!currScope_->IsDerivedType() && kind != Scope::Kind::Module && 1981 kind != Scope::Kind::MainProgram && kind != Scope::Kind::BlockData) { 1982 if (auto *symbol{scope.symbol()}) { 1983 // Create a dummy symbol so we can't create another one with the same 1984 // name. It might already be there if we previously pushed the scope. 1985 if (!FindInScope(scope, symbol->name())) { 1986 auto &newSymbol{MakeSymbol(symbol->name())}; 1987 if (kind == Scope::Kind::Subprogram) { 1988 // Allow for recursive references. If this symbol is a function 1989 // without an explicit RESULT(), this new symbol will be discarded 1990 // and replaced with an object of the same name. 1991 newSymbol.set_details(HostAssocDetails{*symbol}); 1992 } else { 1993 newSymbol.set_details(MiscDetails{MiscDetails::Kind::ScopeName}); 1994 } 1995 } 1996 } 1997 } 1998 } 1999 void ScopeHandler::PopScope() { 2000 // Entities that are not yet classified as objects or procedures are now 2001 // assumed to be objects. 2002 // TODO: Statement functions 2003 for (auto &pair : currScope()) { 2004 ConvertToObjectEntity(*pair.second); 2005 } 2006 SetScope(currScope_->parent()); 2007 } 2008 void ScopeHandler::SetScope(Scope &scope) { 2009 currScope_ = &scope; 2010 ImplicitRulesVisitor::SetScope(InclusiveScope()); 2011 } 2012 2013 Symbol *ScopeHandler::FindSymbol(const parser::Name &name) { 2014 return FindSymbol(currScope(), name); 2015 } 2016 Symbol *ScopeHandler::FindSymbol(const Scope &scope, const parser::Name &name) { 2017 if (scope.IsDerivedType()) { 2018 if (Symbol * symbol{scope.FindComponent(name.source)}) { 2019 if (!symbol->has<ProcBindingDetails>() && 2020 !symbol->test(Symbol::Flag::ParentComp)) { 2021 return Resolve(name, symbol); 2022 } 2023 } 2024 return FindSymbol(scope.parent(), name); 2025 } else { 2026 // In EQUIVALENCE statements only resolve names in the local scope, see 2027 // 19.5.1.4, paragraph 2, item (10) 2028 return Resolve(name, 2029 inEquivalenceStmt_ ? FindInScope(scope, name) 2030 : scope.FindSymbol(name.source)); 2031 } 2032 } 2033 2034 Symbol &ScopeHandler::MakeSymbol( 2035 Scope &scope, const SourceName &name, Attrs attrs) { 2036 if (Symbol * symbol{FindInScope(scope, name)}) { 2037 symbol->attrs() |= attrs; 2038 return *symbol; 2039 } else { 2040 const auto pair{scope.try_emplace(name, attrs, UnknownDetails{})}; 2041 CHECK(pair.second); // name was not found, so must be able to add 2042 return *pair.first->second; 2043 } 2044 } 2045 Symbol &ScopeHandler::MakeSymbol(const SourceName &name, Attrs attrs) { 2046 return MakeSymbol(currScope(), name, attrs); 2047 } 2048 Symbol &ScopeHandler::MakeSymbol(const parser::Name &name, Attrs attrs) { 2049 return Resolve(name, MakeSymbol(name.source, attrs)); 2050 } 2051 Symbol &ScopeHandler::MakeHostAssocSymbol( 2052 const parser::Name &name, const Symbol &hostSymbol) { 2053 Symbol &symbol{*NonDerivedTypeScope() 2054 .try_emplace(name.source, HostAssocDetails{hostSymbol}) 2055 .first->second}; 2056 name.symbol = &symbol; 2057 symbol.attrs() = hostSymbol.attrs(); // TODO: except PRIVATE, PUBLIC? 2058 symbol.flags() = hostSymbol.flags(); 2059 return symbol; 2060 } 2061 Symbol &ScopeHandler::CopySymbol(const SourceName &name, const Symbol &symbol) { 2062 CHECK(!FindInScope(name)); 2063 return MakeSymbol(currScope(), name, symbol.attrs()); 2064 } 2065 2066 // Look for name only in scope, not in enclosing scopes. 2067 Symbol *ScopeHandler::FindInScope( 2068 const Scope &scope, const parser::Name &name) { 2069 return Resolve(name, FindInScope(scope, name.source)); 2070 } 2071 Symbol *ScopeHandler::FindInScope(const Scope &scope, const SourceName &name) { 2072 // all variants of names, e.g. "operator(.ne.)" for "operator(/=)" 2073 for (const std::string &n : GetAllNames(context(), name)) { 2074 auto it{scope.find(SourceName{n})}; 2075 if (it != scope.end()) { 2076 return &*it->second; 2077 } 2078 } 2079 return nullptr; 2080 } 2081 2082 // Find a component or type parameter by name in a derived type or its parents. 2083 Symbol *ScopeHandler::FindInTypeOrParents( 2084 const Scope &scope, const parser::Name &name) { 2085 return Resolve(name, scope.FindComponent(name.source)); 2086 } 2087 Symbol *ScopeHandler::FindInTypeOrParents(const parser::Name &name) { 2088 return FindInTypeOrParents(currScope(), name); 2089 } 2090 2091 void ScopeHandler::EraseSymbol(const parser::Name &name) { 2092 currScope().erase(name.source); 2093 name.symbol = nullptr; 2094 } 2095 2096 static bool NeedsType(const Symbol &symbol) { 2097 return !symbol.GetType() && 2098 std::visit(common::visitors{ 2099 [](const EntityDetails &) { return true; }, 2100 [](const ObjectEntityDetails &) { return true; }, 2101 [](const AssocEntityDetails &) { return true; }, 2102 [&](const ProcEntityDetails &p) { 2103 return symbol.test(Symbol::Flag::Function) && 2104 !symbol.attrs().test(Attr::INTRINSIC) && 2105 !p.interface().type() && !p.interface().symbol(); 2106 }, 2107 [](const auto &) { return false; }, 2108 }, 2109 symbol.details()); 2110 } 2111 2112 void ScopeHandler::ApplyImplicitRules(Symbol &symbol) { 2113 if (NeedsType(symbol)) { 2114 const Scope *scope{&symbol.owner()}; 2115 if (scope->IsGlobal()) { 2116 scope = &currScope(); 2117 } 2118 if (const DeclTypeSpec * 2119 type{GetImplicitType(symbol, GetInclusiveScope(*scope))}) { 2120 symbol.set(Symbol::Flag::Implicit); 2121 symbol.SetType(*type); 2122 return; 2123 } 2124 if (symbol.has<ProcEntityDetails>() && 2125 !symbol.attrs().test(Attr::EXTERNAL)) { 2126 std::optional<Symbol::Flag> functionOrSubroutineFlag; 2127 if (symbol.test(Symbol::Flag::Function)) { 2128 functionOrSubroutineFlag = Symbol::Flag::Function; 2129 } else if (symbol.test(Symbol::Flag::Subroutine)) { 2130 functionOrSubroutineFlag = Symbol::Flag::Subroutine; 2131 } 2132 if (IsIntrinsic(symbol.name(), functionOrSubroutineFlag)) { 2133 // type will be determined in expression semantics 2134 symbol.attrs().set(Attr::INTRINSIC); 2135 return; 2136 } 2137 } 2138 if (!context().HasError(symbol)) { 2139 Say(symbol.name(), "No explicit type declared for '%s'"_err_en_US); 2140 context().SetError(symbol); 2141 } 2142 } 2143 } 2144 2145 const DeclTypeSpec *ScopeHandler::GetImplicitType( 2146 Symbol &symbol, const Scope &scope) { 2147 const auto *type{implicitRulesMap_->at(&scope).GetType(symbol.name())}; 2148 if (type) { 2149 if (const DerivedTypeSpec * derived{type->AsDerived()}) { 2150 // Resolve any forward-referenced derived type; a quick no-op else. 2151 auto &instantiatable{*const_cast<DerivedTypeSpec *>(derived)}; 2152 instantiatable.Instantiate(currScope(), context()); 2153 } 2154 } 2155 return type; 2156 } 2157 2158 // Convert symbol to be a ObjectEntity or return false if it can't be. 2159 bool ScopeHandler::ConvertToObjectEntity(Symbol &symbol) { 2160 if (symbol.has<ObjectEntityDetails>()) { 2161 // nothing to do 2162 } else if (symbol.has<UnknownDetails>()) { 2163 symbol.set_details(ObjectEntityDetails{}); 2164 } else if (auto *details{symbol.detailsIf<EntityDetails>()}) { 2165 symbol.set_details(ObjectEntityDetails{std::move(*details)}); 2166 } else if (auto *useDetails{symbol.detailsIf<UseDetails>()}) { 2167 return useDetails->symbol().has<ObjectEntityDetails>(); 2168 } else { 2169 return false; 2170 } 2171 return true; 2172 } 2173 // Convert symbol to be a ProcEntity or return false if it can't be. 2174 bool ScopeHandler::ConvertToProcEntity(Symbol &symbol) { 2175 if (symbol.has<ProcEntityDetails>()) { 2176 // nothing to do 2177 } else if (symbol.has<UnknownDetails>()) { 2178 symbol.set_details(ProcEntityDetails{}); 2179 } else if (auto *details{symbol.detailsIf<EntityDetails>()}) { 2180 symbol.set_details(ProcEntityDetails{std::move(*details)}); 2181 if (symbol.GetType() && !symbol.test(Symbol::Flag::Implicit)) { 2182 CHECK(!symbol.test(Symbol::Flag::Subroutine)); 2183 symbol.set(Symbol::Flag::Function); 2184 } 2185 } else { 2186 return false; 2187 } 2188 return true; 2189 } 2190 2191 const DeclTypeSpec &ScopeHandler::MakeNumericType( 2192 TypeCategory category, const std::optional<parser::KindSelector> &kind) { 2193 KindExpr value{GetKindParamExpr(category, kind)}; 2194 if (auto known{evaluate::ToInt64(value)}) { 2195 return context().MakeNumericType(category, static_cast<int>(*known)); 2196 } else { 2197 return currScope_->MakeNumericType(category, std::move(value)); 2198 } 2199 } 2200 2201 const DeclTypeSpec &ScopeHandler::MakeLogicalType( 2202 const std::optional<parser::KindSelector> &kind) { 2203 KindExpr value{GetKindParamExpr(TypeCategory::Logical, kind)}; 2204 if (auto known{evaluate::ToInt64(value)}) { 2205 return context().MakeLogicalType(static_cast<int>(*known)); 2206 } else { 2207 return currScope_->MakeLogicalType(std::move(value)); 2208 } 2209 } 2210 2211 void ScopeHandler::NotePossibleBadForwardRef(const parser::Name &name) { 2212 if (inSpecificationPart_ && name.symbol) { 2213 auto kind{currScope().kind()}; 2214 if ((kind == Scope::Kind::Subprogram && !currScope().IsStmtFunction()) || 2215 kind == Scope::Kind::Block) { 2216 bool isHostAssociated{&name.symbol->owner() == &currScope() 2217 ? name.symbol->has<HostAssocDetails>() 2218 : name.symbol->owner().Contains(currScope())}; 2219 if (isHostAssociated) { 2220 specPartForwardRefs_.insert(name.source); 2221 } 2222 } 2223 } 2224 } 2225 2226 std::optional<SourceName> ScopeHandler::HadForwardRef( 2227 const Symbol &symbol) const { 2228 auto iter{specPartForwardRefs_.find(symbol.name())}; 2229 if (iter != specPartForwardRefs_.end()) { 2230 return *iter; 2231 } 2232 return std::nullopt; 2233 } 2234 2235 bool ScopeHandler::CheckPossibleBadForwardRef(const Symbol &symbol) { 2236 if (!context().HasError(symbol)) { 2237 if (auto fwdRef{HadForwardRef(symbol)}) { 2238 Say(*fwdRef, 2239 "Forward reference to '%s' is not allowed in the same specification part"_err_en_US, 2240 *fwdRef) 2241 .Attach(symbol.name(), "Later declaration of '%s'"_en_US, *fwdRef); 2242 context().SetError(symbol); 2243 return true; 2244 } 2245 } 2246 return false; 2247 } 2248 2249 void ScopeHandler::MakeExternal(Symbol &symbol) { 2250 if (!symbol.attrs().test(Attr::EXTERNAL)) { 2251 symbol.attrs().set(Attr::EXTERNAL); 2252 if (symbol.attrs().test(Attr::INTRINSIC)) { // C840 2253 Say(symbol.name(), 2254 "Symbol '%s' cannot have both EXTERNAL and INTRINSIC attributes"_err_en_US, 2255 symbol.name()); 2256 } 2257 } 2258 } 2259 2260 // ModuleVisitor implementation 2261 2262 bool ModuleVisitor::Pre(const parser::Only &x) { 2263 std::visit(common::visitors{ 2264 [&](const Indirection<parser::GenericSpec> &generic) { 2265 AddUse(GenericSpecInfo{generic.value()}); 2266 }, 2267 [&](const parser::Name &name) { 2268 Resolve(name, AddUse(name.source, name.source).use); 2269 }, 2270 [&](const parser::Rename &rename) { Walk(rename); }, 2271 }, 2272 x.u); 2273 return false; 2274 } 2275 2276 bool ModuleVisitor::Pre(const parser::Rename::Names &x) { 2277 const auto &localName{std::get<0>(x.t)}; 2278 const auto &useName{std::get<1>(x.t)}; 2279 SymbolRename rename{AddUse(localName.source, useName.source)}; 2280 Resolve(useName, rename.use); 2281 Resolve(localName, rename.local); 2282 return false; 2283 } 2284 bool ModuleVisitor::Pre(const parser::Rename::Operators &x) { 2285 const parser::DefinedOpName &local{std::get<0>(x.t)}; 2286 const parser::DefinedOpName &use{std::get<1>(x.t)}; 2287 GenericSpecInfo localInfo{local}; 2288 GenericSpecInfo useInfo{use}; 2289 if (IsIntrinsicOperator(context(), local.v.source)) { 2290 Say(local.v, 2291 "Intrinsic operator '%s' may not be used as a defined operator"_err_en_US); 2292 } else if (IsLogicalConstant(context(), local.v.source)) { 2293 Say(local.v, 2294 "Logical constant '%s' may not be used as a defined operator"_err_en_US); 2295 } else { 2296 SymbolRename rename{AddUse(localInfo.symbolName(), useInfo.symbolName())}; 2297 useInfo.Resolve(rename.use); 2298 localInfo.Resolve(rename.local); 2299 } 2300 return false; 2301 } 2302 2303 // Set useModuleScope_ to the Scope of the module being used. 2304 bool ModuleVisitor::Pre(const parser::UseStmt &x) { 2305 useModuleScope_ = FindModule(x.moduleName); 2306 if (!useModuleScope_) { 2307 return false; 2308 } 2309 // use the name from this source file 2310 useModuleScope_->symbol()->ReplaceName(x.moduleName.source); 2311 return true; 2312 } 2313 2314 void ModuleVisitor::Post(const parser::UseStmt &x) { 2315 if (const auto *list{std::get_if<std::list<parser::Rename>>(&x.u)}) { 2316 // Not a use-only: collect the names that were used in renames, 2317 // then add a use for each public name that was not renamed. 2318 std::set<SourceName> useNames; 2319 for (const auto &rename : *list) { 2320 std::visit(common::visitors{ 2321 [&](const parser::Rename::Names &names) { 2322 useNames.insert(std::get<1>(names.t).source); 2323 }, 2324 [&](const parser::Rename::Operators &ops) { 2325 useNames.insert(std::get<1>(ops.t).v.source); 2326 }, 2327 }, 2328 rename.u); 2329 } 2330 for (const auto &[name, symbol] : *useModuleScope_) { 2331 if (symbol->attrs().test(Attr::PUBLIC) && 2332 !symbol->attrs().test(Attr::INTRINSIC) && 2333 !symbol->has<MiscDetails>() && useNames.count(name) == 0) { 2334 SourceName location{x.moduleName.source}; 2335 if (auto *localSymbol{FindInScope(name)}) { 2336 DoAddUse(location, localSymbol->name(), *localSymbol, *symbol); 2337 } else { 2338 DoAddUse(location, location, CopySymbol(name, *symbol), *symbol); 2339 } 2340 } 2341 } 2342 } 2343 useModuleScope_ = nullptr; 2344 } 2345 2346 ModuleVisitor::SymbolRename ModuleVisitor::AddUse( 2347 const SourceName &localName, const SourceName &useName) { 2348 return AddUse(localName, useName, FindInScope(*useModuleScope_, useName)); 2349 } 2350 2351 ModuleVisitor::SymbolRename ModuleVisitor::AddUse( 2352 const SourceName &localName, const SourceName &useName, Symbol *useSymbol) { 2353 if (!useModuleScope_) { 2354 return {}; // error occurred finding module 2355 } 2356 if (!useSymbol) { 2357 Say(useName, "'%s' not found in module '%s'"_err_en_US, MakeOpName(useName), 2358 useModuleScope_->GetName().value()); 2359 return {}; 2360 } 2361 if (useSymbol->attrs().test(Attr::PRIVATE) && 2362 !FindModuleFileContaining(currScope())) { 2363 // Privacy is not enforced in module files so that generic interfaces 2364 // can be resolved to private specific procedures in specification 2365 // expressions. 2366 Say(useName, "'%s' is PRIVATE in '%s'"_err_en_US, MakeOpName(useName), 2367 useModuleScope_->GetName().value()); 2368 return {}; 2369 } 2370 auto &localSymbol{MakeSymbol(localName)}; 2371 DoAddUse(useName, localName, localSymbol, *useSymbol); 2372 return {&localSymbol, useSymbol}; 2373 } 2374 2375 // symbol must be either a Use or a Generic formed by merging two uses. 2376 // Convert it to a UseError with this additional location. 2377 static void ConvertToUseError( 2378 Symbol &symbol, const SourceName &location, const Scope &module) { 2379 const auto *useDetails{symbol.detailsIf<UseDetails>()}; 2380 if (!useDetails) { 2381 auto &genericDetails{symbol.get<GenericDetails>()}; 2382 useDetails = &genericDetails.uses().at(0)->get<UseDetails>(); 2383 } 2384 symbol.set_details( 2385 UseErrorDetails{*useDetails}.add_occurrence(location, module)); 2386 } 2387 2388 void ModuleVisitor::DoAddUse(const SourceName &location, 2389 const SourceName &localName, Symbol &localSymbol, const Symbol &useSymbol) { 2390 localSymbol.attrs() = useSymbol.attrs() & ~Attrs{Attr::PUBLIC, Attr::PRIVATE}; 2391 localSymbol.flags() = useSymbol.flags(); 2392 const Symbol &useUltimate{useSymbol.GetUltimate()}; 2393 if (auto *useDetails{localSymbol.detailsIf<UseDetails>()}) { 2394 const Symbol &localUltimate{localSymbol.GetUltimate()}; 2395 if (localUltimate == useUltimate) { 2396 // use-associating the same symbol again -- ok 2397 } else if (localUltimate.has<GenericDetails>() && 2398 useUltimate.has<GenericDetails>()) { 2399 // use-associating generics with the same names: merge them into a 2400 // new generic in this scope 2401 auto generic1{localUltimate.get<GenericDetails>()}; 2402 AddGenericUse(generic1, localName, useUltimate); 2403 generic1.AddUse(localSymbol); 2404 // useSymbol has specific g and so does generic1 2405 auto &generic2{useUltimate.get<GenericDetails>()}; 2406 if (generic1.derivedType() && generic2.derivedType() && 2407 generic1.derivedType() != generic2.derivedType()) { 2408 Say(location, 2409 "Generic interface '%s' has ambiguous derived types" 2410 " from modules '%s' and '%s'"_err_en_US, 2411 localSymbol.name(), GetUsedModule(*useDetails).name(), 2412 useUltimate.owner().GetName().value()); 2413 context().SetError(localSymbol); 2414 } else { 2415 generic1.CopyFrom(generic2); 2416 } 2417 EraseSymbol(localSymbol); 2418 MakeSymbol(localSymbol.name(), localSymbol.attrs(), std::move(generic1)); 2419 } else { 2420 ConvertToUseError(localSymbol, location, *useModuleScope_); 2421 } 2422 } else if (auto *genericDetails{localSymbol.detailsIf<GenericDetails>()}) { 2423 if (const auto *useDetails{useUltimate.detailsIf<GenericDetails>()}) { 2424 AddGenericUse(*genericDetails, localName, useUltimate); 2425 if (genericDetails->derivedType() && useDetails->derivedType() && 2426 genericDetails->derivedType() != useDetails->derivedType()) { 2427 Say(location, 2428 "Generic interface '%s' has ambiguous derived types" 2429 " from modules '%s' and '%s'"_err_en_US, 2430 localSymbol.name(), 2431 genericDetails->derivedType()->owner().GetName().value(), 2432 useDetails->derivedType()->owner().GetName().value()); 2433 } else { 2434 genericDetails->CopyFrom(*useDetails); 2435 } 2436 } else { 2437 ConvertToUseError(localSymbol, location, *useModuleScope_); 2438 } 2439 } else if (auto *details{localSymbol.detailsIf<UseErrorDetails>()}) { 2440 details->add_occurrence(location, *useModuleScope_); 2441 } else if (!localSymbol.has<UnknownDetails>()) { 2442 Say(location, 2443 "Cannot use-associate '%s'; it is already declared in this scope"_err_en_US, 2444 localName) 2445 .Attach(localSymbol.name(), "Previous declaration of '%s'"_en_US, 2446 localName); 2447 } else { 2448 localSymbol.set_details(UseDetails{localName, useSymbol}); 2449 } 2450 } 2451 2452 void ModuleVisitor::AddUse(const GenericSpecInfo &info) { 2453 if (useModuleScope_) { 2454 const auto &name{info.symbolName()}; 2455 auto rename{AddUse(name, name, FindInScope(*useModuleScope_, name))}; 2456 info.Resolve(rename.use); 2457 } 2458 } 2459 2460 // Create a UseDetails symbol for this USE and add it to generic 2461 void ModuleVisitor::AddGenericUse( 2462 GenericDetails &generic, const SourceName &name, const Symbol &useSymbol) { 2463 generic.AddUse(currScope().MakeSymbol(name, {}, UseDetails{name, useSymbol})); 2464 } 2465 2466 bool ModuleVisitor::BeginSubmodule( 2467 const parser::Name &name, const parser::ParentIdentifier &parentId) { 2468 auto &ancestorName{std::get<parser::Name>(parentId.t)}; 2469 auto &parentName{std::get<std::optional<parser::Name>>(parentId.t)}; 2470 Scope *ancestor{FindModule(ancestorName)}; 2471 if (!ancestor) { 2472 return false; 2473 } 2474 Scope *parentScope{parentName ? FindModule(*parentName, ancestor) : ancestor}; 2475 if (!parentScope) { 2476 return false; 2477 } 2478 PushScope(*parentScope); // submodule is hosted in parent 2479 BeginModule(name, true); 2480 if (!ancestor->AddSubmodule(name.source, currScope())) { 2481 Say(name, "Module '%s' already has a submodule named '%s'"_err_en_US, 2482 ancestorName.source, name.source); 2483 } 2484 return true; 2485 } 2486 2487 void ModuleVisitor::BeginModule(const parser::Name &name, bool isSubmodule) { 2488 auto &symbol{MakeSymbol(name, ModuleDetails{isSubmodule})}; 2489 auto &details{symbol.get<ModuleDetails>()}; 2490 PushScope(Scope::Kind::Module, &symbol); 2491 details.set_scope(&currScope()); 2492 defaultAccess_ = Attr::PUBLIC; 2493 prevAccessStmt_ = std::nullopt; 2494 } 2495 2496 // Find a module or submodule by name and return its scope. 2497 // If ancestor is present, look for a submodule of that ancestor module. 2498 // May have to read a .mod file to find it. 2499 // If an error occurs, report it and return nullptr. 2500 Scope *ModuleVisitor::FindModule(const parser::Name &name, Scope *ancestor) { 2501 ModFileReader reader{context()}; 2502 Scope *scope{reader.Read(name.source, ancestor)}; 2503 if (!scope) { 2504 return nullptr; 2505 } 2506 if (scope->kind() != Scope::Kind::Module) { 2507 Say(name, "'%s' is not a module"_err_en_US); 2508 return nullptr; 2509 } 2510 if (DoesScopeContain(scope, currScope())) { // 14.2.2(1) 2511 Say(name, "Module '%s' cannot USE itself"_err_en_US); 2512 } 2513 Resolve(name, scope->symbol()); 2514 return scope; 2515 } 2516 2517 void ModuleVisitor::ApplyDefaultAccess() { 2518 for (auto &pair : currScope()) { 2519 Symbol &symbol = *pair.second; 2520 if (!symbol.attrs().HasAny({Attr::PUBLIC, Attr::PRIVATE})) { 2521 symbol.attrs().set(defaultAccess_); 2522 } 2523 } 2524 } 2525 2526 // InterfaceVistor implementation 2527 2528 bool InterfaceVisitor::Pre(const parser::InterfaceStmt &x) { 2529 bool isAbstract{std::holds_alternative<parser::Abstract>(x.u)}; 2530 genericInfo_.emplace(/*isInterface*/ true, isAbstract); 2531 return BeginAttrs(); 2532 } 2533 2534 void InterfaceVisitor::Post(const parser::InterfaceStmt &) { EndAttrs(); } 2535 2536 void InterfaceVisitor::Post(const parser::EndInterfaceStmt &) { 2537 genericInfo_.pop(); 2538 } 2539 2540 // Create a symbol in genericSymbol_ for this GenericSpec. 2541 bool InterfaceVisitor::Pre(const parser::GenericSpec &x) { 2542 if (auto *symbol{FindInScope(GenericSpecInfo{x}.symbolName())}) { 2543 SetGenericSymbol(*symbol); 2544 } 2545 return false; 2546 } 2547 2548 bool InterfaceVisitor::Pre(const parser::ProcedureStmt &x) { 2549 if (!isGeneric()) { 2550 Say("A PROCEDURE statement is only allowed in a generic interface block"_err_en_US); 2551 return false; 2552 } 2553 auto kind{std::get<parser::ProcedureStmt::Kind>(x.t)}; 2554 const auto &names{std::get<std::list<parser::Name>>(x.t)}; 2555 AddSpecificProcs(names, kind); 2556 return false; 2557 } 2558 2559 bool InterfaceVisitor::Pre(const parser::GenericStmt &) { 2560 genericInfo_.emplace(/*isInterface*/ false); 2561 return true; 2562 } 2563 void InterfaceVisitor::Post(const parser::GenericStmt &x) { 2564 if (auto &accessSpec{std::get<std::optional<parser::AccessSpec>>(x.t)}) { 2565 GetGenericInfo().symbol->attrs().set(AccessSpecToAttr(*accessSpec)); 2566 } 2567 const auto &names{std::get<std::list<parser::Name>>(x.t)}; 2568 AddSpecificProcs(names, ProcedureKind::Procedure); 2569 genericInfo_.pop(); 2570 } 2571 2572 bool InterfaceVisitor::inInterfaceBlock() const { 2573 return !genericInfo_.empty() && GetGenericInfo().isInterface; 2574 } 2575 bool InterfaceVisitor::isGeneric() const { 2576 return !genericInfo_.empty() && GetGenericInfo().symbol; 2577 } 2578 bool InterfaceVisitor::isAbstract() const { 2579 return !genericInfo_.empty() && GetGenericInfo().isAbstract; 2580 } 2581 GenericDetails &InterfaceVisitor::GetGenericDetails() { 2582 return GetGenericInfo().symbol->get<GenericDetails>(); 2583 } 2584 2585 void InterfaceVisitor::AddSpecificProcs( 2586 const std::list<parser::Name> &names, ProcedureKind kind) { 2587 for (const auto &name : names) { 2588 specificProcs_.emplace( 2589 GetGenericInfo().symbol, std::make_pair(&name, kind)); 2590 } 2591 } 2592 2593 // By now we should have seen all specific procedures referenced by name in 2594 // this generic interface. Resolve those names to symbols. 2595 void InterfaceVisitor::ResolveSpecificsInGeneric(Symbol &generic) { 2596 auto &details{generic.get<GenericDetails>()}; 2597 SymbolSet symbolsSeen; 2598 for (const Symbol &symbol : details.specificProcs()) { 2599 symbolsSeen.insert(symbol); 2600 } 2601 auto range{specificProcs_.equal_range(&generic)}; 2602 for (auto it{range.first}; it != range.second; ++it) { 2603 auto *name{it->second.first}; 2604 auto kind{it->second.second}; 2605 const auto *symbol{FindSymbol(*name)}; 2606 if (!symbol) { 2607 Say(*name, "Procedure '%s' not found"_err_en_US); 2608 continue; 2609 } 2610 if (symbol == &generic) { 2611 if (auto *specific{generic.get<GenericDetails>().specific()}) { 2612 symbol = specific; 2613 } 2614 } 2615 const Symbol &ultimate{symbol->GetUltimate()}; 2616 if (!ultimate.has<SubprogramDetails>() && 2617 !ultimate.has<SubprogramNameDetails>()) { 2618 Say(*name, "'%s' is not a subprogram"_err_en_US); 2619 continue; 2620 } 2621 if (kind == ProcedureKind::ModuleProcedure) { 2622 if (const auto *nd{ultimate.detailsIf<SubprogramNameDetails>()}) { 2623 if (nd->kind() != SubprogramKind::Module) { 2624 Say(*name, "'%s' is not a module procedure"_err_en_US); 2625 } 2626 } else { 2627 // USE-associated procedure 2628 const auto *sd{ultimate.detailsIf<SubprogramDetails>()}; 2629 CHECK(sd); 2630 if (ultimate.owner().kind() != Scope::Kind::Module || 2631 sd->isInterface()) { 2632 Say(*name, "'%s' is not a module procedure"_err_en_US); 2633 } 2634 } 2635 } 2636 if (!symbolsSeen.insert(ultimate).second) { 2637 if (symbol == &ultimate) { 2638 Say(name->source, 2639 "Procedure '%s' is already specified in generic '%s'"_err_en_US, 2640 name->source, MakeOpName(generic.name())); 2641 } else { 2642 Say(name->source, 2643 "Procedure '%s' from module '%s' is already specified in generic '%s'"_err_en_US, 2644 ultimate.name(), ultimate.owner().GetName().value(), 2645 MakeOpName(generic.name())); 2646 } 2647 continue; 2648 } 2649 details.AddSpecificProc(*symbol, name->source); 2650 } 2651 specificProcs_.erase(range.first, range.second); 2652 } 2653 2654 // Check that the specific procedures are all functions or all subroutines. 2655 // If there is a derived type with the same name they must be functions. 2656 // Set the corresponding flag on generic. 2657 void InterfaceVisitor::CheckGenericProcedures(Symbol &generic) { 2658 ResolveSpecificsInGeneric(generic); 2659 auto &details{generic.get<GenericDetails>()}; 2660 if (auto *proc{details.CheckSpecific()}) { 2661 auto msg{ 2662 "'%s' may not be the name of both a generic interface and a" 2663 " procedure unless it is a specific procedure of the generic"_err_en_US}; 2664 if (proc->name().begin() > generic.name().begin()) { 2665 Say(proc->name(), std::move(msg)); 2666 } else { 2667 Say(generic.name(), std::move(msg)); 2668 } 2669 } 2670 auto &specifics{details.specificProcs()}; 2671 if (specifics.empty()) { 2672 if (details.derivedType()) { 2673 generic.set(Symbol::Flag::Function); 2674 } 2675 return; 2676 } 2677 const Symbol &firstSpecific{specifics.front()}; 2678 bool isFunction{firstSpecific.test(Symbol::Flag::Function)}; 2679 for (const Symbol &specific : specifics) { 2680 if (isFunction != specific.test(Symbol::Flag::Function)) { // C1514 2681 auto &msg{Say(generic.name(), 2682 "Generic interface '%s' has both a function and a subroutine"_err_en_US)}; 2683 if (isFunction) { 2684 msg.Attach(firstSpecific.name(), "Function declaration"_en_US); 2685 msg.Attach(specific.name(), "Subroutine declaration"_en_US); 2686 } else { 2687 msg.Attach(firstSpecific.name(), "Subroutine declaration"_en_US); 2688 msg.Attach(specific.name(), "Function declaration"_en_US); 2689 } 2690 } 2691 } 2692 if (!isFunction && details.derivedType()) { 2693 SayDerivedType(generic.name(), 2694 "Generic interface '%s' may only contain functions due to derived type" 2695 " with same name"_err_en_US, 2696 *details.derivedType()->scope()); 2697 } 2698 generic.set(isFunction ? Symbol::Flag::Function : Symbol::Flag::Subroutine); 2699 } 2700 2701 // SubprogramVisitor implementation 2702 2703 // Return false if it is actually an assignment statement. 2704 bool SubprogramVisitor::HandleStmtFunction(const parser::StmtFunctionStmt &x) { 2705 const auto &name{std::get<parser::Name>(x.t)}; 2706 const DeclTypeSpec *resultType{nullptr}; 2707 // Look up name: provides return type or tells us if it's an array 2708 if (auto *symbol{FindSymbol(name)}) { 2709 auto *details{symbol->detailsIf<EntityDetails>()}; 2710 if (!details) { 2711 badStmtFuncFound_ = true; 2712 return false; 2713 } 2714 // TODO: check that attrs are compatible with stmt func 2715 resultType = details->type(); 2716 symbol->details() = UnknownDetails{}; // will be replaced below 2717 } 2718 if (badStmtFuncFound_) { 2719 Say(name, "'%s' has not been declared as an array"_err_en_US); 2720 return true; 2721 } 2722 auto &symbol{PushSubprogramScope(name, Symbol::Flag::Function)}; 2723 symbol.set(Symbol::Flag::StmtFunction); 2724 EraseSymbol(symbol); // removes symbol added by PushSubprogramScope 2725 auto &details{symbol.get<SubprogramDetails>()}; 2726 for (const auto &dummyName : std::get<std::list<parser::Name>>(x.t)) { 2727 ObjectEntityDetails dummyDetails{true}; 2728 if (auto *dummySymbol{FindInScope(currScope().parent(), dummyName)}) { 2729 if (auto *d{dummySymbol->detailsIf<EntityDetails>()}) { 2730 if (d->type()) { 2731 dummyDetails.set_type(*d->type()); 2732 } 2733 } 2734 } 2735 Symbol &dummy{MakeSymbol(dummyName, std::move(dummyDetails))}; 2736 ApplyImplicitRules(dummy); 2737 details.add_dummyArg(dummy); 2738 } 2739 ObjectEntityDetails resultDetails; 2740 if (resultType) { 2741 resultDetails.set_type(*resultType); 2742 } 2743 resultDetails.set_funcResult(true); 2744 Symbol &result{MakeSymbol(name, std::move(resultDetails))}; 2745 ApplyImplicitRules(result); 2746 details.set_result(result); 2747 const auto &parsedExpr{std::get<parser::Scalar<parser::Expr>>(x.t)}; 2748 Walk(parsedExpr); 2749 // The analysis of the expression that constitutes the body of the 2750 // statement function is deferred to FinishSpecificationPart() so that 2751 // all declarations and implicit typing are complete. 2752 PopScope(); 2753 return true; 2754 } 2755 2756 bool SubprogramVisitor::Pre(const parser::Suffix &suffix) { 2757 if (suffix.resultName) { 2758 funcInfo_.resultName = &suffix.resultName.value(); 2759 } 2760 return true; 2761 } 2762 2763 bool SubprogramVisitor::Pre(const parser::PrefixSpec &x) { 2764 // Save this to process after UseStmt and ImplicitPart 2765 if (const auto *parsedType{std::get_if<parser::DeclarationTypeSpec>(&x.u)}) { 2766 if (funcInfo_.parsedType) { // C1543 2767 Say(currStmtSource().value(), 2768 "FUNCTION prefix cannot specify the type more than once"_err_en_US); 2769 return false; 2770 } else { 2771 funcInfo_.parsedType = parsedType; 2772 funcInfo_.source = currStmtSource(); 2773 return false; 2774 } 2775 } else { 2776 return true; 2777 } 2778 } 2779 2780 void SubprogramVisitor::Post(const parser::ImplicitPart &) { 2781 // If the function has a type in the prefix, process it now 2782 if (funcInfo_.parsedType) { 2783 messageHandler().set_currStmtSource(funcInfo_.source); 2784 if (const auto *type{ProcessTypeSpec(*funcInfo_.parsedType, true)}) { 2785 funcInfo_.resultSymbol->SetType(*type); 2786 } 2787 } 2788 funcInfo_ = {}; 2789 } 2790 2791 bool SubprogramVisitor::Pre(const parser::InterfaceBody::Subroutine &x) { 2792 const auto &name{std::get<parser::Name>( 2793 std::get<parser::Statement<parser::SubroutineStmt>>(x.t).statement.t)}; 2794 return BeginSubprogram(name, Symbol::Flag::Subroutine); 2795 } 2796 void SubprogramVisitor::Post(const parser::InterfaceBody::Subroutine &) { 2797 EndSubprogram(); 2798 } 2799 bool SubprogramVisitor::Pre(const parser::InterfaceBody::Function &x) { 2800 const auto &name{std::get<parser::Name>( 2801 std::get<parser::Statement<parser::FunctionStmt>>(x.t).statement.t)}; 2802 return BeginSubprogram(name, Symbol::Flag::Function); 2803 } 2804 void SubprogramVisitor::Post(const parser::InterfaceBody::Function &) { 2805 EndSubprogram(); 2806 } 2807 2808 bool SubprogramVisitor::Pre(const parser::SubroutineStmt &) { 2809 return BeginAttrs(); 2810 } 2811 bool SubprogramVisitor::Pre(const parser::FunctionStmt &) { 2812 return BeginAttrs(); 2813 } 2814 bool SubprogramVisitor::Pre(const parser::EntryStmt &) { return BeginAttrs(); } 2815 2816 void SubprogramVisitor::Post(const parser::SubroutineStmt &stmt) { 2817 const auto &name{std::get<parser::Name>(stmt.t)}; 2818 auto &details{PostSubprogramStmt(name)}; 2819 for (const auto &dummyArg : std::get<std::list<parser::DummyArg>>(stmt.t)) { 2820 if (const auto *dummyName{std::get_if<parser::Name>(&dummyArg.u)}) { 2821 Symbol &dummy{MakeSymbol(*dummyName, EntityDetails(true))}; 2822 details.add_dummyArg(dummy); 2823 } else { 2824 details.add_alternateReturn(); 2825 } 2826 } 2827 } 2828 2829 void SubprogramVisitor::Post(const parser::FunctionStmt &stmt) { 2830 const auto &name{std::get<parser::Name>(stmt.t)}; 2831 auto &details{PostSubprogramStmt(name)}; 2832 for (const auto &dummyName : std::get<std::list<parser::Name>>(stmt.t)) { 2833 Symbol &dummy{MakeSymbol(dummyName, EntityDetails(true))}; 2834 details.add_dummyArg(dummy); 2835 } 2836 const parser::Name *funcResultName; 2837 if (funcInfo_.resultName && funcInfo_.resultName->source != name.source) { 2838 // Note that RESULT is ignored if it has the same name as the function. 2839 funcResultName = funcInfo_.resultName; 2840 } else { 2841 EraseSymbol(name); // was added by PushSubprogramScope 2842 funcResultName = &name; 2843 } 2844 // add function result to function scope 2845 EntityDetails funcResultDetails; 2846 funcResultDetails.set_funcResult(true); 2847 funcInfo_.resultSymbol = 2848 &MakeSymbol(*funcResultName, std::move(funcResultDetails)); 2849 details.set_result(*funcInfo_.resultSymbol); 2850 2851 // C1560. 2852 if (funcInfo_.resultName && funcInfo_.resultName->source == name.source) { 2853 Say(funcInfo_.resultName->source, 2854 "The function name should not appear in RESULT, references to '%s' " 2855 "inside" 2856 " the function will be considered as references to the result only"_en_US, 2857 name.source); 2858 // RESULT name was ignored above, the only side effect from doing so will be 2859 // the inability to make recursive calls. The related parser::Name is still 2860 // resolved to the created function result symbol because every parser::Name 2861 // should be resolved to avoid internal errors. 2862 Resolve(*funcInfo_.resultName, funcInfo_.resultSymbol); 2863 } 2864 name.symbol = currScope().symbol(); // must not be function result symbol 2865 // Clear the RESULT() name now in case an ENTRY statement in the implicit-part 2866 // has a RESULT() suffix. 2867 funcInfo_.resultName = nullptr; 2868 } 2869 2870 SubprogramDetails &SubprogramVisitor::PostSubprogramStmt( 2871 const parser::Name &name) { 2872 Symbol &symbol{*currScope().symbol()}; 2873 CHECK(name.source == symbol.name()); 2874 SetBindNameOn(symbol); 2875 symbol.attrs() |= EndAttrs(); 2876 if (symbol.attrs().test(Attr::MODULE)) { 2877 symbol.attrs().set(Attr::EXTERNAL, false); 2878 } 2879 return symbol.get<SubprogramDetails>(); 2880 } 2881 2882 void SubprogramVisitor::Post(const parser::EntryStmt &stmt) { 2883 auto attrs{EndAttrs()}; // needs to be called even if early return 2884 Scope &inclusiveScope{InclusiveScope()}; 2885 const Symbol *subprogram{inclusiveScope.symbol()}; 2886 if (!subprogram) { 2887 CHECK(context().AnyFatalError()); 2888 return; 2889 } 2890 const auto &name{std::get<parser::Name>(stmt.t)}; 2891 const auto *parentDetails{subprogram->detailsIf<SubprogramDetails>()}; 2892 bool inFunction{parentDetails && parentDetails->isFunction()}; 2893 const parser::Name *resultName{funcInfo_.resultName}; 2894 if (resultName) { // RESULT(result) is present 2895 funcInfo_.resultName = nullptr; 2896 if (!inFunction) { 2897 Say2(resultName->source, 2898 "RESULT(%s) may appear only in a function"_err_en_US, 2899 subprogram->name(), "Containing subprogram"_en_US); 2900 } else if (resultName->source == subprogram->name()) { // C1574 2901 Say2(resultName->source, 2902 "RESULT(%s) may not have the same name as the function"_err_en_US, 2903 subprogram->name(), "Containing function"_en_US); 2904 } else if (const Symbol * 2905 symbol{FindSymbol(inclusiveScope.parent(), *resultName)}) { // C1574 2906 if (const auto *details{symbol->detailsIf<SubprogramDetails>()}) { 2907 if (details->entryScope() == &inclusiveScope) { 2908 Say2(resultName->source, 2909 "RESULT(%s) may not have the same name as an ENTRY in the function"_err_en_US, 2910 symbol->name(), "Conflicting ENTRY"_en_US); 2911 } 2912 } 2913 } 2914 if (Symbol * symbol{FindSymbol(name)}) { // C1570 2915 // When RESULT() appears, ENTRY name can't have been already declared 2916 if (inclusiveScope.Contains(symbol->owner())) { 2917 Say2(name, 2918 "ENTRY name '%s' may not be declared when RESULT() is present"_err_en_US, 2919 *symbol, "Previous declaration of '%s'"_en_US); 2920 } 2921 } 2922 if (resultName->source == name.source) { 2923 // ignore RESULT() hereafter when it's the same name as the ENTRY 2924 resultName = nullptr; 2925 } 2926 } 2927 SubprogramDetails entryDetails; 2928 entryDetails.set_entryScope(inclusiveScope); 2929 if (inFunction) { 2930 // Create the entity to hold the function result, if necessary. 2931 Symbol *resultSymbol{nullptr}; 2932 auto &effectiveResultName{*(resultName ? resultName : &name)}; 2933 resultSymbol = FindInScope(currScope(), effectiveResultName); 2934 if (resultSymbol) { // C1574 2935 std::visit( 2936 common::visitors{[](EntityDetails &x) { x.set_funcResult(true); }, 2937 [](ObjectEntityDetails &x) { x.set_funcResult(true); }, 2938 [](ProcEntityDetails &x) { x.set_funcResult(true); }, 2939 [&](const auto &) { 2940 Say2(effectiveResultName.source, 2941 "'%s' was previously declared as an item that may not be used as a function result"_err_en_US, 2942 resultSymbol->name(), "Previous declaration of '%s'"_en_US); 2943 }}, 2944 resultSymbol->details()); 2945 } else if (inExecutionPart_) { 2946 ObjectEntityDetails entity; 2947 entity.set_funcResult(true); 2948 resultSymbol = &MakeSymbol(effectiveResultName, std::move(entity)); 2949 ApplyImplicitRules(*resultSymbol); 2950 } else { 2951 EntityDetails entity; 2952 entity.set_funcResult(true); 2953 resultSymbol = &MakeSymbol(effectiveResultName, std::move(entity)); 2954 } 2955 if (!resultName) { 2956 name.symbol = nullptr; // symbol will be used for entry point below 2957 } 2958 entryDetails.set_result(*resultSymbol); 2959 } 2960 2961 for (const auto &dummyArg : std::get<std::list<parser::DummyArg>>(stmt.t)) { 2962 if (const auto *dummyName{std::get_if<parser::Name>(&dummyArg.u)}) { 2963 Symbol *dummy{FindSymbol(*dummyName)}; 2964 if (dummy) { 2965 std::visit( 2966 common::visitors{[](EntityDetails &x) { x.set_isDummy(); }, 2967 [](ObjectEntityDetails &x) { x.set_isDummy(); }, 2968 [](ProcEntityDetails &x) { x.set_isDummy(); }, 2969 [&](const auto &) { 2970 Say2(dummyName->source, 2971 "ENTRY dummy argument '%s' is previously declared as an item that may not be used as a dummy argument"_err_en_US, 2972 dummy->name(), "Previous declaration of '%s'"_en_US); 2973 }}, 2974 dummy->details()); 2975 } else { 2976 dummy = &MakeSymbol(*dummyName, EntityDetails(true)); 2977 } 2978 entryDetails.add_dummyArg(*dummy); 2979 } else { 2980 if (inFunction) { // C1573 2981 Say(name, 2982 "ENTRY in a function may not have an alternate return dummy argument"_err_en_US); 2983 break; 2984 } 2985 entryDetails.add_alternateReturn(); 2986 } 2987 } 2988 2989 Symbol::Flag subpFlag{ 2990 inFunction ? Symbol::Flag::Function : Symbol::Flag::Subroutine}; 2991 CheckExtantExternal(name, subpFlag); 2992 Scope &outer{inclusiveScope.parent()}; // global or module scope 2993 if (Symbol * extant{FindSymbol(outer, name)}) { 2994 if (extant->has<ProcEntityDetails>()) { 2995 if (!extant->test(subpFlag)) { 2996 Say2(name, 2997 subpFlag == Symbol::Flag::Function 2998 ? "'%s' was previously called as a subroutine"_err_en_US 2999 : "'%s' was previously called as a function"_err_en_US, 3000 *extant, "Previous call of '%s'"_en_US); 3001 } 3002 if (extant->attrs().test(Attr::PRIVATE)) { 3003 attrs.set(Attr::PRIVATE); 3004 } 3005 outer.erase(extant->name()); 3006 } else { 3007 if (outer.IsGlobal()) { 3008 Say2(name, "'%s' is already defined as a global identifier"_err_en_US, 3009 *extant, "Previous definition of '%s'"_en_US); 3010 } else { 3011 SayAlreadyDeclared(name, *extant); 3012 } 3013 return; 3014 } 3015 } 3016 if (outer.IsModule() && !attrs.test(Attr::PRIVATE)) { 3017 attrs.set(Attr::PUBLIC); 3018 } 3019 Symbol &entrySymbol{MakeSymbol(outer, name.source, attrs)}; 3020 entrySymbol.set_details(std::move(entryDetails)); 3021 if (outer.IsGlobal()) { 3022 MakeExternal(entrySymbol); 3023 } 3024 SetBindNameOn(entrySymbol); 3025 entrySymbol.set(subpFlag); 3026 Resolve(name, entrySymbol); 3027 } 3028 3029 // A subprogram declared with MODULE PROCEDURE 3030 bool SubprogramVisitor::BeginMpSubprogram(const parser::Name &name) { 3031 auto *symbol{FindSymbol(name)}; 3032 if (symbol && symbol->has<SubprogramNameDetails>()) { 3033 symbol = FindSymbol(currScope().parent(), name); 3034 } 3035 if (!IsSeparateModuleProcedureInterface(symbol)) { 3036 Say(name, "'%s' was not declared a separate module procedure"_err_en_US); 3037 return false; 3038 } 3039 if (symbol->owner() == currScope()) { 3040 PushScope(Scope::Kind::Subprogram, symbol); 3041 } else { 3042 Symbol &newSymbol{MakeSymbol(name, SubprogramDetails{})}; 3043 PushScope(Scope::Kind::Subprogram, &newSymbol); 3044 const auto &details{symbol->get<SubprogramDetails>()}; 3045 auto &newDetails{newSymbol.get<SubprogramDetails>()}; 3046 for (const Symbol *dummyArg : details.dummyArgs()) { 3047 if (!dummyArg) { 3048 newDetails.add_alternateReturn(); 3049 } else if (Symbol * copy{currScope().CopySymbol(*dummyArg)}) { 3050 newDetails.add_dummyArg(*copy); 3051 } 3052 } 3053 if (details.isFunction()) { 3054 currScope().erase(symbol->name()); 3055 newDetails.set_result(*currScope().CopySymbol(details.result())); 3056 } 3057 } 3058 return true; 3059 } 3060 3061 // A subprogram declared with SUBROUTINE or FUNCTION 3062 bool SubprogramVisitor::BeginSubprogram( 3063 const parser::Name &name, Symbol::Flag subpFlag, bool hasModulePrefix) { 3064 if (hasModulePrefix && !inInterfaceBlock() && 3065 !IsSeparateModuleProcedureInterface( 3066 FindSymbol(currScope().parent(), name))) { 3067 Say(name, "'%s' was not declared a separate module procedure"_err_en_US); 3068 return false; 3069 } 3070 PushSubprogramScope(name, subpFlag); 3071 return true; 3072 } 3073 3074 void SubprogramVisitor::EndSubprogram() { PopScope(); } 3075 3076 void SubprogramVisitor::CheckExtantExternal( 3077 const parser::Name &name, Symbol::Flag subpFlag) { 3078 if (auto *prev{FindSymbol(name)}) { 3079 if (prev->attrs().test(Attr::EXTERNAL) && prev->has<ProcEntityDetails>()) { 3080 // this subprogram was previously called, now being declared 3081 if (!prev->test(subpFlag)) { 3082 Say2(name, 3083 subpFlag == Symbol::Flag::Function 3084 ? "'%s' was previously called as a subroutine"_err_en_US 3085 : "'%s' was previously called as a function"_err_en_US, 3086 *prev, "Previous call of '%s'"_en_US); 3087 } 3088 EraseSymbol(name); 3089 } 3090 } 3091 } 3092 3093 Symbol &SubprogramVisitor::PushSubprogramScope( 3094 const parser::Name &name, Symbol::Flag subpFlag) { 3095 auto *symbol{GetSpecificFromGeneric(name)}; 3096 if (!symbol) { 3097 CheckExtantExternal(name, subpFlag); 3098 symbol = &MakeSymbol(name, SubprogramDetails{}); 3099 } 3100 symbol->set(subpFlag); 3101 symbol->ReplaceName(name.source); 3102 PushScope(Scope::Kind::Subprogram, symbol); 3103 auto &details{symbol->get<SubprogramDetails>()}; 3104 if (inInterfaceBlock()) { 3105 details.set_isInterface(); 3106 if (isAbstract()) { 3107 symbol->attrs().set(Attr::ABSTRACT); 3108 } else { 3109 MakeExternal(*symbol); 3110 } 3111 if (isGeneric()) { 3112 GetGenericDetails().AddSpecificProc(*symbol, name.source); 3113 } 3114 set_inheritFromParent(false); 3115 } 3116 FindSymbol(name)->set(subpFlag); // PushScope() created symbol 3117 return *symbol; 3118 } 3119 3120 void SubprogramVisitor::PushBlockDataScope(const parser::Name &name) { 3121 if (auto *prev{FindSymbol(name)}) { 3122 if (prev->attrs().test(Attr::EXTERNAL) && prev->has<ProcEntityDetails>()) { 3123 if (prev->test(Symbol::Flag::Subroutine) || 3124 prev->test(Symbol::Flag::Function)) { 3125 Say2(name, "BLOCK DATA '%s' has been called"_err_en_US, *prev, 3126 "Previous call of '%s'"_en_US); 3127 } 3128 EraseSymbol(name); 3129 } 3130 } 3131 if (name.source.empty()) { 3132 // Don't let unnamed BLOCK DATA conflict with unnamed PROGRAM 3133 PushScope(Scope::Kind::BlockData, nullptr); 3134 } else { 3135 PushScope(Scope::Kind::BlockData, &MakeSymbol(name, SubprogramDetails{})); 3136 } 3137 } 3138 3139 // If name is a generic, return specific subprogram with the same name. 3140 Symbol *SubprogramVisitor::GetSpecificFromGeneric(const parser::Name &name) { 3141 if (auto *symbol{FindSymbol(name)}) { 3142 if (auto *details{symbol->detailsIf<GenericDetails>()}) { 3143 // found generic, want subprogram 3144 auto *specific{details->specific()}; 3145 if (!specific) { 3146 specific = 3147 &currScope().MakeSymbol(name.source, Attrs{}, SubprogramDetails{}); 3148 details->set_specific(Resolve(name, *specific)); 3149 } else if (isGeneric()) { 3150 SayAlreadyDeclared(name, *specific); 3151 } 3152 if (!specific->has<SubprogramDetails>()) { 3153 specific->set_details(SubprogramDetails{}); 3154 } 3155 return specific; 3156 } 3157 } 3158 return nullptr; 3159 } 3160 3161 // DeclarationVisitor implementation 3162 3163 bool DeclarationVisitor::BeginDecl() { 3164 BeginDeclTypeSpec(); 3165 BeginArraySpec(); 3166 return BeginAttrs(); 3167 } 3168 void DeclarationVisitor::EndDecl() { 3169 EndDeclTypeSpec(); 3170 EndArraySpec(); 3171 EndAttrs(); 3172 } 3173 3174 bool DeclarationVisitor::CheckUseError(const parser::Name &name) { 3175 const auto *details{name.symbol->detailsIf<UseErrorDetails>()}; 3176 if (!details) { 3177 return false; 3178 } 3179 Message &msg{Say(name, "Reference to '%s' is ambiguous"_err_en_US)}; 3180 for (const auto &[location, module] : details->occurrences()) { 3181 msg.Attach(location, "'%s' was use-associated from module '%s'"_en_US, 3182 name.source, module->GetName().value()); 3183 } 3184 return true; 3185 } 3186 3187 // Report error if accessibility of symbol doesn't match isPrivate. 3188 void DeclarationVisitor::CheckAccessibility( 3189 const SourceName &name, bool isPrivate, Symbol &symbol) { 3190 if (symbol.attrs().test(Attr::PRIVATE) != isPrivate) { 3191 Say2(name, 3192 "'%s' does not have the same accessibility as its previous declaration"_err_en_US, 3193 symbol, "Previous declaration of '%s'"_en_US); 3194 } 3195 } 3196 3197 void DeclarationVisitor::Post(const parser::TypeDeclarationStmt &) { 3198 if (!GetAttrs().HasAny({Attr::POINTER, Attr::ALLOCATABLE})) { // C702 3199 if (const auto *typeSpec{GetDeclTypeSpec()}) { 3200 if (typeSpec->category() == DeclTypeSpec::Character) { 3201 if (typeSpec->characterTypeSpec().length().isDeferred()) { 3202 Say("The type parameter LEN cannot be deferred without" 3203 " the POINTER or ALLOCATABLE attribute"_err_en_US); 3204 } 3205 } else if (const DerivedTypeSpec * derivedSpec{typeSpec->AsDerived()}) { 3206 for (const auto &pair : derivedSpec->parameters()) { 3207 if (pair.second.isDeferred()) { 3208 Say(currStmtSource().value(), 3209 "The value of type parameter '%s' cannot be deferred" 3210 " without the POINTER or ALLOCATABLE attribute"_err_en_US, 3211 pair.first); 3212 } 3213 } 3214 } 3215 } 3216 } 3217 EndDecl(); 3218 } 3219 3220 void DeclarationVisitor::Post(const parser::DimensionStmt::Declaration &x) { 3221 DeclareObjectEntity(std::get<parser::Name>(x.t)); 3222 } 3223 void DeclarationVisitor::Post(const parser::CodimensionDecl &x) { 3224 DeclareObjectEntity(std::get<parser::Name>(x.t)); 3225 } 3226 3227 bool DeclarationVisitor::Pre(const parser::Initialization &) { 3228 // Defer inspection of initializers to Initialization() so that the 3229 // symbol being initialized will be available within the initialization 3230 // expression. 3231 return false; 3232 } 3233 3234 void DeclarationVisitor::Post(const parser::EntityDecl &x) { 3235 // TODO: may be under StructureStmt 3236 const auto &name{std::get<parser::ObjectName>(x.t)}; 3237 Attrs attrs{attrs_ ? HandleSaveName(name.source, *attrs_) : Attrs{}}; 3238 Symbol &symbol{DeclareUnknownEntity(name, attrs)}; 3239 symbol.ReplaceName(name.source); 3240 if (auto &init{std::get<std::optional<parser::Initialization>>(x.t)}) { 3241 if (ConvertToObjectEntity(symbol)) { 3242 Initialization(name, *init, false); 3243 } 3244 } else if (attrs.test(Attr::PARAMETER)) { // C882, C883 3245 Say(name, "Missing initialization for parameter '%s'"_err_en_US); 3246 } 3247 } 3248 3249 void DeclarationVisitor::Post(const parser::PointerDecl &x) { 3250 const auto &name{std::get<parser::Name>(x.t)}; 3251 Symbol &symbol{DeclareUnknownEntity(name, Attrs{Attr::POINTER})}; 3252 symbol.ReplaceName(name.source); 3253 } 3254 3255 bool DeclarationVisitor::Pre(const parser::BindEntity &x) { 3256 auto kind{std::get<parser::BindEntity::Kind>(x.t)}; 3257 auto &name{std::get<parser::Name>(x.t)}; 3258 Symbol *symbol; 3259 if (kind == parser::BindEntity::Kind::Object) { 3260 symbol = &HandleAttributeStmt(Attr::BIND_C, name); 3261 } else { 3262 symbol = &MakeCommonBlockSymbol(name); 3263 symbol->attrs().set(Attr::BIND_C); 3264 } 3265 SetBindNameOn(*symbol); 3266 return false; 3267 } 3268 bool DeclarationVisitor::Pre(const parser::NamedConstantDef &x) { 3269 auto &name{std::get<parser::NamedConstant>(x.t).v}; 3270 auto &symbol{HandleAttributeStmt(Attr::PARAMETER, name)}; 3271 if (!ConvertToObjectEntity(symbol) || 3272 symbol.test(Symbol::Flag::CrayPointer) || 3273 symbol.test(Symbol::Flag::CrayPointee)) { 3274 SayWithDecl( 3275 name, symbol, "PARAMETER attribute not allowed on '%s'"_err_en_US); 3276 return false; 3277 } 3278 const auto &expr{std::get<parser::ConstantExpr>(x.t)}; 3279 ApplyImplicitRules(symbol); 3280 Walk(expr); 3281 if (auto converted{EvaluateNonPointerInitializer( 3282 symbol, expr, expr.thing.value().source)}) { 3283 symbol.get<ObjectEntityDetails>().set_init(std::move(*converted)); 3284 } 3285 return false; 3286 } 3287 bool DeclarationVisitor::Pre(const parser::NamedConstant &x) { 3288 const parser::Name &name{x.v}; 3289 if (!FindSymbol(name)) { 3290 Say(name, "Named constant '%s' not found"_err_en_US); 3291 } else { 3292 CheckUseError(name); 3293 } 3294 return false; 3295 } 3296 3297 bool DeclarationVisitor::Pre(const parser::Enumerator &enumerator) { 3298 const parser::Name &name{std::get<parser::NamedConstant>(enumerator.t).v}; 3299 Symbol *symbol{FindSymbol(name)}; 3300 if (symbol) { 3301 // Contrary to named constants appearing in a PARAMETER statement, 3302 // enumerator names should not have their type, dimension or any other 3303 // attributes defined before they are declared in the enumerator statement. 3304 // This is not explicitly forbidden by the standard, but they are scalars 3305 // which type is left for the compiler to chose, so do not let users try to 3306 // tamper with that. 3307 SayAlreadyDeclared(name, *symbol); 3308 symbol = nullptr; 3309 } else { 3310 // Enumerators are treated as PARAMETER (section 7.6 paragraph (4)) 3311 symbol = &MakeSymbol(name, Attrs{Attr::PARAMETER}, ObjectEntityDetails{}); 3312 symbol->SetType(context().MakeNumericType( 3313 TypeCategory::Integer, evaluate::CInteger::kind)); 3314 } 3315 3316 if (auto &init{std::get<std::optional<parser::ScalarIntConstantExpr>>( 3317 enumerator.t)}) { 3318 Walk(*init); // Resolve names in expression before evaluation. 3319 if (auto value{EvaluateInt64(context(), *init)}) { 3320 // Cast all init expressions to C_INT so that they can then be 3321 // safely incremented (see 7.6 Note 2). 3322 enumerationState_.value = static_cast<int>(*value); 3323 } else { 3324 Say(name, 3325 "Enumerator value could not be computed " 3326 "from the given expression"_err_en_US); 3327 // Prevent resolution of next enumerators value 3328 enumerationState_.value = std::nullopt; 3329 } 3330 } 3331 3332 if (symbol) { 3333 if (enumerationState_.value) { 3334 symbol->get<ObjectEntityDetails>().set_init(SomeExpr{ 3335 evaluate::Expr<evaluate::CInteger>{*enumerationState_.value}}); 3336 } else { 3337 context().SetError(*symbol); 3338 } 3339 } 3340 3341 if (enumerationState_.value) { 3342 (*enumerationState_.value)++; 3343 } 3344 return false; 3345 } 3346 3347 void DeclarationVisitor::Post(const parser::EnumDef &) { 3348 enumerationState_ = EnumeratorState{}; 3349 } 3350 3351 bool DeclarationVisitor::Pre(const parser::AccessSpec &x) { 3352 Attr attr{AccessSpecToAttr(x)}; 3353 if (!NonDerivedTypeScope().IsModule()) { // C817 3354 Say(currStmtSource().value(), 3355 "%s attribute may only appear in the specification part of a module"_err_en_US, 3356 EnumToString(attr)); 3357 } 3358 CheckAndSet(attr); 3359 return false; 3360 } 3361 3362 bool DeclarationVisitor::Pre(const parser::AsynchronousStmt &x) { 3363 return HandleAttributeStmt(Attr::ASYNCHRONOUS, x.v); 3364 } 3365 bool DeclarationVisitor::Pre(const parser::ContiguousStmt &x) { 3366 return HandleAttributeStmt(Attr::CONTIGUOUS, x.v); 3367 } 3368 bool DeclarationVisitor::Pre(const parser::ExternalStmt &x) { 3369 HandleAttributeStmt(Attr::EXTERNAL, x.v); 3370 for (const auto &name : x.v) { 3371 auto *symbol{FindSymbol(name)}; 3372 if (!ConvertToProcEntity(*symbol)) { 3373 SayWithDecl( 3374 name, *symbol, "EXTERNAL attribute not allowed on '%s'"_err_en_US); 3375 } else if (symbol->attrs().test(Attr::INTRINSIC)) { // C840 3376 Say(symbol->name(), 3377 "Symbol '%s' cannot have both INTRINSIC and EXTERNAL attributes"_err_en_US, 3378 symbol->name()); 3379 } 3380 } 3381 return false; 3382 } 3383 bool DeclarationVisitor::Pre(const parser::IntentStmt &x) { 3384 auto &intentSpec{std::get<parser::IntentSpec>(x.t)}; 3385 auto &names{std::get<std::list<parser::Name>>(x.t)}; 3386 return CheckNotInBlock("INTENT") && // C1107 3387 HandleAttributeStmt(IntentSpecToAttr(intentSpec), names); 3388 } 3389 bool DeclarationVisitor::Pre(const parser::IntrinsicStmt &x) { 3390 HandleAttributeStmt(Attr::INTRINSIC, x.v); 3391 for (const auto &name : x.v) { 3392 auto *symbol{FindSymbol(name)}; 3393 if (!ConvertToProcEntity(*symbol)) { 3394 SayWithDecl( 3395 name, *symbol, "INTRINSIC attribute not allowed on '%s'"_err_en_US); 3396 } else if (symbol->attrs().test(Attr::EXTERNAL)) { // C840 3397 Say(symbol->name(), 3398 "Symbol '%s' cannot have both EXTERNAL and INTRINSIC attributes"_err_en_US, 3399 symbol->name()); 3400 } 3401 } 3402 return false; 3403 } 3404 bool DeclarationVisitor::Pre(const parser::OptionalStmt &x) { 3405 return CheckNotInBlock("OPTIONAL") && // C1107 3406 HandleAttributeStmt(Attr::OPTIONAL, x.v); 3407 } 3408 bool DeclarationVisitor::Pre(const parser::ProtectedStmt &x) { 3409 return HandleAttributeStmt(Attr::PROTECTED, x.v); 3410 } 3411 bool DeclarationVisitor::Pre(const parser::ValueStmt &x) { 3412 return CheckNotInBlock("VALUE") && // C1107 3413 HandleAttributeStmt(Attr::VALUE, x.v); 3414 } 3415 bool DeclarationVisitor::Pre(const parser::VolatileStmt &x) { 3416 return HandleAttributeStmt(Attr::VOLATILE, x.v); 3417 } 3418 // Handle a statement that sets an attribute on a list of names. 3419 bool DeclarationVisitor::HandleAttributeStmt( 3420 Attr attr, const std::list<parser::Name> &names) { 3421 for (const auto &name : names) { 3422 HandleAttributeStmt(attr, name); 3423 } 3424 return false; 3425 } 3426 Symbol &DeclarationVisitor::HandleAttributeStmt( 3427 Attr attr, const parser::Name &name) { 3428 if (attr == Attr::INTRINSIC && !IsIntrinsic(name.source, std::nullopt)) { 3429 Say(name.source, "'%s' is not a known intrinsic procedure"_err_en_US); 3430 } 3431 auto *symbol{FindInScope(name)}; 3432 if (attr == Attr::ASYNCHRONOUS || attr == Attr::VOLATILE) { 3433 // these can be set on a symbol that is host-assoc or use-assoc 3434 if (!symbol && 3435 (currScope().kind() == Scope::Kind::Subprogram || 3436 currScope().kind() == Scope::Kind::Block)) { 3437 if (auto *hostSymbol{FindSymbol(name)}) { 3438 symbol = &MakeHostAssocSymbol(name, *hostSymbol); 3439 } 3440 } 3441 } else if (symbol && symbol->has<UseDetails>()) { 3442 Say(currStmtSource().value(), 3443 "Cannot change %s attribute on use-associated '%s'"_err_en_US, 3444 EnumToString(attr), name.source); 3445 return *symbol; 3446 } 3447 if (!symbol) { 3448 symbol = &MakeSymbol(name, EntityDetails{}); 3449 } 3450 symbol->attrs().set(attr); 3451 symbol->attrs() = HandleSaveName(name.source, symbol->attrs()); 3452 return *symbol; 3453 } 3454 // C1107 3455 bool DeclarationVisitor::CheckNotInBlock(const char *stmt) { 3456 if (currScope().kind() == Scope::Kind::Block) { 3457 Say(MessageFormattedText{ 3458 "%s statement is not allowed in a BLOCK construct"_err_en_US, stmt}); 3459 return false; 3460 } else { 3461 return true; 3462 } 3463 } 3464 3465 void DeclarationVisitor::Post(const parser::ObjectDecl &x) { 3466 CHECK(objectDeclAttr_); 3467 const auto &name{std::get<parser::ObjectName>(x.t)}; 3468 DeclareObjectEntity(name, Attrs{*objectDeclAttr_}); 3469 } 3470 3471 // Declare an entity not yet known to be an object or proc. 3472 Symbol &DeclarationVisitor::DeclareUnknownEntity( 3473 const parser::Name &name, Attrs attrs) { 3474 if (!arraySpec().empty() || !coarraySpec().empty()) { 3475 return DeclareObjectEntity(name, attrs); 3476 } else { 3477 Symbol &symbol{DeclareEntity<EntityDetails>(name, attrs)}; 3478 if (auto *type{GetDeclTypeSpec()}) { 3479 SetType(name, *type); 3480 } 3481 charInfo_.length.reset(); 3482 SetBindNameOn(symbol); 3483 if (symbol.attrs().test(Attr::EXTERNAL)) { 3484 ConvertToProcEntity(symbol); 3485 } 3486 return symbol; 3487 } 3488 } 3489 3490 Symbol &DeclarationVisitor::DeclareProcEntity( 3491 const parser::Name &name, Attrs attrs, const ProcInterface &interface) { 3492 Symbol &symbol{DeclareEntity<ProcEntityDetails>(name, attrs)}; 3493 if (auto *details{symbol.detailsIf<ProcEntityDetails>()}) { 3494 if (details->IsInterfaceSet()) { 3495 SayWithDecl(name, symbol, 3496 "The interface for procedure '%s' has already been " 3497 "declared"_err_en_US); 3498 context().SetError(symbol); 3499 } else { 3500 if (interface.type()) { 3501 symbol.set(Symbol::Flag::Function); 3502 } else if (interface.symbol()) { 3503 if (interface.symbol()->test(Symbol::Flag::Function)) { 3504 symbol.set(Symbol::Flag::Function); 3505 } else if (interface.symbol()->test(Symbol::Flag::Subroutine)) { 3506 symbol.set(Symbol::Flag::Subroutine); 3507 } 3508 } 3509 details->set_interface(interface); 3510 SetBindNameOn(symbol); 3511 SetPassNameOn(symbol); 3512 } 3513 } 3514 return symbol; 3515 } 3516 3517 Symbol &DeclarationVisitor::DeclareObjectEntity( 3518 const parser::Name &name, Attrs attrs) { 3519 Symbol &symbol{DeclareEntity<ObjectEntityDetails>(name, attrs)}; 3520 if (auto *details{symbol.detailsIf<ObjectEntityDetails>()}) { 3521 if (auto *type{GetDeclTypeSpec()}) { 3522 SetType(name, *type); 3523 } 3524 if (!arraySpec().empty()) { 3525 if (details->IsArray()) { 3526 if (!context().HasError(symbol)) { 3527 Say(name, 3528 "The dimensions of '%s' have already been declared"_err_en_US); 3529 context().SetError(symbol); 3530 } 3531 } else { 3532 details->set_shape(arraySpec()); 3533 } 3534 } 3535 if (!coarraySpec().empty()) { 3536 if (details->IsCoarray()) { 3537 if (!context().HasError(symbol)) { 3538 Say(name, 3539 "The codimensions of '%s' have already been declared"_err_en_US); 3540 context().SetError(symbol); 3541 } 3542 } else { 3543 details->set_coshape(coarraySpec()); 3544 } 3545 } 3546 SetBindNameOn(symbol); 3547 } 3548 ClearArraySpec(); 3549 ClearCoarraySpec(); 3550 charInfo_.length.reset(); 3551 return symbol; 3552 } 3553 3554 void DeclarationVisitor::Post(const parser::IntegerTypeSpec &x) { 3555 SetDeclTypeSpec(MakeNumericType(TypeCategory::Integer, x.v)); 3556 } 3557 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Real &x) { 3558 SetDeclTypeSpec(MakeNumericType(TypeCategory::Real, x.kind)); 3559 } 3560 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Complex &x) { 3561 SetDeclTypeSpec(MakeNumericType(TypeCategory::Complex, x.kind)); 3562 } 3563 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Logical &x) { 3564 SetDeclTypeSpec(MakeLogicalType(x.kind)); 3565 } 3566 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Character &) { 3567 if (!charInfo_.length) { 3568 charInfo_.length = ParamValue{1, common::TypeParamAttr::Len}; 3569 } 3570 if (!charInfo_.kind) { 3571 charInfo_.kind = 3572 KindExpr{context().GetDefaultKind(TypeCategory::Character)}; 3573 } 3574 SetDeclTypeSpec(currScope().MakeCharacterType( 3575 std::move(*charInfo_.length), std::move(*charInfo_.kind))); 3576 charInfo_ = {}; 3577 } 3578 void DeclarationVisitor::Post(const parser::CharSelector::LengthAndKind &x) { 3579 charInfo_.kind = EvaluateSubscriptIntExpr(x.kind); 3580 std::optional<std::int64_t> intKind{ToInt64(charInfo_.kind)}; 3581 if (intKind && 3582 !evaluate::IsValidKindOfIntrinsicType( 3583 TypeCategory::Character, *intKind)) { // C715, C719 3584 Say(currStmtSource().value(), 3585 "KIND value (%jd) not valid for CHARACTER"_err_en_US, *intKind); 3586 charInfo_.kind = std::nullopt; // prevent further errors 3587 } 3588 if (x.length) { 3589 charInfo_.length = GetParamValue(*x.length, common::TypeParamAttr::Len); 3590 } 3591 } 3592 void DeclarationVisitor::Post(const parser::CharLength &x) { 3593 if (const auto *length{std::get_if<std::uint64_t>(&x.u)}) { 3594 charInfo_.length = ParamValue{ 3595 static_cast<ConstantSubscript>(*length), common::TypeParamAttr::Len}; 3596 } else { 3597 charInfo_.length = GetParamValue( 3598 std::get<parser::TypeParamValue>(x.u), common::TypeParamAttr::Len); 3599 } 3600 } 3601 void DeclarationVisitor::Post(const parser::LengthSelector &x) { 3602 if (const auto *param{std::get_if<parser::TypeParamValue>(&x.u)}) { 3603 charInfo_.length = GetParamValue(*param, common::TypeParamAttr::Len); 3604 } 3605 } 3606 3607 bool DeclarationVisitor::Pre(const parser::KindParam &x) { 3608 if (const auto *kind{std::get_if< 3609 parser::Scalar<parser::Integer<parser::Constant<parser::Name>>>>( 3610 &x.u)}) { 3611 const parser::Name &name{kind->thing.thing.thing}; 3612 if (!FindSymbol(name)) { 3613 Say(name, "Parameter '%s' not found"_err_en_US); 3614 } 3615 } 3616 return false; 3617 } 3618 3619 bool DeclarationVisitor::Pre(const parser::DeclarationTypeSpec::Type &) { 3620 CHECK(GetDeclTypeSpecCategory() == DeclTypeSpec::Category::TypeDerived); 3621 return true; 3622 } 3623 3624 void DeclarationVisitor::Post(const parser::DeclarationTypeSpec::Type &type) { 3625 const parser::Name &derivedName{std::get<parser::Name>(type.derived.t)}; 3626 if (const Symbol * derivedSymbol{derivedName.symbol}) { 3627 CheckForAbstractType(*derivedSymbol); // C706 3628 } 3629 } 3630 3631 bool DeclarationVisitor::Pre(const parser::DeclarationTypeSpec::Class &) { 3632 SetDeclTypeSpecCategory(DeclTypeSpec::Category::ClassDerived); 3633 return true; 3634 } 3635 3636 void DeclarationVisitor::Post( 3637 const parser::DeclarationTypeSpec::Class &parsedClass) { 3638 const auto &typeName{std::get<parser::Name>(parsedClass.derived.t)}; 3639 if (auto spec{ResolveDerivedType(typeName)}; 3640 spec && !IsExtensibleType(&*spec)) { // C705 3641 SayWithDecl(typeName, *typeName.symbol, 3642 "Non-extensible derived type '%s' may not be used with CLASS" 3643 " keyword"_err_en_US); 3644 } 3645 } 3646 3647 bool DeclarationVisitor::Pre(const parser::DeclarationTypeSpec::Record &) { 3648 // TODO 3649 return true; 3650 } 3651 3652 void DeclarationVisitor::Post(const parser::DerivedTypeSpec &x) { 3653 const auto &typeName{std::get<parser::Name>(x.t)}; 3654 auto spec{ResolveDerivedType(typeName)}; 3655 if (!spec) { 3656 return; 3657 } 3658 bool seenAnyName{false}; 3659 for (const auto &typeParamSpec : 3660 std::get<std::list<parser::TypeParamSpec>>(x.t)) { 3661 const auto &optKeyword{ 3662 std::get<std::optional<parser::Keyword>>(typeParamSpec.t)}; 3663 std::optional<SourceName> name; 3664 if (optKeyword) { 3665 seenAnyName = true; 3666 name = optKeyword->v.source; 3667 } else if (seenAnyName) { 3668 Say(typeName.source, "Type parameter value must have a name"_err_en_US); 3669 continue; 3670 } 3671 const auto &value{std::get<parser::TypeParamValue>(typeParamSpec.t)}; 3672 // The expressions in a derived type specifier whose values define 3673 // non-defaulted type parameters are evaluated (folded) in the enclosing 3674 // scope. The KIND/LEN distinction is resolved later in 3675 // DerivedTypeSpec::CookParameters(). 3676 ParamValue param{GetParamValue(value, common::TypeParamAttr::Kind)}; 3677 if (!param.isExplicit() || param.GetExplicit()) { 3678 spec->AddRawParamValue(optKeyword, std::move(param)); 3679 } 3680 } 3681 3682 // The DerivedTypeSpec *spec is used initially as a search key. 3683 // If it turns out to have the same name and actual parameter 3684 // value expressions as another DerivedTypeSpec in the current 3685 // scope does, then we'll use that extant spec; otherwise, when this 3686 // spec is distinct from all derived types previously instantiated 3687 // in the current scope, this spec will be moved into that collection. 3688 const auto &dtDetails{spec->typeSymbol().get<DerivedTypeDetails>()}; 3689 auto category{GetDeclTypeSpecCategory()}; 3690 if (dtDetails.isForwardReferenced()) { 3691 DeclTypeSpec &type{currScope().MakeDerivedType(category, std::move(*spec))}; 3692 SetDeclTypeSpec(type); 3693 return; 3694 } 3695 // Normalize parameters to produce a better search key. 3696 spec->CookParameters(GetFoldingContext()); 3697 if (!spec->MightBeParameterized()) { 3698 spec->EvaluateParameters(context()); 3699 } 3700 if (const DeclTypeSpec * 3701 extant{currScope().FindInstantiatedDerivedType(*spec, category)}) { 3702 // This derived type and parameter expressions (if any) are already present 3703 // in this scope. 3704 SetDeclTypeSpec(*extant); 3705 } else { 3706 DeclTypeSpec &type{currScope().MakeDerivedType(category, std::move(*spec))}; 3707 DerivedTypeSpec &derived{type.derivedTypeSpec()}; 3708 if (derived.MightBeParameterized() && 3709 currScope().IsParameterizedDerivedType()) { 3710 // Defer instantiation; use the derived type's definition's scope. 3711 derived.set_scope(DEREF(spec->typeSymbol().scope())); 3712 } else { 3713 auto restorer{ 3714 GetFoldingContext().messages().SetLocation(currStmtSource().value())}; 3715 derived.Instantiate(currScope(), context()); 3716 } 3717 SetDeclTypeSpec(type); 3718 } 3719 // Capture the DerivedTypeSpec in the parse tree for use in building 3720 // structure constructor expressions. 3721 x.derivedTypeSpec = &GetDeclTypeSpec()->derivedTypeSpec(); 3722 } 3723 3724 // The descendents of DerivedTypeDef in the parse tree are visited directly 3725 // in this Pre() routine so that recursive use of the derived type can be 3726 // supported in the components. 3727 bool DeclarationVisitor::Pre(const parser::DerivedTypeDef &x) { 3728 auto &stmt{std::get<parser::Statement<parser::DerivedTypeStmt>>(x.t)}; 3729 Walk(stmt); 3730 Walk(std::get<std::list<parser::Statement<parser::TypeParamDefStmt>>>(x.t)); 3731 auto &scope{currScope()}; 3732 CHECK(scope.symbol()); 3733 CHECK(scope.symbol()->scope() == &scope); 3734 auto &details{scope.symbol()->get<DerivedTypeDetails>()}; 3735 std::set<SourceName> paramNames; 3736 for (auto ¶mName : std::get<std::list<parser::Name>>(stmt.statement.t)) { 3737 details.add_paramName(paramName.source); 3738 auto *symbol{FindInScope(scope, paramName)}; 3739 if (!symbol) { 3740 Say(paramName, 3741 "No definition found for type parameter '%s'"_err_en_US); // C742 3742 // No symbol for a type param. Create one and mark it as containing an 3743 // error to improve subsequent semantic processing 3744 BeginAttrs(); 3745 Symbol *typeParam{MakeTypeSymbol( 3746 paramName, TypeParamDetails{common::TypeParamAttr::Len})}; 3747 context().SetError(*typeParam); 3748 EndAttrs(); 3749 } else if (!symbol->has<TypeParamDetails>()) { 3750 Say2(paramName, "'%s' is not defined as a type parameter"_err_en_US, 3751 *symbol, "Definition of '%s'"_en_US); // C741 3752 } 3753 if (!paramNames.insert(paramName.source).second) { 3754 Say(paramName, 3755 "Duplicate type parameter name: '%s'"_err_en_US); // C731 3756 } 3757 } 3758 for (const auto &[name, symbol] : currScope()) { 3759 if (symbol->has<TypeParamDetails>() && !paramNames.count(name)) { 3760 SayDerivedType(name, 3761 "'%s' is not a type parameter of this derived type"_err_en_US, 3762 currScope()); // C741 3763 } 3764 } 3765 Walk(std::get<std::list<parser::Statement<parser::PrivateOrSequence>>>(x.t)); 3766 const auto &componentDefs{ 3767 std::get<std::list<parser::Statement<parser::ComponentDefStmt>>>(x.t)}; 3768 Walk(componentDefs); 3769 if (derivedTypeInfo_.sequence) { 3770 details.set_sequence(true); 3771 if (componentDefs.empty()) { // C740 3772 Say(stmt.source, 3773 "A sequence type must have at least one component"_err_en_US); 3774 } 3775 if (!details.paramNames().empty()) { // C740 3776 Say(stmt.source, 3777 "A sequence type may not have type parameters"_err_en_US); 3778 } 3779 if (derivedTypeInfo_.extends) { // C735 3780 Say(stmt.source, 3781 "A sequence type may not have the EXTENDS attribute"_err_en_US); 3782 } else { 3783 for (const auto &componentName : details.componentNames()) { 3784 const Symbol *componentSymbol{scope.FindComponent(componentName)}; 3785 if (componentSymbol && componentSymbol->has<ObjectEntityDetails>()) { 3786 const auto &componentDetails{ 3787 componentSymbol->get<ObjectEntityDetails>()}; 3788 const DeclTypeSpec *componentType{componentDetails.type()}; 3789 if (componentType && // C740 3790 !componentType->AsIntrinsic() && 3791 !componentType->IsSequenceType()) { 3792 Say(componentSymbol->name(), 3793 "A sequence type data component must either be of an" 3794 " intrinsic type or a derived sequence type"_err_en_US); 3795 } 3796 } 3797 } 3798 } 3799 } 3800 Walk(std::get<std::optional<parser::TypeBoundProcedurePart>>(x.t)); 3801 Walk(std::get<parser::Statement<parser::EndTypeStmt>>(x.t)); 3802 derivedTypeInfo_ = {}; 3803 PopScope(); 3804 return false; 3805 } 3806 bool DeclarationVisitor::Pre(const parser::DerivedTypeStmt &) { 3807 return BeginAttrs(); 3808 } 3809 void DeclarationVisitor::Post(const parser::DerivedTypeStmt &x) { 3810 auto &name{std::get<parser::Name>(x.t)}; 3811 // Resolve the EXTENDS() clause before creating the derived 3812 // type's symbol to foil attempts to recursively extend a type. 3813 auto *extendsName{derivedTypeInfo_.extends}; 3814 std::optional<DerivedTypeSpec> extendsType{ 3815 ResolveExtendsType(name, extendsName)}; 3816 auto &symbol{MakeSymbol(name, GetAttrs(), DerivedTypeDetails{})}; 3817 symbol.ReplaceName(name.source); 3818 derivedTypeInfo_.type = &symbol; 3819 PushScope(Scope::Kind::DerivedType, &symbol); 3820 if (extendsType) { 3821 // Declare the "parent component"; private if the type is. 3822 // Any symbol stored in the EXTENDS() clause is temporarily 3823 // hidden so that a new symbol can be created for the parent 3824 // component without producing spurious errors about already 3825 // existing. 3826 const Symbol &extendsSymbol{extendsType->typeSymbol()}; 3827 auto restorer{common::ScopedSet(extendsName->symbol, nullptr)}; 3828 if (OkToAddComponent(*extendsName, &extendsSymbol)) { 3829 auto &comp{DeclareEntity<ObjectEntityDetails>(*extendsName, Attrs{})}; 3830 comp.attrs().set( 3831 Attr::PRIVATE, extendsSymbol.attrs().test(Attr::PRIVATE)); 3832 comp.set(Symbol::Flag::ParentComp); 3833 DeclTypeSpec &type{currScope().MakeDerivedType( 3834 DeclTypeSpec::TypeDerived, std::move(*extendsType))}; 3835 type.derivedTypeSpec().set_scope(*extendsSymbol.scope()); 3836 comp.SetType(type); 3837 DerivedTypeDetails &details{symbol.get<DerivedTypeDetails>()}; 3838 details.add_component(comp); 3839 } 3840 } 3841 EndAttrs(); 3842 } 3843 3844 void DeclarationVisitor::Post(const parser::TypeParamDefStmt &x) { 3845 auto *type{GetDeclTypeSpec()}; 3846 auto attr{std::get<common::TypeParamAttr>(x.t)}; 3847 for (auto &decl : std::get<std::list<parser::TypeParamDecl>>(x.t)) { 3848 auto &name{std::get<parser::Name>(decl.t)}; 3849 if (Symbol * symbol{MakeTypeSymbol(name, TypeParamDetails{attr})}) { 3850 SetType(name, *type); 3851 if (auto &init{ 3852 std::get<std::optional<parser::ScalarIntConstantExpr>>(decl.t)}) { 3853 if (auto maybeExpr{EvaluateNonPointerInitializer( 3854 *symbol, *init, init->thing.thing.thing.value().source)}) { 3855 if (auto *intExpr{std::get_if<SomeIntExpr>(&maybeExpr->u)}) { 3856 symbol->get<TypeParamDetails>().set_init(std::move(*intExpr)); 3857 } 3858 } 3859 } 3860 } 3861 } 3862 EndDecl(); 3863 } 3864 bool DeclarationVisitor::Pre(const parser::TypeAttrSpec::Extends &x) { 3865 if (derivedTypeInfo_.extends) { 3866 Say(currStmtSource().value(), 3867 "Attribute 'EXTENDS' cannot be used more than once"_err_en_US); 3868 } else { 3869 derivedTypeInfo_.extends = &x.v; 3870 } 3871 return false; 3872 } 3873 3874 bool DeclarationVisitor::Pre(const parser::PrivateStmt &) { 3875 if (!currScope().parent().IsModule()) { 3876 Say("PRIVATE is only allowed in a derived type that is" 3877 " in a module"_err_en_US); // C766 3878 } else if (derivedTypeInfo_.sawContains) { 3879 derivedTypeInfo_.privateBindings = true; 3880 } else if (!derivedTypeInfo_.privateComps) { 3881 derivedTypeInfo_.privateComps = true; 3882 } else { 3883 Say("PRIVATE may not appear more than once in" 3884 " derived type components"_en_US); // C738 3885 } 3886 return false; 3887 } 3888 bool DeclarationVisitor::Pre(const parser::SequenceStmt &) { 3889 if (derivedTypeInfo_.sequence) { 3890 Say("SEQUENCE may not appear more than once in" 3891 " derived type components"_en_US); // C738 3892 } 3893 derivedTypeInfo_.sequence = true; 3894 return false; 3895 } 3896 void DeclarationVisitor::Post(const parser::ComponentDecl &x) { 3897 const auto &name{std::get<parser::Name>(x.t)}; 3898 auto attrs{GetAttrs()}; 3899 if (derivedTypeInfo_.privateComps && 3900 !attrs.HasAny({Attr::PUBLIC, Attr::PRIVATE})) { 3901 attrs.set(Attr::PRIVATE); 3902 } 3903 if (const auto *declType{GetDeclTypeSpec()}) { 3904 if (const auto *derived{declType->AsDerived()}) { 3905 if (!attrs.HasAny({Attr::POINTER, Attr::ALLOCATABLE})) { 3906 if (derivedTypeInfo_.type == &derived->typeSymbol()) { // C744 3907 Say("Recursive use of the derived type requires " 3908 "POINTER or ALLOCATABLE"_err_en_US); 3909 } 3910 } 3911 if (!coarraySpec().empty()) { // C747 3912 if (IsTeamType(derived)) { 3913 Say("A coarray component may not be of type TEAM_TYPE from " 3914 "ISO_FORTRAN_ENV"_err_en_US); 3915 } else { 3916 if (IsIsoCType(derived)) { 3917 Say("A coarray component may not be of type C_PTR or C_FUNPTR from " 3918 "ISO_C_BINDING"_err_en_US); 3919 } 3920 } 3921 } 3922 if (auto it{FindCoarrayUltimateComponent(*derived)}) { // C748 3923 std::string ultimateName{it.BuildResultDesignatorName()}; 3924 // Strip off the leading "%" 3925 if (ultimateName.length() > 1) { 3926 ultimateName.erase(0, 1); 3927 if (attrs.HasAny({Attr::POINTER, Attr::ALLOCATABLE})) { 3928 evaluate::AttachDeclaration( 3929 Say(name.source, 3930 "A component with a POINTER or ALLOCATABLE attribute may " 3931 "not " 3932 "be of a type with a coarray ultimate component (named " 3933 "'%s')"_err_en_US, 3934 ultimateName), 3935 derived->typeSymbol()); 3936 } 3937 if (!arraySpec().empty() || !coarraySpec().empty()) { 3938 evaluate::AttachDeclaration( 3939 Say(name.source, 3940 "An array or coarray component may not be of a type with a " 3941 "coarray ultimate component (named '%s')"_err_en_US, 3942 ultimateName), 3943 derived->typeSymbol()); 3944 } 3945 } 3946 } 3947 } 3948 } 3949 if (OkToAddComponent(name)) { 3950 auto &symbol{DeclareObjectEntity(name, attrs)}; 3951 if (symbol.has<ObjectEntityDetails>()) { 3952 if (auto &init{std::get<std::optional<parser::Initialization>>(x.t)}) { 3953 Initialization(name, *init, true); 3954 } 3955 } 3956 currScope().symbol()->get<DerivedTypeDetails>().add_component(symbol); 3957 } 3958 ClearArraySpec(); 3959 ClearCoarraySpec(); 3960 } 3961 bool DeclarationVisitor::Pre(const parser::ProcedureDeclarationStmt &) { 3962 CHECK(!interfaceName_); 3963 return BeginDecl(); 3964 } 3965 void DeclarationVisitor::Post(const parser::ProcedureDeclarationStmt &) { 3966 interfaceName_ = nullptr; 3967 EndDecl(); 3968 } 3969 bool DeclarationVisitor::Pre(const parser::DataComponentDefStmt &x) { 3970 // Overrides parse tree traversal so as to handle attributes first, 3971 // so POINTER & ALLOCATABLE enable forward references to derived types. 3972 Walk(std::get<std::list<parser::ComponentAttrSpec>>(x.t)); 3973 set_allowForwardReferenceToDerivedType( 3974 GetAttrs().HasAny({Attr::POINTER, Attr::ALLOCATABLE})); 3975 Walk(std::get<parser::DeclarationTypeSpec>(x.t)); 3976 set_allowForwardReferenceToDerivedType(false); 3977 Walk(std::get<std::list<parser::ComponentDecl>>(x.t)); 3978 return false; 3979 } 3980 bool DeclarationVisitor::Pre(const parser::ProcComponentDefStmt &) { 3981 CHECK(!interfaceName_); 3982 return true; 3983 } 3984 void DeclarationVisitor::Post(const parser::ProcComponentDefStmt &) { 3985 interfaceName_ = nullptr; 3986 } 3987 bool DeclarationVisitor::Pre(const parser::ProcPointerInit &x) { 3988 if (auto *name{std::get_if<parser::Name>(&x.u)}) { 3989 return !NameIsKnownOrIntrinsic(*name); 3990 } 3991 return true; 3992 } 3993 void DeclarationVisitor::Post(const parser::ProcInterface &x) { 3994 if (auto *name{std::get_if<parser::Name>(&x.u)}) { 3995 interfaceName_ = name; 3996 NoteInterfaceName(*name); 3997 } 3998 } 3999 4000 void DeclarationVisitor::Post(const parser::ProcDecl &x) { 4001 const auto &name{std::get<parser::Name>(x.t)}; 4002 ProcInterface interface; 4003 if (interfaceName_) { 4004 interface.set_symbol(*interfaceName_->symbol); 4005 } else if (auto *type{GetDeclTypeSpec()}) { 4006 interface.set_type(*type); 4007 } 4008 auto attrs{HandleSaveName(name.source, GetAttrs())}; 4009 DerivedTypeDetails *dtDetails{nullptr}; 4010 if (Symbol * symbol{currScope().symbol()}) { 4011 dtDetails = symbol->detailsIf<DerivedTypeDetails>(); 4012 } 4013 if (!dtDetails) { 4014 attrs.set(Attr::EXTERNAL); 4015 } 4016 Symbol &symbol{DeclareProcEntity(name, attrs, interface)}; 4017 symbol.ReplaceName(name.source); 4018 if (dtDetails) { 4019 dtDetails->add_component(symbol); 4020 } 4021 } 4022 4023 bool DeclarationVisitor::Pre(const parser::TypeBoundProcedurePart &) { 4024 derivedTypeInfo_.sawContains = true; 4025 return true; 4026 } 4027 4028 // Resolve binding names from type-bound generics, saved in genericBindings_. 4029 void DeclarationVisitor::Post(const parser::TypeBoundProcedurePart &) { 4030 // track specifics seen for the current generic to detect duplicates: 4031 const Symbol *currGeneric{nullptr}; 4032 std::set<SourceName> specifics; 4033 for (const auto &[generic, bindingName] : genericBindings_) { 4034 if (generic != currGeneric) { 4035 currGeneric = generic; 4036 specifics.clear(); 4037 } 4038 auto [it, inserted]{specifics.insert(bindingName->source)}; 4039 if (!inserted) { 4040 Say(*bindingName, // C773 4041 "Binding name '%s' was already specified for generic '%s'"_err_en_US, 4042 bindingName->source, generic->name()) 4043 .Attach(*it, "Previous specification of '%s'"_en_US, *it); 4044 continue; 4045 } 4046 auto *symbol{FindInTypeOrParents(*bindingName)}; 4047 if (!symbol) { 4048 Say(*bindingName, // C772 4049 "Binding name '%s' not found in this derived type"_err_en_US); 4050 } else if (!symbol->has<ProcBindingDetails>()) { 4051 SayWithDecl(*bindingName, *symbol, // C772 4052 "'%s' is not the name of a specific binding of this type"_err_en_US); 4053 } else { 4054 generic->get<GenericDetails>().AddSpecificProc( 4055 *symbol, bindingName->source); 4056 } 4057 } 4058 genericBindings_.clear(); 4059 } 4060 4061 void DeclarationVisitor::Post(const parser::ContainsStmt &) { 4062 if (derivedTypeInfo_.sequence) { 4063 Say("A sequence type may not have a CONTAINS statement"_err_en_US); // C740 4064 } 4065 } 4066 4067 void DeclarationVisitor::Post( 4068 const parser::TypeBoundProcedureStmt::WithoutInterface &x) { 4069 if (GetAttrs().test(Attr::DEFERRED)) { // C783 4070 Say("DEFERRED is only allowed when an interface-name is provided"_err_en_US); 4071 } 4072 for (auto &declaration : x.declarations) { 4073 auto &bindingName{std::get<parser::Name>(declaration.t)}; 4074 auto &optName{std::get<std::optional<parser::Name>>(declaration.t)}; 4075 const parser::Name &procedureName{optName ? *optName : bindingName}; 4076 Symbol *procedure{FindSymbol(procedureName)}; 4077 if (!procedure) { 4078 procedure = NoteInterfaceName(procedureName); 4079 } 4080 if (auto *s{MakeTypeSymbol(bindingName, ProcBindingDetails{*procedure})}) { 4081 SetPassNameOn(*s); 4082 if (GetAttrs().test(Attr::DEFERRED)) { 4083 context().SetError(*s); 4084 } 4085 } 4086 } 4087 } 4088 4089 void DeclarationVisitor::CheckBindings( 4090 const parser::TypeBoundProcedureStmt::WithoutInterface &tbps) { 4091 CHECK(currScope().IsDerivedType()); 4092 for (auto &declaration : tbps.declarations) { 4093 auto &bindingName{std::get<parser::Name>(declaration.t)}; 4094 if (Symbol * binding{FindInScope(bindingName)}) { 4095 if (auto *details{binding->detailsIf<ProcBindingDetails>()}) { 4096 const Symbol *procedure{FindSubprogram(details->symbol())}; 4097 if (!CanBeTypeBoundProc(procedure)) { 4098 if (details->symbol().name() != binding->name()) { 4099 Say(binding->name(), 4100 "The binding of '%s' ('%s') must be either an accessible " 4101 "module procedure or an external procedure with " 4102 "an explicit interface"_err_en_US, 4103 binding->name(), details->symbol().name()); 4104 } else { 4105 Say(binding->name(), 4106 "'%s' must be either an accessible module procedure " 4107 "or an external procedure with an explicit interface"_err_en_US, 4108 binding->name()); 4109 } 4110 context().SetError(*binding); 4111 } 4112 } 4113 } 4114 } 4115 } 4116 4117 void DeclarationVisitor::Post( 4118 const parser::TypeBoundProcedureStmt::WithInterface &x) { 4119 if (!GetAttrs().test(Attr::DEFERRED)) { // C783 4120 Say("DEFERRED is required when an interface-name is provided"_err_en_US); 4121 } 4122 if (Symbol * interface{NoteInterfaceName(x.interfaceName)}) { 4123 for (auto &bindingName : x.bindingNames) { 4124 if (auto *s{ 4125 MakeTypeSymbol(bindingName, ProcBindingDetails{*interface})}) { 4126 SetPassNameOn(*s); 4127 if (!GetAttrs().test(Attr::DEFERRED)) { 4128 context().SetError(*s); 4129 } 4130 } 4131 } 4132 } 4133 } 4134 4135 void DeclarationVisitor::Post(const parser::FinalProcedureStmt &x) { 4136 if (currScope().IsDerivedType() && currScope().symbol()) { 4137 if (auto *details{currScope().symbol()->detailsIf<DerivedTypeDetails>()}) { 4138 for (const auto &subrName : x.v) { 4139 if (const auto *name{ResolveName(subrName)}) { 4140 auto pair{ 4141 details->finals().emplace(name->source, DEREF(name->symbol))}; 4142 if (!pair.second) { // C787 4143 Say(name->source, 4144 "FINAL subroutine '%s' already appeared in this derived type"_err_en_US, 4145 name->source) 4146 .Attach(pair.first->first, 4147 "earlier appearance of this FINAL subroutine"_en_US); 4148 } 4149 } 4150 } 4151 } 4152 } 4153 } 4154 4155 bool DeclarationVisitor::Pre(const parser::TypeBoundGenericStmt &x) { 4156 const auto &accessSpec{std::get<std::optional<parser::AccessSpec>>(x.t)}; 4157 const auto &genericSpec{std::get<Indirection<parser::GenericSpec>>(x.t)}; 4158 const auto &bindingNames{std::get<std::list<parser::Name>>(x.t)}; 4159 auto info{GenericSpecInfo{genericSpec.value()}}; 4160 SourceName symbolName{info.symbolName()}; 4161 bool isPrivate{accessSpec ? accessSpec->v == parser::AccessSpec::Kind::Private 4162 : derivedTypeInfo_.privateBindings}; 4163 auto *genericSymbol{FindInScope(symbolName)}; 4164 if (genericSymbol) { 4165 if (!genericSymbol->has<GenericDetails>()) { 4166 genericSymbol = nullptr; // MakeTypeSymbol will report the error below 4167 } 4168 } else { 4169 // look in parent types: 4170 Symbol *inheritedSymbol{nullptr}; 4171 for (const auto &name : GetAllNames(context(), symbolName)) { 4172 inheritedSymbol = currScope().FindComponent(SourceName{name}); 4173 if (inheritedSymbol) { 4174 break; 4175 } 4176 } 4177 if (inheritedSymbol && inheritedSymbol->has<GenericDetails>()) { 4178 CheckAccessibility(symbolName, isPrivate, *inheritedSymbol); // C771 4179 } 4180 } 4181 if (genericSymbol) { 4182 CheckAccessibility(symbolName, isPrivate, *genericSymbol); // C771 4183 } else { 4184 genericSymbol = MakeTypeSymbol(symbolName, GenericDetails{}); 4185 if (!genericSymbol) { 4186 return false; 4187 } 4188 if (isPrivate) { 4189 genericSymbol->attrs().set(Attr::PRIVATE); 4190 } 4191 } 4192 for (const parser::Name &bindingName : bindingNames) { 4193 genericBindings_.emplace(genericSymbol, &bindingName); 4194 } 4195 info.Resolve(genericSymbol); 4196 return false; 4197 } 4198 4199 bool DeclarationVisitor::Pre(const parser::AllocateStmt &) { 4200 BeginDeclTypeSpec(); 4201 return true; 4202 } 4203 void DeclarationVisitor::Post(const parser::AllocateStmt &) { 4204 EndDeclTypeSpec(); 4205 } 4206 4207 bool DeclarationVisitor::Pre(const parser::StructureConstructor &x) { 4208 auto &parsedType{std::get<parser::DerivedTypeSpec>(x.t)}; 4209 const DeclTypeSpec *type{ProcessTypeSpec(parsedType)}; 4210 if (!type) { 4211 return false; 4212 } 4213 const DerivedTypeSpec *spec{type->AsDerived()}; 4214 const Scope *typeScope{spec ? spec->scope() : nullptr}; 4215 if (!typeScope) { 4216 return false; 4217 } 4218 4219 // N.B C7102 is implicitly enforced by having inaccessible types not 4220 // being found in resolution. 4221 // More constraints are enforced in expression.cpp so that they 4222 // can apply to structure constructors that have been converted 4223 // from misparsed function references. 4224 for (const auto &component : 4225 std::get<std::list<parser::ComponentSpec>>(x.t)) { 4226 // Visit the component spec expression, but not the keyword, since 4227 // we need to resolve its symbol in the scope of the derived type. 4228 Walk(std::get<parser::ComponentDataSource>(component.t)); 4229 if (const auto &kw{std::get<std::optional<parser::Keyword>>(component.t)}) { 4230 FindInTypeOrParents(*typeScope, kw->v); 4231 } 4232 } 4233 return false; 4234 } 4235 4236 bool DeclarationVisitor::Pre(const parser::BasedPointerStmt &x) { 4237 for (const parser::BasedPointer &bp : x.v) { 4238 const parser::ObjectName &pointerName{std::get<0>(bp.t)}; 4239 const parser::ObjectName &pointeeName{std::get<1>(bp.t)}; 4240 auto *pointer{FindSymbol(pointerName)}; 4241 if (!pointer) { 4242 pointer = &MakeSymbol(pointerName, ObjectEntityDetails{}); 4243 } else if (!ConvertToObjectEntity(*pointer) || IsNamedConstant(*pointer)) { 4244 SayWithDecl(pointerName, *pointer, "'%s' is not a variable"_err_en_US); 4245 } else if (pointer->Rank() > 0) { 4246 SayWithDecl(pointerName, *pointer, 4247 "Cray pointer '%s' must be a scalar"_err_en_US); 4248 } else if (pointer->test(Symbol::Flag::CrayPointee)) { 4249 Say(pointerName, 4250 "'%s' cannot be a Cray pointer as it is already a Cray pointee"_err_en_US); 4251 } 4252 pointer->set(Symbol::Flag::CrayPointer); 4253 const DeclTypeSpec &pointerType{MakeNumericType(TypeCategory::Integer, 4254 context().defaultKinds().subscriptIntegerKind())}; 4255 const auto *type{pointer->GetType()}; 4256 if (!type) { 4257 pointer->SetType(pointerType); 4258 } else if (*type != pointerType) { 4259 Say(pointerName.source, "Cray pointer '%s' must have type %s"_err_en_US, 4260 pointerName.source, pointerType.AsFortran()); 4261 } 4262 if (ResolveName(pointeeName)) { 4263 Symbol &pointee{*pointeeName.symbol}; 4264 if (pointee.has<UseDetails>()) { 4265 Say(pointeeName, 4266 "'%s' cannot be a Cray pointee as it is use-associated"_err_en_US); 4267 continue; 4268 } else if (!ConvertToObjectEntity(pointee) || IsNamedConstant(pointee)) { 4269 Say(pointeeName, "'%s' is not a variable"_err_en_US); 4270 continue; 4271 } else if (pointee.test(Symbol::Flag::CrayPointer)) { 4272 Say(pointeeName, 4273 "'%s' cannot be a Cray pointee as it is already a Cray pointer"_err_en_US); 4274 } else if (pointee.test(Symbol::Flag::CrayPointee)) { 4275 Say(pointeeName, 4276 "'%s' was already declared as a Cray pointee"_err_en_US); 4277 } else { 4278 pointee.set(Symbol::Flag::CrayPointee); 4279 } 4280 if (const auto *pointeeType{pointee.GetType()}) { 4281 if (const auto *derived{pointeeType->AsDerived()}) { 4282 if (!derived->typeSymbol().get<DerivedTypeDetails>().sequence()) { 4283 Say(pointeeName, 4284 "Type of Cray pointee '%s' is a non-sequence derived type"_err_en_US); 4285 } 4286 } 4287 } 4288 // process the pointee array-spec, if present 4289 BeginArraySpec(); 4290 Walk(std::get<std::optional<parser::ArraySpec>>(bp.t)); 4291 const auto &spec{arraySpec()}; 4292 if (!spec.empty()) { 4293 auto &details{pointee.get<ObjectEntityDetails>()}; 4294 if (details.shape().empty()) { 4295 details.set_shape(spec); 4296 } else { 4297 SayWithDecl(pointeeName, pointee, 4298 "Array spec was already declared for '%s'"_err_en_US); 4299 } 4300 } 4301 ClearArraySpec(); 4302 currScope().add_crayPointer(pointeeName.source, *pointer); 4303 } 4304 } 4305 return false; 4306 } 4307 4308 bool DeclarationVisitor::Pre(const parser::NamelistStmt::Group &x) { 4309 if (!CheckNotInBlock("NAMELIST")) { // C1107 4310 return false; 4311 } 4312 4313 NamelistDetails details; 4314 for (const auto &name : std::get<std::list<parser::Name>>(x.t)) { 4315 auto *symbol{FindSymbol(name)}; 4316 if (!symbol) { 4317 symbol = &MakeSymbol(name, ObjectEntityDetails{}); 4318 ApplyImplicitRules(*symbol); 4319 } else if (!ConvertToObjectEntity(*symbol)) { 4320 SayWithDecl(name, *symbol, "'%s' is not a variable"_err_en_US); 4321 } 4322 symbol->GetUltimate().set(Symbol::Flag::InNamelist); 4323 details.add_object(*symbol); 4324 } 4325 4326 const auto &groupName{std::get<parser::Name>(x.t)}; 4327 auto *groupSymbol{FindInScope(groupName)}; 4328 if (!groupSymbol || !groupSymbol->has<NamelistDetails>()) { 4329 groupSymbol = &MakeSymbol(groupName, std::move(details)); 4330 groupSymbol->ReplaceName(groupName.source); 4331 } 4332 groupSymbol->get<NamelistDetails>().add_objects(details.objects()); 4333 return false; 4334 } 4335 4336 bool DeclarationVisitor::Pre(const parser::IoControlSpec &x) { 4337 if (const auto *name{std::get_if<parser::Name>(&x.u)}) { 4338 auto *symbol{FindSymbol(*name)}; 4339 if (!symbol) { 4340 Say(*name, "Namelist group '%s' not found"_err_en_US); 4341 } else if (!symbol->GetUltimate().has<NamelistDetails>()) { 4342 SayWithDecl( 4343 *name, *symbol, "'%s' is not the name of a namelist group"_err_en_US); 4344 } 4345 } 4346 return true; 4347 } 4348 4349 bool DeclarationVisitor::Pre(const parser::CommonStmt::Block &x) { 4350 CheckNotInBlock("COMMON"); // C1107 4351 return true; 4352 } 4353 4354 bool DeclarationVisitor::Pre(const parser::CommonBlockObject &) { 4355 BeginArraySpec(); 4356 return true; 4357 } 4358 4359 void DeclarationVisitor::Post(const parser::CommonBlockObject &x) { 4360 const auto &name{std::get<parser::Name>(x.t)}; 4361 DeclareObjectEntity(name); 4362 auto pair{commonBlockObjects_.insert(name.source)}; 4363 if (!pair.second) { 4364 const SourceName &prev{*pair.first}; 4365 Say2(name.source, "'%s' is already in a COMMON block"_err_en_US, prev, 4366 "Previous occurrence of '%s' in a COMMON block"_en_US); 4367 } 4368 } 4369 4370 bool DeclarationVisitor::Pre(const parser::EquivalenceStmt &x) { 4371 // save equivalence sets to be processed after specification part 4372 if (CheckNotInBlock("EQUIVALENCE")) { // C1107 4373 for (const std::list<parser::EquivalenceObject> &set : x.v) { 4374 equivalenceSets_.push_back(&set); 4375 } 4376 } 4377 return false; // don't implicitly declare names yet 4378 } 4379 4380 void DeclarationVisitor::CheckEquivalenceSets() { 4381 EquivalenceSets equivSets{context()}; 4382 inEquivalenceStmt_ = true; 4383 for (const auto *set : equivalenceSets_) { 4384 const auto &source{set->front().v.value().source}; 4385 if (set->size() <= 1) { // R871 4386 Say(source, "Equivalence set must have more than one object"_err_en_US); 4387 } 4388 for (const parser::EquivalenceObject &object : *set) { 4389 const auto &designator{object.v.value()}; 4390 // The designator was not resolved when it was encountered so do it now. 4391 // AnalyzeExpr causes array sections to be changed to substrings as needed 4392 Walk(designator); 4393 if (AnalyzeExpr(context(), designator)) { 4394 equivSets.AddToSet(designator); 4395 } 4396 } 4397 equivSets.FinishSet(source); 4398 } 4399 inEquivalenceStmt_ = false; 4400 for (auto &set : equivSets.sets()) { 4401 if (!set.empty()) { 4402 currScope().add_equivalenceSet(std::move(set)); 4403 } 4404 } 4405 equivalenceSets_.clear(); 4406 } 4407 4408 bool DeclarationVisitor::Pre(const parser::SaveStmt &x) { 4409 if (x.v.empty()) { 4410 saveInfo_.saveAll = currStmtSource(); 4411 currScope().set_hasSAVE(); 4412 } else { 4413 for (const parser::SavedEntity &y : x.v) { 4414 auto kind{std::get<parser::SavedEntity::Kind>(y.t)}; 4415 const auto &name{std::get<parser::Name>(y.t)}; 4416 if (kind == parser::SavedEntity::Kind::Common) { 4417 MakeCommonBlockSymbol(name); 4418 AddSaveName(saveInfo_.commons, name.source); 4419 } else { 4420 HandleAttributeStmt(Attr::SAVE, name); 4421 } 4422 } 4423 } 4424 return false; 4425 } 4426 4427 void DeclarationVisitor::CheckSaveStmts() { 4428 for (const SourceName &name : saveInfo_.entities) { 4429 auto *symbol{FindInScope(name)}; 4430 if (!symbol) { 4431 // error was reported 4432 } else if (saveInfo_.saveAll) { 4433 // C889 - note that pgi, ifort, xlf do not enforce this constraint 4434 Say2(name, 4435 "Explicit SAVE of '%s' is redundant due to global SAVE statement"_err_en_US, 4436 *saveInfo_.saveAll, "Global SAVE statement"_en_US); 4437 } else if (auto msg{CheckSaveAttr(*symbol)}) { 4438 Say(name, std::move(*msg)); 4439 context().SetError(*symbol); 4440 } else { 4441 SetSaveAttr(*symbol); 4442 } 4443 } 4444 for (const SourceName &name : saveInfo_.commons) { 4445 if (auto *symbol{currScope().FindCommonBlock(name)}) { 4446 auto &objects{symbol->get<CommonBlockDetails>().objects()}; 4447 if (objects.empty()) { 4448 if (currScope().kind() != Scope::Kind::Block) { 4449 Say(name, 4450 "'%s' appears as a COMMON block in a SAVE statement but not in" 4451 " a COMMON statement"_err_en_US); 4452 } else { // C1108 4453 Say(name, 4454 "SAVE statement in BLOCK construct may not contain a" 4455 " common block name '%s'"_err_en_US); 4456 } 4457 } else { 4458 for (auto &object : symbol->get<CommonBlockDetails>().objects()) { 4459 SetSaveAttr(*object); 4460 } 4461 } 4462 } 4463 } 4464 if (saveInfo_.saveAll) { 4465 // Apply SAVE attribute to applicable symbols 4466 for (auto pair : currScope()) { 4467 auto &symbol{*pair.second}; 4468 if (!CheckSaveAttr(symbol)) { 4469 SetSaveAttr(symbol); 4470 } 4471 } 4472 } 4473 saveInfo_ = {}; 4474 } 4475 4476 // If SAVE attribute can't be set on symbol, return error message. 4477 std::optional<MessageFixedText> DeclarationVisitor::CheckSaveAttr( 4478 const Symbol &symbol) { 4479 if (IsDummy(symbol)) { 4480 return "SAVE attribute may not be applied to dummy argument '%s'"_err_en_US; 4481 } else if (symbol.IsFuncResult()) { 4482 return "SAVE attribute may not be applied to function result '%s'"_err_en_US; 4483 } else if (symbol.has<ProcEntityDetails>() && 4484 !symbol.attrs().test(Attr::POINTER)) { 4485 return "Procedure '%s' with SAVE attribute must also have POINTER attribute"_err_en_US; 4486 } else if (IsAutomatic(symbol)) { 4487 return "SAVE attribute may not be applied to automatic data object '%s'"_err_en_US; 4488 } else { 4489 return std::nullopt; 4490 } 4491 } 4492 4493 // Record SAVEd names in saveInfo_.entities. 4494 Attrs DeclarationVisitor::HandleSaveName(const SourceName &name, Attrs attrs) { 4495 if (attrs.test(Attr::SAVE)) { 4496 AddSaveName(saveInfo_.entities, name); 4497 } 4498 return attrs; 4499 } 4500 4501 // Record a name in a set of those to be saved. 4502 void DeclarationVisitor::AddSaveName( 4503 std::set<SourceName> &set, const SourceName &name) { 4504 auto pair{set.insert(name)}; 4505 if (!pair.second) { 4506 Say2(name, "SAVE attribute was already specified on '%s'"_err_en_US, 4507 *pair.first, "Previous specification of SAVE attribute"_en_US); 4508 } 4509 } 4510 4511 // Set the SAVE attribute on symbol unless it is implicitly saved anyway. 4512 void DeclarationVisitor::SetSaveAttr(Symbol &symbol) { 4513 if (!IsSaved(symbol)) { 4514 symbol.attrs().set(Attr::SAVE); 4515 } 4516 } 4517 4518 // Check types of common block objects, now that they are known. 4519 void DeclarationVisitor::CheckCommonBlocks() { 4520 // check for empty common blocks 4521 for (const auto &pair : currScope().commonBlocks()) { 4522 const auto &symbol{*pair.second}; 4523 if (symbol.get<CommonBlockDetails>().objects().empty() && 4524 symbol.attrs().test(Attr::BIND_C)) { 4525 Say(symbol.name(), 4526 "'%s' appears as a COMMON block in a BIND statement but not in" 4527 " a COMMON statement"_err_en_US); 4528 } 4529 } 4530 // check objects in common blocks 4531 for (const auto &name : commonBlockObjects_) { 4532 const auto *symbol{currScope().FindSymbol(name)}; 4533 if (!symbol) { 4534 continue; 4535 } 4536 const auto &attrs{symbol->attrs()}; 4537 if (attrs.test(Attr::ALLOCATABLE)) { 4538 Say(name, 4539 "ALLOCATABLE object '%s' may not appear in a COMMON block"_err_en_US); 4540 } else if (attrs.test(Attr::BIND_C)) { 4541 Say(name, 4542 "Variable '%s' with BIND attribute may not appear in a COMMON block"_err_en_US); 4543 } else if (IsDummy(*symbol)) { 4544 Say(name, 4545 "Dummy argument '%s' may not appear in a COMMON block"_err_en_US); 4546 } else if (symbol->IsFuncResult()) { 4547 Say(name, 4548 "Function result '%s' may not appear in a COMMON block"_err_en_US); 4549 } else if (const DeclTypeSpec * type{symbol->GetType()}) { 4550 if (type->category() == DeclTypeSpec::ClassStar) { 4551 Say(name, 4552 "Unlimited polymorphic pointer '%s' may not appear in a COMMON block"_err_en_US); 4553 } else if (const auto *derived{type->AsDerived()}) { 4554 auto &typeSymbol{derived->typeSymbol()}; 4555 if (!typeSymbol.attrs().test(Attr::BIND_C) && 4556 !typeSymbol.get<DerivedTypeDetails>().sequence()) { 4557 Say(name, 4558 "Derived type '%s' in COMMON block must have the BIND or" 4559 " SEQUENCE attribute"_err_en_US); 4560 } 4561 CheckCommonBlockDerivedType(name, typeSymbol); 4562 } 4563 } 4564 } 4565 commonBlockObjects_ = {}; 4566 } 4567 4568 Symbol &DeclarationVisitor::MakeCommonBlockSymbol(const parser::Name &name) { 4569 return Resolve(name, currScope().MakeCommonBlock(name.source)); 4570 } 4571 Symbol &DeclarationVisitor::MakeCommonBlockSymbol( 4572 const std::optional<parser::Name> &name) { 4573 if (name) { 4574 return MakeCommonBlockSymbol(*name); 4575 } else { 4576 return MakeCommonBlockSymbol(parser::Name{}); 4577 } 4578 } 4579 4580 bool DeclarationVisitor::NameIsKnownOrIntrinsic(const parser::Name &name) { 4581 return FindSymbol(name) || HandleUnrestrictedSpecificIntrinsicFunction(name); 4582 } 4583 4584 // Check if this derived type can be in a COMMON block. 4585 void DeclarationVisitor::CheckCommonBlockDerivedType( 4586 const SourceName &name, const Symbol &typeSymbol) { 4587 if (const auto *scope{typeSymbol.scope()}) { 4588 for (const auto &pair : *scope) { 4589 const Symbol &component{*pair.second}; 4590 if (component.attrs().test(Attr::ALLOCATABLE)) { 4591 Say2(name, 4592 "Derived type variable '%s' may not appear in a COMMON block" 4593 " due to ALLOCATABLE component"_err_en_US, 4594 component.name(), "Component with ALLOCATABLE attribute"_en_US); 4595 return; 4596 } 4597 if (const auto *details{component.detailsIf<ObjectEntityDetails>()}) { 4598 if (details->init()) { 4599 Say2(name, 4600 "Derived type variable '%s' may not appear in a COMMON block" 4601 " due to component with default initialization"_err_en_US, 4602 component.name(), "Component with default initialization"_en_US); 4603 return; 4604 } 4605 if (const auto *type{details->type()}) { 4606 if (const auto *derived{type->AsDerived()}) { 4607 CheckCommonBlockDerivedType(name, derived->typeSymbol()); 4608 } 4609 } 4610 } 4611 } 4612 } 4613 } 4614 4615 bool DeclarationVisitor::HandleUnrestrictedSpecificIntrinsicFunction( 4616 const parser::Name &name) { 4617 if (auto interface{context().intrinsics().IsSpecificIntrinsicFunction( 4618 name.source.ToString())}) { 4619 // Unrestricted specific intrinsic function names (e.g., "cos") 4620 // are acceptable as procedure interfaces. 4621 Symbol &symbol{ 4622 MakeSymbol(InclusiveScope(), name.source, Attrs{Attr::INTRINSIC})}; 4623 if (interface->IsElemental()) { 4624 symbol.attrs().set(Attr::ELEMENTAL); 4625 } 4626 symbol.set_details(ProcEntityDetails{}); 4627 Resolve(name, symbol); 4628 return true; 4629 } else { 4630 return false; 4631 } 4632 } 4633 4634 // Checks for all locality-specs: LOCAL, LOCAL_INIT, and SHARED 4635 bool DeclarationVisitor::PassesSharedLocalityChecks( 4636 const parser::Name &name, Symbol &symbol) { 4637 if (!IsVariableName(symbol)) { 4638 SayLocalMustBeVariable(name, symbol); // C1124 4639 return false; 4640 } 4641 if (symbol.owner() == currScope()) { // C1125 and C1126 4642 SayAlreadyDeclared(name, symbol); 4643 return false; 4644 } 4645 return true; 4646 } 4647 4648 // Checks for locality-specs LOCAL and LOCAL_INIT 4649 bool DeclarationVisitor::PassesLocalityChecks( 4650 const parser::Name &name, Symbol &symbol) { 4651 if (IsAllocatable(symbol)) { // C1128 4652 SayWithDecl(name, symbol, 4653 "ALLOCATABLE variable '%s' not allowed in a locality-spec"_err_en_US); 4654 return false; 4655 } 4656 if (IsOptional(symbol)) { // C1128 4657 SayWithDecl(name, symbol, 4658 "OPTIONAL argument '%s' not allowed in a locality-spec"_err_en_US); 4659 return false; 4660 } 4661 if (IsIntentIn(symbol)) { // C1128 4662 SayWithDecl(name, symbol, 4663 "INTENT IN argument '%s' not allowed in a locality-spec"_err_en_US); 4664 return false; 4665 } 4666 if (IsFinalizable(symbol)) { // C1128 4667 SayWithDecl(name, symbol, 4668 "Finalizable variable '%s' not allowed in a locality-spec"_err_en_US); 4669 return false; 4670 } 4671 if (IsCoarray(symbol)) { // C1128 4672 SayWithDecl( 4673 name, symbol, "Coarray '%s' not allowed in a locality-spec"_err_en_US); 4674 return false; 4675 } 4676 if (const DeclTypeSpec * type{symbol.GetType()}) { 4677 if (type->IsPolymorphic() && IsDummy(symbol) && 4678 !IsPointer(symbol)) { // C1128 4679 SayWithDecl(name, symbol, 4680 "Nonpointer polymorphic argument '%s' not allowed in a " 4681 "locality-spec"_err_en_US); 4682 return false; 4683 } 4684 } 4685 if (IsAssumedSizeArray(symbol)) { // C1128 4686 SayWithDecl(name, symbol, 4687 "Assumed size array '%s' not allowed in a locality-spec"_err_en_US); 4688 return false; 4689 } 4690 if (std::optional<MessageFixedText> msg{ 4691 WhyNotModifiable(symbol, currScope())}) { 4692 SayWithReason(name, symbol, 4693 "'%s' may not appear in a locality-spec because it is not " 4694 "definable"_err_en_US, 4695 std::move(*msg)); 4696 return false; 4697 } 4698 return PassesSharedLocalityChecks(name, symbol); 4699 } 4700 4701 Symbol &DeclarationVisitor::FindOrDeclareEnclosingEntity( 4702 const parser::Name &name) { 4703 Symbol *prev{FindSymbol(name)}; 4704 if (!prev) { 4705 // Declare the name as an object in the enclosing scope so that 4706 // the name can't be repurposed there later as something else. 4707 prev = &MakeSymbol(InclusiveScope(), name.source, Attrs{}); 4708 ConvertToObjectEntity(*prev); 4709 ApplyImplicitRules(*prev); 4710 } 4711 return *prev; 4712 } 4713 4714 Symbol *DeclarationVisitor::DeclareLocalEntity(const parser::Name &name) { 4715 Symbol &prev{FindOrDeclareEnclosingEntity(name)}; 4716 if (!PassesLocalityChecks(name, prev)) { 4717 return nullptr; 4718 } 4719 return &MakeHostAssocSymbol(name, prev); 4720 } 4721 4722 Symbol *DeclarationVisitor::DeclareStatementEntity(const parser::Name &name, 4723 const std::optional<parser::IntegerTypeSpec> &type) { 4724 const DeclTypeSpec *declTypeSpec{nullptr}; 4725 if (auto *prev{FindSymbol(name)}) { 4726 if (prev->owner() == currScope()) { 4727 SayAlreadyDeclared(name, *prev); 4728 return nullptr; 4729 } 4730 name.symbol = nullptr; 4731 declTypeSpec = prev->GetType(); 4732 } 4733 Symbol &symbol{DeclareEntity<ObjectEntityDetails>(name, {})}; 4734 if (!symbol.has<ObjectEntityDetails>()) { 4735 return nullptr; // error was reported in DeclareEntity 4736 } 4737 if (type) { 4738 declTypeSpec = ProcessTypeSpec(*type); 4739 } 4740 if (declTypeSpec) { 4741 // Subtlety: Don't let a "*length" specifier (if any is pending) affect the 4742 // declaration of this implied DO loop control variable. 4743 auto restorer{ 4744 common::ScopedSet(charInfo_.length, std::optional<ParamValue>{})}; 4745 SetType(name, *declTypeSpec); 4746 } else { 4747 ApplyImplicitRules(symbol); 4748 } 4749 return Resolve(name, &symbol); 4750 } 4751 4752 // Set the type of an entity or report an error. 4753 void DeclarationVisitor::SetType( 4754 const parser::Name &name, const DeclTypeSpec &type) { 4755 CHECK(name.symbol); 4756 auto &symbol{*name.symbol}; 4757 if (charInfo_.length) { // Declaration has "*length" (R723) 4758 auto length{std::move(*charInfo_.length)}; 4759 charInfo_.length.reset(); 4760 if (type.category() == DeclTypeSpec::Character) { 4761 auto kind{type.characterTypeSpec().kind()}; 4762 // Recurse with correct type. 4763 SetType(name, 4764 currScope().MakeCharacterType(std::move(length), std::move(kind))); 4765 return; 4766 } else { // C753 4767 Say(name, 4768 "A length specifier cannot be used to declare the non-character entity '%s'"_err_en_US); 4769 } 4770 } 4771 auto *prevType{symbol.GetType()}; 4772 if (!prevType) { 4773 symbol.SetType(type); 4774 } else if (symbol.has<UseDetails>()) { 4775 // error recovery case, redeclaration of use-associated name 4776 } else if (HadForwardRef(symbol)) { 4777 // error recovery after use of host-associated name 4778 } else if (!symbol.test(Symbol::Flag::Implicit)) { 4779 SayWithDecl( 4780 name, symbol, "The type of '%s' has already been declared"_err_en_US); 4781 context().SetError(symbol); 4782 } else if (type != *prevType) { 4783 SayWithDecl(name, symbol, 4784 "The type of '%s' has already been implicitly declared"_err_en_US); 4785 context().SetError(symbol); 4786 } else { 4787 symbol.set(Symbol::Flag::Implicit, false); 4788 } 4789 } 4790 4791 std::optional<DerivedTypeSpec> DeclarationVisitor::ResolveDerivedType( 4792 const parser::Name &name) { 4793 Symbol *symbol{FindSymbol(NonDerivedTypeScope(), name)}; 4794 if (!symbol || symbol->has<UnknownDetails>()) { 4795 if (allowForwardReferenceToDerivedType()) { 4796 if (!symbol) { 4797 symbol = &MakeSymbol(InclusiveScope(), name.source, Attrs{}); 4798 Resolve(name, *symbol); 4799 }; 4800 DerivedTypeDetails details; 4801 details.set_isForwardReferenced(); 4802 symbol->set_details(std::move(details)); 4803 } else { // C732 4804 Say(name, "Derived type '%s' not found"_err_en_US); 4805 return std::nullopt; 4806 } 4807 } 4808 if (CheckUseError(name)) { 4809 return std::nullopt; 4810 } 4811 symbol = &symbol->GetUltimate(); 4812 if (auto *details{symbol->detailsIf<GenericDetails>()}) { 4813 if (details->derivedType()) { 4814 symbol = details->derivedType(); 4815 } 4816 } 4817 if (symbol->has<DerivedTypeDetails>()) { 4818 return DerivedTypeSpec{name.source, *symbol}; 4819 } else { 4820 Say(name, "'%s' is not a derived type"_err_en_US); 4821 return std::nullopt; 4822 } 4823 } 4824 4825 std::optional<DerivedTypeSpec> DeclarationVisitor::ResolveExtendsType( 4826 const parser::Name &typeName, const parser::Name *extendsName) { 4827 if (!extendsName) { 4828 return std::nullopt; 4829 } else if (typeName.source == extendsName->source) { 4830 Say(extendsName->source, 4831 "Derived type '%s' cannot extend itself"_err_en_US); 4832 return std::nullopt; 4833 } else { 4834 return ResolveDerivedType(*extendsName); 4835 } 4836 } 4837 4838 Symbol *DeclarationVisitor::NoteInterfaceName(const parser::Name &name) { 4839 // The symbol is checked later by CheckExplicitInterface() and 4840 // CheckBindings(). It can be a forward reference. 4841 if (!NameIsKnownOrIntrinsic(name)) { 4842 Symbol &symbol{MakeSymbol(InclusiveScope(), name.source, Attrs{})}; 4843 Resolve(name, symbol); 4844 } 4845 return name.symbol; 4846 } 4847 4848 void DeclarationVisitor::CheckExplicitInterface(const parser::Name &name) { 4849 if (const Symbol * symbol{name.symbol}) { 4850 if (!symbol->HasExplicitInterface()) { 4851 Say(name, 4852 "'%s' must be an abstract interface or a procedure with " 4853 "an explicit interface"_err_en_US, 4854 symbol->name()); 4855 } 4856 } 4857 } 4858 4859 // Create a symbol for a type parameter, component, or procedure binding in 4860 // the current derived type scope. Return false on error. 4861 Symbol *DeclarationVisitor::MakeTypeSymbol( 4862 const parser::Name &name, Details &&details) { 4863 return Resolve(name, MakeTypeSymbol(name.source, std::move(details))); 4864 } 4865 Symbol *DeclarationVisitor::MakeTypeSymbol( 4866 const SourceName &name, Details &&details) { 4867 Scope &derivedType{currScope()}; 4868 CHECK(derivedType.IsDerivedType()); 4869 if (auto *symbol{FindInScope(derivedType, name)}) { // C742 4870 Say2(name, 4871 "Type parameter, component, or procedure binding '%s'" 4872 " already defined in this type"_err_en_US, 4873 *symbol, "Previous definition of '%s'"_en_US); 4874 return nullptr; 4875 } else { 4876 auto attrs{GetAttrs()}; 4877 // Apply binding-private-stmt if present and this is a procedure binding 4878 if (derivedTypeInfo_.privateBindings && 4879 !attrs.HasAny({Attr::PUBLIC, Attr::PRIVATE}) && 4880 std::holds_alternative<ProcBindingDetails>(details)) { 4881 attrs.set(Attr::PRIVATE); 4882 } 4883 Symbol &result{MakeSymbol(name, attrs, std::move(details))}; 4884 if (result.has<TypeParamDetails>()) { 4885 derivedType.symbol()->get<DerivedTypeDetails>().add_paramDecl(result); 4886 } 4887 return &result; 4888 } 4889 } 4890 4891 // Return true if it is ok to declare this component in the current scope. 4892 // Otherwise, emit an error and return false. 4893 bool DeclarationVisitor::OkToAddComponent( 4894 const parser::Name &name, const Symbol *extends) { 4895 for (const Scope *scope{&currScope()}; scope;) { 4896 CHECK(scope->IsDerivedType()); 4897 if (auto *prev{FindInScope(*scope, name)}) { 4898 if (!context().HasError(*prev)) { 4899 auto msg{""_en_US}; 4900 if (extends) { 4901 msg = "Type cannot be extended as it has a component named" 4902 " '%s'"_err_en_US; 4903 } else if (prev->test(Symbol::Flag::ParentComp)) { 4904 msg = "'%s' is a parent type of this type and so cannot be" 4905 " a component"_err_en_US; 4906 } else if (scope != &currScope()) { 4907 msg = "Component '%s' is already declared in a parent of this" 4908 " derived type"_err_en_US; 4909 } else { 4910 msg = "Component '%s' is already declared in this" 4911 " derived type"_err_en_US; 4912 } 4913 Say2(name, std::move(msg), *prev, "Previous declaration of '%s'"_en_US); 4914 } 4915 return false; 4916 } 4917 if (scope == &currScope() && extends) { 4918 // The parent component has not yet been added to the scope. 4919 scope = extends->scope(); 4920 } else { 4921 scope = scope->GetDerivedTypeParent(); 4922 } 4923 } 4924 return true; 4925 } 4926 4927 ParamValue DeclarationVisitor::GetParamValue( 4928 const parser::TypeParamValue &x, common::TypeParamAttr attr) { 4929 return std::visit( 4930 common::visitors{ 4931 [=](const parser::ScalarIntExpr &x) { // C704 4932 return ParamValue{EvaluateIntExpr(x), attr}; 4933 }, 4934 [=](const parser::Star &) { return ParamValue::Assumed(attr); }, 4935 [=](const parser::TypeParamValue::Deferred &) { 4936 return ParamValue::Deferred(attr); 4937 }, 4938 }, 4939 x.u); 4940 } 4941 4942 // ConstructVisitor implementation 4943 4944 void ConstructVisitor::ResolveIndexName( 4945 const parser::ConcurrentControl &control) { 4946 const parser::Name &name{std::get<parser::Name>(control.t)}; 4947 auto *prev{FindSymbol(name)}; 4948 if (prev) { 4949 if (prev->owner().kind() == Scope::Kind::Forall || 4950 prev->owner() == currScope()) { 4951 SayAlreadyDeclared(name, *prev); 4952 return; 4953 } 4954 name.symbol = nullptr; 4955 } 4956 auto &symbol{DeclareObjectEntity(name)}; 4957 if (symbol.GetType()) { 4958 // type came from explicit type-spec 4959 } else if (!prev) { 4960 ApplyImplicitRules(symbol); 4961 } else { 4962 const Symbol &prevRoot{ResolveAssociations(*prev)}; 4963 // prev could be host- use- or construct-associated with another symbol 4964 if (!prevRoot.has<ObjectEntityDetails>() && 4965 !prevRoot.has<EntityDetails>()) { 4966 Say2(name, "Index name '%s' conflicts with existing identifier"_err_en_US, 4967 *prev, "Previous declaration of '%s'"_en_US); 4968 return; 4969 } else { 4970 if (const auto *type{prevRoot.GetType()}) { 4971 symbol.SetType(*type); 4972 } 4973 if (prevRoot.IsObjectArray()) { 4974 SayWithDecl(name, *prev, "Index variable '%s' is not scalar"_err_en_US); 4975 return; 4976 } 4977 } 4978 } 4979 EvaluateExpr(parser::Scalar{parser::Integer{common::Clone(name)}}); 4980 } 4981 4982 // We need to make sure that all of the index-names get declared before the 4983 // expressions in the loop control are evaluated so that references to the 4984 // index-names in the expressions are correctly detected. 4985 bool ConstructVisitor::Pre(const parser::ConcurrentHeader &header) { 4986 BeginDeclTypeSpec(); 4987 Walk(std::get<std::optional<parser::IntegerTypeSpec>>(header.t)); 4988 const auto &controls{ 4989 std::get<std::list<parser::ConcurrentControl>>(header.t)}; 4990 for (const auto &control : controls) { 4991 ResolveIndexName(control); 4992 } 4993 Walk(controls); 4994 Walk(std::get<std::optional<parser::ScalarLogicalExpr>>(header.t)); 4995 EndDeclTypeSpec(); 4996 return false; 4997 } 4998 4999 bool ConstructVisitor::Pre(const parser::LocalitySpec::Local &x) { 5000 for (auto &name : x.v) { 5001 if (auto *symbol{DeclareLocalEntity(name)}) { 5002 symbol->set(Symbol::Flag::LocalityLocal); 5003 } 5004 } 5005 return false; 5006 } 5007 5008 bool ConstructVisitor::Pre(const parser::LocalitySpec::LocalInit &x) { 5009 for (auto &name : x.v) { 5010 if (auto *symbol{DeclareLocalEntity(name)}) { 5011 symbol->set(Symbol::Flag::LocalityLocalInit); 5012 } 5013 } 5014 return false; 5015 } 5016 5017 bool ConstructVisitor::Pre(const parser::LocalitySpec::Shared &x) { 5018 for (const auto &name : x.v) { 5019 if (!FindSymbol(name)) { 5020 Say(name, "Variable '%s' with SHARED locality implicitly declared"_en_US); 5021 } 5022 Symbol &prev{FindOrDeclareEnclosingEntity(name)}; 5023 if (PassesSharedLocalityChecks(name, prev)) { 5024 MakeHostAssocSymbol(name, prev).set(Symbol::Flag::LocalityShared); 5025 } 5026 } 5027 return false; 5028 } 5029 5030 bool ConstructVisitor::Pre(const parser::AcSpec &x) { 5031 ProcessTypeSpec(x.type); 5032 PushScope(Scope::Kind::ImpliedDos, nullptr); 5033 Walk(x.values); 5034 PopScope(); 5035 return false; 5036 } 5037 5038 // Section 19.4, paragraph 5 says that each ac-do-variable has the scope of the 5039 // enclosing ac-implied-do 5040 bool ConstructVisitor::Pre(const parser::AcImpliedDo &x) { 5041 auto &values{std::get<std::list<parser::AcValue>>(x.t)}; 5042 auto &control{std::get<parser::AcImpliedDoControl>(x.t)}; 5043 auto &type{std::get<std::optional<parser::IntegerTypeSpec>>(control.t)}; 5044 auto &bounds{std::get<parser::AcImpliedDoControl::Bounds>(control.t)}; 5045 PushScope(Scope::Kind::ImpliedDos, nullptr); 5046 DeclareStatementEntity(bounds.name.thing.thing, type); 5047 Walk(bounds); 5048 Walk(values); 5049 PopScope(); 5050 return false; 5051 } 5052 5053 bool ConstructVisitor::Pre(const parser::DataImpliedDo &x) { 5054 auto &objects{std::get<std::list<parser::DataIDoObject>>(x.t)}; 5055 auto &type{std::get<std::optional<parser::IntegerTypeSpec>>(x.t)}; 5056 auto &bounds{std::get<parser::DataImpliedDo::Bounds>(x.t)}; 5057 DeclareStatementEntity(bounds.name.thing.thing, type); 5058 Walk(bounds); 5059 Walk(objects); 5060 return false; 5061 } 5062 5063 // Sets InDataStmt flag on a variable (or misidentified function) in a DATA 5064 // statement so that the predicate IsStaticallyInitialized() will be true 5065 // during semantic analysis before the symbol's initializer is constructed. 5066 bool ConstructVisitor::Pre(const parser::DataIDoObject &x) { 5067 std::visit( 5068 common::visitors{ 5069 [&](const parser::Scalar<Indirection<parser::Designator>> &y) { 5070 Walk(y.thing.value()); 5071 const parser::Name &first{parser::GetFirstName(y.thing.value())}; 5072 if (first.symbol) { 5073 first.symbol->set(Symbol::Flag::InDataStmt); 5074 } 5075 }, 5076 [&](const Indirection<parser::DataImpliedDo> &y) { Walk(y.value()); }, 5077 }, 5078 x.u); 5079 return false; 5080 } 5081 5082 bool ConstructVisitor::Pre(const parser::DataStmtObject &x) { 5083 std::visit(common::visitors{ 5084 [&](const Indirection<parser::Variable> &y) { 5085 Walk(y.value()); 5086 const parser::Name &first{parser::GetFirstName(y.value())}; 5087 if (first.symbol) { 5088 first.symbol->set(Symbol::Flag::InDataStmt); 5089 } 5090 }, 5091 [&](const parser::DataImpliedDo &y) { 5092 PushScope(Scope::Kind::ImpliedDos, nullptr); 5093 Walk(y); 5094 PopScope(); 5095 }, 5096 }, 5097 x.u); 5098 return false; 5099 } 5100 5101 bool ConstructVisitor::Pre(const parser::DataStmtValue &x) { 5102 const auto &data{std::get<parser::DataStmtConstant>(x.t)}; 5103 auto &mutableData{const_cast<parser::DataStmtConstant &>(data)}; 5104 if (auto *elem{parser::Unwrap<parser::ArrayElement>(mutableData)}) { 5105 if (const auto *name{std::get_if<parser::Name>(&elem->base.u)}) { 5106 if (const Symbol * symbol{FindSymbol(*name)}) { 5107 const Symbol &ultimate{symbol->GetUltimate()}; 5108 if (ultimate.has<DerivedTypeDetails>()) { 5109 mutableData.u = elem->ConvertToStructureConstructor( 5110 DerivedTypeSpec{name->source, ultimate}); 5111 } 5112 } 5113 } 5114 } 5115 return true; 5116 } 5117 5118 bool ConstructVisitor::Pre(const parser::DoConstruct &x) { 5119 if (x.IsDoConcurrent()) { 5120 PushScope(Scope::Kind::Block, nullptr); 5121 } 5122 return true; 5123 } 5124 void ConstructVisitor::Post(const parser::DoConstruct &x) { 5125 if (x.IsDoConcurrent()) { 5126 PopScope(); 5127 } 5128 } 5129 5130 bool ConstructVisitor::Pre(const parser::ForallConstruct &) { 5131 PushScope(Scope::Kind::Forall, nullptr); 5132 return true; 5133 } 5134 void ConstructVisitor::Post(const parser::ForallConstruct &) { PopScope(); } 5135 bool ConstructVisitor::Pre(const parser::ForallStmt &) { 5136 PushScope(Scope::Kind::Forall, nullptr); 5137 return true; 5138 } 5139 void ConstructVisitor::Post(const parser::ForallStmt &) { PopScope(); } 5140 5141 bool ConstructVisitor::Pre(const parser::BlockStmt &x) { 5142 CheckDef(x.v); 5143 PushScope(Scope::Kind::Block, nullptr); 5144 return false; 5145 } 5146 bool ConstructVisitor::Pre(const parser::EndBlockStmt &x) { 5147 PopScope(); 5148 CheckRef(x.v); 5149 return false; 5150 } 5151 5152 void ConstructVisitor::Post(const parser::Selector &x) { 5153 GetCurrentAssociation().selector = ResolveSelector(x); 5154 } 5155 5156 bool ConstructVisitor::Pre(const parser::AssociateStmt &x) { 5157 CheckDef(x.t); 5158 PushScope(Scope::Kind::Block, nullptr); 5159 PushAssociation(); 5160 return true; 5161 } 5162 void ConstructVisitor::Post(const parser::EndAssociateStmt &x) { 5163 PopAssociation(); 5164 PopScope(); 5165 CheckRef(x.v); 5166 } 5167 5168 void ConstructVisitor::Post(const parser::Association &x) { 5169 const auto &name{std::get<parser::Name>(x.t)}; 5170 GetCurrentAssociation().name = &name; 5171 if (auto *symbol{MakeAssocEntity()}) { 5172 if (ExtractCoarrayRef(GetCurrentAssociation().selector.expr)) { // C1103 5173 Say("Selector must not be a coindexed object"_err_en_US); 5174 } 5175 SetTypeFromAssociation(*symbol); 5176 SetAttrsFromAssociation(*symbol); 5177 } 5178 GetCurrentAssociation() = {}; // clean for further parser::Association. 5179 } 5180 5181 bool ConstructVisitor::Pre(const parser::ChangeTeamStmt &x) { 5182 CheckDef(x.t); 5183 PushScope(Scope::Kind::Block, nullptr); 5184 PushAssociation(); 5185 return true; 5186 } 5187 5188 void ConstructVisitor::Post(const parser::CoarrayAssociation &x) { 5189 const auto &decl{std::get<parser::CodimensionDecl>(x.t)}; 5190 const auto &name{std::get<parser::Name>(decl.t)}; 5191 if (auto *symbol{FindInScope(name)}) { 5192 const auto &selector{std::get<parser::Selector>(x.t)}; 5193 if (auto sel{ResolveSelector(selector)}) { 5194 const Symbol *whole{UnwrapWholeSymbolDataRef(sel.expr)}; 5195 if (!whole || whole->Corank() == 0) { 5196 Say(sel.source, // C1116 5197 "Selector in coarray association must name a coarray"_err_en_US); 5198 } else if (auto dynType{sel.expr->GetType()}) { 5199 if (!symbol->GetType()) { 5200 symbol->SetType(ToDeclTypeSpec(std::move(*dynType))); 5201 } 5202 } 5203 } 5204 } 5205 } 5206 5207 void ConstructVisitor::Post(const parser::EndChangeTeamStmt &x) { 5208 PopAssociation(); 5209 PopScope(); 5210 CheckRef(x.t); 5211 } 5212 5213 bool ConstructVisitor::Pre(const parser::SelectTypeConstruct &) { 5214 PushAssociation(); 5215 return true; 5216 } 5217 5218 void ConstructVisitor::Post(const parser::SelectTypeConstruct &) { 5219 PopAssociation(); 5220 } 5221 5222 void ConstructVisitor::Post(const parser::SelectTypeStmt &x) { 5223 auto &association{GetCurrentAssociation()}; 5224 if (const std::optional<parser::Name> &name{std::get<1>(x.t)}) { 5225 // This isn't a name in the current scope, it is in each TypeGuardStmt 5226 MakePlaceholder(*name, MiscDetails::Kind::SelectTypeAssociateName); 5227 association.name = &*name; 5228 auto exprType{association.selector.expr->GetType()}; 5229 if (ExtractCoarrayRef(association.selector.expr)) { // C1103 5230 Say("Selector must not be a coindexed object"_err_en_US); 5231 } 5232 if (exprType && !exprType->IsPolymorphic()) { // C1159 5233 Say(association.selector.source, 5234 "Selector '%s' in SELECT TYPE statement must be " 5235 "polymorphic"_err_en_US); 5236 } 5237 } else { 5238 if (const Symbol * 5239 whole{UnwrapWholeSymbolDataRef(association.selector.expr)}) { 5240 ConvertToObjectEntity(const_cast<Symbol &>(*whole)); 5241 if (!IsVariableName(*whole)) { 5242 Say(association.selector.source, // C901 5243 "Selector is not a variable"_err_en_US); 5244 association = {}; 5245 } 5246 if (const DeclTypeSpec * type{whole->GetType()}) { 5247 if (!type->IsPolymorphic()) { // C1159 5248 Say(association.selector.source, 5249 "Selector '%s' in SELECT TYPE statement must be " 5250 "polymorphic"_err_en_US); 5251 } 5252 } 5253 } else { 5254 Say(association.selector.source, // C1157 5255 "Selector is not a named variable: 'associate-name =>' is required"_err_en_US); 5256 association = {}; 5257 } 5258 } 5259 } 5260 5261 void ConstructVisitor::Post(const parser::SelectRankStmt &x) { 5262 auto &association{GetCurrentAssociation()}; 5263 if (const std::optional<parser::Name> &name{std::get<1>(x.t)}) { 5264 // This isn't a name in the current scope, it is in each SelectRankCaseStmt 5265 MakePlaceholder(*name, MiscDetails::Kind::SelectRankAssociateName); 5266 association.name = &*name; 5267 } 5268 } 5269 5270 bool ConstructVisitor::Pre(const parser::SelectTypeConstruct::TypeCase &) { 5271 PushScope(Scope::Kind::Block, nullptr); 5272 return true; 5273 } 5274 void ConstructVisitor::Post(const parser::SelectTypeConstruct::TypeCase &) { 5275 PopScope(); 5276 } 5277 5278 bool ConstructVisitor::Pre(const parser::SelectRankConstruct::RankCase &) { 5279 PushScope(Scope::Kind::Block, nullptr); 5280 return true; 5281 } 5282 void ConstructVisitor::Post(const parser::SelectRankConstruct::RankCase &) { 5283 PopScope(); 5284 } 5285 5286 void ConstructVisitor::Post(const parser::TypeGuardStmt::Guard &x) { 5287 if (auto *symbol{MakeAssocEntity()}) { 5288 if (std::holds_alternative<parser::Default>(x.u)) { 5289 SetTypeFromAssociation(*symbol); 5290 } else if (const auto *type{GetDeclTypeSpec()}) { 5291 symbol->SetType(*type); 5292 } 5293 SetAttrsFromAssociation(*symbol); 5294 } 5295 } 5296 5297 void ConstructVisitor::Post(const parser::SelectRankCaseStmt::Rank &x) { 5298 if (auto *symbol{MakeAssocEntity()}) { 5299 SetTypeFromAssociation(*symbol); 5300 SetAttrsFromAssociation(*symbol); 5301 if (const auto *init{std::get_if<parser::ScalarIntConstantExpr>(&x.u)}) { 5302 if (auto val{EvaluateInt64(context(), *init)}) { 5303 auto &details{symbol->get<AssocEntityDetails>()}; 5304 details.set_rank(*val); 5305 } 5306 } 5307 } 5308 } 5309 5310 bool ConstructVisitor::Pre(const parser::SelectRankConstruct &) { 5311 PushAssociation(); 5312 return true; 5313 } 5314 5315 void ConstructVisitor::Post(const parser::SelectRankConstruct &) { 5316 PopAssociation(); 5317 } 5318 5319 bool ConstructVisitor::CheckDef(const std::optional<parser::Name> &x) { 5320 if (x) { 5321 MakeSymbol(*x, MiscDetails{MiscDetails::Kind::ConstructName}); 5322 } 5323 return true; 5324 } 5325 5326 void ConstructVisitor::CheckRef(const std::optional<parser::Name> &x) { 5327 if (x) { 5328 // Just add an occurrence of this name; checking is done in ValidateLabels 5329 FindSymbol(*x); 5330 } 5331 } 5332 5333 // Make a symbol representing an associating entity from current association. 5334 Symbol *ConstructVisitor::MakeAssocEntity() { 5335 Symbol *symbol{nullptr}; 5336 auto &association{GetCurrentAssociation()}; 5337 if (association.name) { 5338 symbol = &MakeSymbol(*association.name, UnknownDetails{}); 5339 if (symbol->has<AssocEntityDetails>() && symbol->owner() == currScope()) { 5340 Say(*association.name, // C1104 5341 "The associate name '%s' is already used in this associate statement"_err_en_US); 5342 return nullptr; 5343 } 5344 } else if (const Symbol * 5345 whole{UnwrapWholeSymbolDataRef(association.selector.expr)}) { 5346 symbol = &MakeSymbol(whole->name()); 5347 } else { 5348 return nullptr; 5349 } 5350 if (auto &expr{association.selector.expr}) { 5351 symbol->set_details(AssocEntityDetails{common::Clone(*expr)}); 5352 } else { 5353 symbol->set_details(AssocEntityDetails{}); 5354 } 5355 return symbol; 5356 } 5357 5358 // Set the type of symbol based on the current association selector. 5359 void ConstructVisitor::SetTypeFromAssociation(Symbol &symbol) { 5360 auto &details{symbol.get<AssocEntityDetails>()}; 5361 const MaybeExpr *pexpr{&details.expr()}; 5362 if (!*pexpr) { 5363 pexpr = &GetCurrentAssociation().selector.expr; 5364 } 5365 if (*pexpr) { 5366 const SomeExpr &expr{**pexpr}; 5367 if (std::optional<evaluate::DynamicType> type{expr.GetType()}) { 5368 if (const auto *charExpr{ 5369 evaluate::UnwrapExpr<evaluate::Expr<evaluate::SomeCharacter>>( 5370 expr)}) { 5371 symbol.SetType(ToDeclTypeSpec(std::move(*type), 5372 FoldExpr( 5373 std::visit([](const auto &kindChar) { return kindChar.LEN(); }, 5374 charExpr->u)))); 5375 } else { 5376 symbol.SetType(ToDeclTypeSpec(std::move(*type))); 5377 } 5378 } else { 5379 // BOZ literals, procedure designators, &c. are not acceptable 5380 Say(symbol.name(), "Associate name '%s' must have a type"_err_en_US); 5381 } 5382 } 5383 } 5384 5385 // If current selector is a variable, set some of its attributes on symbol. 5386 void ConstructVisitor::SetAttrsFromAssociation(Symbol &symbol) { 5387 Attrs attrs{evaluate::GetAttrs(GetCurrentAssociation().selector.expr)}; 5388 symbol.attrs() |= attrs & 5389 Attrs{Attr::TARGET, Attr::ASYNCHRONOUS, Attr::VOLATILE, Attr::CONTIGUOUS}; 5390 if (attrs.test(Attr::POINTER)) { 5391 symbol.attrs().set(Attr::TARGET); 5392 } 5393 } 5394 5395 ConstructVisitor::Selector ConstructVisitor::ResolveSelector( 5396 const parser::Selector &x) { 5397 return std::visit(common::visitors{ 5398 [&](const parser::Expr &expr) { 5399 return Selector{expr.source, EvaluateExpr(expr)}; 5400 }, 5401 [&](const parser::Variable &var) { 5402 return Selector{var.GetSource(), EvaluateExpr(var)}; 5403 }, 5404 }, 5405 x.u); 5406 } 5407 5408 ConstructVisitor::Association &ConstructVisitor::GetCurrentAssociation() { 5409 CHECK(!associationStack_.empty()); 5410 return associationStack_.back(); 5411 } 5412 5413 void ConstructVisitor::PushAssociation() { 5414 associationStack_.emplace_back(Association{}); 5415 } 5416 5417 void ConstructVisitor::PopAssociation() { 5418 CHECK(!associationStack_.empty()); 5419 associationStack_.pop_back(); 5420 } 5421 5422 const DeclTypeSpec &ConstructVisitor::ToDeclTypeSpec( 5423 evaluate::DynamicType &&type) { 5424 switch (type.category()) { 5425 SWITCH_COVERS_ALL_CASES 5426 case common::TypeCategory::Integer: 5427 case common::TypeCategory::Real: 5428 case common::TypeCategory::Complex: 5429 return context().MakeNumericType(type.category(), type.kind()); 5430 case common::TypeCategory::Logical: 5431 return context().MakeLogicalType(type.kind()); 5432 case common::TypeCategory::Derived: 5433 if (type.IsAssumedType()) { 5434 return currScope().MakeTypeStarType(); 5435 } else if (type.IsUnlimitedPolymorphic()) { 5436 return currScope().MakeClassStarType(); 5437 } else { 5438 return currScope().MakeDerivedType( 5439 type.IsPolymorphic() ? DeclTypeSpec::ClassDerived 5440 : DeclTypeSpec::TypeDerived, 5441 common::Clone(type.GetDerivedTypeSpec()) 5442 5443 ); 5444 } 5445 case common::TypeCategory::Character: 5446 CRASH_NO_CASE; 5447 } 5448 } 5449 5450 const DeclTypeSpec &ConstructVisitor::ToDeclTypeSpec( 5451 evaluate::DynamicType &&type, MaybeSubscriptIntExpr &&length) { 5452 CHECK(type.category() == common::TypeCategory::Character); 5453 if (length) { 5454 return currScope().MakeCharacterType( 5455 ParamValue{SomeIntExpr{*std::move(length)}, common::TypeParamAttr::Len}, 5456 KindExpr{type.kind()}); 5457 } else { 5458 return currScope().MakeCharacterType( 5459 ParamValue::Deferred(common::TypeParamAttr::Len), 5460 KindExpr{type.kind()}); 5461 } 5462 } 5463 5464 // ResolveNamesVisitor implementation 5465 5466 bool ResolveNamesVisitor::Pre(const parser::FunctionReference &x) { 5467 HandleCall(Symbol::Flag::Function, x.v); 5468 return false; 5469 } 5470 bool ResolveNamesVisitor::Pre(const parser::CallStmt &x) { 5471 HandleCall(Symbol::Flag::Subroutine, x.v); 5472 return false; 5473 } 5474 5475 bool ResolveNamesVisitor::Pre(const parser::ImportStmt &x) { 5476 auto &scope{currScope()}; 5477 // Check C896 and C899: where IMPORT statements are allowed 5478 switch (scope.kind()) { 5479 case Scope::Kind::Module: 5480 if (scope.IsModule()) { 5481 Say("IMPORT is not allowed in a module scoping unit"_err_en_US); 5482 return false; 5483 } else if (x.kind == common::ImportKind::None) { 5484 Say("IMPORT,NONE is not allowed in a submodule scoping unit"_err_en_US); 5485 return false; 5486 } 5487 break; 5488 case Scope::Kind::MainProgram: 5489 Say("IMPORT is not allowed in a main program scoping unit"_err_en_US); 5490 return false; 5491 case Scope::Kind::Subprogram: 5492 if (scope.parent().IsGlobal()) { 5493 Say("IMPORT is not allowed in an external subprogram scoping unit"_err_en_US); 5494 return false; 5495 } 5496 break; 5497 case Scope::Kind::BlockData: // C1415 (in part) 5498 Say("IMPORT is not allowed in a BLOCK DATA subprogram"_err_en_US); 5499 return false; 5500 default:; 5501 } 5502 if (auto error{scope.SetImportKind(x.kind)}) { 5503 Say(std::move(*error)); 5504 } 5505 for (auto &name : x.names) { 5506 if (FindSymbol(scope.parent(), name)) { 5507 scope.add_importName(name.source); 5508 } else { 5509 Say(name, "'%s' not found in host scope"_err_en_US); 5510 } 5511 } 5512 prevImportStmt_ = currStmtSource(); 5513 return false; 5514 } 5515 5516 const parser::Name *DeclarationVisitor::ResolveStructureComponent( 5517 const parser::StructureComponent &x) { 5518 return FindComponent(ResolveDataRef(x.base), x.component); 5519 } 5520 5521 const parser::Name *DeclarationVisitor::ResolveDesignator( 5522 const parser::Designator &x) { 5523 return std::visit( 5524 common::visitors{ 5525 [&](const parser::DataRef &x) { return ResolveDataRef(x); }, 5526 [&](const parser::Substring &x) { 5527 return ResolveDataRef(std::get<parser::DataRef>(x.t)); 5528 }, 5529 }, 5530 x.u); 5531 } 5532 5533 const parser::Name *DeclarationVisitor::ResolveDataRef( 5534 const parser::DataRef &x) { 5535 return std::visit( 5536 common::visitors{ 5537 [=](const parser::Name &y) { return ResolveName(y); }, 5538 [=](const Indirection<parser::StructureComponent> &y) { 5539 return ResolveStructureComponent(y.value()); 5540 }, 5541 [&](const Indirection<parser::ArrayElement> &y) { 5542 Walk(y.value().subscripts); 5543 const parser::Name *name{ResolveDataRef(y.value().base)}; 5544 if (!name) { 5545 } else if (!name->symbol->has<ProcEntityDetails>()) { 5546 ConvertToObjectEntity(*name->symbol); 5547 } else if (!context().HasError(*name->symbol)) { 5548 SayWithDecl(*name, *name->symbol, 5549 "Cannot reference function '%s' as data"_err_en_US); 5550 } 5551 return name; 5552 }, 5553 [&](const Indirection<parser::CoindexedNamedObject> &y) { 5554 Walk(y.value().imageSelector); 5555 return ResolveDataRef(y.value().base); 5556 }, 5557 }, 5558 x.u); 5559 } 5560 5561 // If implicit types are allowed, ensure name is in the symbol table. 5562 // Otherwise, report an error if it hasn't been declared. 5563 const parser::Name *DeclarationVisitor::ResolveName(const parser::Name &name) { 5564 FindSymbol(name); 5565 if (CheckForHostAssociatedImplicit(name)) { 5566 NotePossibleBadForwardRef(name); 5567 return &name; 5568 } 5569 if (Symbol * symbol{name.symbol}) { 5570 if (CheckUseError(name)) { 5571 return nullptr; // reported an error 5572 } 5573 NotePossibleBadForwardRef(name); 5574 symbol->set(Symbol::Flag::ImplicitOrError, false); 5575 if (IsUplevelReference(*symbol)) { 5576 MakeHostAssocSymbol(name, *symbol); 5577 } else if (IsDummy(*symbol) || 5578 (!symbol->GetType() && FindCommonBlockContaining(*symbol))) { 5579 ConvertToObjectEntity(*symbol); 5580 ApplyImplicitRules(*symbol); 5581 } 5582 return &name; 5583 } 5584 if (isImplicitNoneType()) { 5585 Say(name, "No explicit type declared for '%s'"_err_en_US); 5586 return nullptr; 5587 } 5588 // Create the symbol then ensure it is accessible 5589 MakeSymbol(InclusiveScope(), name.source, Attrs{}); 5590 auto *symbol{FindSymbol(name)}; 5591 if (!symbol) { 5592 Say(name, 5593 "'%s' from host scoping unit is not accessible due to IMPORT"_err_en_US); 5594 return nullptr; 5595 } 5596 ConvertToObjectEntity(*symbol); 5597 ApplyImplicitRules(*symbol); 5598 NotePossibleBadForwardRef(name); 5599 return &name; 5600 } 5601 5602 // A specification expression may refer to a symbol in the host procedure that 5603 // is implicitly typed. Because specification parts are processed before 5604 // execution parts, this may be the first time we see the symbol. It can't be a 5605 // local in the current scope (because it's in a specification expression) so 5606 // either it is implicitly declared in the host procedure or it is an error. 5607 // We create a symbol in the host assuming it is the former; if that proves to 5608 // be wrong we report an error later in CheckDeclarations(). 5609 bool DeclarationVisitor::CheckForHostAssociatedImplicit( 5610 const parser::Name &name) { 5611 if (inExecutionPart_) { 5612 return false; 5613 } 5614 if (name.symbol) { 5615 ApplyImplicitRules(*name.symbol); 5616 } 5617 Symbol *hostSymbol; 5618 Scope *host{GetHostProcedure()}; 5619 if (!host || isImplicitNoneType(*host)) { 5620 return false; 5621 } 5622 if (!name.symbol) { 5623 hostSymbol = &MakeSymbol(*host, name.source, Attrs{}); 5624 ConvertToObjectEntity(*hostSymbol); 5625 ApplyImplicitRules(*hostSymbol); 5626 hostSymbol->set(Symbol::Flag::ImplicitOrError); 5627 } else if (name.symbol->test(Symbol::Flag::ImplicitOrError)) { 5628 hostSymbol = name.symbol; 5629 } else { 5630 return false; 5631 } 5632 Symbol &symbol{MakeHostAssocSymbol(name, *hostSymbol)}; 5633 if (isImplicitNoneType()) { 5634 symbol.get<HostAssocDetails>().implicitOrExplicitTypeError = true; 5635 } else { 5636 symbol.get<HostAssocDetails>().implicitOrSpecExprError = true; 5637 } 5638 return true; 5639 } 5640 5641 bool DeclarationVisitor::IsUplevelReference(const Symbol &symbol) { 5642 const Scope &symbolUnit{GetProgramUnitContaining(symbol)}; 5643 if (symbolUnit == GetProgramUnitContaining(currScope())) { 5644 return false; 5645 } else { 5646 Scope::Kind kind{symbolUnit.kind()}; 5647 return kind == Scope::Kind::Subprogram || kind == Scope::Kind::MainProgram; 5648 } 5649 } 5650 5651 // base is a part-ref of a derived type; find the named component in its type. 5652 // Also handles intrinsic type parameter inquiries (%kind, %len) and 5653 // COMPLEX component references (%re, %im). 5654 const parser::Name *DeclarationVisitor::FindComponent( 5655 const parser::Name *base, const parser::Name &component) { 5656 if (!base || !base->symbol) { 5657 return nullptr; 5658 } 5659 auto &symbol{base->symbol->GetUltimate()}; 5660 if (!symbol.has<AssocEntityDetails>() && !ConvertToObjectEntity(symbol)) { 5661 SayWithDecl(*base, symbol, 5662 "'%s' is an invalid base for a component reference"_err_en_US); 5663 return nullptr; 5664 } 5665 auto *type{symbol.GetType()}; 5666 if (!type) { 5667 return nullptr; // should have already reported error 5668 } 5669 if (const IntrinsicTypeSpec * intrinsic{type->AsIntrinsic()}) { 5670 auto name{component.ToString()}; 5671 auto category{intrinsic->category()}; 5672 MiscDetails::Kind miscKind{MiscDetails::Kind::None}; 5673 if (name == "kind") { 5674 miscKind = MiscDetails::Kind::KindParamInquiry; 5675 } else if (category == TypeCategory::Character) { 5676 if (name == "len") { 5677 miscKind = MiscDetails::Kind::LenParamInquiry; 5678 } 5679 } else if (category == TypeCategory::Complex) { 5680 if (name == "re") { 5681 miscKind = MiscDetails::Kind::ComplexPartRe; 5682 } else if (name == "im") { 5683 miscKind = MiscDetails::Kind::ComplexPartIm; 5684 } 5685 } 5686 if (miscKind != MiscDetails::Kind::None) { 5687 MakePlaceholder(component, miscKind); 5688 return nullptr; 5689 } 5690 } else if (const DerivedTypeSpec * derived{type->AsDerived()}) { 5691 if (const Scope * scope{derived->scope()}) { 5692 if (Resolve(component, scope->FindComponent(component.source))) { 5693 if (auto msg{ 5694 CheckAccessibleComponent(currScope(), *component.symbol)}) { 5695 context().Say(component.source, *msg); 5696 } 5697 return &component; 5698 } else { 5699 SayDerivedType(component.source, 5700 "Component '%s' not found in derived type '%s'"_err_en_US, *scope); 5701 } 5702 } 5703 return nullptr; 5704 } 5705 if (symbol.test(Symbol::Flag::Implicit)) { 5706 Say(*base, 5707 "'%s' is not an object of derived type; it is implicitly typed"_err_en_US); 5708 } else { 5709 SayWithDecl( 5710 *base, symbol, "'%s' is not an object of derived type"_err_en_US); 5711 } 5712 return nullptr; 5713 } 5714 5715 void DeclarationVisitor::Initialization(const parser::Name &name, 5716 const parser::Initialization &init, bool inComponentDecl) { 5717 // Traversal of the initializer was deferred to here so that the 5718 // symbol being declared can be available for use in the expression, e.g.: 5719 // real, parameter :: x = tiny(x) 5720 if (!name.symbol) { 5721 return; 5722 } 5723 Symbol &ultimate{name.symbol->GetUltimate()}; 5724 if (IsAllocatable(ultimate)) { 5725 Say(name, "Allocatable object '%s' cannot be initialized"_err_en_US); 5726 return; 5727 } 5728 if (auto *object{ultimate.detailsIf<ObjectEntityDetails>()}) { 5729 // TODO: check C762 - all bounds and type parameters of component 5730 // are colons or constant expressions if component is initialized 5731 std::visit( 5732 common::visitors{ 5733 [&](const parser::ConstantExpr &expr) { 5734 NonPointerInitialization(name, expr); 5735 }, 5736 [&](const parser::NullInit &null) { 5737 Walk(null); 5738 if (auto nullInit{EvaluateExpr(null)}) { 5739 if (!evaluate::IsNullPointer(*nullInit)) { 5740 Say(name, 5741 "Pointer initializer must be intrinsic NULL()"_err_en_US); // C813 5742 } else if (IsPointer(ultimate)) { 5743 object->set_init(std::move(*nullInit)); 5744 } else { 5745 Say(name, 5746 "Non-pointer component '%s' initialized with null pointer"_err_en_US); 5747 } 5748 } 5749 }, 5750 [&](const parser::InitialDataTarget &) { 5751 // Defer analysis to the end of the specification part 5752 // so that forward references and attribute checks like SAVE 5753 // work better. 5754 }, 5755 [&](const std::list<Indirection<parser::DataStmtValue>> &) { 5756 // TODO: Need to Walk(init.u); when implementing this case 5757 if (inComponentDecl) { 5758 Say(name, 5759 "Component '%s' initialized with DATA statement values"_err_en_US); 5760 } else { 5761 // TODO - DATA statements and DATA-like initialization extension 5762 } 5763 }, 5764 }, 5765 init.u); 5766 } 5767 } 5768 5769 void DeclarationVisitor::PointerInitialization( 5770 const parser::Name &name, const parser::InitialDataTarget &target) { 5771 if (name.symbol) { 5772 Symbol &ultimate{name.symbol->GetUltimate()}; 5773 if (!context().HasError(ultimate)) { 5774 if (IsPointer(ultimate)) { 5775 if (auto *details{ultimate.detailsIf<ObjectEntityDetails>()}) { 5776 CHECK(!details->init()); 5777 Walk(target); 5778 if (MaybeExpr expr{EvaluateExpr(target)}) { 5779 // Validation is done in declaration checking. 5780 details->set_init(std::move(*expr)); 5781 } 5782 } 5783 } else { 5784 Say(name, 5785 "'%s' is not a pointer but is initialized like one"_err_en_US); 5786 context().SetError(ultimate); 5787 } 5788 } 5789 } 5790 } 5791 void DeclarationVisitor::PointerInitialization( 5792 const parser::Name &name, const parser::ProcPointerInit &target) { 5793 if (name.symbol) { 5794 Symbol &ultimate{name.symbol->GetUltimate()}; 5795 if (!context().HasError(ultimate)) { 5796 if (IsProcedurePointer(ultimate)) { 5797 auto &details{ultimate.get<ProcEntityDetails>()}; 5798 CHECK(!details.init()); 5799 Walk(target); 5800 if (const auto *targetName{std::get_if<parser::Name>(&target.u)}) { 5801 if (targetName->symbol) { 5802 // Validation is done in declaration checking. 5803 details.set_init(*targetName->symbol); 5804 } 5805 } else { 5806 details.set_init(nullptr); // explicit NULL() 5807 } 5808 } else { 5809 Say(name, 5810 "'%s' is not a procedure pointer but is initialized " 5811 "like one"_err_en_US); 5812 context().SetError(ultimate); 5813 } 5814 } 5815 } 5816 } 5817 5818 void DeclarationVisitor::NonPointerInitialization( 5819 const parser::Name &name, const parser::ConstantExpr &expr) { 5820 if (name.symbol) { 5821 Symbol &ultimate{name.symbol->GetUltimate()}; 5822 if (!context().HasError(ultimate)) { 5823 if (IsPointer(ultimate)) { 5824 Say(name, 5825 "'%s' is a pointer but is not initialized like one"_err_en_US); 5826 } else if (auto *details{ultimate.detailsIf<ObjectEntityDetails>()}) { 5827 CHECK(!details->init()); 5828 Walk(expr); 5829 if (ultimate.owner().IsParameterizedDerivedType()) { 5830 // Can't convert to type of component, which might not yet 5831 // be known; that's done later during PDT instantiation. 5832 if (MaybeExpr value{EvaluateExpr(expr)}) { 5833 details->set_init(std::move(*value)); 5834 } 5835 } else if (MaybeExpr folded{EvaluateNonPointerInitializer( 5836 ultimate, expr, expr.thing.value().source)}) { 5837 details->set_init(std::move(*folded)); 5838 } 5839 } 5840 } 5841 } 5842 } 5843 5844 void ResolveNamesVisitor::HandleCall( 5845 Symbol::Flag procFlag, const parser::Call &call) { 5846 std::visit( 5847 common::visitors{ 5848 [&](const parser::Name &x) { HandleProcedureName(procFlag, x); }, 5849 [&](const parser::ProcComponentRef &x) { Walk(x); }, 5850 }, 5851 std::get<parser::ProcedureDesignator>(call.t).u); 5852 Walk(std::get<std::list<parser::ActualArgSpec>>(call.t)); 5853 } 5854 5855 void ResolveNamesVisitor::HandleProcedureName( 5856 Symbol::Flag flag, const parser::Name &name) { 5857 CHECK(flag == Symbol::Flag::Function || flag == Symbol::Flag::Subroutine); 5858 auto *symbol{FindSymbol(NonDerivedTypeScope(), name)}; 5859 if (!symbol) { 5860 if (IsIntrinsic(name.source, flag)) { 5861 symbol = 5862 &MakeSymbol(InclusiveScope(), name.source, Attrs{Attr::INTRINSIC}); 5863 } else { 5864 symbol = &MakeSymbol(context().globalScope(), name.source, Attrs{}); 5865 } 5866 Resolve(name, *symbol); 5867 if (symbol->has<ModuleDetails>()) { 5868 SayWithDecl(name, *symbol, 5869 "Use of '%s' as a procedure conflicts with its declaration"_err_en_US); 5870 return; 5871 } 5872 if (!symbol->attrs().test(Attr::INTRINSIC)) { 5873 if (!CheckImplicitNoneExternal(name.source, *symbol)) { 5874 return; 5875 } 5876 MakeExternal(*symbol); 5877 } 5878 ConvertToProcEntity(*symbol); 5879 SetProcFlag(name, *symbol, flag); 5880 } else if (CheckUseError(name)) { 5881 // error was reported 5882 } else { 5883 symbol = &Resolve(name, symbol)->GetUltimate(); 5884 bool convertedToProcEntity{ConvertToProcEntity(*symbol)}; 5885 if (convertedToProcEntity && !symbol->attrs().test(Attr::EXTERNAL) && 5886 IsIntrinsic(symbol->name(), flag) && !IsDummy(*symbol)) { 5887 symbol->attrs().set(Attr::INTRINSIC); 5888 // 8.2(3): ignore type from intrinsic in type-declaration-stmt 5889 symbol->get<ProcEntityDetails>().set_interface(ProcInterface{}); 5890 } 5891 if (!SetProcFlag(name, *symbol, flag)) { 5892 return; // reported error 5893 } 5894 CheckImplicitNoneExternal(name.source, *symbol); 5895 if (symbol->has<SubprogramDetails>() && 5896 symbol->attrs().test(Attr::ABSTRACT)) { 5897 Say(name, "Abstract interface '%s' may not be called"_err_en_US); 5898 } else if (IsProcedure(*symbol) || symbol->has<DerivedTypeDetails>() || 5899 symbol->has<ObjectEntityDetails>() || 5900 symbol->has<AssocEntityDetails>()) { 5901 // Symbols with DerivedTypeDetails, ObjectEntityDetails and 5902 // AssocEntityDetails are accepted here as procedure-designators because 5903 // this means the related FunctionReference are mis-parsed structure 5904 // constructors or array references that will be fixed later when 5905 // analyzing expressions. 5906 } else if (symbol->test(Symbol::Flag::Implicit)) { 5907 Say(name, 5908 "Use of '%s' as a procedure conflicts with its implicit definition"_err_en_US); 5909 } else { 5910 SayWithDecl(name, *symbol, 5911 "Use of '%s' as a procedure conflicts with its declaration"_err_en_US); 5912 } 5913 } 5914 } 5915 5916 bool ResolveNamesVisitor::CheckImplicitNoneExternal( 5917 const SourceName &name, const Symbol &symbol) { 5918 if (isImplicitNoneExternal() && !symbol.attrs().test(Attr::EXTERNAL) && 5919 !symbol.attrs().test(Attr::INTRINSIC) && !symbol.HasExplicitInterface()) { 5920 Say(name, 5921 "'%s' is an external procedure without the EXTERNAL" 5922 " attribute in a scope with IMPLICIT NONE(EXTERNAL)"_err_en_US); 5923 return false; 5924 } 5925 return true; 5926 } 5927 5928 // Variant of HandleProcedureName() for use while skimming the executable 5929 // part of a subprogram to catch calls to dummy procedures that are part 5930 // of the subprogram's interface, and to mark as procedures any symbols 5931 // that might otherwise have been miscategorized as objects. 5932 void ResolveNamesVisitor::NoteExecutablePartCall( 5933 Symbol::Flag flag, const parser::Call &call) { 5934 auto &designator{std::get<parser::ProcedureDesignator>(call.t)}; 5935 if (const auto *name{std::get_if<parser::Name>(&designator.u)}) { 5936 // Subtlety: The symbol pointers in the parse tree are not set, because 5937 // they might end up resolving elsewhere (e.g., construct entities in 5938 // SELECT TYPE). 5939 if (Symbol * symbol{currScope().FindSymbol(name->source)}) { 5940 Symbol::Flag other{flag == Symbol::Flag::Subroutine 5941 ? Symbol::Flag::Function 5942 : Symbol::Flag::Subroutine}; 5943 if (!symbol->test(other)) { 5944 ConvertToProcEntity(*symbol); 5945 if (symbol->has<ProcEntityDetails>()) { 5946 symbol->set(flag); 5947 if (IsDummy(*symbol)) { 5948 symbol->attrs().set(Attr::EXTERNAL); 5949 } 5950 ApplyImplicitRules(*symbol); 5951 } 5952 } 5953 } 5954 } 5955 } 5956 5957 // Check and set the Function or Subroutine flag on symbol; false on error. 5958 bool ResolveNamesVisitor::SetProcFlag( 5959 const parser::Name &name, Symbol &symbol, Symbol::Flag flag) { 5960 if (symbol.test(Symbol::Flag::Function) && flag == Symbol::Flag::Subroutine) { 5961 SayWithDecl( 5962 name, symbol, "Cannot call function '%s' like a subroutine"_err_en_US); 5963 return false; 5964 } else if (symbol.test(Symbol::Flag::Subroutine) && 5965 flag == Symbol::Flag::Function) { 5966 SayWithDecl( 5967 name, symbol, "Cannot call subroutine '%s' like a function"_err_en_US); 5968 return false; 5969 } else if (symbol.has<ProcEntityDetails>()) { 5970 symbol.set(flag); // in case it hasn't been set yet 5971 if (flag == Symbol::Flag::Function) { 5972 ApplyImplicitRules(symbol); 5973 } 5974 } else if (symbol.GetType() && flag == Symbol::Flag::Subroutine) { 5975 SayWithDecl( 5976 name, symbol, "Cannot call function '%s' like a subroutine"_err_en_US); 5977 } 5978 return true; 5979 } 5980 5981 bool ModuleVisitor::Pre(const parser::AccessStmt &x) { 5982 Attr accessAttr{AccessSpecToAttr(std::get<parser::AccessSpec>(x.t))}; 5983 if (!currScope().IsModule()) { // C869 5984 Say(currStmtSource().value(), 5985 "%s statement may only appear in the specification part of a module"_err_en_US, 5986 EnumToString(accessAttr)); 5987 return false; 5988 } 5989 const auto &accessIds{std::get<std::list<parser::AccessId>>(x.t)}; 5990 if (accessIds.empty()) { 5991 if (prevAccessStmt_) { // C869 5992 Say("The default accessibility of this module has already been declared"_err_en_US) 5993 .Attach(*prevAccessStmt_, "Previous declaration"_en_US); 5994 } 5995 prevAccessStmt_ = currStmtSource(); 5996 defaultAccess_ = accessAttr; 5997 } else { 5998 for (const auto &accessId : accessIds) { 5999 std::visit( 6000 common::visitors{ 6001 [=](const parser::Name &y) { 6002 Resolve(y, SetAccess(y.source, accessAttr)); 6003 }, 6004 [=](const Indirection<parser::GenericSpec> &y) { 6005 auto info{GenericSpecInfo{y.value()}}; 6006 const auto &symbolName{info.symbolName()}; 6007 if (auto *symbol{FindInScope(symbolName)}) { 6008 info.Resolve(&SetAccess(symbolName, accessAttr, symbol)); 6009 } else if (info.kind().IsName()) { 6010 info.Resolve(&SetAccess(symbolName, accessAttr)); 6011 } else { 6012 Say(symbolName, "Generic spec '%s' not found"_err_en_US); 6013 } 6014 }, 6015 }, 6016 accessId.u); 6017 } 6018 } 6019 return false; 6020 } 6021 6022 // Set the access specification for this symbol. 6023 Symbol &ModuleVisitor::SetAccess( 6024 const SourceName &name, Attr attr, Symbol *symbol) { 6025 if (!symbol) { 6026 symbol = &MakeSymbol(name); 6027 } 6028 Attrs &attrs{symbol->attrs()}; 6029 if (attrs.HasAny({Attr::PUBLIC, Attr::PRIVATE})) { 6030 // PUBLIC/PRIVATE already set: make it a fatal error if it changed 6031 Attr prev = attrs.test(Attr::PUBLIC) ? Attr::PUBLIC : Attr::PRIVATE; 6032 Say(name, 6033 WithIsFatal( 6034 "The accessibility of '%s' has already been specified as %s"_en_US, 6035 attr != prev), 6036 MakeOpName(name), EnumToString(prev)); 6037 } else { 6038 attrs.set(attr); 6039 } 6040 return *symbol; 6041 } 6042 6043 static bool NeedsExplicitType(const Symbol &symbol) { 6044 if (symbol.has<UnknownDetails>()) { 6045 return true; 6046 } else if (const auto *details{symbol.detailsIf<EntityDetails>()}) { 6047 return !details->type(); 6048 } else if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) { 6049 return !details->type(); 6050 } else if (const auto *details{symbol.detailsIf<ProcEntityDetails>()}) { 6051 return !details->interface().symbol() && !details->interface().type(); 6052 } else { 6053 return false; 6054 } 6055 } 6056 6057 bool ResolveNamesVisitor::Pre(const parser::SpecificationPart &x) { 6058 const auto &[accDecls, ompDecls, compilerDirectives, useStmts, importStmts, 6059 implicitPart, decls] = x.t; 6060 auto flagRestorer{common::ScopedSet(inSpecificationPart_, true)}; 6061 Walk(accDecls); 6062 Walk(ompDecls); 6063 Walk(compilerDirectives); 6064 Walk(useStmts); 6065 Walk(importStmts); 6066 Walk(implicitPart); 6067 auto setRestorer{ 6068 common::ScopedSet(specPartForwardRefs_, std::set<SourceName>{})}; 6069 for (const auto &decl : decls) { 6070 if (const auto *spec{ 6071 std::get_if<parser::SpecificationConstruct>(&decl.u)}) { 6072 PreSpecificationConstruct(*spec); 6073 } 6074 } 6075 Walk(decls); 6076 FinishSpecificationPart(decls); 6077 return false; 6078 } 6079 6080 // Initial processing on specification constructs, before visiting them. 6081 void ResolveNamesVisitor::PreSpecificationConstruct( 6082 const parser::SpecificationConstruct &spec) { 6083 std::visit( 6084 common::visitors{ 6085 [&](const parser::Statement<Indirection<parser::GenericStmt>> &y) { 6086 CreateGeneric(std::get<parser::GenericSpec>(y.statement.value().t)); 6087 }, 6088 [&](const Indirection<parser::InterfaceBlock> &y) { 6089 const auto &stmt{std::get<parser::Statement<parser::InterfaceStmt>>( 6090 y.value().t)}; 6091 if (const auto *spec{parser::Unwrap<parser::GenericSpec>(stmt)}) { 6092 CreateGeneric(*spec); 6093 } 6094 }, 6095 [&](const parser::Statement<parser::OtherSpecificationStmt> &y) { 6096 if (const auto *commonStmt{parser::Unwrap<parser::CommonStmt>(y)}) { 6097 CreateCommonBlockSymbols(*commonStmt); 6098 } 6099 }, 6100 [&](const auto &) {}, 6101 }, 6102 spec.u); 6103 } 6104 6105 void ResolveNamesVisitor::CreateCommonBlockSymbols( 6106 const parser::CommonStmt &commonStmt) { 6107 for (const parser::CommonStmt::Block &block : commonStmt.blocks) { 6108 const auto &[name, objects] = block.t; 6109 Symbol &commonBlock{MakeCommonBlockSymbol(name)}; 6110 for (const auto &object : objects) { 6111 Symbol &obj{DeclareObjectEntity(std::get<parser::Name>(object.t))}; 6112 if (auto *details{obj.detailsIf<ObjectEntityDetails>()}) { 6113 details->set_commonBlock(commonBlock); 6114 commonBlock.get<CommonBlockDetails>().add_object(obj); 6115 } 6116 } 6117 } 6118 } 6119 6120 void ResolveNamesVisitor::CreateGeneric(const parser::GenericSpec &x) { 6121 auto info{GenericSpecInfo{x}}; 6122 const SourceName &symbolName{info.symbolName()}; 6123 if (IsLogicalConstant(context(), symbolName)) { 6124 Say(symbolName, 6125 "Logical constant '%s' may not be used as a defined operator"_err_en_US); 6126 return; 6127 } 6128 GenericDetails genericDetails; 6129 if (Symbol * existing{FindInScope(symbolName)}) { 6130 if (existing->has<GenericDetails>()) { 6131 info.Resolve(existing); 6132 return; // already have generic, add to it 6133 } 6134 Symbol &ultimate{existing->GetUltimate()}; 6135 if (auto *ultimateDetails{ultimate.detailsIf<GenericDetails>()}) { 6136 // convert a use-associated generic into a local generic 6137 genericDetails.CopyFrom(*ultimateDetails); 6138 AddGenericUse(genericDetails, existing->name(), 6139 existing->get<UseDetails>().symbol()); 6140 } else if (ultimate.has<SubprogramDetails>() || 6141 ultimate.has<SubprogramNameDetails>()) { 6142 genericDetails.set_specific(ultimate); 6143 } else if (ultimate.has<DerivedTypeDetails>()) { 6144 genericDetails.set_derivedType(ultimate); 6145 } else { 6146 SayAlreadyDeclared(symbolName, *existing); 6147 } 6148 EraseSymbol(*existing); 6149 } 6150 info.Resolve(&MakeSymbol(symbolName, Attrs{}, std::move(genericDetails))); 6151 } 6152 6153 void ResolveNamesVisitor::FinishSpecificationPart( 6154 const std::list<parser::DeclarationConstruct> &decls) { 6155 badStmtFuncFound_ = false; 6156 CheckImports(); 6157 bool inModule{currScope().kind() == Scope::Kind::Module}; 6158 for (auto &pair : currScope()) { 6159 auto &symbol{*pair.second}; 6160 if (NeedsExplicitType(symbol)) { 6161 ApplyImplicitRules(symbol); 6162 } 6163 if (symbol.has<GenericDetails>()) { 6164 CheckGenericProcedures(symbol); 6165 } 6166 if (inModule && symbol.attrs().test(Attr::EXTERNAL) && 6167 !symbol.test(Symbol::Flag::Function) && 6168 !symbol.test(Symbol::Flag::Subroutine)) { 6169 // in a module, external proc without return type is subroutine 6170 symbol.set( 6171 symbol.GetType() ? Symbol::Flag::Function : Symbol::Flag::Subroutine); 6172 } 6173 if (!symbol.has<HostAssocDetails>()) { 6174 CheckPossibleBadForwardRef(symbol); 6175 } 6176 } 6177 currScope().InstantiateDerivedTypes(context()); 6178 for (const auto &decl : decls) { 6179 if (const auto *statement{std::get_if< 6180 parser::Statement<common::Indirection<parser::StmtFunctionStmt>>>( 6181 &decl.u)}) { 6182 AnalyzeStmtFunctionStmt(statement->statement.value()); 6183 } 6184 } 6185 // TODO: what about instantiations in BLOCK? 6186 CheckSaveStmts(); 6187 CheckCommonBlocks(); 6188 if (!inInterfaceBlock()) { 6189 // TODO: warn for the case where the EQUIVALENCE statement is in a 6190 // procedure declaration in an interface block 6191 CheckEquivalenceSets(); 6192 } 6193 } 6194 6195 // Analyze the bodies of statement functions now that the symbols in this 6196 // specification part have been fully declared and implicitly typed. 6197 void ResolveNamesVisitor::AnalyzeStmtFunctionStmt( 6198 const parser::StmtFunctionStmt &stmtFunc) { 6199 Symbol *symbol{std::get<parser::Name>(stmtFunc.t).symbol}; 6200 if (!symbol || !symbol->has<SubprogramDetails>()) { 6201 return; 6202 } 6203 auto &details{symbol->get<SubprogramDetails>()}; 6204 auto expr{AnalyzeExpr( 6205 context(), std::get<parser::Scalar<parser::Expr>>(stmtFunc.t))}; 6206 if (!expr) { 6207 context().SetError(*symbol); 6208 return; 6209 } 6210 if (auto type{evaluate::DynamicType::From(*symbol)}) { 6211 auto converted{ConvertToType(*type, std::move(*expr))}; 6212 if (!converted) { 6213 context().SetError(*symbol); 6214 return; 6215 } 6216 details.set_stmtFunction(std::move(*converted)); 6217 } else { 6218 details.set_stmtFunction(std::move(*expr)); 6219 } 6220 } 6221 6222 void ResolveNamesVisitor::CheckImports() { 6223 auto &scope{currScope()}; 6224 switch (scope.GetImportKind()) { 6225 case common::ImportKind::None: 6226 break; 6227 case common::ImportKind::All: 6228 // C8102: all entities in host must not be hidden 6229 for (const auto &pair : scope.parent()) { 6230 auto &name{pair.first}; 6231 std::optional<SourceName> scopeName{scope.GetName()}; 6232 if (!scopeName || name != *scopeName) { 6233 CheckImport(prevImportStmt_.value(), name); 6234 } 6235 } 6236 break; 6237 case common::ImportKind::Default: 6238 case common::ImportKind::Only: 6239 // C8102: entities named in IMPORT must not be hidden 6240 for (auto &name : scope.importNames()) { 6241 CheckImport(name, name); 6242 } 6243 break; 6244 } 6245 } 6246 6247 void ResolveNamesVisitor::CheckImport( 6248 const SourceName &location, const SourceName &name) { 6249 if (auto *symbol{FindInScope(name)}) { 6250 Say(location, "'%s' from host is not accessible"_err_en_US, name) 6251 .Attach(symbol->name(), "'%s' is hidden by this entity"_en_US, 6252 symbol->name()); 6253 } 6254 } 6255 6256 bool ResolveNamesVisitor::Pre(const parser::ImplicitStmt &x) { 6257 return CheckNotInBlock("IMPLICIT") && // C1107 6258 ImplicitRulesVisitor::Pre(x); 6259 } 6260 6261 void ResolveNamesVisitor::Post(const parser::PointerObject &x) { 6262 std::visit(common::visitors{ 6263 [&](const parser::Name &x) { ResolveName(x); }, 6264 [&](const parser::StructureComponent &x) { 6265 ResolveStructureComponent(x); 6266 }, 6267 }, 6268 x.u); 6269 } 6270 void ResolveNamesVisitor::Post(const parser::AllocateObject &x) { 6271 std::visit(common::visitors{ 6272 [&](const parser::Name &x) { ResolveName(x); }, 6273 [&](const parser::StructureComponent &x) { 6274 ResolveStructureComponent(x); 6275 }, 6276 }, 6277 x.u); 6278 } 6279 6280 bool ResolveNamesVisitor::Pre(const parser::PointerAssignmentStmt &x) { 6281 const auto &dataRef{std::get<parser::DataRef>(x.t)}; 6282 const auto &bounds{std::get<parser::PointerAssignmentStmt::Bounds>(x.t)}; 6283 const auto &expr{std::get<parser::Expr>(x.t)}; 6284 ResolveDataRef(dataRef); 6285 Walk(bounds); 6286 // Resolve unrestricted specific intrinsic procedures as in "p => cos". 6287 if (const parser::Name * name{parser::Unwrap<parser::Name>(expr)}) { 6288 if (NameIsKnownOrIntrinsic(*name)) { 6289 return false; 6290 } 6291 } 6292 Walk(expr); 6293 return false; 6294 } 6295 void ResolveNamesVisitor::Post(const parser::Designator &x) { 6296 ResolveDesignator(x); 6297 } 6298 6299 void ResolveNamesVisitor::Post(const parser::ProcComponentRef &x) { 6300 ResolveStructureComponent(x.v.thing); 6301 } 6302 void ResolveNamesVisitor::Post(const parser::TypeGuardStmt &x) { 6303 DeclTypeSpecVisitor::Post(x); 6304 ConstructVisitor::Post(x); 6305 } 6306 bool ResolveNamesVisitor::Pre(const parser::StmtFunctionStmt &x) { 6307 CheckNotInBlock("STATEMENT FUNCTION"); // C1107 6308 if (HandleStmtFunction(x)) { 6309 return false; 6310 } else { 6311 // This is an array element assignment: resolve names of indices 6312 const auto &names{std::get<std::list<parser::Name>>(x.t)}; 6313 for (auto &name : names) { 6314 ResolveName(name); 6315 } 6316 return true; 6317 } 6318 } 6319 6320 bool ResolveNamesVisitor::Pre(const parser::DefinedOpName &x) { 6321 const parser::Name &name{x.v}; 6322 if (FindSymbol(name)) { 6323 // OK 6324 } else if (IsLogicalConstant(context(), name.source)) { 6325 Say(name, 6326 "Logical constant '%s' may not be used as a defined operator"_err_en_US); 6327 } else { 6328 // Resolved later in expression semantics 6329 MakePlaceholder(name, MiscDetails::Kind::TypeBoundDefinedOp); 6330 } 6331 return false; 6332 } 6333 6334 void ResolveNamesVisitor::Post(const parser::AssignStmt &x) { 6335 if (auto *name{ResolveName(std::get<parser::Name>(x.t))}) { 6336 ConvertToObjectEntity(DEREF(name->symbol)); 6337 } 6338 } 6339 void ResolveNamesVisitor::Post(const parser::AssignedGotoStmt &x) { 6340 if (auto *name{ResolveName(std::get<parser::Name>(x.t))}) { 6341 ConvertToObjectEntity(DEREF(name->symbol)); 6342 } 6343 } 6344 6345 bool ResolveNamesVisitor::Pre(const parser::ProgramUnit &x) { 6346 if (std::holds_alternative<common::Indirection<parser::CompilerDirective>>( 6347 x.u)) { 6348 // TODO: global directives 6349 return true; 6350 } 6351 auto root{ProgramTree::Build(x)}; 6352 SetScope(context().globalScope()); 6353 ResolveSpecificationParts(root); 6354 FinishSpecificationParts(root); 6355 inExecutionPart_ = true; 6356 ResolveExecutionParts(root); 6357 inExecutionPart_ = false; 6358 ResolveAccParts(context(), x); 6359 ResolveOmpParts(context(), x); 6360 return false; 6361 } 6362 6363 // References to procedures need to record that their symbols are known 6364 // to be procedures, so that they don't get converted to objects by default. 6365 class ExecutionPartSkimmer { 6366 public: 6367 explicit ExecutionPartSkimmer(ResolveNamesVisitor &resolver) 6368 : resolver_{resolver} {} 6369 6370 void Walk(const parser::ExecutionPart *exec) { 6371 if (exec) { 6372 parser::Walk(*exec, *this); 6373 } 6374 } 6375 6376 template <typename A> bool Pre(const A &) { return true; } 6377 template <typename A> void Post(const A &) {} 6378 void Post(const parser::FunctionReference &fr) { 6379 resolver_.NoteExecutablePartCall(Symbol::Flag::Function, fr.v); 6380 } 6381 void Post(const parser::CallStmt &cs) { 6382 resolver_.NoteExecutablePartCall(Symbol::Flag::Subroutine, cs.v); 6383 } 6384 6385 private: 6386 ResolveNamesVisitor &resolver_; 6387 }; 6388 6389 // Build the scope tree and resolve names in the specification parts of this 6390 // node and its children 6391 void ResolveNamesVisitor::ResolveSpecificationParts(ProgramTree &node) { 6392 if (node.isSpecificationPartResolved()) { 6393 return; // been here already 6394 } 6395 node.set_isSpecificationPartResolved(); 6396 if (!BeginScopeForNode(node)) { 6397 return; // an error prevented scope from being created 6398 } 6399 Scope &scope{currScope()}; 6400 node.set_scope(scope); 6401 AddSubpNames(node); 6402 std::visit( 6403 [&](const auto *x) { 6404 if (x) { 6405 Walk(*x); 6406 } 6407 }, 6408 node.stmt()); 6409 Walk(node.spec()); 6410 // If this is a function, convert result to an object. This is to prevent the 6411 // result from being converted later to a function symbol if it is called 6412 // inside the function. 6413 // If the result is function pointer, then ConvertToObjectEntity will not 6414 // convert the result to an object, and calling the symbol inside the function 6415 // will result in calls to the result pointer. 6416 // A function cannot be called recursively if RESULT was not used to define a 6417 // distinct result name (15.6.2.2 point 4.). 6418 if (Symbol * symbol{scope.symbol()}) { 6419 if (auto *details{symbol->detailsIf<SubprogramDetails>()}) { 6420 if (details->isFunction()) { 6421 ConvertToObjectEntity(const_cast<Symbol &>(details->result())); 6422 } 6423 } 6424 } 6425 if (node.IsModule()) { 6426 ApplyDefaultAccess(); 6427 } 6428 for (auto &child : node.children()) { 6429 ResolveSpecificationParts(child); 6430 } 6431 ExecutionPartSkimmer{*this}.Walk(node.exec()); 6432 PopScope(); 6433 // Ensure that every object entity has a type. 6434 for (auto &pair : *node.scope()) { 6435 ApplyImplicitRules(*pair.second); 6436 } 6437 } 6438 6439 // Add SubprogramNameDetails symbols for module and internal subprograms 6440 void ResolveNamesVisitor::AddSubpNames(ProgramTree &node) { 6441 auto kind{ 6442 node.IsModule() ? SubprogramKind::Module : SubprogramKind::Internal}; 6443 for (auto &child : node.children()) { 6444 auto &symbol{MakeSymbol(child.name(), SubprogramNameDetails{kind, child})}; 6445 symbol.set(child.GetSubpFlag()); 6446 } 6447 } 6448 6449 // Push a new scope for this node or return false on error. 6450 bool ResolveNamesVisitor::BeginScopeForNode(const ProgramTree &node) { 6451 switch (node.GetKind()) { 6452 SWITCH_COVERS_ALL_CASES 6453 case ProgramTree::Kind::Program: 6454 PushScope(Scope::Kind::MainProgram, 6455 &MakeSymbol(node.name(), MainProgramDetails{})); 6456 return true; 6457 case ProgramTree::Kind::Function: 6458 case ProgramTree::Kind::Subroutine: 6459 return BeginSubprogram( 6460 node.name(), node.GetSubpFlag(), node.HasModulePrefix()); 6461 case ProgramTree::Kind::MpSubprogram: 6462 return BeginMpSubprogram(node.name()); 6463 case ProgramTree::Kind::Module: 6464 BeginModule(node.name(), false); 6465 return true; 6466 case ProgramTree::Kind::Submodule: 6467 return BeginSubmodule(node.name(), node.GetParentId()); 6468 case ProgramTree::Kind::BlockData: 6469 PushBlockDataScope(node.name()); 6470 return true; 6471 } 6472 } 6473 6474 // Some analyses and checks, such as the processing of initializers of 6475 // pointers, are deferred until all of the pertinent specification parts 6476 // have been visited. This deferred processing enables the use of forward 6477 // references in these circumstances. 6478 class DeferredCheckVisitor { 6479 public: 6480 explicit DeferredCheckVisitor(ResolveNamesVisitor &resolver) 6481 : resolver_{resolver} {} 6482 6483 template <typename A> void Walk(const A &x) { parser::Walk(x, *this); } 6484 6485 template <typename A> bool Pre(const A &) { return true; } 6486 template <typename A> void Post(const A &) {} 6487 6488 void Post(const parser::DerivedTypeStmt &x) { 6489 const auto &name{std::get<parser::Name>(x.t)}; 6490 if (Symbol * symbol{name.symbol}) { 6491 if (Scope * scope{symbol->scope()}) { 6492 if (scope->IsDerivedType()) { 6493 resolver_.PushScope(*scope); 6494 pushedScope_ = true; 6495 } 6496 } 6497 } 6498 } 6499 void Post(const parser::EndTypeStmt &) { 6500 if (pushedScope_) { 6501 resolver_.PopScope(); 6502 pushedScope_ = false; 6503 } 6504 } 6505 6506 void Post(const parser::ProcInterface &pi) { 6507 if (const auto *name{std::get_if<parser::Name>(&pi.u)}) { 6508 resolver_.CheckExplicitInterface(*name); 6509 } 6510 } 6511 bool Pre(const parser::EntityDecl &decl) { 6512 Init(std::get<parser::Name>(decl.t), 6513 std::get<std::optional<parser::Initialization>>(decl.t)); 6514 return false; 6515 } 6516 bool Pre(const parser::ComponentDecl &decl) { 6517 Init(std::get<parser::Name>(decl.t), 6518 std::get<std::optional<parser::Initialization>>(decl.t)); 6519 return false; 6520 } 6521 bool Pre(const parser::ProcDecl &decl) { 6522 if (const auto &init{ 6523 std::get<std::optional<parser::ProcPointerInit>>(decl.t)}) { 6524 resolver_.PointerInitialization(std::get<parser::Name>(decl.t), *init); 6525 } 6526 return false; 6527 } 6528 void Post(const parser::TypeBoundProcedureStmt::WithInterface &tbps) { 6529 resolver_.CheckExplicitInterface(tbps.interfaceName); 6530 } 6531 void Post(const parser::TypeBoundProcedureStmt::WithoutInterface &tbps) { 6532 if (pushedScope_) { 6533 resolver_.CheckBindings(tbps); 6534 } 6535 } 6536 6537 private: 6538 void Init(const parser::Name &name, 6539 const std::optional<parser::Initialization> &init) { 6540 if (init) { 6541 if (const auto *target{ 6542 std::get_if<parser::InitialDataTarget>(&init->u)}) { 6543 resolver_.PointerInitialization(name, *target); 6544 } 6545 } 6546 } 6547 6548 ResolveNamesVisitor &resolver_; 6549 bool pushedScope_{false}; 6550 }; 6551 6552 // Perform checks and completions that need to happen after all of 6553 // the specification parts but before any of the execution parts. 6554 void ResolveNamesVisitor::FinishSpecificationParts(const ProgramTree &node) { 6555 if (!node.scope()) { 6556 return; // error occurred creating scope 6557 } 6558 SetScope(*node.scope()); 6559 // The initializers of pointers, the default initializers of pointer 6560 // components, and non-deferred type-bound procedure bindings have not 6561 // yet been traversed. 6562 // We do that now, when any (formerly) forward references that appear 6563 // in those initializers will resolve to the right symbols without 6564 // incurring spurious errors with IMPLICIT NONE. 6565 DeferredCheckVisitor{*this}.Walk(node.spec()); 6566 DeferredCheckVisitor{*this}.Walk(node.exec()); // for BLOCK 6567 for (Scope &childScope : currScope().children()) { 6568 if (childScope.IsParameterizedDerivedTypeInstantiation()) { 6569 FinishDerivedTypeInstantiation(childScope); 6570 } 6571 } 6572 for (const auto &child : node.children()) { 6573 FinishSpecificationParts(child); 6574 } 6575 } 6576 6577 // Duplicate and fold component object pointer default initializer designators 6578 // using the actual type parameter values of each particular instantiation. 6579 // Validation is done later in declaration checking. 6580 void ResolveNamesVisitor::FinishDerivedTypeInstantiation(Scope &scope) { 6581 CHECK(scope.IsDerivedType() && !scope.symbol()); 6582 if (DerivedTypeSpec * spec{scope.derivedTypeSpec()}) { 6583 spec->Instantiate(currScope(), context()); 6584 const Symbol &origTypeSymbol{spec->typeSymbol()}; 6585 if (const Scope * origTypeScope{origTypeSymbol.scope()}) { 6586 CHECK(origTypeScope->IsDerivedType() && 6587 origTypeScope->symbol() == &origTypeSymbol); 6588 auto &foldingContext{GetFoldingContext()}; 6589 auto restorer{foldingContext.WithPDTInstance(*spec)}; 6590 for (auto &pair : scope) { 6591 Symbol &comp{*pair.second}; 6592 const Symbol &origComp{DEREF(FindInScope(*origTypeScope, comp.name()))}; 6593 if (IsPointer(comp)) { 6594 if (auto *details{comp.detailsIf<ObjectEntityDetails>()}) { 6595 auto origDetails{origComp.get<ObjectEntityDetails>()}; 6596 if (const MaybeExpr & init{origDetails.init()}) { 6597 SomeExpr newInit{*init}; 6598 MaybeExpr folded{ 6599 evaluate::Fold(foldingContext, std::move(newInit))}; 6600 details->set_init(std::move(folded)); 6601 } 6602 } 6603 } 6604 } 6605 } 6606 } 6607 } 6608 6609 // Resolve names in the execution part of this node and its children 6610 void ResolveNamesVisitor::ResolveExecutionParts(const ProgramTree &node) { 6611 if (!node.scope()) { 6612 return; // error occurred creating scope 6613 } 6614 SetScope(*node.scope()); 6615 if (const auto *exec{node.exec()}) { 6616 Walk(*exec); 6617 } 6618 PopScope(); // converts unclassified entities into objects 6619 for (const auto &child : node.children()) { 6620 ResolveExecutionParts(child); 6621 } 6622 } 6623 6624 void ResolveNamesVisitor::Post(const parser::Program &) { 6625 // ensure that all temps were deallocated 6626 CHECK(!attrs_); 6627 CHECK(!GetDeclTypeSpec()); 6628 } 6629 6630 // A singleton instance of the scope -> IMPLICIT rules mapping is 6631 // shared by all instances of ResolveNamesVisitor and accessed by this 6632 // pointer when the visitors (other than the top-level original) are 6633 // constructed. 6634 static ImplicitRulesMap *sharedImplicitRulesMap{nullptr}; 6635 6636 bool ResolveNames(SemanticsContext &context, const parser::Program &program) { 6637 ImplicitRulesMap implicitRulesMap; 6638 auto restorer{common::ScopedSet(sharedImplicitRulesMap, &implicitRulesMap)}; 6639 ResolveNamesVisitor{context, implicitRulesMap}.Walk(program); 6640 return !context.AnyFatalError(); 6641 } 6642 6643 // Processes a module (but not internal) function when it is referenced 6644 // in a specification expression in a sibling procedure. 6645 void ResolveSpecificationParts( 6646 SemanticsContext &context, const Symbol &subprogram) { 6647 auto originalLocation{context.location()}; 6648 ResolveNamesVisitor visitor{context, DEREF(sharedImplicitRulesMap)}; 6649 ProgramTree &node{subprogram.get<SubprogramNameDetails>().node()}; 6650 const Scope &moduleScope{subprogram.owner()}; 6651 visitor.SetScope(const_cast<Scope &>(moduleScope)); 6652 visitor.ResolveSpecificationParts(node); 6653 context.set_location(std::move(originalLocation)); 6654 } 6655 6656 } // namespace Fortran::semantics 6657