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