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