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