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