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