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