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