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