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