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