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 const auto &ancestorName{std::get<parser::Name>(parentId.t)}; 2942 Scope *parentScope{nullptr}; 2943 Scope *ancestor{FindModule(ancestorName, false /*not intrinsic*/)}; 2944 if (ancestor) { 2945 if (const auto &parentName{ 2946 std::get<std::optional<parser::Name>>(parentId.t)}) { 2947 parentScope = FindModule(*parentName, false /*not intrinsic*/, ancestor); 2948 } else { 2949 parentScope = ancestor; 2950 } 2951 } 2952 if (parentScope) { 2953 PushScope(*parentScope); 2954 } else { 2955 // Error recovery: there's no ancestor scope, so create a dummy one to 2956 // hold the submodule's scope. 2957 SourceName dummyName{context().GetTempName(currScope())}; 2958 Symbol &dummySymbol{MakeSymbol(dummyName, Attrs{}, ModuleDetails{false})}; 2959 PushScope(Scope::Kind::Module, &dummySymbol); 2960 parentScope = &currScope(); 2961 } 2962 BeginModule(name, true); 2963 if (ancestor && !ancestor->AddSubmodule(name.source, currScope())) { 2964 Say(name, "Module '%s' already has a submodule named '%s'"_err_en_US, 2965 ancestorName.source, name.source); 2966 } 2967 return true; 2968 } 2969 2970 void ModuleVisitor::BeginModule(const parser::Name &name, bool isSubmodule) { 2971 auto &symbol{MakeSymbol(name, ModuleDetails{isSubmodule})}; 2972 auto &details{symbol.get<ModuleDetails>()}; 2973 PushScope(Scope::Kind::Module, &symbol); 2974 details.set_scope(&currScope()); 2975 defaultAccess_ = Attr::PUBLIC; 2976 prevAccessStmt_ = std::nullopt; 2977 } 2978 2979 // Find a module or submodule by name and return its scope. 2980 // If ancestor is present, look for a submodule of that ancestor module. 2981 // May have to read a .mod file to find it. 2982 // If an error occurs, report it and return nullptr. 2983 Scope *ModuleVisitor::FindModule(const parser::Name &name, 2984 std::optional<bool> isIntrinsic, Scope *ancestor) { 2985 ModFileReader reader{context()}; 2986 Scope *scope{reader.Read(name.source, isIntrinsic, ancestor)}; 2987 if (!scope) { 2988 return nullptr; 2989 } 2990 if (DoesScopeContain(scope, currScope())) { // 14.2.2(1) 2991 Say(name, "Module '%s' cannot USE itself"_err_en_US); 2992 } 2993 Resolve(name, scope->symbol()); 2994 return scope; 2995 } 2996 2997 void ModuleVisitor::ApplyDefaultAccess() { 2998 for (auto &pair : currScope()) { 2999 Symbol &symbol = *pair.second; 3000 if (!symbol.attrs().HasAny({Attr::PUBLIC, Attr::PRIVATE})) { 3001 symbol.attrs().set(defaultAccess_); 3002 } 3003 } 3004 } 3005 3006 // InterfaceVistor implementation 3007 3008 bool InterfaceVisitor::Pre(const parser::InterfaceStmt &x) { 3009 bool isAbstract{std::holds_alternative<parser::Abstract>(x.u)}; 3010 genericInfo_.emplace(/*isInterface*/ true, isAbstract); 3011 return BeginAttrs(); 3012 } 3013 3014 void InterfaceVisitor::Post(const parser::InterfaceStmt &) { EndAttrs(); } 3015 3016 void InterfaceVisitor::Post(const parser::EndInterfaceStmt &) { 3017 genericInfo_.pop(); 3018 } 3019 3020 // Create a symbol in genericSymbol_ for this GenericSpec. 3021 bool InterfaceVisitor::Pre(const parser::GenericSpec &x) { 3022 if (auto *symbol{FindInScope(GenericSpecInfo{x}.symbolName())}) { 3023 SetGenericSymbol(*symbol); 3024 } 3025 return false; 3026 } 3027 3028 bool InterfaceVisitor::Pre(const parser::ProcedureStmt &x) { 3029 if (!isGeneric()) { 3030 Say("A PROCEDURE statement is only allowed in a generic interface block"_err_en_US); 3031 return false; 3032 } 3033 auto kind{std::get<parser::ProcedureStmt::Kind>(x.t)}; 3034 const auto &names{std::get<std::list<parser::Name>>(x.t)}; 3035 AddSpecificProcs(names, kind); 3036 return false; 3037 } 3038 3039 bool InterfaceVisitor::Pre(const parser::GenericStmt &) { 3040 genericInfo_.emplace(/*isInterface*/ false); 3041 return true; 3042 } 3043 void InterfaceVisitor::Post(const parser::GenericStmt &x) { 3044 if (auto &accessSpec{std::get<std::optional<parser::AccessSpec>>(x.t)}) { 3045 GetGenericInfo().symbol->attrs().set(AccessSpecToAttr(*accessSpec)); 3046 } 3047 const auto &names{std::get<std::list<parser::Name>>(x.t)}; 3048 AddSpecificProcs(names, ProcedureKind::Procedure); 3049 genericInfo_.pop(); 3050 } 3051 3052 bool InterfaceVisitor::inInterfaceBlock() const { 3053 return !genericInfo_.empty() && GetGenericInfo().isInterface; 3054 } 3055 bool InterfaceVisitor::isGeneric() const { 3056 return !genericInfo_.empty() && GetGenericInfo().symbol; 3057 } 3058 bool InterfaceVisitor::isAbstract() const { 3059 return !genericInfo_.empty() && GetGenericInfo().isAbstract; 3060 } 3061 3062 void InterfaceVisitor::AddSpecificProcs( 3063 const std::list<parser::Name> &names, ProcedureKind kind) { 3064 for (const auto &name : names) { 3065 specificProcs_.emplace( 3066 GetGenericInfo().symbol, std::make_pair(&name, kind)); 3067 } 3068 } 3069 3070 // By now we should have seen all specific procedures referenced by name in 3071 // this generic interface. Resolve those names to symbols. 3072 void InterfaceVisitor::ResolveSpecificsInGeneric(Symbol &generic) { 3073 auto &details{generic.get<GenericDetails>()}; 3074 UnorderedSymbolSet symbolsSeen; 3075 for (const Symbol &symbol : details.specificProcs()) { 3076 symbolsSeen.insert(symbol.GetUltimate()); 3077 } 3078 auto range{specificProcs_.equal_range(&generic)}; 3079 for (auto it{range.first}; it != range.second; ++it) { 3080 const parser::Name *name{it->second.first}; 3081 auto kind{it->second.second}; 3082 const auto *symbol{FindSymbol(*name)}; 3083 if (!symbol) { 3084 Say(*name, "Procedure '%s' not found"_err_en_US); 3085 continue; 3086 } 3087 const Symbol &specific{BypassGeneric(*symbol)}; 3088 const Symbol &ultimate{specific.GetUltimate()}; 3089 if (!ultimate.has<SubprogramDetails>() && 3090 !ultimate.has<SubprogramNameDetails>()) { 3091 Say(*name, "'%s' is not a subprogram"_err_en_US); 3092 continue; 3093 } 3094 if (kind == ProcedureKind::ModuleProcedure) { 3095 if (const auto *nd{ultimate.detailsIf<SubprogramNameDetails>()}) { 3096 if (nd->kind() != SubprogramKind::Module) { 3097 Say(*name, "'%s' is not a module procedure"_err_en_US); 3098 } 3099 } else { 3100 // USE-associated procedure 3101 const auto *sd{ultimate.detailsIf<SubprogramDetails>()}; 3102 CHECK(sd); 3103 if (ultimate.owner().kind() != Scope::Kind::Module || 3104 sd->isInterface()) { 3105 Say(*name, "'%s' is not a module procedure"_err_en_US); 3106 } 3107 } 3108 } 3109 if (symbolsSeen.insert(ultimate).second /*true if added*/) { 3110 // When a specific procedure is a USE association, that association 3111 // is saved in the generic's specifics, not its ultimate symbol, 3112 // so that module file output of interfaces can distinguish them. 3113 details.AddSpecificProc(specific, name->source); 3114 } else if (&specific == &ultimate) { 3115 Say(name->source, 3116 "Procedure '%s' is already specified in generic '%s'"_err_en_US, 3117 name->source, MakeOpName(generic.name())); 3118 } else { 3119 Say(name->source, 3120 "Procedure '%s' from module '%s' is already specified in generic '%s'"_err_en_US, 3121 ultimate.name(), ultimate.owner().GetName().value(), 3122 MakeOpName(generic.name())); 3123 } 3124 } 3125 specificProcs_.erase(range.first, range.second); 3126 } 3127 3128 // Check that the specific procedures are all functions or all subroutines. 3129 // If there is a derived type with the same name they must be functions. 3130 // Set the corresponding flag on generic. 3131 void InterfaceVisitor::CheckGenericProcedures(Symbol &generic) { 3132 ResolveSpecificsInGeneric(generic); 3133 auto &details{generic.get<GenericDetails>()}; 3134 if (auto *proc{details.CheckSpecific()}) { 3135 auto msg{ 3136 "'%s' may not be the name of both a generic interface and a" 3137 " procedure unless it is a specific procedure of the generic"_err_en_US}; 3138 if (proc->name().begin() > generic.name().begin()) { 3139 Say(proc->name(), std::move(msg)); 3140 } else { 3141 Say(generic.name(), std::move(msg)); 3142 } 3143 } 3144 auto &specifics{details.specificProcs()}; 3145 if (specifics.empty()) { 3146 if (details.derivedType()) { 3147 generic.set(Symbol::Flag::Function); 3148 } 3149 return; 3150 } 3151 const Symbol &firstSpecific{specifics.front()}; 3152 bool isFunction{firstSpecific.test(Symbol::Flag::Function)}; 3153 for (const Symbol &specific : specifics) { 3154 if (isFunction != specific.test(Symbol::Flag::Function)) { // C1514 3155 auto &msg{Say(generic.name(), 3156 "Generic interface '%s' has both a function and a subroutine"_err_en_US)}; 3157 if (isFunction) { 3158 msg.Attach(firstSpecific.name(), "Function declaration"_en_US); 3159 msg.Attach(specific.name(), "Subroutine declaration"_en_US); 3160 } else { 3161 msg.Attach(firstSpecific.name(), "Subroutine declaration"_en_US); 3162 msg.Attach(specific.name(), "Function declaration"_en_US); 3163 } 3164 } 3165 } 3166 if (!isFunction && details.derivedType()) { 3167 SayDerivedType(generic.name(), 3168 "Generic interface '%s' may only contain functions due to derived type" 3169 " with same name"_err_en_US, 3170 *details.derivedType()->scope()); 3171 } 3172 generic.set(isFunction ? Symbol::Flag::Function : Symbol::Flag::Subroutine); 3173 } 3174 3175 // SubprogramVisitor implementation 3176 3177 // Return false if it is actually an assignment statement. 3178 bool SubprogramVisitor::HandleStmtFunction(const parser::StmtFunctionStmt &x) { 3179 const auto &name{std::get<parser::Name>(x.t)}; 3180 const DeclTypeSpec *resultType{nullptr}; 3181 // Look up name: provides return type or tells us if it's an array 3182 if (auto *symbol{FindSymbol(name)}) { 3183 auto *details{symbol->detailsIf<EntityDetails>()}; 3184 if (!details) { 3185 badStmtFuncFound_ = true; 3186 return false; 3187 } 3188 // TODO: check that attrs are compatible with stmt func 3189 resultType = details->type(); 3190 symbol->details() = UnknownDetails{}; // will be replaced below 3191 } 3192 if (badStmtFuncFound_) { 3193 Say(name, "'%s' has not been declared as an array"_err_en_US); 3194 return true; 3195 } 3196 auto &symbol{PushSubprogramScope(name, Symbol::Flag::Function)}; 3197 symbol.set(Symbol::Flag::StmtFunction); 3198 EraseSymbol(symbol); // removes symbol added by PushSubprogramScope 3199 auto &details{symbol.get<SubprogramDetails>()}; 3200 for (const auto &dummyName : std::get<std::list<parser::Name>>(x.t)) { 3201 ObjectEntityDetails dummyDetails{true}; 3202 if (auto *dummySymbol{FindInScope(currScope().parent(), dummyName)}) { 3203 if (auto *d{dummySymbol->detailsIf<EntityDetails>()}) { 3204 if (d->type()) { 3205 dummyDetails.set_type(*d->type()); 3206 } 3207 } 3208 } 3209 Symbol &dummy{MakeSymbol(dummyName, std::move(dummyDetails))}; 3210 ApplyImplicitRules(dummy); 3211 details.add_dummyArg(dummy); 3212 } 3213 ObjectEntityDetails resultDetails; 3214 if (resultType) { 3215 resultDetails.set_type(*resultType); 3216 } 3217 resultDetails.set_funcResult(true); 3218 Symbol &result{MakeSymbol(name, std::move(resultDetails))}; 3219 ApplyImplicitRules(result); 3220 details.set_result(result); 3221 const auto &parsedExpr{std::get<parser::Scalar<parser::Expr>>(x.t)}; 3222 Walk(parsedExpr); 3223 // The analysis of the expression that constitutes the body of the 3224 // statement function is deferred to FinishSpecificationPart() so that 3225 // all declarations and implicit typing are complete. 3226 PopScope(); 3227 return true; 3228 } 3229 3230 bool SubprogramVisitor::Pre(const parser::Suffix &suffix) { 3231 if (suffix.resultName) { 3232 if (IsFunction(currScope())) { 3233 if (FuncResultStack::FuncInfo * info{funcResultStack().Top()}) { 3234 if (info->inFunctionStmt) { 3235 info->resultName = &suffix.resultName.value(); 3236 } else { 3237 // will check the result name in Post(EntryStmt) 3238 } 3239 } 3240 } else { 3241 Message &msg{Say(*suffix.resultName, 3242 "RESULT(%s) may appear only in a function"_err_en_US)}; 3243 if (const Symbol * subprogram{InclusiveScope().symbol()}) { 3244 msg.Attach(subprogram->name(), "Containing subprogram"_en_US); 3245 } 3246 } 3247 } 3248 // LanguageBindingSpec deferred to Post(EntryStmt) or, for FunctionStmt, 3249 // all the way to EndSubprogram(). 3250 return false; 3251 } 3252 3253 bool SubprogramVisitor::Pre(const parser::PrefixSpec &x) { 3254 // Save this to process after UseStmt and ImplicitPart 3255 if (const auto *parsedType{std::get_if<parser::DeclarationTypeSpec>(&x.u)}) { 3256 FuncResultStack::FuncInfo &info{DEREF(funcResultStack().Top())}; 3257 if (info.parsedType) { // C1543 3258 Say(currStmtSource().value(), 3259 "FUNCTION prefix cannot specify the type more than once"_err_en_US); 3260 return false; 3261 } else { 3262 info.parsedType = parsedType; 3263 info.source = currStmtSource(); 3264 return false; 3265 } 3266 } else { 3267 return true; 3268 } 3269 } 3270 3271 bool SubprogramVisitor::Pre(const parser::InterfaceBody::Subroutine &x) { 3272 const auto &name{std::get<parser::Name>( 3273 std::get<parser::Statement<parser::SubroutineStmt>>(x.t).statement.t)}; 3274 return BeginSubprogram(name, Symbol::Flag::Subroutine); 3275 } 3276 void SubprogramVisitor::Post(const parser::InterfaceBody::Subroutine &x) { 3277 const auto &stmt{std::get<parser::Statement<parser::SubroutineStmt>>(x.t)}; 3278 EndSubprogram(stmt.source, 3279 &std::get<std::optional<parser::LanguageBindingSpec>>(stmt.statement.t)); 3280 } 3281 bool SubprogramVisitor::Pre(const parser::InterfaceBody::Function &x) { 3282 const auto &name{std::get<parser::Name>( 3283 std::get<parser::Statement<parser::FunctionStmt>>(x.t).statement.t)}; 3284 return BeginSubprogram(name, Symbol::Flag::Function); 3285 } 3286 void SubprogramVisitor::Post(const parser::InterfaceBody::Function &x) { 3287 const auto &stmt{std::get<parser::Statement<parser::FunctionStmt>>(x.t)}; 3288 const auto &maybeSuffix{ 3289 std::get<std::optional<parser::Suffix>>(stmt.statement.t)}; 3290 EndSubprogram(stmt.source, maybeSuffix ? &maybeSuffix->binding : nullptr); 3291 } 3292 3293 bool SubprogramVisitor::Pre(const parser::SubroutineStmt &stmt) { 3294 BeginAttrs(); 3295 Walk(std::get<std::list<parser::PrefixSpec>>(stmt.t)); 3296 Walk(std::get<parser::Name>(stmt.t)); 3297 Walk(std::get<std::list<parser::DummyArg>>(stmt.t)); 3298 // Don't traverse the LanguageBindingSpec now; it's deferred to EndSubprogram. 3299 const auto &name{std::get<parser::Name>(stmt.t)}; 3300 auto &details{PostSubprogramStmt(name)}; 3301 for (const auto &dummyArg : std::get<std::list<parser::DummyArg>>(stmt.t)) { 3302 if (const auto *dummyName{std::get_if<parser::Name>(&dummyArg.u)}) { 3303 Symbol &dummy{MakeSymbol(*dummyName, EntityDetails{true})}; 3304 details.add_dummyArg(dummy); 3305 } else { 3306 details.add_alternateReturn(); 3307 } 3308 } 3309 return false; 3310 } 3311 bool SubprogramVisitor::Pre(const parser::FunctionStmt &) { 3312 FuncResultStack::FuncInfo &info{DEREF(funcResultStack().Top())}; 3313 CHECK(!info.inFunctionStmt); 3314 info.inFunctionStmt = true; 3315 return BeginAttrs(); 3316 } 3317 bool SubprogramVisitor::Pre(const parser::EntryStmt &) { return BeginAttrs(); } 3318 3319 void SubprogramVisitor::Post(const parser::FunctionStmt &stmt) { 3320 const auto &name{std::get<parser::Name>(stmt.t)}; 3321 auto &details{PostSubprogramStmt(name)}; 3322 for (const auto &dummyName : std::get<std::list<parser::Name>>(stmt.t)) { 3323 Symbol &dummy{MakeSymbol(dummyName, EntityDetails{true})}; 3324 details.add_dummyArg(dummy); 3325 } 3326 const parser::Name *funcResultName; 3327 FuncResultStack::FuncInfo &info{DEREF(funcResultStack().Top())}; 3328 CHECK(info.inFunctionStmt); 3329 info.inFunctionStmt = false; 3330 bool distinctResultName{ 3331 info.resultName && info.resultName->source != name.source}; 3332 if (distinctResultName) { 3333 // Note that RESULT is ignored if it has the same name as the function. 3334 // The symbol created by PushScope() is retained as a place-holder 3335 // for error detection. 3336 funcResultName = info.resultName; 3337 } else { 3338 EraseSymbol(name); // was added by PushScope() 3339 funcResultName = &name; 3340 } 3341 if (details.isFunction()) { 3342 CHECK(context().HasError(currScope().symbol())); 3343 } else { 3344 // RESULT(x) can be the same explicitly-named RESULT(x) as an ENTRY 3345 // statement. 3346 Symbol *result{nullptr}; 3347 if (distinctResultName) { 3348 if (auto iter{currScope().find(funcResultName->source)}; 3349 iter != currScope().end()) { 3350 Symbol &entryResult{*iter->second}; 3351 if (IsFunctionResult(entryResult)) { 3352 result = &entryResult; 3353 } 3354 } 3355 } 3356 if (result) { 3357 Resolve(*funcResultName, *result); 3358 } else { 3359 // add function result to function scope 3360 EntityDetails funcResultDetails; 3361 funcResultDetails.set_funcResult(true); 3362 result = &MakeSymbol(*funcResultName, std::move(funcResultDetails)); 3363 } 3364 info.resultSymbol = result; 3365 details.set_result(*result); 3366 } 3367 // C1560. 3368 if (info.resultName && !distinctResultName) { 3369 Say(info.resultName->source, 3370 "The function name should not appear in RESULT, references to '%s' " 3371 "inside the function will be considered as references to the " 3372 "result only"_warn_en_US, 3373 name.source); 3374 // RESULT name was ignored above, the only side effect from doing so will be 3375 // the inability to make recursive calls. The related parser::Name is still 3376 // resolved to the created function result symbol because every parser::Name 3377 // should be resolved to avoid internal errors. 3378 Resolve(*info.resultName, info.resultSymbol); 3379 } 3380 name.symbol = currScope().symbol(); // must not be function result symbol 3381 // Clear the RESULT() name now in case an ENTRY statement in the implicit-part 3382 // has a RESULT() suffix. 3383 info.resultName = nullptr; 3384 } 3385 3386 SubprogramDetails &SubprogramVisitor::PostSubprogramStmt( 3387 const parser::Name &name) { 3388 Symbol &symbol{*currScope().symbol()}; 3389 symbol.attrs() |= EndAttrs(); 3390 if (symbol.attrs().test(Attr::MODULE)) { 3391 symbol.attrs().set(Attr::EXTERNAL, false); 3392 } 3393 return symbol.get<SubprogramDetails>(); 3394 } 3395 3396 void SubprogramVisitor::Post(const parser::EntryStmt &stmt) { 3397 if (const auto &suffix{std::get<std::optional<parser::Suffix>>(stmt.t)}) { 3398 Walk(suffix->binding); 3399 } 3400 PostEntryStmt(stmt); 3401 EndAttrs(); 3402 } 3403 3404 void SubprogramVisitor::CreateEntry( 3405 const parser::EntryStmt &stmt, Symbol &subprogram) { 3406 const auto &entryName{std::get<parser::Name>(stmt.t)}; 3407 Scope &outer{currScope().parent()}; 3408 Symbol::Flag subpFlag{subprogram.test(Symbol::Flag::Function) 3409 ? Symbol::Flag::Function 3410 : Symbol::Flag::Subroutine}; 3411 Attrs attrs; 3412 if (Symbol * extant{FindSymbol(outer, entryName)}) { 3413 if (!HandlePreviousCalls(entryName, *extant, subpFlag)) { 3414 if (outer.IsTopLevel()) { 3415 Say2(entryName, 3416 "'%s' is already defined as a global identifier"_err_en_US, *extant, 3417 "Previous definition of '%s'"_en_US); 3418 } else { 3419 SayAlreadyDeclared(entryName, *extant); 3420 } 3421 return; 3422 } 3423 attrs = extant->attrs(); 3424 } 3425 const auto &suffix{std::get<std::optional<parser::Suffix>>(stmt.t)}; 3426 bool badResultName{false}; 3427 std::optional<SourceName> distinctResultName; 3428 if (suffix && suffix->resultName && 3429 suffix->resultName->source != entryName.source) { 3430 distinctResultName = suffix->resultName->source; 3431 const parser::Name &resultName{*suffix->resultName}; 3432 if (resultName.source == subprogram.name()) { // C1574 3433 Say2(resultName.source, 3434 "RESULT(%s) may not have the same name as the function"_err_en_US, 3435 subprogram, "Containing function"_en_US); 3436 badResultName = true; 3437 } else if (const Symbol * extant{FindSymbol(outer, resultName)}) { // C1574 3438 if (const auto *details{extant->detailsIf<SubprogramDetails>()}) { 3439 if (details->entryScope() == &currScope()) { 3440 Say2(resultName.source, 3441 "RESULT(%s) may not have the same name as an ENTRY in the function"_err_en_US, 3442 extant->name(), "Conflicting ENTRY"_en_US); 3443 badResultName = true; 3444 } 3445 } 3446 } 3447 } 3448 if (outer.IsModule() && !attrs.test(Attr::PRIVATE)) { 3449 attrs.set(Attr::PUBLIC); 3450 } 3451 Symbol *entrySymbol{FindInScope(outer, entryName.source)}; 3452 if (entrySymbol) { 3453 if (auto *generic{entrySymbol->detailsIf<GenericDetails>()}) { 3454 if (auto *specific{generic->specific()}) { 3455 // Forward reference to ENTRY from a generic interface 3456 entrySymbol = specific; 3457 entrySymbol->attrs() |= attrs; 3458 } 3459 } 3460 } else { 3461 entrySymbol = &MakeSymbol(outer, entryName.source, attrs); 3462 } 3463 SubprogramDetails entryDetails; 3464 entryDetails.set_entryScope(currScope()); 3465 entrySymbol->set(subpFlag); 3466 if (subpFlag == Symbol::Flag::Function) { 3467 Symbol *result{nullptr}; 3468 EntityDetails resultDetails; 3469 resultDetails.set_funcResult(true); 3470 if (distinctResultName) { 3471 if (!badResultName) { 3472 // RESULT(x) can be the same explicitly-named RESULT(x) as 3473 // the enclosing function or another ENTRY. 3474 if (auto iter{currScope().find(suffix->resultName->source)}; 3475 iter != currScope().end()) { 3476 result = &*iter->second; 3477 } 3478 if (!result) { 3479 result = &MakeSymbol( 3480 *distinctResultName, Attrs{}, std::move(resultDetails)); 3481 } 3482 Resolve(*suffix->resultName, *result); 3483 } 3484 } else { 3485 result = &MakeSymbol(entryName.source, Attrs{}, std::move(resultDetails)); 3486 } 3487 if (result) { 3488 entryDetails.set_result(*result); 3489 } 3490 } 3491 if (subpFlag == Symbol::Flag::Subroutine || 3492 (distinctResultName && !badResultName)) { 3493 Symbol &assoc{MakeSymbol(entryName.source)}; 3494 assoc.set_details(HostAssocDetails{*entrySymbol}); 3495 assoc.set(Symbol::Flag::Subroutine); 3496 } 3497 Resolve(entryName, *entrySymbol); 3498 Details details{std::move(entryDetails)}; 3499 entrySymbol->set_details(std::move(entryDetails)); 3500 } 3501 3502 void SubprogramVisitor::PostEntryStmt(const parser::EntryStmt &stmt) { 3503 // The entry symbol should have already been created and resolved 3504 // in CreateEntry(), called by BeginSubprogram(), with one exception (below). 3505 const auto &name{std::get<parser::Name>(stmt.t)}; 3506 Scope &inclusiveScope{InclusiveScope()}; 3507 if (!name.symbol) { 3508 if (inclusiveScope.kind() != Scope::Kind::Subprogram) { 3509 Say(name.source, 3510 "ENTRY '%s' may appear only in a subroutine or function"_err_en_US, 3511 name.source); 3512 } else if (FindSeparateModuleSubprogramInterface(inclusiveScope.symbol())) { 3513 Say(name.source, 3514 "ENTRY '%s' may not appear in a separate module procedure"_err_en_US, 3515 name.source); 3516 } else { 3517 // C1571 - entry is nested, so was not put into the program tree; error 3518 // is emitted from MiscChecker in semantics.cpp. 3519 } 3520 return; 3521 } 3522 Symbol &entrySymbol{*name.symbol}; 3523 if (context().HasError(entrySymbol)) { 3524 return; 3525 } 3526 if (!entrySymbol.has<SubprogramDetails>()) { 3527 SayAlreadyDeclared(name, entrySymbol); 3528 return; 3529 } 3530 SubprogramDetails &entryDetails{entrySymbol.get<SubprogramDetails>()}; 3531 CHECK(entryDetails.entryScope() == &inclusiveScope); 3532 entrySymbol.attrs() |= GetAttrs(); 3533 SetBindNameOn(entrySymbol); 3534 for (const auto &dummyArg : std::get<std::list<parser::DummyArg>>(stmt.t)) { 3535 if (const auto *dummyName{std::get_if<parser::Name>(&dummyArg.u)}) { 3536 Symbol *dummy{FindSymbol(*dummyName)}; 3537 if (dummy) { 3538 common::visit( 3539 common::visitors{[](EntityDetails &x) { x.set_isDummy(); }, 3540 [](ObjectEntityDetails &x) { x.set_isDummy(); }, 3541 [](ProcEntityDetails &x) { x.set_isDummy(); }, 3542 [](SubprogramDetails &x) { x.set_isDummy(); }, 3543 [&](const auto &) { 3544 Say2(dummyName->source, 3545 "ENTRY dummy argument '%s' is previously declared as an item that may not be used as a dummy argument"_err_en_US, 3546 dummy->name(), "Previous declaration of '%s'"_en_US); 3547 }}, 3548 dummy->details()); 3549 } else { 3550 dummy = &MakeSymbol(*dummyName, EntityDetails{true}); 3551 if (!inSpecificationPart_) { 3552 ApplyImplicitRules(*dummy); 3553 } 3554 } 3555 entryDetails.add_dummyArg(*dummy); 3556 } else { 3557 if (entrySymbol.test(Symbol::Flag::Function)) { // C1573 3558 Say(name, 3559 "ENTRY in a function may not have an alternate return dummy argument"_err_en_US); 3560 break; 3561 } 3562 entryDetails.add_alternateReturn(); 3563 } 3564 } 3565 } 3566 3567 // A subprogram declared with MODULE PROCEDURE 3568 bool SubprogramVisitor::BeginMpSubprogram(const parser::Name &name) { 3569 auto *symbol{FindSymbol(name)}; 3570 if (symbol && symbol->has<SubprogramNameDetails>()) { 3571 symbol = FindSymbol(currScope().parent(), name); 3572 } 3573 if (!IsSeparateModuleProcedureInterface(symbol)) { 3574 Say(name, "'%s' was not declared a separate module procedure"_err_en_US); 3575 return false; 3576 } 3577 if (symbol->owner() == currScope() && symbol->scope()) { 3578 // This is a MODULE PROCEDURE whose interface appears in its host. 3579 // Convert the module procedure's interface into a subprogram. 3580 SetScope(DEREF(symbol->scope())); 3581 symbol->get<SubprogramDetails>().set_isInterface(false); 3582 } else { 3583 // Copy the interface into a new subprogram scope. 3584 Symbol &newSymbol{MakeSymbol(name, SubprogramDetails{})}; 3585 PushScope(Scope::Kind::Subprogram, &newSymbol); 3586 const auto &details{symbol->get<SubprogramDetails>()}; 3587 auto &newDetails{newSymbol.get<SubprogramDetails>()}; 3588 newDetails.set_moduleInterface(*symbol); 3589 for (const Symbol *dummyArg : details.dummyArgs()) { 3590 if (!dummyArg) { 3591 newDetails.add_alternateReturn(); 3592 } else if (Symbol * copy{currScope().CopySymbol(*dummyArg)}) { 3593 newDetails.add_dummyArg(*copy); 3594 } 3595 } 3596 if (details.isFunction()) { 3597 currScope().erase(symbol->name()); 3598 newDetails.set_result(*currScope().CopySymbol(details.result())); 3599 } 3600 } 3601 return true; 3602 } 3603 3604 // A subprogram or interface declared with SUBROUTINE or FUNCTION 3605 bool SubprogramVisitor::BeginSubprogram(const parser::Name &name, 3606 Symbol::Flag subpFlag, bool hasModulePrefix, 3607 const parser::LanguageBindingSpec *bindingSpec, 3608 const ProgramTree::EntryStmtList *entryStmts) { 3609 if (hasModulePrefix && currScope().IsGlobal()) { // C1547 3610 Say(name, 3611 "'%s' is a MODULE procedure which must be declared within a " 3612 "MODULE or SUBMODULE"_err_en_US); 3613 return false; 3614 } 3615 Symbol *moduleInterface{nullptr}; 3616 if (hasModulePrefix && !inInterfaceBlock()) { 3617 moduleInterface = FindSymbol(currScope(), name); 3618 if (IsSeparateModuleProcedureInterface(moduleInterface)) { 3619 // Subprogram is MODULE FUNCTION or MODULE SUBROUTINE with an interface 3620 // previously defined in the same scope. 3621 currScope().erase(moduleInterface->name()); 3622 } else { 3623 moduleInterface = nullptr; 3624 } 3625 if (!moduleInterface) { 3626 moduleInterface = FindSymbol(currScope().parent(), name); 3627 if (!IsSeparateModuleProcedureInterface(moduleInterface)) { 3628 Say(name, 3629 "'%s' was not declared a separate module procedure"_err_en_US); 3630 return false; 3631 } 3632 } 3633 } 3634 Symbol &newSymbol{PushSubprogramScope(name, subpFlag, bindingSpec)}; 3635 if (moduleInterface) { 3636 newSymbol.get<SubprogramDetails>().set_moduleInterface(*moduleInterface); 3637 if (moduleInterface->attrs().test(Attr::PRIVATE)) { 3638 newSymbol.attrs().set(Attr::PRIVATE); 3639 } else if (moduleInterface->attrs().test(Attr::PUBLIC)) { 3640 newSymbol.attrs().set(Attr::PUBLIC); 3641 } 3642 } 3643 if (entryStmts) { 3644 for (const auto &ref : *entryStmts) { 3645 CreateEntry(*ref, newSymbol); 3646 } 3647 } 3648 return true; 3649 } 3650 3651 void SubprogramVisitor::EndSubprogram( 3652 std::optional<parser::CharBlock> stmtSource, 3653 const std::optional<parser::LanguageBindingSpec> *binding) { 3654 if (binding && *binding && currScope().symbol()) { 3655 // Finally process the BIND(C,NAME=name) now that symbols in the name 3656 // expression will resolve local names. 3657 auto flagRestorer{common::ScopedSet(inSpecificationPart_, false)}; 3658 auto originalStmtSource{messageHandler().currStmtSource()}; 3659 messageHandler().set_currStmtSource(stmtSource); 3660 BeginAttrs(); 3661 Walk(**binding); 3662 SetBindNameOn(*currScope().symbol()); 3663 currScope().symbol()->attrs() |= EndAttrs(); 3664 messageHandler().set_currStmtSource(originalStmtSource); 3665 } 3666 PopScope(); 3667 } 3668 3669 bool SubprogramVisitor::HandlePreviousCalls( 3670 const parser::Name &name, Symbol &symbol, Symbol::Flag subpFlag) { 3671 // If the extant symbol is a generic, check its homonymous specific 3672 // procedure instead if it has one. 3673 if (auto *generic{symbol.detailsIf<GenericDetails>()}) { 3674 return generic->specific() && 3675 HandlePreviousCalls(name, *generic->specific(), subpFlag); 3676 } else if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}; proc && 3677 !proc->isDummy() && 3678 !symbol.attrs().HasAny(Attrs{Attr::INTRINSIC, Attr::POINTER})) { 3679 // There's a symbol created for previous calls to this subprogram or 3680 // ENTRY's name. We have to replace that symbol in situ to avoid the 3681 // obligation to rewrite symbol pointers in the parse tree. 3682 if (!symbol.test(subpFlag)) { 3683 Say2(name, 3684 subpFlag == Symbol::Flag::Function 3685 ? "'%s' was previously called as a subroutine"_err_en_US 3686 : "'%s' was previously called as a function"_err_en_US, 3687 symbol, "Previous call of '%s'"_en_US); 3688 } 3689 EntityDetails entity; 3690 if (proc->type()) { 3691 entity.set_type(*proc->type()); 3692 } 3693 symbol.details() = std::move(entity); 3694 return true; 3695 } else { 3696 return symbol.has<UnknownDetails>() || symbol.has<SubprogramNameDetails>(); 3697 } 3698 } 3699 3700 void SubprogramVisitor::CheckExtantProc( 3701 const parser::Name &name, Symbol::Flag subpFlag) { 3702 if (auto *prev{FindSymbol(name)}) { 3703 if (IsDummy(*prev)) { 3704 } else if (auto *entity{prev->detailsIf<EntityDetails>()}; 3705 IsPointer(*prev) && !entity->type()) { 3706 // POINTER attribute set before interface 3707 } else if (inInterfaceBlock() && currScope() != prev->owner()) { 3708 // Procedures in an INTERFACE block do not resolve to symbols 3709 // in scopes between the global scope and the current scope. 3710 } else if (!HandlePreviousCalls(name, *prev, subpFlag)) { 3711 SayAlreadyDeclared(name, *prev); 3712 } 3713 } 3714 } 3715 3716 Symbol &SubprogramVisitor::PushSubprogramScope(const parser::Name &name, 3717 Symbol::Flag subpFlag, const parser::LanguageBindingSpec *bindingSpec) { 3718 Symbol *symbol{GetSpecificFromGeneric(name)}; 3719 if (!symbol) { 3720 if (bindingSpec && currScope().IsGlobal() && bindingSpec->v) { 3721 // Create this new top-level subprogram with a binding label 3722 // in a new global scope, so that its symbol's name won't clash 3723 // with another symbol that has a distinct binding label. 3724 PushScope(Scope::Kind::Global, 3725 &MakeSymbol(context().GetTempName(currScope()), Attrs{}, 3726 MiscDetails{MiscDetails::Kind::ScopeName})); 3727 } 3728 CheckExtantProc(name, subpFlag); 3729 symbol = &MakeSymbol(name, SubprogramDetails{}); 3730 } 3731 symbol->ReplaceName(name.source); 3732 symbol->set(subpFlag); 3733 PushScope(Scope::Kind::Subprogram, symbol); 3734 if (subpFlag == Symbol::Flag::Function) { 3735 funcResultStack().Push(currScope()); 3736 } 3737 if (inInterfaceBlock()) { 3738 auto &details{symbol->get<SubprogramDetails>()}; 3739 details.set_isInterface(); 3740 if (isAbstract()) { 3741 symbol->attrs().set(Attr::ABSTRACT); 3742 } else { 3743 MakeExternal(*symbol); 3744 } 3745 if (isGeneric()) { 3746 Symbol &genericSymbol{GetGenericSymbol()}; 3747 if (genericSymbol.has<GenericDetails>()) { 3748 genericSymbol.get<GenericDetails>().AddSpecificProc( 3749 *symbol, name.source); 3750 } else { 3751 CHECK(context().HasError(genericSymbol)); 3752 } 3753 } 3754 set_inheritFromParent(false); 3755 } 3756 FindSymbol(name)->set(subpFlag); // PushScope() created symbol 3757 return *symbol; 3758 } 3759 3760 void SubprogramVisitor::PushBlockDataScope(const parser::Name &name) { 3761 if (auto *prev{FindSymbol(name)}) { 3762 if (prev->attrs().test(Attr::EXTERNAL) && prev->has<ProcEntityDetails>()) { 3763 if (prev->test(Symbol::Flag::Subroutine) || 3764 prev->test(Symbol::Flag::Function)) { 3765 Say2(name, "BLOCK DATA '%s' has been called"_err_en_US, *prev, 3766 "Previous call of '%s'"_en_US); 3767 } 3768 EraseSymbol(name); 3769 } 3770 } 3771 if (name.source.empty()) { 3772 // Don't let unnamed BLOCK DATA conflict with unnamed PROGRAM 3773 PushScope(Scope::Kind::BlockData, nullptr); 3774 } else { 3775 PushScope(Scope::Kind::BlockData, &MakeSymbol(name, SubprogramDetails{})); 3776 } 3777 } 3778 3779 // If name is a generic, return specific subprogram with the same name. 3780 Symbol *SubprogramVisitor::GetSpecificFromGeneric(const parser::Name &name) { 3781 // Search for the name but don't resolve it 3782 if (auto *symbol{currScope().FindSymbol(name.source)}) { 3783 if (auto *details{symbol->detailsIf<GenericDetails>()}) { 3784 // found generic, want subprogram 3785 auto *specific{details->specific()}; 3786 if (!specific) { 3787 specific = 3788 &currScope().MakeSymbol(name.source, Attrs{}, SubprogramDetails{}); 3789 if (details->derivedType()) { 3790 // A specific procedure with the same name as a derived type 3791 SayAlreadyDeclared(name, *details->derivedType()); 3792 } else { 3793 details->set_specific(Resolve(name, *specific)); 3794 } 3795 } else if (isGeneric()) { 3796 SayAlreadyDeclared(name, *specific); 3797 } 3798 if (!specific->has<SubprogramDetails>()) { 3799 specific->set_details(SubprogramDetails{}); 3800 } 3801 return specific; 3802 } 3803 } 3804 return nullptr; 3805 } 3806 3807 // DeclarationVisitor implementation 3808 3809 bool DeclarationVisitor::BeginDecl() { 3810 BeginDeclTypeSpec(); 3811 BeginArraySpec(); 3812 return BeginAttrs(); 3813 } 3814 void DeclarationVisitor::EndDecl() { 3815 EndDeclTypeSpec(); 3816 EndArraySpec(); 3817 EndAttrs(); 3818 } 3819 3820 bool DeclarationVisitor::CheckUseError(const parser::Name &name) { 3821 const auto *details{ 3822 name.symbol ? name.symbol->detailsIf<UseErrorDetails>() : nullptr}; 3823 if (!details) { 3824 return false; 3825 } 3826 Message &msg{Say(name, "Reference to '%s' is ambiguous"_err_en_US)}; 3827 for (const auto &[location, module] : details->occurrences()) { 3828 msg.Attach(location, "'%s' was use-associated from module '%s'"_en_US, 3829 name.source, module->GetName().value()); 3830 } 3831 context().SetError(*name.symbol); 3832 return true; 3833 } 3834 3835 // Report error if accessibility of symbol doesn't match isPrivate. 3836 void DeclarationVisitor::CheckAccessibility( 3837 const SourceName &name, bool isPrivate, Symbol &symbol) { 3838 if (symbol.attrs().test(Attr::PRIVATE) != isPrivate) { 3839 Say2(name, 3840 "'%s' does not have the same accessibility as its previous declaration"_err_en_US, 3841 symbol, "Previous declaration of '%s'"_en_US); 3842 } 3843 } 3844 3845 void DeclarationVisitor::Post(const parser::TypeDeclarationStmt &) { 3846 if (!GetAttrs().HasAny({Attr::POINTER, Attr::ALLOCATABLE})) { // C702 3847 if (const auto *typeSpec{GetDeclTypeSpec()}) { 3848 if (typeSpec->category() == DeclTypeSpec::Character) { 3849 if (typeSpec->characterTypeSpec().length().isDeferred()) { 3850 Say("The type parameter LEN cannot be deferred without" 3851 " the POINTER or ALLOCATABLE attribute"_err_en_US); 3852 } 3853 } else if (const DerivedTypeSpec * derivedSpec{typeSpec->AsDerived()}) { 3854 for (const auto &pair : derivedSpec->parameters()) { 3855 if (pair.second.isDeferred()) { 3856 Say(currStmtSource().value(), 3857 "The value of type parameter '%s' cannot be deferred" 3858 " without the POINTER or ALLOCATABLE attribute"_err_en_US, 3859 pair.first); 3860 } 3861 } 3862 } 3863 } 3864 } 3865 EndDecl(); 3866 } 3867 3868 void DeclarationVisitor::Post(const parser::DimensionStmt::Declaration &x) { 3869 DeclareObjectEntity(std::get<parser::Name>(x.t)); 3870 } 3871 void DeclarationVisitor::Post(const parser::CodimensionDecl &x) { 3872 DeclareObjectEntity(std::get<parser::Name>(x.t)); 3873 } 3874 3875 bool DeclarationVisitor::Pre(const parser::Initialization &) { 3876 // Defer inspection of initializers to Initialization() so that the 3877 // symbol being initialized will be available within the initialization 3878 // expression. 3879 return false; 3880 } 3881 3882 void DeclarationVisitor::Post(const parser::EntityDecl &x) { 3883 const auto &name{std::get<parser::ObjectName>(x.t)}; 3884 Attrs attrs{attrs_ ? HandleSaveName(name.source, *attrs_) : Attrs{}}; 3885 Symbol &symbol{DeclareUnknownEntity(name, attrs)}; 3886 symbol.ReplaceName(name.source); 3887 if (const auto &init{std::get<std::optional<parser::Initialization>>(x.t)}) { 3888 ConvertToObjectEntity(symbol) || ConvertToProcEntity(symbol); 3889 Initialization(name, *init, false); 3890 } else if (attrs.test(Attr::PARAMETER)) { // C882, C883 3891 Say(name, "Missing initialization for parameter '%s'"_err_en_US); 3892 } 3893 } 3894 3895 void DeclarationVisitor::Post(const parser::PointerDecl &x) { 3896 const auto &name{std::get<parser::Name>(x.t)}; 3897 if (const auto &deferredShapeSpecs{ 3898 std::get<std::optional<parser::DeferredShapeSpecList>>(x.t)}) { 3899 CHECK(arraySpec().empty()); 3900 BeginArraySpec(); 3901 set_arraySpec(AnalyzeDeferredShapeSpecList(context(), *deferredShapeSpecs)); 3902 Symbol &symbol{DeclareObjectEntity(name, Attrs{Attr::POINTER})}; 3903 symbol.ReplaceName(name.source); 3904 EndArraySpec(); 3905 } else { 3906 HandleAttributeStmt(Attr::POINTER, std::get<parser::Name>(x.t)); 3907 } 3908 } 3909 3910 bool DeclarationVisitor::Pre(const parser::BindEntity &x) { 3911 auto kind{std::get<parser::BindEntity::Kind>(x.t)}; 3912 auto &name{std::get<parser::Name>(x.t)}; 3913 Symbol *symbol; 3914 if (kind == parser::BindEntity::Kind::Object) { 3915 symbol = &HandleAttributeStmt(Attr::BIND_C, name); 3916 } else { 3917 symbol = &MakeCommonBlockSymbol(name); 3918 symbol->attrs().set(Attr::BIND_C); 3919 } 3920 // 8.6.4(1) 3921 // Some entities such as named constant or module name need to checked 3922 // elsewhere. This is to skip the ICE caused by setting Bind name for non-name 3923 // things such as data type and also checks for procedures. 3924 if (symbol->has<CommonBlockDetails>() || symbol->has<ObjectEntityDetails>() || 3925 symbol->has<EntityDetails>()) { 3926 SetBindNameOn(*symbol); 3927 } else { 3928 Say(name, 3929 "Only variable and named common block can be in BIND statement"_err_en_US); 3930 } 3931 return false; 3932 } 3933 bool DeclarationVisitor::Pre(const parser::OldParameterStmt &x) { 3934 inOldStyleParameterStmt_ = true; 3935 Walk(x.v); 3936 inOldStyleParameterStmt_ = false; 3937 return false; 3938 } 3939 bool DeclarationVisitor::Pre(const parser::NamedConstantDef &x) { 3940 auto &name{std::get<parser::NamedConstant>(x.t).v}; 3941 auto &symbol{HandleAttributeStmt(Attr::PARAMETER, name)}; 3942 if (!ConvertToObjectEntity(symbol) || 3943 symbol.test(Symbol::Flag::CrayPointer) || 3944 symbol.test(Symbol::Flag::CrayPointee)) { 3945 SayWithDecl( 3946 name, symbol, "PARAMETER attribute not allowed on '%s'"_err_en_US); 3947 return false; 3948 } 3949 const auto &expr{std::get<parser::ConstantExpr>(x.t)}; 3950 auto &details{symbol.get<ObjectEntityDetails>()}; 3951 if (inOldStyleParameterStmt_) { 3952 // non-standard extension PARAMETER statement (no parentheses) 3953 Walk(expr); 3954 auto folded{EvaluateExpr(expr)}; 3955 if (details.type()) { 3956 SayWithDecl(name, symbol, 3957 "Alternative style PARAMETER '%s' must not already have an explicit type"_err_en_US); 3958 } else if (folded) { 3959 auto at{expr.thing.value().source}; 3960 if (evaluate::IsActuallyConstant(*folded)) { 3961 if (const auto *type{currScope().GetType(*folded)}) { 3962 if (type->IsPolymorphic()) { 3963 Say(at, "The expression must not be polymorphic"_err_en_US); 3964 } else if (auto shape{ToArraySpec( 3965 GetFoldingContext(), evaluate::GetShape(*folded))}) { 3966 // The type of the named constant is assumed from the expression. 3967 details.set_type(*type); 3968 details.set_init(std::move(*folded)); 3969 details.set_shape(std::move(*shape)); 3970 } else { 3971 Say(at, "The expression must have constant shape"_err_en_US); 3972 } 3973 } else { 3974 Say(at, "The expression must have a known type"_err_en_US); 3975 } 3976 } else { 3977 Say(at, "The expression must be a constant of known type"_err_en_US); 3978 } 3979 } 3980 } else { 3981 // standard-conforming PARAMETER statement (with parentheses) 3982 ApplyImplicitRules(symbol); 3983 Walk(expr); 3984 if (auto converted{EvaluateNonPointerInitializer( 3985 symbol, expr, expr.thing.value().source)}) { 3986 details.set_init(std::move(*converted)); 3987 } 3988 } 3989 return false; 3990 } 3991 bool DeclarationVisitor::Pre(const parser::NamedConstant &x) { 3992 const parser::Name &name{x.v}; 3993 if (!FindSymbol(name)) { 3994 Say(name, "Named constant '%s' not found"_err_en_US); 3995 } else { 3996 CheckUseError(name); 3997 } 3998 return false; 3999 } 4000 4001 bool DeclarationVisitor::Pre(const parser::Enumerator &enumerator) { 4002 const parser::Name &name{std::get<parser::NamedConstant>(enumerator.t).v}; 4003 Symbol *symbol{FindSymbol(name)}; 4004 if (symbol && !symbol->has<UnknownDetails>()) { 4005 // Contrary to named constants appearing in a PARAMETER statement, 4006 // enumerator names should not have their type, dimension or any other 4007 // attributes defined before they are declared in the enumerator statement, 4008 // with the exception of accessibility. 4009 // This is not explicitly forbidden by the standard, but they are scalars 4010 // which type is left for the compiler to chose, so do not let users try to 4011 // tamper with that. 4012 SayAlreadyDeclared(name, *symbol); 4013 symbol = nullptr; 4014 } else { 4015 // Enumerators are treated as PARAMETER (section 7.6 paragraph (4)) 4016 symbol = &MakeSymbol(name, Attrs{Attr::PARAMETER}, ObjectEntityDetails{}); 4017 symbol->SetType(context().MakeNumericType( 4018 TypeCategory::Integer, evaluate::CInteger::kind)); 4019 } 4020 4021 if (auto &init{std::get<std::optional<parser::ScalarIntConstantExpr>>( 4022 enumerator.t)}) { 4023 Walk(*init); // Resolve names in expression before evaluation. 4024 if (auto value{EvaluateInt64(context(), *init)}) { 4025 // Cast all init expressions to C_INT so that they can then be 4026 // safely incremented (see 7.6 Note 2). 4027 enumerationState_.value = static_cast<int>(*value); 4028 } else { 4029 Say(name, 4030 "Enumerator value could not be computed " 4031 "from the given expression"_err_en_US); 4032 // Prevent resolution of next enumerators value 4033 enumerationState_.value = std::nullopt; 4034 } 4035 } 4036 4037 if (symbol) { 4038 if (enumerationState_.value) { 4039 symbol->get<ObjectEntityDetails>().set_init(SomeExpr{ 4040 evaluate::Expr<evaluate::CInteger>{*enumerationState_.value}}); 4041 } else { 4042 context().SetError(*symbol); 4043 } 4044 } 4045 4046 if (enumerationState_.value) { 4047 (*enumerationState_.value)++; 4048 } 4049 return false; 4050 } 4051 4052 void DeclarationVisitor::Post(const parser::EnumDef &) { 4053 enumerationState_ = EnumeratorState{}; 4054 } 4055 4056 bool DeclarationVisitor::Pre(const parser::AccessSpec &x) { 4057 Attr attr{AccessSpecToAttr(x)}; 4058 if (!NonDerivedTypeScope().IsModule()) { // C817 4059 Say(currStmtSource().value(), 4060 "%s attribute may only appear in the specification part of a module"_err_en_US, 4061 EnumToString(attr)); 4062 } 4063 CheckAndSet(attr); 4064 return false; 4065 } 4066 4067 bool DeclarationVisitor::Pre(const parser::AsynchronousStmt &x) { 4068 return HandleAttributeStmt(Attr::ASYNCHRONOUS, x.v); 4069 } 4070 bool DeclarationVisitor::Pre(const parser::ContiguousStmt &x) { 4071 return HandleAttributeStmt(Attr::CONTIGUOUS, x.v); 4072 } 4073 bool DeclarationVisitor::Pre(const parser::ExternalStmt &x) { 4074 HandleAttributeStmt(Attr::EXTERNAL, x.v); 4075 for (const auto &name : x.v) { 4076 auto *symbol{FindSymbol(name)}; 4077 if (!ConvertToProcEntity(DEREF(symbol))) { 4078 SayWithDecl( 4079 name, *symbol, "EXTERNAL attribute not allowed on '%s'"_err_en_US); 4080 } else if (symbol->attrs().test(Attr::INTRINSIC)) { // C840 4081 Say(symbol->name(), 4082 "Symbol '%s' cannot have both INTRINSIC and EXTERNAL attributes"_err_en_US, 4083 symbol->name()); 4084 } 4085 } 4086 return false; 4087 } 4088 bool DeclarationVisitor::Pre(const parser::IntentStmt &x) { 4089 auto &intentSpec{std::get<parser::IntentSpec>(x.t)}; 4090 auto &names{std::get<std::list<parser::Name>>(x.t)}; 4091 return CheckNotInBlock("INTENT") && // C1107 4092 HandleAttributeStmt(IntentSpecToAttr(intentSpec), names); 4093 } 4094 bool DeclarationVisitor::Pre(const parser::IntrinsicStmt &x) { 4095 HandleAttributeStmt(Attr::INTRINSIC, x.v); 4096 for (const auto &name : x.v) { 4097 if (!IsIntrinsic(name.source, std::nullopt)) { 4098 Say(name.source, "'%s' is not a known intrinsic procedure"_err_en_US); 4099 } 4100 auto &symbol{DEREF(FindSymbol(name))}; 4101 if (symbol.has<GenericDetails>()) { 4102 // Generic interface is extending intrinsic; ok 4103 } else if (!ConvertToProcEntity(symbol)) { 4104 SayWithDecl( 4105 name, symbol, "INTRINSIC attribute not allowed on '%s'"_err_en_US); 4106 } else if (symbol.attrs().test(Attr::EXTERNAL)) { // C840 4107 Say(symbol.name(), 4108 "Symbol '%s' cannot have both EXTERNAL and INTRINSIC attributes"_err_en_US, 4109 symbol.name()); 4110 } else if (symbol.GetType()) { 4111 // These warnings are worded so that they should make sense in either 4112 // order. 4113 Say(symbol.name(), 4114 "Explicit type declaration ignored for intrinsic function '%s'"_warn_en_US, 4115 symbol.name()) 4116 .Attach(name.source, 4117 "INTRINSIC statement for explicitly-typed '%s'"_en_US, 4118 name.source); 4119 } 4120 } 4121 return false; 4122 } 4123 bool DeclarationVisitor::Pre(const parser::OptionalStmt &x) { 4124 return CheckNotInBlock("OPTIONAL") && // C1107 4125 HandleAttributeStmt(Attr::OPTIONAL, x.v); 4126 } 4127 bool DeclarationVisitor::Pre(const parser::ProtectedStmt &x) { 4128 return HandleAttributeStmt(Attr::PROTECTED, x.v); 4129 } 4130 bool DeclarationVisitor::Pre(const parser::ValueStmt &x) { 4131 return CheckNotInBlock("VALUE") && // C1107 4132 HandleAttributeStmt(Attr::VALUE, x.v); 4133 } 4134 bool DeclarationVisitor::Pre(const parser::VolatileStmt &x) { 4135 return HandleAttributeStmt(Attr::VOLATILE, x.v); 4136 } 4137 // Handle a statement that sets an attribute on a list of names. 4138 bool DeclarationVisitor::HandleAttributeStmt( 4139 Attr attr, const std::list<parser::Name> &names) { 4140 for (const auto &name : names) { 4141 HandleAttributeStmt(attr, name); 4142 } 4143 return false; 4144 } 4145 Symbol &DeclarationVisitor::HandleAttributeStmt( 4146 Attr attr, const parser::Name &name) { 4147 auto *symbol{FindInScope(name)}; 4148 if (attr == Attr::ASYNCHRONOUS || attr == Attr::VOLATILE) { 4149 // these can be set on a symbol that is host-assoc or use-assoc 4150 if (!symbol && 4151 (currScope().kind() == Scope::Kind::Subprogram || 4152 currScope().kind() == Scope::Kind::Block)) { 4153 if (auto *hostSymbol{FindSymbol(name)}) { 4154 symbol = &MakeHostAssocSymbol(name, *hostSymbol); 4155 } 4156 } 4157 } else if (symbol && symbol->has<UseDetails>()) { 4158 Say(currStmtSource().value(), 4159 "Cannot change %s attribute on use-associated '%s'"_err_en_US, 4160 EnumToString(attr), name.source); 4161 return *symbol; 4162 } 4163 if (!symbol) { 4164 symbol = &MakeSymbol(name, EntityDetails{}); 4165 } 4166 symbol->attrs().set(attr); 4167 symbol->attrs() = HandleSaveName(name.source, symbol->attrs()); 4168 return *symbol; 4169 } 4170 // C1107 4171 bool DeclarationVisitor::CheckNotInBlock(const char *stmt) { 4172 if (currScope().kind() == Scope::Kind::Block) { 4173 Say(MessageFormattedText{ 4174 "%s statement is not allowed in a BLOCK construct"_err_en_US, stmt}); 4175 return false; 4176 } else { 4177 return true; 4178 } 4179 } 4180 4181 void DeclarationVisitor::Post(const parser::ObjectDecl &x) { 4182 CHECK(objectDeclAttr_); 4183 const auto &name{std::get<parser::ObjectName>(x.t)}; 4184 DeclareObjectEntity(name, Attrs{*objectDeclAttr_}); 4185 } 4186 4187 // Declare an entity not yet known to be an object or proc. 4188 Symbol &DeclarationVisitor::DeclareUnknownEntity( 4189 const parser::Name &name, Attrs attrs) { 4190 if (!arraySpec().empty() || !coarraySpec().empty()) { 4191 return DeclareObjectEntity(name, attrs); 4192 } else { 4193 Symbol &symbol{DeclareEntity<EntityDetails>(name, attrs)}; 4194 if (auto *type{GetDeclTypeSpec()}) { 4195 SetType(name, *type); 4196 } 4197 charInfo_.length.reset(); 4198 if (symbol.attrs().test(Attr::EXTERNAL)) { 4199 ConvertToProcEntity(symbol); 4200 } 4201 SetBindNameOn(symbol); 4202 return symbol; 4203 } 4204 } 4205 4206 bool DeclarationVisitor::HasCycle( 4207 const Symbol &procSymbol, const ProcInterface &interface) { 4208 SourceOrderedSymbolSet procsInCycle; 4209 procsInCycle.insert(procSymbol); 4210 const ProcInterface *thisInterface{&interface}; 4211 bool haveInterface{true}; 4212 while (haveInterface) { 4213 haveInterface = false; 4214 if (const Symbol * interfaceSymbol{thisInterface->symbol()}) { 4215 if (procsInCycle.count(*interfaceSymbol) > 0) { 4216 for (const auto &procInCycle : procsInCycle) { 4217 Say(procInCycle->name(), 4218 "The interface for procedure '%s' is recursively " 4219 "defined"_err_en_US, 4220 procInCycle->name()); 4221 context().SetError(*procInCycle); 4222 } 4223 return true; 4224 } else if (const auto *procDetails{ 4225 interfaceSymbol->detailsIf<ProcEntityDetails>()}) { 4226 haveInterface = true; 4227 thisInterface = &procDetails->interface(); 4228 procsInCycle.insert(*interfaceSymbol); 4229 } 4230 } 4231 } 4232 return false; 4233 } 4234 4235 Symbol &DeclarationVisitor::DeclareProcEntity( 4236 const parser::Name &name, Attrs attrs, const ProcInterface &interface) { 4237 Symbol &symbol{DeclareEntity<ProcEntityDetails>(name, attrs)}; 4238 if (auto *details{symbol.detailsIf<ProcEntityDetails>()}) { 4239 if (details->IsInterfaceSet()) { 4240 SayWithDecl(name, symbol, 4241 "The interface for procedure '%s' has already been " 4242 "declared"_err_en_US); 4243 context().SetError(symbol); 4244 } else if (HasCycle(symbol, interface)) { 4245 return symbol; 4246 } else if (interface.type()) { 4247 symbol.set(Symbol::Flag::Function); 4248 } else if (interface.symbol()) { 4249 if (interface.symbol()->test(Symbol::Flag::Function)) { 4250 symbol.set(Symbol::Flag::Function); 4251 } else if (interface.symbol()->test(Symbol::Flag::Subroutine)) { 4252 symbol.set(Symbol::Flag::Subroutine); 4253 } 4254 } 4255 details->set_interface(interface); 4256 SetBindNameOn(symbol); 4257 SetPassNameOn(symbol); 4258 } 4259 return symbol; 4260 } 4261 4262 Symbol &DeclarationVisitor::DeclareObjectEntity( 4263 const parser::Name &name, Attrs attrs) { 4264 Symbol &symbol{DeclareEntity<ObjectEntityDetails>(name, attrs)}; 4265 if (auto *details{symbol.detailsIf<ObjectEntityDetails>()}) { 4266 if (auto *type{GetDeclTypeSpec()}) { 4267 SetType(name, *type); 4268 } 4269 if (!arraySpec().empty()) { 4270 if (details->IsArray()) { 4271 if (!context().HasError(symbol)) { 4272 Say(name, 4273 "The dimensions of '%s' have already been declared"_err_en_US); 4274 context().SetError(symbol); 4275 } 4276 } else { 4277 details->set_shape(arraySpec()); 4278 } 4279 } 4280 if (!coarraySpec().empty()) { 4281 if (details->IsCoarray()) { 4282 if (!context().HasError(symbol)) { 4283 Say(name, 4284 "The codimensions of '%s' have already been declared"_err_en_US); 4285 context().SetError(symbol); 4286 } 4287 } else { 4288 details->set_coshape(coarraySpec()); 4289 } 4290 } 4291 SetBindNameOn(symbol); 4292 } 4293 ClearArraySpec(); 4294 ClearCoarraySpec(); 4295 charInfo_.length.reset(); 4296 return symbol; 4297 } 4298 4299 void DeclarationVisitor::Post(const parser::IntegerTypeSpec &x) { 4300 SetDeclTypeSpec(MakeNumericType(TypeCategory::Integer, x.v)); 4301 } 4302 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Real &x) { 4303 SetDeclTypeSpec(MakeNumericType(TypeCategory::Real, x.kind)); 4304 } 4305 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Complex &x) { 4306 SetDeclTypeSpec(MakeNumericType(TypeCategory::Complex, x.kind)); 4307 } 4308 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Logical &x) { 4309 SetDeclTypeSpec(MakeLogicalType(x.kind)); 4310 } 4311 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Character &) { 4312 if (!charInfo_.length) { 4313 charInfo_.length = ParamValue{1, common::TypeParamAttr::Len}; 4314 } 4315 if (!charInfo_.kind) { 4316 charInfo_.kind = 4317 KindExpr{context().GetDefaultKind(TypeCategory::Character)}; 4318 } 4319 SetDeclTypeSpec(currScope().MakeCharacterType( 4320 std::move(*charInfo_.length), std::move(*charInfo_.kind))); 4321 charInfo_ = {}; 4322 } 4323 void DeclarationVisitor::Post(const parser::CharSelector::LengthAndKind &x) { 4324 charInfo_.kind = EvaluateSubscriptIntExpr(x.kind); 4325 std::optional<std::int64_t> intKind{ToInt64(charInfo_.kind)}; 4326 if (intKind && 4327 !context().targetCharacteristics().IsTypeEnabled( 4328 TypeCategory::Character, *intKind)) { // C715, C719 4329 Say(currStmtSource().value(), 4330 "KIND value (%jd) not valid for CHARACTER"_err_en_US, *intKind); 4331 charInfo_.kind = std::nullopt; // prevent further errors 4332 } 4333 if (x.length) { 4334 charInfo_.length = GetParamValue(*x.length, common::TypeParamAttr::Len); 4335 } 4336 } 4337 void DeclarationVisitor::Post(const parser::CharLength &x) { 4338 if (const auto *length{std::get_if<std::uint64_t>(&x.u)}) { 4339 charInfo_.length = ParamValue{ 4340 static_cast<ConstantSubscript>(*length), common::TypeParamAttr::Len}; 4341 } else { 4342 charInfo_.length = GetParamValue( 4343 std::get<parser::TypeParamValue>(x.u), common::TypeParamAttr::Len); 4344 } 4345 } 4346 void DeclarationVisitor::Post(const parser::LengthSelector &x) { 4347 if (const auto *param{std::get_if<parser::TypeParamValue>(&x.u)}) { 4348 charInfo_.length = GetParamValue(*param, common::TypeParamAttr::Len); 4349 } 4350 } 4351 4352 bool DeclarationVisitor::Pre(const parser::KindParam &x) { 4353 if (const auto *kind{std::get_if< 4354 parser::Scalar<parser::Integer<parser::Constant<parser::Name>>>>( 4355 &x.u)}) { 4356 const parser::Name &name{kind->thing.thing.thing}; 4357 if (!FindSymbol(name)) { 4358 Say(name, "Parameter '%s' not found"_err_en_US); 4359 } 4360 } 4361 return false; 4362 } 4363 4364 bool DeclarationVisitor::Pre(const parser::DeclarationTypeSpec::Type &) { 4365 CHECK(GetDeclTypeSpecCategory() == DeclTypeSpec::Category::TypeDerived); 4366 return true; 4367 } 4368 4369 void DeclarationVisitor::Post(const parser::DeclarationTypeSpec::Type &type) { 4370 const parser::Name &derivedName{std::get<parser::Name>(type.derived.t)}; 4371 if (const Symbol * derivedSymbol{derivedName.symbol}) { 4372 CheckForAbstractType(*derivedSymbol); // C706 4373 } 4374 } 4375 4376 bool DeclarationVisitor::Pre(const parser::DeclarationTypeSpec::Class &) { 4377 SetDeclTypeSpecCategory(DeclTypeSpec::Category::ClassDerived); 4378 return true; 4379 } 4380 4381 void DeclarationVisitor::Post( 4382 const parser::DeclarationTypeSpec::Class &parsedClass) { 4383 const auto &typeName{std::get<parser::Name>(parsedClass.derived.t)}; 4384 if (auto spec{ResolveDerivedType(typeName)}; 4385 spec && !IsExtensibleType(&*spec)) { // C705 4386 SayWithDecl(typeName, *typeName.symbol, 4387 "Non-extensible derived type '%s' may not be used with CLASS" 4388 " keyword"_err_en_US); 4389 } 4390 } 4391 4392 void DeclarationVisitor::Post(const parser::DerivedTypeSpec &x) { 4393 const auto &typeName{std::get<parser::Name>(x.t)}; 4394 auto spec{ResolveDerivedType(typeName)}; 4395 if (!spec) { 4396 return; 4397 } 4398 bool seenAnyName{false}; 4399 for (const auto &typeParamSpec : 4400 std::get<std::list<parser::TypeParamSpec>>(x.t)) { 4401 const auto &optKeyword{ 4402 std::get<std::optional<parser::Keyword>>(typeParamSpec.t)}; 4403 std::optional<SourceName> name; 4404 if (optKeyword) { 4405 seenAnyName = true; 4406 name = optKeyword->v.source; 4407 } else if (seenAnyName) { 4408 Say(typeName.source, "Type parameter value must have a name"_err_en_US); 4409 continue; 4410 } 4411 const auto &value{std::get<parser::TypeParamValue>(typeParamSpec.t)}; 4412 // The expressions in a derived type specifier whose values define 4413 // non-defaulted type parameters are evaluated (folded) in the enclosing 4414 // scope. The KIND/LEN distinction is resolved later in 4415 // DerivedTypeSpec::CookParameters(). 4416 ParamValue param{GetParamValue(value, common::TypeParamAttr::Kind)}; 4417 if (!param.isExplicit() || param.GetExplicit()) { 4418 spec->AddRawParamValue(optKeyword, std::move(param)); 4419 } 4420 } 4421 // The DerivedTypeSpec *spec is used initially as a search key. 4422 // If it turns out to have the same name and actual parameter 4423 // value expressions as another DerivedTypeSpec in the current 4424 // scope does, then we'll use that extant spec; otherwise, when this 4425 // spec is distinct from all derived types previously instantiated 4426 // in the current scope, this spec will be moved into that collection. 4427 const auto &dtDetails{spec->typeSymbol().get<DerivedTypeDetails>()}; 4428 auto category{GetDeclTypeSpecCategory()}; 4429 if (dtDetails.isForwardReferenced()) { 4430 DeclTypeSpec &type{currScope().MakeDerivedType(category, std::move(*spec))}; 4431 SetDeclTypeSpec(type); 4432 return; 4433 } 4434 // Normalize parameters to produce a better search key. 4435 spec->CookParameters(GetFoldingContext()); 4436 if (!spec->MightBeParameterized()) { 4437 spec->EvaluateParameters(context()); 4438 } 4439 if (const DeclTypeSpec * 4440 extant{currScope().FindInstantiatedDerivedType(*spec, category)}) { 4441 // This derived type and parameter expressions (if any) are already present 4442 // in this scope. 4443 SetDeclTypeSpec(*extant); 4444 } else { 4445 DeclTypeSpec &type{currScope().MakeDerivedType(category, std::move(*spec))}; 4446 DerivedTypeSpec &derived{type.derivedTypeSpec()}; 4447 if (derived.MightBeParameterized() && 4448 currScope().IsParameterizedDerivedType()) { 4449 // Defer instantiation; use the derived type's definition's scope. 4450 derived.set_scope(DEREF(spec->typeSymbol().scope())); 4451 } else if (&currScope() == spec->typeSymbol().scope()) { 4452 // Direct recursive use of a type in the definition of one of its 4453 // components: defer instantiation 4454 } else { 4455 auto restorer{ 4456 GetFoldingContext().messages().SetLocation(currStmtSource().value())}; 4457 derived.Instantiate(currScope()); 4458 } 4459 SetDeclTypeSpec(type); 4460 } 4461 // Capture the DerivedTypeSpec in the parse tree for use in building 4462 // structure constructor expressions. 4463 x.derivedTypeSpec = &GetDeclTypeSpec()->derivedTypeSpec(); 4464 } 4465 4466 void DeclarationVisitor::Post(const parser::DeclarationTypeSpec::Record &rec) { 4467 const auto &typeName{rec.v}; 4468 if (auto spec{ResolveDerivedType(typeName)}) { 4469 spec->CookParameters(GetFoldingContext()); 4470 spec->EvaluateParameters(context()); 4471 if (const DeclTypeSpec * 4472 extant{currScope().FindInstantiatedDerivedType( 4473 *spec, DeclTypeSpec::TypeDerived)}) { 4474 SetDeclTypeSpec(*extant); 4475 } else { 4476 Say(typeName.source, "%s is not a known STRUCTURE"_err_en_US, 4477 typeName.source); 4478 } 4479 } 4480 } 4481 4482 // The descendents of DerivedTypeDef in the parse tree are visited directly 4483 // in this Pre() routine so that recursive use of the derived type can be 4484 // supported in the components. 4485 bool DeclarationVisitor::Pre(const parser::DerivedTypeDef &x) { 4486 auto &stmt{std::get<parser::Statement<parser::DerivedTypeStmt>>(x.t)}; 4487 Walk(stmt); 4488 Walk(std::get<std::list<parser::Statement<parser::TypeParamDefStmt>>>(x.t)); 4489 auto &scope{currScope()}; 4490 CHECK(scope.symbol()); 4491 CHECK(scope.symbol()->scope() == &scope); 4492 auto &details{scope.symbol()->get<DerivedTypeDetails>()}; 4493 details.set_isForwardReferenced(false); 4494 std::set<SourceName> paramNames; 4495 for (auto ¶mName : std::get<std::list<parser::Name>>(stmt.statement.t)) { 4496 details.add_paramName(paramName.source); 4497 auto *symbol{FindInScope(scope, paramName)}; 4498 if (!symbol) { 4499 Say(paramName, 4500 "No definition found for type parameter '%s'"_err_en_US); // C742 4501 // No symbol for a type param. Create one and mark it as containing an 4502 // error to improve subsequent semantic processing 4503 BeginAttrs(); 4504 Symbol *typeParam{MakeTypeSymbol( 4505 paramName, TypeParamDetails{common::TypeParamAttr::Len})}; 4506 context().SetError(*typeParam); 4507 EndAttrs(); 4508 } else if (!symbol->has<TypeParamDetails>()) { 4509 Say2(paramName, "'%s' is not defined as a type parameter"_err_en_US, 4510 *symbol, "Definition of '%s'"_en_US); // C741 4511 } 4512 if (!paramNames.insert(paramName.source).second) { 4513 Say(paramName, 4514 "Duplicate type parameter name: '%s'"_err_en_US); // C731 4515 } 4516 } 4517 for (const auto &[name, symbol] : currScope()) { 4518 if (symbol->has<TypeParamDetails>() && !paramNames.count(name)) { 4519 SayDerivedType(name, 4520 "'%s' is not a type parameter of this derived type"_err_en_US, 4521 currScope()); // C741 4522 } 4523 } 4524 Walk(std::get<std::list<parser::Statement<parser::PrivateOrSequence>>>(x.t)); 4525 const auto &componentDefs{ 4526 std::get<std::list<parser::Statement<parser::ComponentDefStmt>>>(x.t)}; 4527 Walk(componentDefs); 4528 if (derivedTypeInfo_.sequence) { 4529 details.set_sequence(true); 4530 if (componentDefs.empty()) { // C740 4531 Say(stmt.source, 4532 "A sequence type must have at least one component"_err_en_US); 4533 } 4534 if (!details.paramNames().empty()) { // C740 4535 Say(stmt.source, 4536 "A sequence type may not have type parameters"_err_en_US); 4537 } 4538 if (derivedTypeInfo_.extends) { // C735 4539 Say(stmt.source, 4540 "A sequence type may not have the EXTENDS attribute"_err_en_US); 4541 } 4542 } 4543 Walk(std::get<std::optional<parser::TypeBoundProcedurePart>>(x.t)); 4544 Walk(std::get<parser::Statement<parser::EndTypeStmt>>(x.t)); 4545 derivedTypeInfo_ = {}; 4546 PopScope(); 4547 return false; 4548 } 4549 4550 bool DeclarationVisitor::Pre(const parser::DerivedTypeStmt &) { 4551 return BeginAttrs(); 4552 } 4553 void DeclarationVisitor::Post(const parser::DerivedTypeStmt &x) { 4554 auto &name{std::get<parser::Name>(x.t)}; 4555 // Resolve the EXTENDS() clause before creating the derived 4556 // type's symbol to foil attempts to recursively extend a type. 4557 auto *extendsName{derivedTypeInfo_.extends}; 4558 std::optional<DerivedTypeSpec> extendsType{ 4559 ResolveExtendsType(name, extendsName)}; 4560 auto &symbol{MakeSymbol(name, GetAttrs(), DerivedTypeDetails{})}; 4561 symbol.ReplaceName(name.source); 4562 derivedTypeInfo_.type = &symbol; 4563 PushScope(Scope::Kind::DerivedType, &symbol); 4564 if (extendsType) { 4565 // Declare the "parent component"; private if the type is. 4566 // Any symbol stored in the EXTENDS() clause is temporarily 4567 // hidden so that a new symbol can be created for the parent 4568 // component without producing spurious errors about already 4569 // existing. 4570 const Symbol &extendsSymbol{extendsType->typeSymbol()}; 4571 auto restorer{common::ScopedSet(extendsName->symbol, nullptr)}; 4572 if (OkToAddComponent(*extendsName, &extendsSymbol)) { 4573 auto &comp{DeclareEntity<ObjectEntityDetails>(*extendsName, Attrs{})}; 4574 comp.attrs().set( 4575 Attr::PRIVATE, extendsSymbol.attrs().test(Attr::PRIVATE)); 4576 comp.set(Symbol::Flag::ParentComp); 4577 DeclTypeSpec &type{currScope().MakeDerivedType( 4578 DeclTypeSpec::TypeDerived, std::move(*extendsType))}; 4579 type.derivedTypeSpec().set_scope(*extendsSymbol.scope()); 4580 comp.SetType(type); 4581 DerivedTypeDetails &details{symbol.get<DerivedTypeDetails>()}; 4582 details.add_component(comp); 4583 } 4584 } 4585 EndAttrs(); 4586 } 4587 4588 void DeclarationVisitor::Post(const parser::TypeParamDefStmt &x) { 4589 auto *type{GetDeclTypeSpec()}; 4590 auto attr{std::get<common::TypeParamAttr>(x.t)}; 4591 for (auto &decl : std::get<std::list<parser::TypeParamDecl>>(x.t)) { 4592 auto &name{std::get<parser::Name>(decl.t)}; 4593 if (Symbol * symbol{MakeTypeSymbol(name, TypeParamDetails{attr})}) { 4594 SetType(name, *type); 4595 if (auto &init{ 4596 std::get<std::optional<parser::ScalarIntConstantExpr>>(decl.t)}) { 4597 if (auto maybeExpr{EvaluateNonPointerInitializer( 4598 *symbol, *init, init->thing.thing.thing.value().source)}) { 4599 if (auto *intExpr{std::get_if<SomeIntExpr>(&maybeExpr->u)}) { 4600 symbol->get<TypeParamDetails>().set_init(std::move(*intExpr)); 4601 } 4602 } 4603 } 4604 } 4605 } 4606 EndDecl(); 4607 } 4608 bool DeclarationVisitor::Pre(const parser::TypeAttrSpec::Extends &x) { 4609 if (derivedTypeInfo_.extends) { 4610 Say(currStmtSource().value(), 4611 "Attribute 'EXTENDS' cannot be used more than once"_err_en_US); 4612 } else { 4613 derivedTypeInfo_.extends = &x.v; 4614 } 4615 return false; 4616 } 4617 4618 bool DeclarationVisitor::Pre(const parser::PrivateStmt &) { 4619 if (!currScope().parent().IsModule()) { 4620 Say("PRIVATE is only allowed in a derived type that is" 4621 " in a module"_err_en_US); // C766 4622 } else if (derivedTypeInfo_.sawContains) { 4623 derivedTypeInfo_.privateBindings = true; 4624 } else if (!derivedTypeInfo_.privateComps) { 4625 derivedTypeInfo_.privateComps = true; 4626 } else { 4627 Say("PRIVATE may not appear more than once in" 4628 " derived type components"_warn_en_US); // C738 4629 } 4630 return false; 4631 } 4632 bool DeclarationVisitor::Pre(const parser::SequenceStmt &) { 4633 if (derivedTypeInfo_.sequence) { 4634 Say("SEQUENCE may not appear more than once in" 4635 " derived type components"_warn_en_US); // C738 4636 } 4637 derivedTypeInfo_.sequence = true; 4638 return false; 4639 } 4640 void DeclarationVisitor::Post(const parser::ComponentDecl &x) { 4641 const auto &name{std::get<parser::Name>(x.t)}; 4642 auto attrs{GetAttrs()}; 4643 if (derivedTypeInfo_.privateComps && 4644 !attrs.HasAny({Attr::PUBLIC, Attr::PRIVATE})) { 4645 attrs.set(Attr::PRIVATE); 4646 } 4647 if (const auto *declType{GetDeclTypeSpec()}) { 4648 if (const auto *derived{declType->AsDerived()}) { 4649 if (!attrs.HasAny({Attr::POINTER, Attr::ALLOCATABLE})) { 4650 if (derivedTypeInfo_.type == &derived->typeSymbol()) { // C744 4651 Say("Recursive use of the derived type requires " 4652 "POINTER or ALLOCATABLE"_err_en_US); 4653 } 4654 } 4655 // TODO: This would be more appropriate in CheckDerivedType() 4656 if (auto it{FindCoarrayUltimateComponent(*derived)}) { // C748 4657 std::string ultimateName{it.BuildResultDesignatorName()}; 4658 // Strip off the leading "%" 4659 if (ultimateName.length() > 1) { 4660 ultimateName.erase(0, 1); 4661 if (attrs.HasAny({Attr::POINTER, Attr::ALLOCATABLE})) { 4662 evaluate::AttachDeclaration( 4663 Say(name.source, 4664 "A component with a POINTER or ALLOCATABLE attribute may " 4665 "not " 4666 "be of a type with a coarray ultimate component (named " 4667 "'%s')"_err_en_US, 4668 ultimateName), 4669 derived->typeSymbol()); 4670 } 4671 if (!arraySpec().empty() || !coarraySpec().empty()) { 4672 evaluate::AttachDeclaration( 4673 Say(name.source, 4674 "An array or coarray component may not be of a type with a " 4675 "coarray ultimate component (named '%s')"_err_en_US, 4676 ultimateName), 4677 derived->typeSymbol()); 4678 } 4679 } 4680 } 4681 } 4682 } 4683 if (OkToAddComponent(name)) { 4684 auto &symbol{DeclareObjectEntity(name, attrs)}; 4685 if (symbol.has<ObjectEntityDetails>()) { 4686 if (auto &init{std::get<std::optional<parser::Initialization>>(x.t)}) { 4687 Initialization(name, *init, true); 4688 } 4689 } 4690 currScope().symbol()->get<DerivedTypeDetails>().add_component(symbol); 4691 } 4692 ClearArraySpec(); 4693 ClearCoarraySpec(); 4694 } 4695 void DeclarationVisitor::Post(const parser::FillDecl &x) { 4696 // Replace "%FILL" with a distinct generated name 4697 const auto &name{std::get<parser::Name>(x.t)}; 4698 const_cast<SourceName &>(name.source) = context().GetTempName(currScope()); 4699 if (OkToAddComponent(name)) { 4700 auto &symbol{DeclareObjectEntity(name, GetAttrs())}; 4701 currScope().symbol()->get<DerivedTypeDetails>().add_component(symbol); 4702 } 4703 ClearArraySpec(); 4704 } 4705 bool DeclarationVisitor::Pre(const parser::ProcedureDeclarationStmt &x) { 4706 CHECK(!interfaceName_); 4707 const auto &procAttrSpec{std::get<std::list<parser::ProcAttrSpec>>(x.t)}; 4708 for (const parser::ProcAttrSpec &procAttr : procAttrSpec) { 4709 if (auto *bindC{std::get_if<parser::LanguageBindingSpec>(&procAttr.u)}) { 4710 if (bindC->v.has_value()) { 4711 hasBindCName_ = true; 4712 break; 4713 } 4714 } 4715 } 4716 return BeginDecl(); 4717 } 4718 void DeclarationVisitor::Post(const parser::ProcedureDeclarationStmt &) { 4719 interfaceName_ = nullptr; 4720 hasBindCName_ = false; 4721 EndDecl(); 4722 } 4723 bool DeclarationVisitor::Pre(const parser::DataComponentDefStmt &x) { 4724 // Overrides parse tree traversal so as to handle attributes first, 4725 // so POINTER & ALLOCATABLE enable forward references to derived types. 4726 Walk(std::get<std::list<parser::ComponentAttrSpec>>(x.t)); 4727 set_allowForwardReferenceToDerivedType( 4728 GetAttrs().HasAny({Attr::POINTER, Attr::ALLOCATABLE})); 4729 Walk(std::get<parser::DeclarationTypeSpec>(x.t)); 4730 set_allowForwardReferenceToDerivedType(false); 4731 if (derivedTypeInfo_.sequence) { // C740 4732 if (const auto *declType{GetDeclTypeSpec()}) { 4733 if (!declType->AsIntrinsic() && !declType->IsSequenceType()) { 4734 if (GetAttrs().test(Attr::POINTER) && 4735 context().IsEnabled(common::LanguageFeature::PointerInSeqType)) { 4736 if (context().ShouldWarn(common::LanguageFeature::PointerInSeqType)) { 4737 Say("A sequence type data component that is a pointer to a non-sequence type is not standard"_port_en_US); 4738 } 4739 } else { 4740 Say("A sequence type data component must either be of an intrinsic type or a derived sequence type"_err_en_US); 4741 } 4742 } 4743 } 4744 } 4745 Walk(std::get<std::list<parser::ComponentOrFill>>(x.t)); 4746 return false; 4747 } 4748 bool DeclarationVisitor::Pre(const parser::ProcComponentDefStmt &) { 4749 CHECK(!interfaceName_); 4750 return true; 4751 } 4752 void DeclarationVisitor::Post(const parser::ProcComponentDefStmt &) { 4753 interfaceName_ = nullptr; 4754 } 4755 bool DeclarationVisitor::Pre(const parser::ProcPointerInit &x) { 4756 if (auto *name{std::get_if<parser::Name>(&x.u)}) { 4757 return !NameIsKnownOrIntrinsic(*name); 4758 } 4759 return true; 4760 } 4761 void DeclarationVisitor::Post(const parser::ProcInterface &x) { 4762 if (auto *name{std::get_if<parser::Name>(&x.u)}) { 4763 interfaceName_ = name; 4764 NoteInterfaceName(*name); 4765 } 4766 } 4767 void DeclarationVisitor::Post(const parser::ProcDecl &x) { 4768 const auto &name{std::get<parser::Name>(x.t)}; 4769 ProcInterface interface; 4770 if (interfaceName_) { 4771 interface.set_symbol(*interfaceName_->symbol); 4772 } else if (auto *type{GetDeclTypeSpec()}) { 4773 interface.set_type(*type); 4774 } 4775 auto attrs{HandleSaveName(name.source, GetAttrs())}; 4776 DerivedTypeDetails *dtDetails{nullptr}; 4777 if (Symbol * symbol{currScope().symbol()}) { 4778 dtDetails = symbol->detailsIf<DerivedTypeDetails>(); 4779 } 4780 if (!dtDetails) { 4781 attrs.set(Attr::EXTERNAL); 4782 } 4783 Symbol &symbol{DeclareProcEntity(name, attrs, interface)}; 4784 symbol.ReplaceName(name.source); 4785 if (dtDetails) { 4786 dtDetails->add_component(symbol); 4787 } 4788 if (hasBindCName_ && (IsPointer(symbol) || IsDummy(symbol))) { 4789 Say(symbol.name(), 4790 "BIND(C) procedure with NAME= specified can neither have POINTER attribute nor be a dummy procedure"_err_en_US); 4791 } 4792 } 4793 4794 bool DeclarationVisitor::Pre(const parser::TypeBoundProcedurePart &) { 4795 derivedTypeInfo_.sawContains = true; 4796 return true; 4797 } 4798 4799 // Resolve binding names from type-bound generics, saved in genericBindings_. 4800 void DeclarationVisitor::Post(const parser::TypeBoundProcedurePart &) { 4801 // track specifics seen for the current generic to detect duplicates: 4802 const Symbol *currGeneric{nullptr}; 4803 std::set<SourceName> specifics; 4804 for (const auto &[generic, bindingName] : genericBindings_) { 4805 if (generic != currGeneric) { 4806 currGeneric = generic; 4807 specifics.clear(); 4808 } 4809 auto [it, inserted]{specifics.insert(bindingName->source)}; 4810 if (!inserted) { 4811 Say(*bindingName, // C773 4812 "Binding name '%s' was already specified for generic '%s'"_err_en_US, 4813 bindingName->source, generic->name()) 4814 .Attach(*it, "Previous specification of '%s'"_en_US, *it); 4815 continue; 4816 } 4817 auto *symbol{FindInTypeOrParents(*bindingName)}; 4818 if (!symbol) { 4819 Say(*bindingName, // C772 4820 "Binding name '%s' not found in this derived type"_err_en_US); 4821 } else if (!symbol->has<ProcBindingDetails>()) { 4822 SayWithDecl(*bindingName, *symbol, // C772 4823 "'%s' is not the name of a specific binding of this type"_err_en_US); 4824 } else { 4825 generic->get<GenericDetails>().AddSpecificProc( 4826 *symbol, bindingName->source); 4827 } 4828 } 4829 genericBindings_.clear(); 4830 } 4831 4832 void DeclarationVisitor::Post(const parser::ContainsStmt &) { 4833 if (derivedTypeInfo_.sequence) { 4834 Say("A sequence type may not have a CONTAINS statement"_err_en_US); // C740 4835 } 4836 } 4837 4838 void DeclarationVisitor::Post( 4839 const parser::TypeBoundProcedureStmt::WithoutInterface &x) { 4840 if (GetAttrs().test(Attr::DEFERRED)) { // C783 4841 Say("DEFERRED is only allowed when an interface-name is provided"_err_en_US); 4842 } 4843 for (auto &declaration : x.declarations) { 4844 auto &bindingName{std::get<parser::Name>(declaration.t)}; 4845 auto &optName{std::get<std::optional<parser::Name>>(declaration.t)}; 4846 const parser::Name &procedureName{optName ? *optName : bindingName}; 4847 Symbol *procedure{FindSymbol(procedureName)}; 4848 if (!procedure) { 4849 procedure = NoteInterfaceName(procedureName); 4850 } 4851 if (auto *s{MakeTypeSymbol(bindingName, ProcBindingDetails{*procedure})}) { 4852 SetPassNameOn(*s); 4853 if (GetAttrs().test(Attr::DEFERRED)) { 4854 context().SetError(*s); 4855 } 4856 } 4857 } 4858 } 4859 4860 void DeclarationVisitor::CheckBindings( 4861 const parser::TypeBoundProcedureStmt::WithoutInterface &tbps) { 4862 CHECK(currScope().IsDerivedType()); 4863 for (auto &declaration : tbps.declarations) { 4864 auto &bindingName{std::get<parser::Name>(declaration.t)}; 4865 if (Symbol * binding{FindInScope(bindingName)}) { 4866 if (auto *details{binding->detailsIf<ProcBindingDetails>()}) { 4867 const Symbol *procedure{FindSubprogram(details->symbol())}; 4868 if (!CanBeTypeBoundProc(procedure)) { 4869 if (details->symbol().name() != binding->name()) { 4870 Say(binding->name(), 4871 "The binding of '%s' ('%s') must be either an accessible " 4872 "module procedure or an external procedure with " 4873 "an explicit interface"_err_en_US, 4874 binding->name(), details->symbol().name()); 4875 } else { 4876 Say(binding->name(), 4877 "'%s' must be either an accessible module procedure " 4878 "or an external procedure with an explicit interface"_err_en_US, 4879 binding->name()); 4880 } 4881 context().SetError(*binding); 4882 } 4883 } 4884 } 4885 } 4886 } 4887 4888 void DeclarationVisitor::Post( 4889 const parser::TypeBoundProcedureStmt::WithInterface &x) { 4890 if (!GetAttrs().test(Attr::DEFERRED)) { // C783 4891 Say("DEFERRED is required when an interface-name is provided"_err_en_US); 4892 } 4893 if (Symbol * interface{NoteInterfaceName(x.interfaceName)}) { 4894 for (auto &bindingName : x.bindingNames) { 4895 if (auto *s{ 4896 MakeTypeSymbol(bindingName, ProcBindingDetails{*interface})}) { 4897 SetPassNameOn(*s); 4898 if (!GetAttrs().test(Attr::DEFERRED)) { 4899 context().SetError(*s); 4900 } 4901 } 4902 } 4903 } 4904 } 4905 4906 void DeclarationVisitor::Post(const parser::FinalProcedureStmt &x) { 4907 if (currScope().IsDerivedType() && currScope().symbol()) { 4908 if (auto *details{currScope().symbol()->detailsIf<DerivedTypeDetails>()}) { 4909 for (const auto &subrName : x.v) { 4910 if (const auto *name{ResolveName(subrName)}) { 4911 auto pair{ 4912 details->finals().emplace(name->source, DEREF(name->symbol))}; 4913 if (!pair.second) { // C787 4914 Say(name->source, 4915 "FINAL subroutine '%s' already appeared in this derived type"_err_en_US, 4916 name->source) 4917 .Attach(pair.first->first, 4918 "earlier appearance of this FINAL subroutine"_en_US); 4919 } 4920 } 4921 } 4922 } 4923 } 4924 } 4925 4926 bool DeclarationVisitor::Pre(const parser::TypeBoundGenericStmt &x) { 4927 const auto &accessSpec{std::get<std::optional<parser::AccessSpec>>(x.t)}; 4928 const auto &genericSpec{std::get<Indirection<parser::GenericSpec>>(x.t)}; 4929 const auto &bindingNames{std::get<std::list<parser::Name>>(x.t)}; 4930 auto info{GenericSpecInfo{genericSpec.value()}}; 4931 SourceName symbolName{info.symbolName()}; 4932 bool isPrivate{accessSpec ? accessSpec->v == parser::AccessSpec::Kind::Private 4933 : derivedTypeInfo_.privateBindings}; 4934 auto *genericSymbol{FindInScope(symbolName)}; 4935 if (genericSymbol) { 4936 if (!genericSymbol->has<GenericDetails>()) { 4937 genericSymbol = nullptr; // MakeTypeSymbol will report the error below 4938 } 4939 } else { 4940 // look in parent types: 4941 Symbol *inheritedSymbol{nullptr}; 4942 for (const auto &name : GetAllNames(context(), symbolName)) { 4943 inheritedSymbol = currScope().FindComponent(SourceName{name}); 4944 if (inheritedSymbol) { 4945 break; 4946 } 4947 } 4948 if (inheritedSymbol && inheritedSymbol->has<GenericDetails>()) { 4949 CheckAccessibility(symbolName, isPrivate, *inheritedSymbol); // C771 4950 } 4951 } 4952 if (genericSymbol) { 4953 CheckAccessibility(symbolName, isPrivate, *genericSymbol); // C771 4954 } else { 4955 genericSymbol = MakeTypeSymbol(symbolName, GenericDetails{}); 4956 if (!genericSymbol) { 4957 return false; 4958 } 4959 if (isPrivate) { 4960 genericSymbol->attrs().set(Attr::PRIVATE); 4961 } 4962 } 4963 for (const parser::Name &bindingName : bindingNames) { 4964 genericBindings_.emplace(genericSymbol, &bindingName); 4965 } 4966 info.Resolve(genericSymbol); 4967 return false; 4968 } 4969 4970 // DEC STRUCTUREs are handled thus to allow for nested definitions. 4971 bool DeclarationVisitor::Pre(const parser::StructureDef &def) { 4972 const auto &structureStatement{ 4973 std::get<parser::Statement<parser::StructureStmt>>(def.t)}; 4974 auto saveDerivedTypeInfo{derivedTypeInfo_}; 4975 derivedTypeInfo_ = {}; 4976 derivedTypeInfo_.isStructure = true; 4977 derivedTypeInfo_.sequence = true; 4978 Scope *previousStructure{nullptr}; 4979 if (saveDerivedTypeInfo.isStructure) { 4980 previousStructure = &currScope(); 4981 PopScope(); 4982 } 4983 const parser::StructureStmt &structStmt{structureStatement.statement}; 4984 const auto &name{std::get<std::optional<parser::Name>>(structStmt.t)}; 4985 if (!name) { 4986 // Construct a distinct generated name for an anonymous structure 4987 auto &mutableName{const_cast<std::optional<parser::Name> &>(name)}; 4988 mutableName.emplace( 4989 parser::Name{context().GetTempName(currScope()), nullptr}); 4990 } 4991 auto &symbol{MakeSymbol(*name, DerivedTypeDetails{})}; 4992 symbol.ReplaceName(name->source); 4993 symbol.get<DerivedTypeDetails>().set_sequence(true); 4994 symbol.get<DerivedTypeDetails>().set_isDECStructure(true); 4995 derivedTypeInfo_.type = &symbol; 4996 PushScope(Scope::Kind::DerivedType, &symbol); 4997 const auto &fields{std::get<std::list<parser::StructureField>>(def.t)}; 4998 Walk(fields); 4999 PopScope(); 5000 // Complete the definition 5001 DerivedTypeSpec derivedTypeSpec{symbol.name(), symbol}; 5002 derivedTypeSpec.set_scope(DEREF(symbol.scope())); 5003 derivedTypeSpec.CookParameters(GetFoldingContext()); 5004 derivedTypeSpec.EvaluateParameters(context()); 5005 DeclTypeSpec &type{currScope().MakeDerivedType( 5006 DeclTypeSpec::TypeDerived, std::move(derivedTypeSpec))}; 5007 type.derivedTypeSpec().Instantiate(currScope()); 5008 // Restore previous structure definition context, if any 5009 derivedTypeInfo_ = saveDerivedTypeInfo; 5010 if (previousStructure) { 5011 PushScope(*previousStructure); 5012 } 5013 // Handle any entity declarations on the STRUCTURE statement 5014 const auto &decls{std::get<std::list<parser::EntityDecl>>(structStmt.t)}; 5015 if (!decls.empty()) { 5016 BeginDecl(); 5017 SetDeclTypeSpec(type); 5018 Walk(decls); 5019 EndDecl(); 5020 } 5021 return false; 5022 } 5023 5024 bool DeclarationVisitor::Pre(const parser::Union::UnionStmt &) { 5025 Say("support for UNION"_todo_en_US); // TODO 5026 return true; 5027 } 5028 5029 bool DeclarationVisitor::Pre(const parser::StructureField &x) { 5030 if (std::holds_alternative<parser::Statement<parser::DataComponentDefStmt>>( 5031 x.u)) { 5032 BeginDecl(); 5033 } 5034 return true; 5035 } 5036 5037 void DeclarationVisitor::Post(const parser::StructureField &x) { 5038 if (std::holds_alternative<parser::Statement<parser::DataComponentDefStmt>>( 5039 x.u)) { 5040 EndDecl(); 5041 } 5042 } 5043 5044 bool DeclarationVisitor::Pre(const parser::AllocateStmt &) { 5045 BeginDeclTypeSpec(); 5046 return true; 5047 } 5048 void DeclarationVisitor::Post(const parser::AllocateStmt &) { 5049 EndDeclTypeSpec(); 5050 } 5051 5052 bool DeclarationVisitor::Pre(const parser::StructureConstructor &x) { 5053 auto &parsedType{std::get<parser::DerivedTypeSpec>(x.t)}; 5054 const DeclTypeSpec *type{ProcessTypeSpec(parsedType)}; 5055 if (!type) { 5056 return false; 5057 } 5058 const DerivedTypeSpec *spec{type->AsDerived()}; 5059 const Scope *typeScope{spec ? spec->scope() : nullptr}; 5060 if (!typeScope) { 5061 return false; 5062 } 5063 5064 // N.B C7102 is implicitly enforced by having inaccessible types not 5065 // being found in resolution. 5066 // More constraints are enforced in expression.cpp so that they 5067 // can apply to structure constructors that have been converted 5068 // from misparsed function references. 5069 for (const auto &component : 5070 std::get<std::list<parser::ComponentSpec>>(x.t)) { 5071 // Visit the component spec expression, but not the keyword, since 5072 // we need to resolve its symbol in the scope of the derived type. 5073 Walk(std::get<parser::ComponentDataSource>(component.t)); 5074 if (const auto &kw{std::get<std::optional<parser::Keyword>>(component.t)}) { 5075 FindInTypeOrParents(*typeScope, kw->v); 5076 } 5077 } 5078 return false; 5079 } 5080 5081 bool DeclarationVisitor::Pre(const parser::BasedPointerStmt &x) { 5082 for (const parser::BasedPointer &bp : x.v) { 5083 const parser::ObjectName &pointerName{std::get<0>(bp.t)}; 5084 const parser::ObjectName &pointeeName{std::get<1>(bp.t)}; 5085 auto *pointer{FindSymbol(pointerName)}; 5086 if (!pointer) { 5087 pointer = &MakeSymbol(pointerName, ObjectEntityDetails{}); 5088 } else if (!ConvertToObjectEntity(*pointer) || IsNamedConstant(*pointer)) { 5089 SayWithDecl(pointerName, *pointer, "'%s' is not a variable"_err_en_US); 5090 } else if (pointer->Rank() > 0) { 5091 SayWithDecl(pointerName, *pointer, 5092 "Cray pointer '%s' must be a scalar"_err_en_US); 5093 } else if (pointer->test(Symbol::Flag::CrayPointee)) { 5094 Say(pointerName, 5095 "'%s' cannot be a Cray pointer as it is already a Cray pointee"_err_en_US); 5096 } 5097 pointer->set(Symbol::Flag::CrayPointer); 5098 const DeclTypeSpec &pointerType{MakeNumericType(TypeCategory::Integer, 5099 context().defaultKinds().subscriptIntegerKind())}; 5100 const auto *type{pointer->GetType()}; 5101 if (!type) { 5102 pointer->SetType(pointerType); 5103 } else if (*type != pointerType) { 5104 Say(pointerName.source, "Cray pointer '%s' must have type %s"_err_en_US, 5105 pointerName.source, pointerType.AsFortran()); 5106 } 5107 if (ResolveName(pointeeName)) { 5108 Symbol &pointee{*pointeeName.symbol}; 5109 if (pointee.has<UseDetails>()) { 5110 Say(pointeeName, 5111 "'%s' cannot be a Cray pointee as it is use-associated"_err_en_US); 5112 continue; 5113 } else if (!ConvertToObjectEntity(pointee) || IsNamedConstant(pointee)) { 5114 Say(pointeeName, "'%s' is not a variable"_err_en_US); 5115 continue; 5116 } else if (pointee.test(Symbol::Flag::CrayPointer)) { 5117 Say(pointeeName, 5118 "'%s' cannot be a Cray pointee as it is already a Cray pointer"_err_en_US); 5119 } else if (pointee.test(Symbol::Flag::CrayPointee)) { 5120 Say(pointeeName, 5121 "'%s' was already declared as a Cray pointee"_err_en_US); 5122 } else { 5123 pointee.set(Symbol::Flag::CrayPointee); 5124 } 5125 if (const auto *pointeeType{pointee.GetType()}) { 5126 if (const auto *derived{pointeeType->AsDerived()}) { 5127 if (!derived->typeSymbol().get<DerivedTypeDetails>().sequence()) { 5128 Say(pointeeName, 5129 "Type of Cray pointee '%s' is a non-sequence derived type"_err_en_US); 5130 } 5131 } 5132 } 5133 // process the pointee array-spec, if present 5134 BeginArraySpec(); 5135 Walk(std::get<std::optional<parser::ArraySpec>>(bp.t)); 5136 const auto &spec{arraySpec()}; 5137 if (!spec.empty()) { 5138 auto &details{pointee.get<ObjectEntityDetails>()}; 5139 if (details.shape().empty()) { 5140 details.set_shape(spec); 5141 } else { 5142 SayWithDecl(pointeeName, pointee, 5143 "Array spec was already declared for '%s'"_err_en_US); 5144 } 5145 } 5146 ClearArraySpec(); 5147 currScope().add_crayPointer(pointeeName.source, *pointer); 5148 } 5149 } 5150 return false; 5151 } 5152 5153 bool DeclarationVisitor::Pre(const parser::NamelistStmt::Group &x) { 5154 if (!CheckNotInBlock("NAMELIST")) { // C1107 5155 return false; 5156 } 5157 const auto &groupName{std::get<parser::Name>(x.t)}; 5158 auto *groupSymbol{FindInScope(groupName)}; 5159 if (!groupSymbol || !groupSymbol->has<NamelistDetails>()) { 5160 groupSymbol = &MakeSymbol(groupName, NamelistDetails{}); 5161 groupSymbol->ReplaceName(groupName.source); 5162 } 5163 // Name resolution of group items is deferred to FinishNamelists() 5164 // so that host association is handled correctly. 5165 GetDeferredDeclarationState(true)->namelistGroups.emplace_back(&x); 5166 return false; 5167 } 5168 5169 void DeclarationVisitor::FinishNamelists() { 5170 if (auto *deferred{GetDeferredDeclarationState()}) { 5171 for (const parser::NamelistStmt::Group *group : deferred->namelistGroups) { 5172 if (auto *groupSymbol{FindInScope(std::get<parser::Name>(group->t))}) { 5173 if (auto *details{groupSymbol->detailsIf<NamelistDetails>()}) { 5174 for (const auto &name : std::get<std::list<parser::Name>>(group->t)) { 5175 auto *symbol{FindSymbol(name)}; 5176 if (!symbol) { 5177 symbol = &MakeSymbol(name, ObjectEntityDetails{}); 5178 ApplyImplicitRules(*symbol); 5179 } else if (!ConvertToObjectEntity(*symbol)) { 5180 SayWithDecl(name, *symbol, "'%s' is not a variable"_err_en_US); 5181 } 5182 symbol->GetUltimate().set(Symbol::Flag::InNamelist); 5183 details->add_object(*symbol); 5184 } 5185 } 5186 } 5187 } 5188 deferred->namelistGroups.clear(); 5189 } 5190 } 5191 5192 bool DeclarationVisitor::Pre(const parser::IoControlSpec &x) { 5193 if (const auto *name{std::get_if<parser::Name>(&x.u)}) { 5194 auto *symbol{FindSymbol(*name)}; 5195 if (!symbol) { 5196 Say(*name, "Namelist group '%s' not found"_err_en_US); 5197 } else if (!symbol->GetUltimate().has<NamelistDetails>()) { 5198 SayWithDecl( 5199 *name, *symbol, "'%s' is not the name of a namelist group"_err_en_US); 5200 } 5201 } 5202 return true; 5203 } 5204 5205 bool DeclarationVisitor::Pre(const parser::CommonStmt::Block &x) { 5206 CheckNotInBlock("COMMON"); // C1107 5207 return true; 5208 } 5209 5210 bool DeclarationVisitor::Pre(const parser::CommonBlockObject &) { 5211 BeginArraySpec(); 5212 return true; 5213 } 5214 5215 void DeclarationVisitor::Post(const parser::CommonBlockObject &x) { 5216 const auto &name{std::get<parser::Name>(x.t)}; 5217 DeclareObjectEntity(name); 5218 auto pair{specPartState_.commonBlockObjects.insert(name.source)}; 5219 if (!pair.second) { 5220 const SourceName &prev{*pair.first}; 5221 Say2(name.source, "'%s' is already in a COMMON block"_err_en_US, prev, 5222 "Previous occurrence of '%s' in a COMMON block"_en_US); 5223 } 5224 } 5225 5226 bool DeclarationVisitor::Pre(const parser::EquivalenceStmt &x) { 5227 // save equivalence sets to be processed after specification part 5228 if (CheckNotInBlock("EQUIVALENCE")) { // C1107 5229 for (const std::list<parser::EquivalenceObject> &set : x.v) { 5230 specPartState_.equivalenceSets.push_back(&set); 5231 } 5232 } 5233 return false; // don't implicitly declare names yet 5234 } 5235 5236 void DeclarationVisitor::CheckEquivalenceSets() { 5237 EquivalenceSets equivSets{context()}; 5238 inEquivalenceStmt_ = true; 5239 for (const auto *set : specPartState_.equivalenceSets) { 5240 const auto &source{set->front().v.value().source}; 5241 if (set->size() <= 1) { // R871 5242 Say(source, "Equivalence set must have more than one object"_err_en_US); 5243 } 5244 for (const parser::EquivalenceObject &object : *set) { 5245 const auto &designator{object.v.value()}; 5246 // The designator was not resolved when it was encountered so do it now. 5247 // AnalyzeExpr causes array sections to be changed to substrings as needed 5248 Walk(designator); 5249 if (AnalyzeExpr(context(), designator)) { 5250 equivSets.AddToSet(designator); 5251 } 5252 } 5253 equivSets.FinishSet(source); 5254 } 5255 inEquivalenceStmt_ = false; 5256 for (auto &set : equivSets.sets()) { 5257 if (!set.empty()) { 5258 currScope().add_equivalenceSet(std::move(set)); 5259 } 5260 } 5261 specPartState_.equivalenceSets.clear(); 5262 } 5263 5264 bool DeclarationVisitor::Pre(const parser::SaveStmt &x) { 5265 if (x.v.empty()) { 5266 specPartState_.saveInfo.saveAll = currStmtSource(); 5267 currScope().set_hasSAVE(); 5268 } else { 5269 for (const parser::SavedEntity &y : x.v) { 5270 auto kind{std::get<parser::SavedEntity::Kind>(y.t)}; 5271 const auto &name{std::get<parser::Name>(y.t)}; 5272 if (kind == parser::SavedEntity::Kind::Common) { 5273 MakeCommonBlockSymbol(name); 5274 AddSaveName(specPartState_.saveInfo.commons, name.source); 5275 } else { 5276 HandleAttributeStmt(Attr::SAVE, name); 5277 } 5278 } 5279 } 5280 return false; 5281 } 5282 5283 void DeclarationVisitor::CheckSaveStmts() { 5284 for (const SourceName &name : specPartState_.saveInfo.entities) { 5285 auto *symbol{FindInScope(name)}; 5286 if (!symbol) { 5287 // error was reported 5288 } else if (specPartState_.saveInfo.saveAll) { 5289 // C889 - note that pgi, ifort, xlf do not enforce this constraint 5290 Say2(name, 5291 "Explicit SAVE of '%s' is redundant due to global SAVE statement"_warn_en_US, 5292 *specPartState_.saveInfo.saveAll, "Global SAVE statement"_en_US); 5293 } else if (auto msg{CheckSaveAttr(*symbol)}) { 5294 Say(name, std::move(*msg)); 5295 context().SetError(*symbol); 5296 } else { 5297 SetSaveAttr(*symbol); 5298 } 5299 } 5300 for (const SourceName &name : specPartState_.saveInfo.commons) { 5301 if (auto *symbol{currScope().FindCommonBlock(name)}) { 5302 auto &objects{symbol->get<CommonBlockDetails>().objects()}; 5303 if (objects.empty()) { 5304 if (currScope().kind() != Scope::Kind::Block) { 5305 Say(name, 5306 "'%s' appears as a COMMON block in a SAVE statement but not in" 5307 " a COMMON statement"_err_en_US); 5308 } else { // C1108 5309 Say(name, 5310 "SAVE statement in BLOCK construct may not contain a" 5311 " common block name '%s'"_err_en_US); 5312 } 5313 } else { 5314 for (auto &object : symbol->get<CommonBlockDetails>().objects()) { 5315 SetSaveAttr(*object); 5316 } 5317 } 5318 } 5319 } 5320 if (specPartState_.saveInfo.saveAll) { 5321 // Apply SAVE attribute to applicable symbols 5322 for (auto pair : currScope()) { 5323 auto &symbol{*pair.second}; 5324 if (!CheckSaveAttr(symbol)) { 5325 SetSaveAttr(symbol); 5326 } 5327 } 5328 } 5329 specPartState_.saveInfo = {}; 5330 } 5331 5332 // If SAVE attribute can't be set on symbol, return error message. 5333 std::optional<MessageFixedText> DeclarationVisitor::CheckSaveAttr( 5334 const Symbol &symbol) { 5335 if (IsDummy(symbol)) { 5336 return "SAVE attribute may not be applied to dummy argument '%s'"_err_en_US; 5337 } else if (symbol.IsFuncResult()) { 5338 return "SAVE attribute may not be applied to function result '%s'"_err_en_US; 5339 } else if (symbol.has<ProcEntityDetails>() && 5340 !symbol.attrs().test(Attr::POINTER)) { 5341 return "Procedure '%s' with SAVE attribute must also have POINTER attribute"_err_en_US; 5342 } else if (IsAutomatic(symbol)) { 5343 return "SAVE attribute may not be applied to automatic data object '%s'"_err_en_US; 5344 } else { 5345 return std::nullopt; 5346 } 5347 } 5348 5349 // Record SAVEd names in specPartState_.saveInfo.entities. 5350 Attrs DeclarationVisitor::HandleSaveName(const SourceName &name, Attrs attrs) { 5351 if (attrs.test(Attr::SAVE)) { 5352 AddSaveName(specPartState_.saveInfo.entities, name); 5353 } 5354 return attrs; 5355 } 5356 5357 // Record a name in a set of those to be saved. 5358 void DeclarationVisitor::AddSaveName( 5359 std::set<SourceName> &set, const SourceName &name) { 5360 auto pair{set.insert(name)}; 5361 if (!pair.second) { 5362 Say2(name, "SAVE attribute was already specified on '%s'"_warn_en_US, 5363 *pair.first, "Previous specification of SAVE attribute"_en_US); 5364 } 5365 } 5366 5367 // Set the SAVE attribute on symbol unless it is implicitly saved anyway. 5368 void DeclarationVisitor::SetSaveAttr(Symbol &symbol) { 5369 if (!IsSaved(symbol)) { 5370 symbol.attrs().set(Attr::SAVE); 5371 } 5372 } 5373 5374 // Check types of common block objects, now that they are known. 5375 void DeclarationVisitor::CheckCommonBlocks() { 5376 // check for empty common blocks 5377 for (const auto &pair : currScope().commonBlocks()) { 5378 const auto &symbol{*pair.second}; 5379 if (symbol.get<CommonBlockDetails>().objects().empty() && 5380 symbol.attrs().test(Attr::BIND_C)) { 5381 Say(symbol.name(), 5382 "'%s' appears as a COMMON block in a BIND statement but not in" 5383 " a COMMON statement"_err_en_US); 5384 } 5385 } 5386 // check objects in common blocks 5387 for (const auto &name : specPartState_.commonBlockObjects) { 5388 const auto *symbol{currScope().FindSymbol(name)}; 5389 if (!symbol) { 5390 continue; 5391 } 5392 const auto &attrs{symbol->attrs()}; 5393 if (attrs.test(Attr::ALLOCATABLE)) { 5394 Say(name, 5395 "ALLOCATABLE object '%s' may not appear in a COMMON block"_err_en_US); 5396 } else if (attrs.test(Attr::BIND_C)) { 5397 Say(name, 5398 "Variable '%s' with BIND attribute may not appear in a COMMON block"_err_en_US); 5399 } else if (IsNamedConstant(*symbol)) { 5400 Say(name, 5401 "A named constant '%s' may not appear in a COMMON block"_err_en_US); 5402 } else if (IsDummy(*symbol)) { 5403 Say(name, 5404 "Dummy argument '%s' may not appear in a COMMON block"_err_en_US); 5405 } else if (symbol->IsFuncResult()) { 5406 Say(name, 5407 "Function result '%s' may not appear in a COMMON block"_err_en_US); 5408 } else if (const DeclTypeSpec * type{symbol->GetType()}) { 5409 if (type->category() == DeclTypeSpec::ClassStar) { 5410 Say(name, 5411 "Unlimited polymorphic pointer '%s' may not appear in a COMMON block"_err_en_US); 5412 } else if (const auto *derived{type->AsDerived()}) { 5413 auto &typeSymbol{derived->typeSymbol()}; 5414 if (!typeSymbol.attrs().test(Attr::BIND_C) && 5415 !typeSymbol.get<DerivedTypeDetails>().sequence()) { 5416 Say(name, 5417 "Derived type '%s' in COMMON block must have the BIND or" 5418 " SEQUENCE attribute"_err_en_US); 5419 } 5420 CheckCommonBlockDerivedType(name, typeSymbol); 5421 } 5422 } 5423 } 5424 specPartState_.commonBlockObjects = {}; 5425 } 5426 5427 Symbol &DeclarationVisitor::MakeCommonBlockSymbol(const parser::Name &name) { 5428 return Resolve(name, currScope().MakeCommonBlock(name.source)); 5429 } 5430 Symbol &DeclarationVisitor::MakeCommonBlockSymbol( 5431 const std::optional<parser::Name> &name) { 5432 if (name) { 5433 return MakeCommonBlockSymbol(*name); 5434 } else { 5435 return MakeCommonBlockSymbol(parser::Name{}); 5436 } 5437 } 5438 5439 bool DeclarationVisitor::NameIsKnownOrIntrinsic(const parser::Name &name) { 5440 return FindSymbol(name) || HandleUnrestrictedSpecificIntrinsicFunction(name); 5441 } 5442 5443 // Check if this derived type can be in a COMMON block. 5444 void DeclarationVisitor::CheckCommonBlockDerivedType( 5445 const SourceName &name, const Symbol &typeSymbol) { 5446 if (const auto *scope{typeSymbol.scope()}) { 5447 for (const auto &pair : *scope) { 5448 const Symbol &component{*pair.second}; 5449 if (component.attrs().test(Attr::ALLOCATABLE)) { 5450 Say2(name, 5451 "Derived type variable '%s' may not appear in a COMMON block" 5452 " due to ALLOCATABLE component"_err_en_US, 5453 component.name(), "Component with ALLOCATABLE attribute"_en_US); 5454 return; 5455 } 5456 const auto *details{component.detailsIf<ObjectEntityDetails>()}; 5457 if (component.test(Symbol::Flag::InDataStmt) || 5458 (details && details->init())) { 5459 Say2(name, 5460 "Derived type variable '%s' may not appear in a COMMON block due to component with default initialization"_err_en_US, 5461 component.name(), "Component with default initialization"_en_US); 5462 return; 5463 } 5464 if (details) { 5465 if (const auto *type{details->type()}) { 5466 if (const auto *derived{type->AsDerived()}) { 5467 CheckCommonBlockDerivedType(name, derived->typeSymbol()); 5468 } 5469 } 5470 } 5471 } 5472 } 5473 } 5474 5475 bool DeclarationVisitor::HandleUnrestrictedSpecificIntrinsicFunction( 5476 const parser::Name &name) { 5477 if (auto interface{context().intrinsics().IsSpecificIntrinsicFunction( 5478 name.source.ToString())}) { 5479 // Unrestricted specific intrinsic function names (e.g., "cos") 5480 // are acceptable as procedure interfaces. The presence of the 5481 // INTRINSIC flag will cause this symbol to have a complete interface 5482 // recreated for it later on demand, but capturing its result type here 5483 // will make GetType() return a correct result without having to 5484 // probe the intrinsics table again. 5485 Symbol &symbol{ 5486 MakeSymbol(InclusiveScope(), name.source, Attrs{Attr::INTRINSIC})}; 5487 CHECK(interface->functionResult.has_value()); 5488 evaluate::DynamicType dyType{ 5489 DEREF(interface->functionResult->GetTypeAndShape()).type()}; 5490 CHECK(common::IsNumericTypeCategory(dyType.category())); 5491 const DeclTypeSpec &typeSpec{ 5492 MakeNumericType(dyType.category(), dyType.kind())}; 5493 ProcEntityDetails details; 5494 ProcInterface procInterface; 5495 procInterface.set_type(typeSpec); 5496 details.set_interface(procInterface); 5497 symbol.set_details(std::move(details)); 5498 symbol.set(Symbol::Flag::Function); 5499 if (interface->IsElemental()) { 5500 symbol.attrs().set(Attr::ELEMENTAL); 5501 } 5502 if (interface->IsPure()) { 5503 symbol.attrs().set(Attr::PURE); 5504 } 5505 Resolve(name, symbol); 5506 return true; 5507 } else { 5508 return false; 5509 } 5510 } 5511 5512 // Checks for all locality-specs: LOCAL, LOCAL_INIT, and SHARED 5513 bool DeclarationVisitor::PassesSharedLocalityChecks( 5514 const parser::Name &name, Symbol &symbol) { 5515 if (!IsVariableName(symbol)) { 5516 SayLocalMustBeVariable(name, symbol); // C1124 5517 return false; 5518 } 5519 if (symbol.owner() == currScope()) { // C1125 and C1126 5520 SayAlreadyDeclared(name, symbol); 5521 return false; 5522 } 5523 return true; 5524 } 5525 5526 // Checks for locality-specs LOCAL and LOCAL_INIT 5527 bool DeclarationVisitor::PassesLocalityChecks( 5528 const parser::Name &name, Symbol &symbol) { 5529 if (IsAllocatable(symbol)) { // C1128 5530 SayWithDecl(name, symbol, 5531 "ALLOCATABLE variable '%s' not allowed in a locality-spec"_err_en_US); 5532 return false; 5533 } 5534 if (IsOptional(symbol)) { // C1128 5535 SayWithDecl(name, symbol, 5536 "OPTIONAL argument '%s' not allowed in a locality-spec"_err_en_US); 5537 return false; 5538 } 5539 if (IsIntentIn(symbol)) { // C1128 5540 SayWithDecl(name, symbol, 5541 "INTENT IN argument '%s' not allowed in a locality-spec"_err_en_US); 5542 return false; 5543 } 5544 if (IsFinalizable(symbol)) { // C1128 5545 SayWithDecl(name, symbol, 5546 "Finalizable variable '%s' not allowed in a locality-spec"_err_en_US); 5547 return false; 5548 } 5549 if (evaluate::IsCoarray(symbol)) { // C1128 5550 SayWithDecl( 5551 name, symbol, "Coarray '%s' not allowed in a locality-spec"_err_en_US); 5552 return false; 5553 } 5554 if (const DeclTypeSpec * type{symbol.GetType()}) { 5555 if (type->IsPolymorphic() && IsDummy(symbol) && 5556 !IsPointer(symbol)) { // C1128 5557 SayWithDecl(name, symbol, 5558 "Nonpointer polymorphic argument '%s' not allowed in a " 5559 "locality-spec"_err_en_US); 5560 return false; 5561 } 5562 } 5563 if (IsAssumedSizeArray(symbol)) { // C1128 5564 SayWithDecl(name, symbol, 5565 "Assumed size array '%s' not allowed in a locality-spec"_err_en_US); 5566 return false; 5567 } 5568 if (std::optional<Message> msg{WhyNotModifiable(symbol, currScope())}) { 5569 SayWithReason(name, symbol, 5570 "'%s' may not appear in a locality-spec because it is not " 5571 "definable"_err_en_US, 5572 std::move(*msg)); 5573 return false; 5574 } 5575 return PassesSharedLocalityChecks(name, symbol); 5576 } 5577 5578 Symbol &DeclarationVisitor::FindOrDeclareEnclosingEntity( 5579 const parser::Name &name) { 5580 Symbol *prev{FindSymbol(name)}; 5581 if (!prev) { 5582 // Declare the name as an object in the enclosing scope so that 5583 // the name can't be repurposed there later as something else. 5584 prev = &MakeSymbol(InclusiveScope(), name.source, Attrs{}); 5585 ConvertToObjectEntity(*prev); 5586 ApplyImplicitRules(*prev); 5587 } 5588 return *prev; 5589 } 5590 5591 Symbol *DeclarationVisitor::DeclareLocalEntity(const parser::Name &name) { 5592 Symbol &prev{FindOrDeclareEnclosingEntity(name)}; 5593 if (!PassesLocalityChecks(name, prev)) { 5594 return nullptr; 5595 } 5596 return &MakeHostAssocSymbol(name, prev); 5597 } 5598 5599 Symbol *DeclarationVisitor::DeclareStatementEntity( 5600 const parser::DoVariable &doVar, 5601 const std::optional<parser::IntegerTypeSpec> &type) { 5602 const parser::Name &name{doVar.thing.thing}; 5603 const DeclTypeSpec *declTypeSpec{nullptr}; 5604 if (auto *prev{FindSymbol(name)}) { 5605 if (prev->owner() == currScope()) { 5606 SayAlreadyDeclared(name, *prev); 5607 return nullptr; 5608 } 5609 name.symbol = nullptr; 5610 declTypeSpec = prev->GetType(); 5611 } 5612 Symbol &symbol{DeclareEntity<ObjectEntityDetails>(name, {})}; 5613 if (!symbol.has<ObjectEntityDetails>()) { 5614 return nullptr; // error was reported in DeclareEntity 5615 } 5616 if (type) { 5617 declTypeSpec = ProcessTypeSpec(*type); 5618 } 5619 if (declTypeSpec) { 5620 // Subtlety: Don't let a "*length" specifier (if any is pending) affect the 5621 // declaration of this implied DO loop control variable. 5622 auto restorer{ 5623 common::ScopedSet(charInfo_.length, std::optional<ParamValue>{})}; 5624 SetType(name, *declTypeSpec); 5625 } else { 5626 ApplyImplicitRules(symbol); 5627 } 5628 Symbol *result{Resolve(name, &symbol)}; 5629 AnalyzeExpr(context(), doVar); // enforce INTEGER type 5630 return result; 5631 } 5632 5633 // Set the type of an entity or report an error. 5634 void DeclarationVisitor::SetType( 5635 const parser::Name &name, const DeclTypeSpec &type) { 5636 CHECK(name.symbol); 5637 auto &symbol{*name.symbol}; 5638 if (charInfo_.length) { // Declaration has "*length" (R723) 5639 auto length{std::move(*charInfo_.length)}; 5640 charInfo_.length.reset(); 5641 if (type.category() == DeclTypeSpec::Character) { 5642 auto kind{type.characterTypeSpec().kind()}; 5643 // Recurse with correct type. 5644 SetType(name, 5645 currScope().MakeCharacterType(std::move(length), std::move(kind))); 5646 return; 5647 } else { // C753 5648 Say(name, 5649 "A length specifier cannot be used to declare the non-character entity '%s'"_err_en_US); 5650 } 5651 } 5652 auto *prevType{symbol.GetType()}; 5653 if (!prevType) { 5654 symbol.SetType(type); 5655 } else if (symbol.has<UseDetails>()) { 5656 // error recovery case, redeclaration of use-associated name 5657 } else if (HadForwardRef(symbol)) { 5658 // error recovery after use of host-associated name 5659 } else if (!symbol.test(Symbol::Flag::Implicit)) { 5660 SayWithDecl( 5661 name, symbol, "The type of '%s' has already been declared"_err_en_US); 5662 context().SetError(symbol); 5663 } else if (type != *prevType) { 5664 SayWithDecl(name, symbol, 5665 "The type of '%s' has already been implicitly declared"_err_en_US); 5666 context().SetError(symbol); 5667 } else { 5668 symbol.set(Symbol::Flag::Implicit, false); 5669 } 5670 } 5671 5672 std::optional<DerivedTypeSpec> DeclarationVisitor::ResolveDerivedType( 5673 const parser::Name &name) { 5674 Scope &outer{NonDerivedTypeScope()}; 5675 Symbol *symbol{FindSymbol(outer, name)}; 5676 Symbol *ultimate{symbol ? &symbol->GetUltimate() : nullptr}; 5677 auto *generic{ultimate ? ultimate->detailsIf<GenericDetails>() : nullptr}; 5678 if (generic) { 5679 if (Symbol * genDT{generic->derivedType()}) { 5680 symbol = genDT; 5681 generic = nullptr; 5682 } 5683 } 5684 if (!symbol || symbol->has<UnknownDetails>() || 5685 (generic && &ultimate->owner() == &outer)) { 5686 if (allowForwardReferenceToDerivedType()) { 5687 if (!symbol) { 5688 symbol = &MakeSymbol(outer, name.source, Attrs{}); 5689 Resolve(name, *symbol); 5690 } else if (generic) { 5691 // forward ref to type with later homonymous generic 5692 symbol = &outer.MakeSymbol(name.source, Attrs{}, UnknownDetails{}); 5693 generic->set_derivedType(*symbol); 5694 name.symbol = symbol; 5695 } 5696 DerivedTypeDetails details; 5697 details.set_isForwardReferenced(true); 5698 symbol->set_details(std::move(details)); 5699 } else { // C732 5700 Say(name, "Derived type '%s' not found"_err_en_US); 5701 return std::nullopt; 5702 } 5703 } 5704 if (CheckUseError(name)) { 5705 return std::nullopt; 5706 } 5707 symbol = &symbol->GetUltimate(); 5708 if (symbol->has<DerivedTypeDetails>()) { 5709 return DerivedTypeSpec{name.source, *symbol}; 5710 } else { 5711 Say(name, "'%s' is not a derived type"_err_en_US); 5712 return std::nullopt; 5713 } 5714 } 5715 5716 std::optional<DerivedTypeSpec> DeclarationVisitor::ResolveExtendsType( 5717 const parser::Name &typeName, const parser::Name *extendsName) { 5718 if (!extendsName) { 5719 return std::nullopt; 5720 } else if (typeName.source == extendsName->source) { 5721 Say(extendsName->source, 5722 "Derived type '%s' cannot extend itself"_err_en_US); 5723 return std::nullopt; 5724 } else { 5725 return ResolveDerivedType(*extendsName); 5726 } 5727 } 5728 5729 Symbol *DeclarationVisitor::NoteInterfaceName(const parser::Name &name) { 5730 // The symbol is checked later by CheckExplicitInterface() and 5731 // CheckBindings(). It can be a forward reference. 5732 if (!NameIsKnownOrIntrinsic(name)) { 5733 Symbol &symbol{MakeSymbol(InclusiveScope(), name.source, Attrs{})}; 5734 Resolve(name, symbol); 5735 } 5736 return name.symbol; 5737 } 5738 5739 void DeclarationVisitor::CheckExplicitInterface(const parser::Name &name) { 5740 if (const Symbol * symbol{name.symbol}) { 5741 if (!context().HasError(*symbol) && !symbol->HasExplicitInterface()) { 5742 Say(name, 5743 "'%s' must be an abstract interface or a procedure with " 5744 "an explicit interface"_err_en_US, 5745 symbol->name()); 5746 } 5747 } 5748 } 5749 5750 // Create a symbol for a type parameter, component, or procedure binding in 5751 // the current derived type scope. Return false on error. 5752 Symbol *DeclarationVisitor::MakeTypeSymbol( 5753 const parser::Name &name, Details &&details) { 5754 return Resolve(name, MakeTypeSymbol(name.source, std::move(details))); 5755 } 5756 Symbol *DeclarationVisitor::MakeTypeSymbol( 5757 const SourceName &name, Details &&details) { 5758 Scope &derivedType{currScope()}; 5759 CHECK(derivedType.IsDerivedType()); 5760 if (auto *symbol{FindInScope(derivedType, name)}) { // C742 5761 Say2(name, 5762 "Type parameter, component, or procedure binding '%s'" 5763 " already defined in this type"_err_en_US, 5764 *symbol, "Previous definition of '%s'"_en_US); 5765 return nullptr; 5766 } else { 5767 auto attrs{GetAttrs()}; 5768 // Apply binding-private-stmt if present and this is a procedure binding 5769 if (derivedTypeInfo_.privateBindings && 5770 !attrs.HasAny({Attr::PUBLIC, Attr::PRIVATE}) && 5771 std::holds_alternative<ProcBindingDetails>(details)) { 5772 attrs.set(Attr::PRIVATE); 5773 } 5774 Symbol &result{MakeSymbol(name, attrs, std::move(details))}; 5775 if (result.has<TypeParamDetails>()) { 5776 derivedType.symbol()->get<DerivedTypeDetails>().add_paramDecl(result); 5777 } 5778 return &result; 5779 } 5780 } 5781 5782 // Return true if it is ok to declare this component in the current scope. 5783 // Otherwise, emit an error and return false. 5784 bool DeclarationVisitor::OkToAddComponent( 5785 const parser::Name &name, const Symbol *extends) { 5786 for (const Scope *scope{&currScope()}; scope;) { 5787 CHECK(scope->IsDerivedType()); 5788 if (auto *prev{FindInScope(*scope, name)}) { 5789 if (!context().HasError(*prev)) { 5790 parser::MessageFixedText msg; 5791 if (extends) { 5792 msg = "Type cannot be extended as it has a component named" 5793 " '%s'"_err_en_US; 5794 } else if (prev->test(Symbol::Flag::ParentComp)) { 5795 msg = "'%s' is a parent type of this type and so cannot be" 5796 " a component"_err_en_US; 5797 } else if (scope != &currScope()) { 5798 msg = "Component '%s' is already declared in a parent of this" 5799 " derived type"_err_en_US; 5800 } else { 5801 msg = "Component '%s' is already declared in this" 5802 " derived type"_err_en_US; 5803 } 5804 Say2(name, std::move(msg), *prev, "Previous declaration of '%s'"_en_US); 5805 } 5806 return false; 5807 } 5808 if (scope == &currScope() && extends) { 5809 // The parent component has not yet been added to the scope. 5810 scope = extends->scope(); 5811 } else { 5812 scope = scope->GetDerivedTypeParent(); 5813 } 5814 } 5815 return true; 5816 } 5817 5818 ParamValue DeclarationVisitor::GetParamValue( 5819 const parser::TypeParamValue &x, common::TypeParamAttr attr) { 5820 return common::visit( 5821 common::visitors{ 5822 [=](const parser::ScalarIntExpr &x) { // C704 5823 return ParamValue{EvaluateIntExpr(x), attr}; 5824 }, 5825 [=](const parser::Star &) { return ParamValue::Assumed(attr); }, 5826 [=](const parser::TypeParamValue::Deferred &) { 5827 return ParamValue::Deferred(attr); 5828 }, 5829 }, 5830 x.u); 5831 } 5832 5833 // ConstructVisitor implementation 5834 5835 void ConstructVisitor::ResolveIndexName( 5836 const parser::ConcurrentControl &control) { 5837 const parser::Name &name{std::get<parser::Name>(control.t)}; 5838 auto *prev{FindSymbol(name)}; 5839 if (prev) { 5840 if (prev->owner().kind() == Scope::Kind::Forall || 5841 prev->owner() == currScope()) { 5842 SayAlreadyDeclared(name, *prev); 5843 return; 5844 } 5845 name.symbol = nullptr; 5846 } 5847 auto &symbol{DeclareObjectEntity(name)}; 5848 if (symbol.GetType()) { 5849 // type came from explicit type-spec 5850 } else if (!prev) { 5851 ApplyImplicitRules(symbol); 5852 } else { 5853 const Symbol &prevRoot{ResolveAssociations(*prev)}; 5854 // prev could be host- use- or construct-associated with another symbol 5855 if (!prevRoot.has<ObjectEntityDetails>() && 5856 !prevRoot.has<EntityDetails>()) { 5857 Say2(name, "Index name '%s' conflicts with existing identifier"_err_en_US, 5858 *prev, "Previous declaration of '%s'"_en_US); 5859 context().SetError(symbol); 5860 return; 5861 } else { 5862 if (const auto *type{prevRoot.GetType()}) { 5863 symbol.SetType(*type); 5864 } 5865 if (prevRoot.IsObjectArray()) { 5866 SayWithDecl(name, *prev, "Index variable '%s' is not scalar"_err_en_US); 5867 return; 5868 } 5869 } 5870 } 5871 EvaluateExpr(parser::Scalar{parser::Integer{common::Clone(name)}}); 5872 } 5873 5874 // We need to make sure that all of the index-names get declared before the 5875 // expressions in the loop control are evaluated so that references to the 5876 // index-names in the expressions are correctly detected. 5877 bool ConstructVisitor::Pre(const parser::ConcurrentHeader &header) { 5878 BeginDeclTypeSpec(); 5879 Walk(std::get<std::optional<parser::IntegerTypeSpec>>(header.t)); 5880 const auto &controls{ 5881 std::get<std::list<parser::ConcurrentControl>>(header.t)}; 5882 for (const auto &control : controls) { 5883 ResolveIndexName(control); 5884 } 5885 Walk(controls); 5886 Walk(std::get<std::optional<parser::ScalarLogicalExpr>>(header.t)); 5887 EndDeclTypeSpec(); 5888 return false; 5889 } 5890 5891 bool ConstructVisitor::Pre(const parser::LocalitySpec::Local &x) { 5892 for (auto &name : x.v) { 5893 if (auto *symbol{DeclareLocalEntity(name)}) { 5894 symbol->set(Symbol::Flag::LocalityLocal); 5895 } 5896 } 5897 return false; 5898 } 5899 5900 bool ConstructVisitor::Pre(const parser::LocalitySpec::LocalInit &x) { 5901 for (auto &name : x.v) { 5902 if (auto *symbol{DeclareLocalEntity(name)}) { 5903 symbol->set(Symbol::Flag::LocalityLocalInit); 5904 } 5905 } 5906 return false; 5907 } 5908 5909 bool ConstructVisitor::Pre(const parser::LocalitySpec::Shared &x) { 5910 for (const auto &name : x.v) { 5911 if (!FindSymbol(name)) { 5912 Say(name, 5913 "Variable '%s' with SHARED locality implicitly declared"_warn_en_US); 5914 } 5915 Symbol &prev{FindOrDeclareEnclosingEntity(name)}; 5916 if (PassesSharedLocalityChecks(name, prev)) { 5917 MakeHostAssocSymbol(name, prev).set(Symbol::Flag::LocalityShared); 5918 } 5919 } 5920 return false; 5921 } 5922 5923 bool ConstructVisitor::Pre(const parser::AcSpec &x) { 5924 ProcessTypeSpec(x.type); 5925 Walk(x.values); 5926 return false; 5927 } 5928 5929 // Section 19.4, paragraph 5 says that each ac-do-variable has the scope of the 5930 // enclosing ac-implied-do 5931 bool ConstructVisitor::Pre(const parser::AcImpliedDo &x) { 5932 auto &values{std::get<std::list<parser::AcValue>>(x.t)}; 5933 auto &control{std::get<parser::AcImpliedDoControl>(x.t)}; 5934 auto &type{std::get<std::optional<parser::IntegerTypeSpec>>(control.t)}; 5935 auto &bounds{std::get<parser::AcImpliedDoControl::Bounds>(control.t)}; 5936 // F'2018 has the scope of the implied DO variable covering the entire 5937 // implied DO production (19.4(5)), which seems wrong in cases where the name 5938 // of the implied DO variable appears in one of the bound expressions. Thus 5939 // this extension, which shrinks the scope of the variable to exclude the 5940 // expressions in the bounds. 5941 auto restore{BeginCheckOnIndexUseInOwnBounds(bounds.name)}; 5942 Walk(bounds.lower); 5943 Walk(bounds.upper); 5944 Walk(bounds.step); 5945 EndCheckOnIndexUseInOwnBounds(restore); 5946 PushScope(Scope::Kind::ImpliedDos, nullptr); 5947 DeclareStatementEntity(bounds.name, type); 5948 Walk(values); 5949 PopScope(); 5950 return false; 5951 } 5952 5953 bool ConstructVisitor::Pre(const parser::DataImpliedDo &x) { 5954 auto &objects{std::get<std::list<parser::DataIDoObject>>(x.t)}; 5955 auto &type{std::get<std::optional<parser::IntegerTypeSpec>>(x.t)}; 5956 auto &bounds{std::get<parser::DataImpliedDo::Bounds>(x.t)}; 5957 // See comment in Pre(AcImpliedDo) above. 5958 auto restore{BeginCheckOnIndexUseInOwnBounds(bounds.name)}; 5959 Walk(bounds.lower); 5960 Walk(bounds.upper); 5961 Walk(bounds.step); 5962 EndCheckOnIndexUseInOwnBounds(restore); 5963 bool pushScope{currScope().kind() != Scope::Kind::ImpliedDos}; 5964 if (pushScope) { 5965 PushScope(Scope::Kind::ImpliedDos, nullptr); 5966 } 5967 DeclareStatementEntity(bounds.name, type); 5968 Walk(objects); 5969 if (pushScope) { 5970 PopScope(); 5971 } 5972 return false; 5973 } 5974 5975 // Sets InDataStmt flag on a variable (or misidentified function) in a DATA 5976 // statement so that the predicate IsInitialized() will be true 5977 // during semantic analysis before the symbol's initializer is constructed. 5978 bool ConstructVisitor::Pre(const parser::DataIDoObject &x) { 5979 common::visit( 5980 common::visitors{ 5981 [&](const parser::Scalar<Indirection<parser::Designator>> &y) { 5982 Walk(y.thing.value()); 5983 const parser::Name &first{parser::GetFirstName(y.thing.value())}; 5984 if (first.symbol) { 5985 first.symbol->set(Symbol::Flag::InDataStmt); 5986 } 5987 }, 5988 [&](const Indirection<parser::DataImpliedDo> &y) { Walk(y.value()); }, 5989 }, 5990 x.u); 5991 return false; 5992 } 5993 5994 bool ConstructVisitor::Pre(const parser::DataStmtObject &x) { 5995 // Subtle: DATA statements may appear in both the specification and 5996 // execution parts, but should be treated as if in the execution part 5997 // for purposes of implicit variable declaration vs. host association. 5998 // When a name first appears as an object in a DATA statement, it should 5999 // be implicitly declared locally as if it had been assigned. 6000 auto flagRestorer{common::ScopedSet(inSpecificationPart_, false)}; 6001 common::visit(common::visitors{ 6002 [&](const Indirection<parser::Variable> &y) { 6003 Walk(y.value()); 6004 const parser::Name &first{ 6005 parser::GetFirstName(y.value())}; 6006 if (first.symbol) { 6007 first.symbol->set(Symbol::Flag::InDataStmt); 6008 } 6009 }, 6010 [&](const parser::DataImpliedDo &y) { 6011 PushScope(Scope::Kind::ImpliedDos, nullptr); 6012 Walk(y); 6013 PopScope(); 6014 }, 6015 }, 6016 x.u); 6017 return false; 6018 } 6019 6020 bool ConstructVisitor::Pre(const parser::DataStmtValue &x) { 6021 const auto &data{std::get<parser::DataStmtConstant>(x.t)}; 6022 auto &mutableData{const_cast<parser::DataStmtConstant &>(data)}; 6023 if (auto *elem{parser::Unwrap<parser::ArrayElement>(mutableData)}) { 6024 if (const auto *name{std::get_if<parser::Name>(&elem->base.u)}) { 6025 if (const Symbol * symbol{FindSymbol(*name)}) { 6026 const Symbol &ultimate{symbol->GetUltimate()}; 6027 if (ultimate.has<DerivedTypeDetails>()) { 6028 mutableData.u = elem->ConvertToStructureConstructor( 6029 DerivedTypeSpec{name->source, ultimate}); 6030 } 6031 } 6032 } 6033 } 6034 return true; 6035 } 6036 6037 bool ConstructVisitor::Pre(const parser::DoConstruct &x) { 6038 if (x.IsDoConcurrent()) { 6039 PushScope(Scope::Kind::Block, nullptr); 6040 } 6041 return true; 6042 } 6043 void ConstructVisitor::Post(const parser::DoConstruct &x) { 6044 if (x.IsDoConcurrent()) { 6045 PopScope(); 6046 } 6047 } 6048 6049 bool ConstructVisitor::Pre(const parser::ForallConstruct &) { 6050 PushScope(Scope::Kind::Forall, nullptr); 6051 return true; 6052 } 6053 void ConstructVisitor::Post(const parser::ForallConstruct &) { PopScope(); } 6054 bool ConstructVisitor::Pre(const parser::ForallStmt &) { 6055 PushScope(Scope::Kind::Forall, nullptr); 6056 return true; 6057 } 6058 void ConstructVisitor::Post(const parser::ForallStmt &) { PopScope(); } 6059 6060 bool ConstructVisitor::Pre(const parser::BlockStmt &x) { 6061 CheckDef(x.v); 6062 PushScope(Scope::Kind::Block, nullptr); 6063 return false; 6064 } 6065 bool ConstructVisitor::Pre(const parser::EndBlockStmt &x) { 6066 PopScope(); 6067 CheckRef(x.v); 6068 return false; 6069 } 6070 6071 void ConstructVisitor::Post(const parser::Selector &x) { 6072 GetCurrentAssociation().selector = ResolveSelector(x); 6073 } 6074 6075 void ConstructVisitor::Post(const parser::AssociateStmt &x) { 6076 CheckDef(x.t); 6077 PushScope(Scope::Kind::Block, nullptr); 6078 const auto assocCount{std::get<std::list<parser::Association>>(x.t).size()}; 6079 for (auto nthLastAssoc{assocCount}; nthLastAssoc > 0; --nthLastAssoc) { 6080 SetCurrentAssociation(nthLastAssoc); 6081 if (auto *symbol{MakeAssocEntity()}) { 6082 if (ExtractCoarrayRef(GetCurrentAssociation().selector.expr)) { // C1103 6083 Say("Selector must not be a coindexed object"_err_en_US); 6084 } 6085 SetTypeFromAssociation(*symbol); 6086 SetAttrsFromAssociation(*symbol); 6087 } 6088 } 6089 PopAssociation(assocCount); 6090 } 6091 6092 void ConstructVisitor::Post(const parser::EndAssociateStmt &x) { 6093 PopScope(); 6094 CheckRef(x.v); 6095 } 6096 6097 bool ConstructVisitor::Pre(const parser::Association &x) { 6098 PushAssociation(); 6099 const auto &name{std::get<parser::Name>(x.t)}; 6100 GetCurrentAssociation().name = &name; 6101 return true; 6102 } 6103 6104 bool ConstructVisitor::Pre(const parser::ChangeTeamStmt &x) { 6105 CheckDef(x.t); 6106 PushScope(Scope::Kind::Block, nullptr); 6107 PushAssociation(); 6108 return true; 6109 } 6110 6111 void ConstructVisitor::Post(const parser::CoarrayAssociation &x) { 6112 const auto &decl{std::get<parser::CodimensionDecl>(x.t)}; 6113 const auto &name{std::get<parser::Name>(decl.t)}; 6114 if (auto *symbol{FindInScope(name)}) { 6115 const auto &selector{std::get<parser::Selector>(x.t)}; 6116 if (auto sel{ResolveSelector(selector)}) { 6117 const Symbol *whole{UnwrapWholeSymbolDataRef(sel.expr)}; 6118 if (!whole || whole->Corank() == 0) { 6119 Say(sel.source, // C1116 6120 "Selector in coarray association must name a coarray"_err_en_US); 6121 } else if (auto dynType{sel.expr->GetType()}) { 6122 if (!symbol->GetType()) { 6123 symbol->SetType(ToDeclTypeSpec(std::move(*dynType))); 6124 } 6125 } 6126 } 6127 } 6128 } 6129 6130 void ConstructVisitor::Post(const parser::EndChangeTeamStmt &x) { 6131 PopAssociation(); 6132 PopScope(); 6133 CheckRef(x.t); 6134 } 6135 6136 bool ConstructVisitor::Pre(const parser::SelectTypeConstruct &) { 6137 PushAssociation(); 6138 return true; 6139 } 6140 6141 void ConstructVisitor::Post(const parser::SelectTypeConstruct &) { 6142 PopAssociation(); 6143 } 6144 6145 void ConstructVisitor::Post(const parser::SelectTypeStmt &x) { 6146 auto &association{GetCurrentAssociation()}; 6147 if (const std::optional<parser::Name> &name{std::get<1>(x.t)}) { 6148 // This isn't a name in the current scope, it is in each TypeGuardStmt 6149 MakePlaceholder(*name, MiscDetails::Kind::SelectTypeAssociateName); 6150 association.name = &*name; 6151 auto exprType{association.selector.expr->GetType()}; 6152 if (ExtractCoarrayRef(association.selector.expr)) { // C1103 6153 Say("Selector must not be a coindexed object"_err_en_US); 6154 } 6155 if (exprType && !exprType->IsPolymorphic()) { // C1159 6156 Say(association.selector.source, 6157 "Selector '%s' in SELECT TYPE statement must be " 6158 "polymorphic"_err_en_US); 6159 } 6160 } else { 6161 if (const Symbol * 6162 whole{UnwrapWholeSymbolDataRef(association.selector.expr)}) { 6163 ConvertToObjectEntity(const_cast<Symbol &>(*whole)); 6164 if (!IsVariableName(*whole)) { 6165 Say(association.selector.source, // C901 6166 "Selector is not a variable"_err_en_US); 6167 association = {}; 6168 } 6169 if (const DeclTypeSpec * type{whole->GetType()}) { 6170 if (!type->IsPolymorphic()) { // C1159 6171 Say(association.selector.source, 6172 "Selector '%s' in SELECT TYPE statement must be " 6173 "polymorphic"_err_en_US); 6174 } 6175 } 6176 } else { 6177 Say(association.selector.source, // C1157 6178 "Selector is not a named variable: 'associate-name =>' is required"_err_en_US); 6179 association = {}; 6180 } 6181 } 6182 } 6183 6184 void ConstructVisitor::Post(const parser::SelectRankStmt &x) { 6185 auto &association{GetCurrentAssociation()}; 6186 if (const std::optional<parser::Name> &name{std::get<1>(x.t)}) { 6187 // This isn't a name in the current scope, it is in each SelectRankCaseStmt 6188 MakePlaceholder(*name, MiscDetails::Kind::SelectRankAssociateName); 6189 association.name = &*name; 6190 } 6191 } 6192 6193 bool ConstructVisitor::Pre(const parser::SelectTypeConstruct::TypeCase &) { 6194 PushScope(Scope::Kind::Block, nullptr); 6195 return true; 6196 } 6197 void ConstructVisitor::Post(const parser::SelectTypeConstruct::TypeCase &) { 6198 PopScope(); 6199 } 6200 6201 bool ConstructVisitor::Pre(const parser::SelectRankConstruct::RankCase &) { 6202 PushScope(Scope::Kind::Block, nullptr); 6203 return true; 6204 } 6205 void ConstructVisitor::Post(const parser::SelectRankConstruct::RankCase &) { 6206 PopScope(); 6207 } 6208 6209 void ConstructVisitor::Post(const parser::TypeGuardStmt::Guard &x) { 6210 if (auto *symbol{MakeAssocEntity()}) { 6211 if (std::holds_alternative<parser::Default>(x.u)) { 6212 SetTypeFromAssociation(*symbol); 6213 } else if (const auto *type{GetDeclTypeSpec()}) { 6214 symbol->SetType(*type); 6215 } 6216 SetAttrsFromAssociation(*symbol); 6217 } 6218 } 6219 6220 void ConstructVisitor::Post(const parser::SelectRankCaseStmt::Rank &x) { 6221 if (auto *symbol{MakeAssocEntity()}) { 6222 SetTypeFromAssociation(*symbol); 6223 SetAttrsFromAssociation(*symbol); 6224 if (const auto *init{std::get_if<parser::ScalarIntConstantExpr>(&x.u)}) { 6225 if (auto val{EvaluateInt64(context(), *init)}) { 6226 auto &details{symbol->get<AssocEntityDetails>()}; 6227 details.set_rank(*val); 6228 } 6229 } 6230 } 6231 } 6232 6233 bool ConstructVisitor::Pre(const parser::SelectRankConstruct &) { 6234 PushAssociation(); 6235 return true; 6236 } 6237 6238 void ConstructVisitor::Post(const parser::SelectRankConstruct &) { 6239 PopAssociation(); 6240 } 6241 6242 bool ConstructVisitor::CheckDef(const std::optional<parser::Name> &x) { 6243 if (x) { 6244 MakeSymbol(*x, MiscDetails{MiscDetails::Kind::ConstructName}); 6245 } 6246 return true; 6247 } 6248 6249 void ConstructVisitor::CheckRef(const std::optional<parser::Name> &x) { 6250 if (x) { 6251 // Just add an occurrence of this name; checking is done in ValidateLabels 6252 FindSymbol(*x); 6253 } 6254 } 6255 6256 // Make a symbol for the associating entity of the current association. 6257 Symbol *ConstructVisitor::MakeAssocEntity() { 6258 Symbol *symbol{nullptr}; 6259 auto &association{GetCurrentAssociation()}; 6260 if (association.name) { 6261 symbol = &MakeSymbol(*association.name, UnknownDetails{}); 6262 if (symbol->has<AssocEntityDetails>() && symbol->owner() == currScope()) { 6263 Say(*association.name, // C1102 6264 "The associate name '%s' is already used in this associate statement"_err_en_US); 6265 return nullptr; 6266 } 6267 } else if (const Symbol * 6268 whole{UnwrapWholeSymbolDataRef(association.selector.expr)}) { 6269 symbol = &MakeSymbol(whole->name()); 6270 } else { 6271 return nullptr; 6272 } 6273 if (auto &expr{association.selector.expr}) { 6274 symbol->set_details(AssocEntityDetails{common::Clone(*expr)}); 6275 } else { 6276 symbol->set_details(AssocEntityDetails{}); 6277 } 6278 return symbol; 6279 } 6280 6281 // Set the type of symbol based on the current association selector. 6282 void ConstructVisitor::SetTypeFromAssociation(Symbol &symbol) { 6283 auto &details{symbol.get<AssocEntityDetails>()}; 6284 const MaybeExpr *pexpr{&details.expr()}; 6285 if (!*pexpr) { 6286 pexpr = &GetCurrentAssociation().selector.expr; 6287 } 6288 if (*pexpr) { 6289 const SomeExpr &expr{**pexpr}; 6290 if (std::optional<evaluate::DynamicType> type{expr.GetType()}) { 6291 if (const auto *charExpr{ 6292 evaluate::UnwrapExpr<evaluate::Expr<evaluate::SomeCharacter>>( 6293 expr)}) { 6294 symbol.SetType(ToDeclTypeSpec(std::move(*type), 6295 FoldExpr(common::visit( 6296 [](const auto &kindChar) { return kindChar.LEN(); }, 6297 charExpr->u)))); 6298 } else { 6299 symbol.SetType(ToDeclTypeSpec(std::move(*type))); 6300 } 6301 } else { 6302 // BOZ literals, procedure designators, &c. are not acceptable 6303 Say(symbol.name(), "Associate name '%s' must have a type"_err_en_US); 6304 } 6305 } 6306 } 6307 6308 // If current selector is a variable, set some of its attributes on symbol. 6309 void ConstructVisitor::SetAttrsFromAssociation(Symbol &symbol) { 6310 Attrs attrs{evaluate::GetAttrs(GetCurrentAssociation().selector.expr)}; 6311 symbol.attrs() |= attrs & 6312 Attrs{Attr::TARGET, Attr::ASYNCHRONOUS, Attr::VOLATILE, Attr::CONTIGUOUS}; 6313 if (attrs.test(Attr::POINTER)) { 6314 symbol.attrs().set(Attr::TARGET); 6315 } 6316 } 6317 6318 ConstructVisitor::Selector ConstructVisitor::ResolveSelector( 6319 const parser::Selector &x) { 6320 return common::visit(common::visitors{ 6321 [&](const parser::Expr &expr) { 6322 return Selector{expr.source, EvaluateExpr(x)}; 6323 }, 6324 [&](const parser::Variable &var) { 6325 return Selector{var.GetSource(), EvaluateExpr(x)}; 6326 }, 6327 }, 6328 x.u); 6329 } 6330 6331 // Set the current association to the nth to the last association on the 6332 // association stack. The top of the stack is at n = 1. This allows access 6333 // to the interior of a list of associations at the top of the stack. 6334 void ConstructVisitor::SetCurrentAssociation(std::size_t n) { 6335 CHECK(n > 0 && n <= associationStack_.size()); 6336 currentAssociation_ = &associationStack_[associationStack_.size() - n]; 6337 } 6338 6339 ConstructVisitor::Association &ConstructVisitor::GetCurrentAssociation() { 6340 CHECK(currentAssociation_); 6341 return *currentAssociation_; 6342 } 6343 6344 void ConstructVisitor::PushAssociation() { 6345 associationStack_.emplace_back(Association{}); 6346 currentAssociation_ = &associationStack_.back(); 6347 } 6348 6349 void ConstructVisitor::PopAssociation(std::size_t count) { 6350 CHECK(count > 0 && count <= associationStack_.size()); 6351 associationStack_.resize(associationStack_.size() - count); 6352 currentAssociation_ = 6353 associationStack_.empty() ? nullptr : &associationStack_.back(); 6354 } 6355 6356 const DeclTypeSpec &ConstructVisitor::ToDeclTypeSpec( 6357 evaluate::DynamicType &&type) { 6358 switch (type.category()) { 6359 SWITCH_COVERS_ALL_CASES 6360 case common::TypeCategory::Integer: 6361 case common::TypeCategory::Real: 6362 case common::TypeCategory::Complex: 6363 return context().MakeNumericType(type.category(), type.kind()); 6364 case common::TypeCategory::Logical: 6365 return context().MakeLogicalType(type.kind()); 6366 case common::TypeCategory::Derived: 6367 if (type.IsAssumedType()) { 6368 return currScope().MakeTypeStarType(); 6369 } else if (type.IsUnlimitedPolymorphic()) { 6370 return currScope().MakeClassStarType(); 6371 } else { 6372 return currScope().MakeDerivedType( 6373 type.IsPolymorphic() ? DeclTypeSpec::ClassDerived 6374 : DeclTypeSpec::TypeDerived, 6375 common::Clone(type.GetDerivedTypeSpec()) 6376 6377 ); 6378 } 6379 case common::TypeCategory::Character: 6380 CRASH_NO_CASE; 6381 } 6382 } 6383 6384 const DeclTypeSpec &ConstructVisitor::ToDeclTypeSpec( 6385 evaluate::DynamicType &&type, MaybeSubscriptIntExpr &&length) { 6386 CHECK(type.category() == common::TypeCategory::Character); 6387 if (length) { 6388 return currScope().MakeCharacterType( 6389 ParamValue{SomeIntExpr{*std::move(length)}, common::TypeParamAttr::Len}, 6390 KindExpr{type.kind()}); 6391 } else { 6392 return currScope().MakeCharacterType( 6393 ParamValue::Deferred(common::TypeParamAttr::Len), 6394 KindExpr{type.kind()}); 6395 } 6396 } 6397 6398 // ResolveNamesVisitor implementation 6399 6400 bool ResolveNamesVisitor::Pre(const parser::FunctionReference &x) { 6401 HandleCall(Symbol::Flag::Function, x.v); 6402 return false; 6403 } 6404 bool ResolveNamesVisitor::Pre(const parser::CallStmt &x) { 6405 HandleCall(Symbol::Flag::Subroutine, x.v); 6406 return false; 6407 } 6408 6409 bool ResolveNamesVisitor::Pre(const parser::ImportStmt &x) { 6410 auto &scope{currScope()}; 6411 // Check C896 and C899: where IMPORT statements are allowed 6412 switch (scope.kind()) { 6413 case Scope::Kind::Module: 6414 if (scope.IsModule()) { 6415 Say("IMPORT is not allowed in a module scoping unit"_err_en_US); 6416 return false; 6417 } else if (x.kind == common::ImportKind::None) { 6418 Say("IMPORT,NONE is not allowed in a submodule scoping unit"_err_en_US); 6419 return false; 6420 } 6421 break; 6422 case Scope::Kind::MainProgram: 6423 Say("IMPORT is not allowed in a main program scoping unit"_err_en_US); 6424 return false; 6425 case Scope::Kind::Subprogram: 6426 if (scope.parent().IsGlobal()) { 6427 Say("IMPORT is not allowed in an external subprogram scoping unit"_err_en_US); 6428 return false; 6429 } 6430 break; 6431 case Scope::Kind::BlockData: // C1415 (in part) 6432 Say("IMPORT is not allowed in a BLOCK DATA subprogram"_err_en_US); 6433 return false; 6434 default:; 6435 } 6436 if (auto error{scope.SetImportKind(x.kind)}) { 6437 Say(std::move(*error)); 6438 } 6439 for (auto &name : x.names) { 6440 if (FindSymbol(scope.parent(), name)) { 6441 scope.add_importName(name.source); 6442 } else { 6443 Say(name, "'%s' not found in host scope"_err_en_US); 6444 } 6445 } 6446 prevImportStmt_ = currStmtSource(); 6447 return false; 6448 } 6449 6450 const parser::Name *DeclarationVisitor::ResolveStructureComponent( 6451 const parser::StructureComponent &x) { 6452 return FindComponent(ResolveDataRef(x.base), x.component); 6453 } 6454 6455 const parser::Name *DeclarationVisitor::ResolveDesignator( 6456 const parser::Designator &x) { 6457 return common::visit( 6458 common::visitors{ 6459 [&](const parser::DataRef &x) { return ResolveDataRef(x); }, 6460 [&](const parser::Substring &x) { 6461 return ResolveDataRef(std::get<parser::DataRef>(x.t)); 6462 }, 6463 }, 6464 x.u); 6465 } 6466 6467 const parser::Name *DeclarationVisitor::ResolveDataRef( 6468 const parser::DataRef &x) { 6469 return common::visit( 6470 common::visitors{ 6471 [=](const parser::Name &y) { return ResolveName(y); }, 6472 [=](const Indirection<parser::StructureComponent> &y) { 6473 return ResolveStructureComponent(y.value()); 6474 }, 6475 [&](const Indirection<parser::ArrayElement> &y) { 6476 Walk(y.value().subscripts); 6477 const parser::Name *name{ResolveDataRef(y.value().base)}; 6478 if (name && name->symbol) { 6479 if (!IsProcedure(*name->symbol)) { 6480 ConvertToObjectEntity(*name->symbol); 6481 } else if (!context().HasError(*name->symbol)) { 6482 SayWithDecl(*name, *name->symbol, 6483 "Cannot reference function '%s' as data"_err_en_US); 6484 } 6485 } 6486 return name; 6487 }, 6488 [&](const Indirection<parser::CoindexedNamedObject> &y) { 6489 Walk(y.value().imageSelector); 6490 return ResolveDataRef(y.value().base); 6491 }, 6492 }, 6493 x.u); 6494 } 6495 6496 // If implicit types are allowed, ensure name is in the symbol table. 6497 // Otherwise, report an error if it hasn't been declared. 6498 const parser::Name *DeclarationVisitor::ResolveName(const parser::Name &name) { 6499 FindSymbol(name); 6500 if (CheckForHostAssociatedImplicit(name)) { 6501 NotePossibleBadForwardRef(name); 6502 return &name; 6503 } 6504 if (Symbol * symbol{name.symbol}) { 6505 if (CheckUseError(name)) { 6506 return nullptr; // reported an error 6507 } 6508 NotePossibleBadForwardRef(name); 6509 symbol->set(Symbol::Flag::ImplicitOrError, false); 6510 if (IsUplevelReference(*symbol)) { 6511 MakeHostAssocSymbol(name, *symbol); 6512 } else if (IsDummy(*symbol) || 6513 (!symbol->GetType() && FindCommonBlockContaining(*symbol))) { 6514 ConvertToObjectEntity(*symbol); 6515 ApplyImplicitRules(*symbol); 6516 } 6517 if (checkIndexUseInOwnBounds_ && 6518 *checkIndexUseInOwnBounds_ == name.source) { 6519 Say(name, 6520 "Implied DO index '%s' uses an object of the same name in its bounds expressions"_port_en_US, 6521 name.source); 6522 } 6523 return &name; 6524 } 6525 if (isImplicitNoneType()) { 6526 Say(name, "No explicit type declared for '%s'"_err_en_US); 6527 return nullptr; 6528 } 6529 // Create the symbol then ensure it is accessible 6530 if (checkIndexUseInOwnBounds_ && *checkIndexUseInOwnBounds_ == name.source) { 6531 Say(name, 6532 "Implied DO index '%s' uses itself in its own bounds expressions"_err_en_US, 6533 name.source); 6534 } 6535 MakeSymbol(InclusiveScope(), name.source, Attrs{}); 6536 auto *symbol{FindSymbol(name)}; 6537 if (!symbol) { 6538 Say(name, 6539 "'%s' from host scoping unit is not accessible due to IMPORT"_err_en_US); 6540 return nullptr; 6541 } 6542 ConvertToObjectEntity(*symbol); 6543 ApplyImplicitRules(*symbol); 6544 NotePossibleBadForwardRef(name); 6545 return &name; 6546 } 6547 6548 // A specification expression may refer to a symbol in the host procedure that 6549 // is implicitly typed. Because specification parts are processed before 6550 // execution parts, this may be the first time we see the symbol. It can't be a 6551 // local in the current scope (because it's in a specification expression) so 6552 // either it is implicitly declared in the host procedure or it is an error. 6553 // We create a symbol in the host assuming it is the former; if that proves to 6554 // be wrong we report an error later in CheckDeclarations(). 6555 bool DeclarationVisitor::CheckForHostAssociatedImplicit( 6556 const parser::Name &name) { 6557 if (!inSpecificationPart_) { 6558 return false; 6559 } 6560 if (name.symbol) { 6561 ApplyImplicitRules(*name.symbol, true); 6562 } 6563 Symbol *hostSymbol; 6564 Scope *host{GetHostProcedure()}; 6565 if (!host || isImplicitNoneType(*host)) { 6566 return false; 6567 } 6568 if (!name.symbol) { 6569 hostSymbol = &MakeSymbol(*host, name.source, Attrs{}); 6570 ConvertToObjectEntity(*hostSymbol); 6571 ApplyImplicitRules(*hostSymbol); 6572 hostSymbol->set(Symbol::Flag::ImplicitOrError); 6573 } else if (name.symbol->test(Symbol::Flag::ImplicitOrError)) { 6574 hostSymbol = name.symbol; 6575 } else { 6576 return false; 6577 } 6578 Symbol &symbol{MakeHostAssocSymbol(name, *hostSymbol)}; 6579 if (isImplicitNoneType()) { 6580 symbol.get<HostAssocDetails>().implicitOrExplicitTypeError = true; 6581 } else { 6582 symbol.get<HostAssocDetails>().implicitOrSpecExprError = true; 6583 } 6584 return true; 6585 } 6586 6587 bool DeclarationVisitor::IsUplevelReference(const Symbol &symbol) { 6588 const Scope &symbolUnit{GetProgramUnitContaining(symbol)}; 6589 if (symbolUnit == GetProgramUnitContaining(currScope())) { 6590 return false; 6591 } else { 6592 Scope::Kind kind{symbolUnit.kind()}; 6593 return kind == Scope::Kind::Subprogram || kind == Scope::Kind::MainProgram; 6594 } 6595 } 6596 6597 // base is a part-ref of a derived type; find the named component in its type. 6598 // Also handles intrinsic type parameter inquiries (%kind, %len) and 6599 // COMPLEX component references (%re, %im). 6600 const parser::Name *DeclarationVisitor::FindComponent( 6601 const parser::Name *base, const parser::Name &component) { 6602 if (!base || !base->symbol) { 6603 return nullptr; 6604 } 6605 if (auto *misc{base->symbol->detailsIf<MiscDetails>()}) { 6606 if (component.source == "kind") { 6607 if (misc->kind() == MiscDetails::Kind::ComplexPartRe || 6608 misc->kind() == MiscDetails::Kind::ComplexPartIm || 6609 misc->kind() == MiscDetails::Kind::KindParamInquiry || 6610 misc->kind() == MiscDetails::Kind::LenParamInquiry) { 6611 // x%{re,im,kind,len}%kind 6612 MakePlaceholder(component, MiscDetails::Kind::KindParamInquiry); 6613 return &component; 6614 } 6615 } 6616 } 6617 auto &symbol{base->symbol->GetUltimate()}; 6618 if (!symbol.has<AssocEntityDetails>() && !ConvertToObjectEntity(symbol)) { 6619 SayWithDecl(*base, symbol, 6620 "'%s' is an invalid base for a component reference"_err_en_US); 6621 return nullptr; 6622 } 6623 auto *type{symbol.GetType()}; 6624 if (!type) { 6625 return nullptr; // should have already reported error 6626 } 6627 if (const IntrinsicTypeSpec * intrinsic{type->AsIntrinsic()}) { 6628 auto category{intrinsic->category()}; 6629 MiscDetails::Kind miscKind{MiscDetails::Kind::None}; 6630 if (component.source == "kind") { 6631 miscKind = MiscDetails::Kind::KindParamInquiry; 6632 } else if (category == TypeCategory::Character) { 6633 if (component.source == "len") { 6634 miscKind = MiscDetails::Kind::LenParamInquiry; 6635 } 6636 } else if (category == TypeCategory::Complex) { 6637 if (component.source == "re") { 6638 miscKind = MiscDetails::Kind::ComplexPartRe; 6639 } else if (component.source == "im") { 6640 miscKind = MiscDetails::Kind::ComplexPartIm; 6641 } 6642 } 6643 if (miscKind != MiscDetails::Kind::None) { 6644 MakePlaceholder(component, miscKind); 6645 return &component; 6646 } 6647 } else if (DerivedTypeSpec * derived{type->AsDerived()}) { 6648 derived->Instantiate(currScope()); // in case of forward referenced type 6649 if (const Scope * scope{derived->scope()}) { 6650 if (Resolve(component, scope->FindComponent(component.source))) { 6651 if (auto msg{ 6652 CheckAccessibleComponent(currScope(), *component.symbol)}) { 6653 context().Say(component.source, *msg); 6654 } 6655 return &component; 6656 } else { 6657 SayDerivedType(component.source, 6658 "Component '%s' not found in derived type '%s'"_err_en_US, *scope); 6659 } 6660 } 6661 return nullptr; 6662 } 6663 if (symbol.test(Symbol::Flag::Implicit)) { 6664 Say(*base, 6665 "'%s' is not an object of derived type; it is implicitly typed"_err_en_US); 6666 } else { 6667 SayWithDecl( 6668 *base, symbol, "'%s' is not an object of derived type"_err_en_US); 6669 } 6670 return nullptr; 6671 } 6672 6673 void DeclarationVisitor::Initialization(const parser::Name &name, 6674 const parser::Initialization &init, bool inComponentDecl) { 6675 // Traversal of the initializer was deferred to here so that the 6676 // symbol being declared can be available for use in the expression, e.g.: 6677 // real, parameter :: x = tiny(x) 6678 if (!name.symbol) { 6679 return; 6680 } 6681 Symbol &ultimate{name.symbol->GetUltimate()}; 6682 if (IsAllocatable(ultimate)) { 6683 Say(name, "Allocatable object '%s' cannot be initialized"_err_en_US); 6684 return; 6685 } 6686 // TODO: check C762 - all bounds and type parameters of component 6687 // are colons or constant expressions if component is initialized 6688 common::visit( 6689 common::visitors{ 6690 [&](const parser::ConstantExpr &expr) { 6691 NonPointerInitialization(name, expr); 6692 }, 6693 [&](const parser::NullInit &null) { // => NULL() 6694 Walk(null); 6695 if (auto nullInit{EvaluateExpr(null)}) { 6696 if (!evaluate::IsNullPointer(*nullInit)) { 6697 Say(name, 6698 "Pointer initializer must be intrinsic NULL()"_err_en_US); // C813 6699 } else if (IsPointer(ultimate)) { 6700 if (auto *object{ultimate.detailsIf<ObjectEntityDetails>()}) { 6701 object->set_init(std::move(*nullInit)); 6702 } else if (auto *procPtr{ 6703 ultimate.detailsIf<ProcEntityDetails>()}) { 6704 procPtr->set_init(nullptr); 6705 } 6706 } else { 6707 Say(name, 6708 "Non-pointer component '%s' initialized with null pointer"_err_en_US); 6709 } 6710 } 6711 }, 6712 [&](const parser::InitialDataTarget &) { 6713 // Defer analysis to the end of the specification part 6714 // so that forward references and attribute checks like SAVE 6715 // work better. 6716 ultimate.set(Symbol::Flag::InDataStmt); 6717 }, 6718 [&](const std::list<Indirection<parser::DataStmtValue>> &values) { 6719 // Handled later in data-to-inits conversion 6720 ultimate.set(Symbol::Flag::InDataStmt); 6721 Walk(values); 6722 }, 6723 }, 6724 init.u); 6725 } 6726 6727 void DeclarationVisitor::PointerInitialization( 6728 const parser::Name &name, const parser::InitialDataTarget &target) { 6729 if (name.symbol) { 6730 Symbol &ultimate{name.symbol->GetUltimate()}; 6731 if (!context().HasError(ultimate)) { 6732 if (IsPointer(ultimate)) { 6733 if (auto *details{ultimate.detailsIf<ObjectEntityDetails>()}) { 6734 CHECK(!details->init()); 6735 Walk(target); 6736 if (MaybeExpr expr{EvaluateExpr(target)}) { 6737 // Validation is done in declaration checking. 6738 details->set_init(std::move(*expr)); 6739 } 6740 } 6741 } else { 6742 Say(name, 6743 "'%s' is not a pointer but is initialized like one"_err_en_US); 6744 context().SetError(ultimate); 6745 } 6746 } 6747 } 6748 } 6749 void DeclarationVisitor::PointerInitialization( 6750 const parser::Name &name, const parser::ProcPointerInit &target) { 6751 if (name.symbol) { 6752 Symbol &ultimate{name.symbol->GetUltimate()}; 6753 if (!context().HasError(ultimate)) { 6754 if (IsProcedurePointer(ultimate)) { 6755 auto &details{ultimate.get<ProcEntityDetails>()}; 6756 CHECK(!details.init()); 6757 Walk(target); 6758 if (const auto *targetName{std::get_if<parser::Name>(&target.u)}) { 6759 if (targetName->symbol) { 6760 // Validation is done in declaration checking. 6761 details.set_init(*targetName->symbol); 6762 } 6763 } else { 6764 details.set_init(nullptr); // explicit NULL() 6765 } 6766 } else { 6767 Say(name, 6768 "'%s' is not a procedure pointer but is initialized " 6769 "like one"_err_en_US); 6770 context().SetError(ultimate); 6771 } 6772 } 6773 } 6774 } 6775 6776 void DeclarationVisitor::NonPointerInitialization( 6777 const parser::Name &name, const parser::ConstantExpr &expr) { 6778 if (name.symbol) { 6779 Symbol &ultimate{name.symbol->GetUltimate()}; 6780 if (!context().HasError(ultimate) && !context().HasError(name.symbol)) { 6781 if (IsPointer(ultimate)) { 6782 Say(name, 6783 "'%s' is a pointer but is not initialized like one"_err_en_US); 6784 } else if (auto *details{ultimate.detailsIf<ObjectEntityDetails>()}) { 6785 CHECK(!details->init()); 6786 Walk(expr); 6787 if (ultimate.owner().IsParameterizedDerivedType()) { 6788 // Save the expression for per-instantiation analysis. 6789 details->set_unanalyzedPDTComponentInit(&expr.thing.value()); 6790 } else { 6791 if (MaybeExpr folded{EvaluateNonPointerInitializer( 6792 ultimate, expr, expr.thing.value().source)}) { 6793 details->set_init(std::move(*folded)); 6794 } 6795 } 6796 } 6797 } 6798 } 6799 } 6800 6801 void ResolveNamesVisitor::HandleCall( 6802 Symbol::Flag procFlag, const parser::Call &call) { 6803 common::visit( 6804 common::visitors{ 6805 [&](const parser::Name &x) { HandleProcedureName(procFlag, x); }, 6806 [&](const parser::ProcComponentRef &x) { Walk(x); }, 6807 }, 6808 std::get<parser::ProcedureDesignator>(call.t).u); 6809 Walk(std::get<std::list<parser::ActualArgSpec>>(call.t)); 6810 } 6811 6812 void ResolveNamesVisitor::HandleProcedureName( 6813 Symbol::Flag flag, const parser::Name &name) { 6814 CHECK(flag == Symbol::Flag::Function || flag == Symbol::Flag::Subroutine); 6815 auto *symbol{FindSymbol(NonDerivedTypeScope(), name)}; 6816 if (!symbol) { 6817 if (IsIntrinsic(name.source, flag)) { 6818 symbol = 6819 &MakeSymbol(InclusiveScope(), name.source, Attrs{Attr::INTRINSIC}); 6820 } else { 6821 symbol = &MakeSymbol(context().globalScope(), name.source, Attrs{}); 6822 } 6823 Resolve(name, *symbol); 6824 if (!symbol->attrs().test(Attr::INTRINSIC)) { 6825 if (CheckImplicitNoneExternal(name.source, *symbol)) { 6826 MakeExternal(*symbol); 6827 } 6828 } 6829 ConvertToProcEntity(*symbol); 6830 SetProcFlag(name, *symbol, flag); 6831 } else if (CheckUseError(name)) { 6832 // error was reported 6833 } else { 6834 auto &nonUltimateSymbol{*symbol}; 6835 symbol = &Resolve(name, symbol)->GetUltimate(); 6836 bool convertedToProcEntity{ConvertToProcEntity(*symbol)}; 6837 if (convertedToProcEntity && !symbol->attrs().test(Attr::EXTERNAL) && 6838 IsIntrinsic(symbol->name(), flag) && !IsDummy(*symbol)) { 6839 AcquireIntrinsicProcedureFlags(*symbol); 6840 } 6841 if (!SetProcFlag(name, *symbol, flag)) { 6842 return; // reported error 6843 } 6844 if (!symbol->has<GenericDetails>()) { 6845 CheckImplicitNoneExternal(name.source, *symbol); 6846 } 6847 if (symbol->has<SubprogramDetails>() && 6848 symbol->attrs().test(Attr::ABSTRACT)) { 6849 Say(name, "Abstract interface '%s' may not be called"_err_en_US); 6850 } else if (IsProcedure(*symbol) || symbol->has<DerivedTypeDetails>() || 6851 symbol->has<AssocEntityDetails>()) { 6852 // Symbols with DerivedTypeDetails and AssocEntityDetails are accepted 6853 // here as procedure-designators because this means the related 6854 // FunctionReference are mis-parsed structure constructors or array 6855 // references that will be fixed later when analyzing expressions. 6856 } else if (symbol->has<ObjectEntityDetails>()) { 6857 // Symbols with ObjectEntityDetails are also accepted because this can be 6858 // a mis-parsed array references that will be fixed later. Ensure that if 6859 // this is a symbol from a host procedure, a symbol with HostAssocDetails 6860 // is created for the current scope. 6861 // Operate on non ultimate symbol so that HostAssocDetails are also 6862 // created for symbols used associated in the host procedure. 6863 if (IsUplevelReference(nonUltimateSymbol)) { 6864 MakeHostAssocSymbol(name, nonUltimateSymbol); 6865 } 6866 } else if (symbol->test(Symbol::Flag::Implicit)) { 6867 Say(name, 6868 "Use of '%s' as a procedure conflicts with its implicit definition"_err_en_US); 6869 } else { 6870 SayWithDecl(name, *symbol, 6871 "Use of '%s' as a procedure conflicts with its declaration"_err_en_US); 6872 } 6873 } 6874 } 6875 6876 bool ResolveNamesVisitor::CheckImplicitNoneExternal( 6877 const SourceName &name, const Symbol &symbol) { 6878 if (isImplicitNoneExternal() && !symbol.attrs().test(Attr::EXTERNAL) && 6879 !symbol.attrs().test(Attr::INTRINSIC) && !symbol.HasExplicitInterface()) { 6880 Say(name, 6881 "'%s' is an external procedure without the EXTERNAL" 6882 " attribute in a scope with IMPLICIT NONE(EXTERNAL)"_err_en_US); 6883 return false; 6884 } 6885 return true; 6886 } 6887 6888 // Variant of HandleProcedureName() for use while skimming the executable 6889 // part of a subprogram to catch calls to dummy procedures that are part 6890 // of the subprogram's interface, and to mark as procedures any symbols 6891 // that might otherwise have been miscategorized as objects. 6892 void ResolveNamesVisitor::NoteExecutablePartCall( 6893 Symbol::Flag flag, const parser::Call &call) { 6894 auto &designator{std::get<parser::ProcedureDesignator>(call.t)}; 6895 if (const auto *name{std::get_if<parser::Name>(&designator.u)}) { 6896 // Subtlety: The symbol pointers in the parse tree are not set, because 6897 // they might end up resolving elsewhere (e.g., construct entities in 6898 // SELECT TYPE). 6899 if (Symbol * symbol{currScope().FindSymbol(name->source)}) { 6900 Symbol::Flag other{flag == Symbol::Flag::Subroutine 6901 ? Symbol::Flag::Function 6902 : Symbol::Flag::Subroutine}; 6903 if (!symbol->test(other)) { 6904 ConvertToProcEntity(*symbol); 6905 if (symbol->has<ProcEntityDetails>()) { 6906 symbol->set(flag); 6907 if (IsDummy(*symbol)) { 6908 symbol->attrs().set(Attr::EXTERNAL); 6909 } 6910 ApplyImplicitRules(*symbol); 6911 } 6912 } 6913 } 6914 } 6915 } 6916 6917 static bool IsLocallyImplicitGlobalSymbol( 6918 const Symbol &symbol, const parser::Name &localName) { 6919 return symbol.owner().IsGlobal() && 6920 (!symbol.scope() || 6921 !symbol.scope()->sourceRange().Contains(localName.source)); 6922 } 6923 6924 static bool TypesMismatchIfNonNull( 6925 const DeclTypeSpec *type1, const DeclTypeSpec *type2) { 6926 return type1 && type2 && *type1 != *type2; 6927 } 6928 6929 // Check and set the Function or Subroutine flag on symbol; false on error. 6930 bool ResolveNamesVisitor::SetProcFlag( 6931 const parser::Name &name, Symbol &symbol, Symbol::Flag flag) { 6932 if (symbol.test(Symbol::Flag::Function) && flag == Symbol::Flag::Subroutine) { 6933 SayWithDecl( 6934 name, symbol, "Cannot call function '%s' like a subroutine"_err_en_US); 6935 return false; 6936 } else if (symbol.test(Symbol::Flag::Subroutine) && 6937 flag == Symbol::Flag::Function) { 6938 SayWithDecl( 6939 name, symbol, "Cannot call subroutine '%s' like a function"_err_en_US); 6940 return false; 6941 } else if (flag == Symbol::Flag::Function && 6942 IsLocallyImplicitGlobalSymbol(symbol, name) && 6943 TypesMismatchIfNonNull(symbol.GetType(), GetImplicitType(symbol))) { 6944 SayWithDecl(name, symbol, 6945 "Implicit declaration of function '%s' has a different result type than in previous declaration"_err_en_US); 6946 return false; 6947 } else if (symbol.has<ProcEntityDetails>()) { 6948 symbol.set(flag); // in case it hasn't been set yet 6949 if (flag == Symbol::Flag::Function) { 6950 ApplyImplicitRules(symbol); 6951 } 6952 if (symbol.attrs().test(Attr::INTRINSIC)) { 6953 AcquireIntrinsicProcedureFlags(symbol); 6954 } 6955 } else if (symbol.GetType() && flag == Symbol::Flag::Subroutine) { 6956 SayWithDecl( 6957 name, symbol, "Cannot call function '%s' like a subroutine"_err_en_US); 6958 } else if (symbol.attrs().test(Attr::INTRINSIC)) { 6959 AcquireIntrinsicProcedureFlags(symbol); 6960 } 6961 return true; 6962 } 6963 6964 bool ModuleVisitor::Pre(const parser::AccessStmt &x) { 6965 Attr accessAttr{AccessSpecToAttr(std::get<parser::AccessSpec>(x.t))}; 6966 if (!currScope().IsModule()) { // C869 6967 Say(currStmtSource().value(), 6968 "%s statement may only appear in the specification part of a module"_err_en_US, 6969 EnumToString(accessAttr)); 6970 return false; 6971 } 6972 const auto &accessIds{std::get<std::list<parser::AccessId>>(x.t)}; 6973 if (accessIds.empty()) { 6974 if (prevAccessStmt_) { // C869 6975 Say("The default accessibility of this module has already been declared"_err_en_US) 6976 .Attach(*prevAccessStmt_, "Previous declaration"_en_US); 6977 } 6978 prevAccessStmt_ = currStmtSource(); 6979 defaultAccess_ = accessAttr; 6980 } else { 6981 for (const auto &accessId : accessIds) { 6982 common::visit( 6983 common::visitors{ 6984 [=](const parser::Name &y) { 6985 Resolve(y, SetAccess(y.source, accessAttr)); 6986 }, 6987 [=](const Indirection<parser::GenericSpec> &y) { 6988 auto info{GenericSpecInfo{y.value()}}; 6989 const auto &symbolName{info.symbolName()}; 6990 if (auto *symbol{FindInScope(symbolName)}) { 6991 info.Resolve(&SetAccess(symbolName, accessAttr, symbol)); 6992 } else if (info.kind().IsName()) { 6993 info.Resolve(&SetAccess(symbolName, accessAttr)); 6994 } else { 6995 Say(symbolName, "Generic spec '%s' not found"_err_en_US); 6996 } 6997 }, 6998 }, 6999 accessId.u); 7000 } 7001 } 7002 return false; 7003 } 7004 7005 // Set the access specification for this symbol. 7006 Symbol &ModuleVisitor::SetAccess( 7007 const SourceName &name, Attr attr, Symbol *symbol) { 7008 if (!symbol) { 7009 symbol = &MakeSymbol(name); 7010 } 7011 Attrs &attrs{symbol->attrs()}; 7012 if (attrs.HasAny({Attr::PUBLIC, Attr::PRIVATE})) { 7013 // PUBLIC/PRIVATE already set: make it a fatal error if it changed 7014 Attr prev = attrs.test(Attr::PUBLIC) ? Attr::PUBLIC : Attr::PRIVATE; 7015 Say(name, 7016 WithSeverity( 7017 "The accessibility of '%s' has already been specified as %s"_warn_en_US, 7018 attr != prev ? parser::Severity::Error : parser::Severity::Warning), 7019 MakeOpName(name), EnumToString(prev)); 7020 } else { 7021 attrs.set(attr); 7022 } 7023 return *symbol; 7024 } 7025 7026 static bool NeedsExplicitType(const Symbol &symbol) { 7027 if (symbol.has<UnknownDetails>()) { 7028 return true; 7029 } else if (const auto *details{symbol.detailsIf<EntityDetails>()}) { 7030 return !details->type(); 7031 } else if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) { 7032 return !details->type(); 7033 } else if (const auto *details{symbol.detailsIf<ProcEntityDetails>()}) { 7034 return !details->interface().symbol() && !details->interface().type(); 7035 } else { 7036 return false; 7037 } 7038 } 7039 7040 bool ResolveNamesVisitor::Pre(const parser::SpecificationPart &x) { 7041 const auto &[accDecls, ompDecls, compilerDirectives, useStmts, importStmts, 7042 implicitPart, decls] = x.t; 7043 auto flagRestorer{common::ScopedSet(inSpecificationPart_, true)}; 7044 auto stateRestorer{ 7045 common::ScopedSet(specPartState_, SpecificationPartState{})}; 7046 Walk(accDecls); 7047 Walk(ompDecls); 7048 Walk(compilerDirectives); 7049 Walk(useStmts); 7050 ClearUseRenames(); 7051 ClearUseOnly(); 7052 ClearExplicitIntrinsicUses(); 7053 Walk(importStmts); 7054 Walk(implicitPart); 7055 for (const auto &decl : decls) { 7056 if (const auto *spec{ 7057 std::get_if<parser::SpecificationConstruct>(&decl.u)}) { 7058 PreSpecificationConstruct(*spec); 7059 } 7060 } 7061 Walk(decls); 7062 FinishSpecificationPart(decls); 7063 return false; 7064 } 7065 7066 // Initial processing on specification constructs, before visiting them. 7067 void ResolveNamesVisitor::PreSpecificationConstruct( 7068 const parser::SpecificationConstruct &spec) { 7069 common::visit( 7070 common::visitors{ 7071 [&](const parser::Statement<Indirection<parser::GenericStmt>> &y) { 7072 CreateGeneric(std::get<parser::GenericSpec>(y.statement.value().t)); 7073 }, 7074 [&](const Indirection<parser::InterfaceBlock> &y) { 7075 const auto &stmt{std::get<parser::Statement<parser::InterfaceStmt>>( 7076 y.value().t)}; 7077 if (const auto *spec{parser::Unwrap<parser::GenericSpec>(stmt)}) { 7078 CreateGeneric(*spec); 7079 } 7080 }, 7081 [&](const parser::Statement<parser::OtherSpecificationStmt> &y) { 7082 if (const auto *commonStmt{parser::Unwrap<parser::CommonStmt>(y)}) { 7083 CreateCommonBlockSymbols(*commonStmt); 7084 } 7085 }, 7086 [&](const auto &) {}, 7087 }, 7088 spec.u); 7089 } 7090 7091 void ResolveNamesVisitor::CreateCommonBlockSymbols( 7092 const parser::CommonStmt &commonStmt) { 7093 for (const parser::CommonStmt::Block &block : commonStmt.blocks) { 7094 const auto &[name, objects] = block.t; 7095 Symbol &commonBlock{MakeCommonBlockSymbol(name)}; 7096 for (const auto &object : objects) { 7097 Symbol &obj{DeclareObjectEntity(std::get<parser::Name>(object.t))}; 7098 if (auto *details{obj.detailsIf<ObjectEntityDetails>()}) { 7099 details->set_commonBlock(commonBlock); 7100 commonBlock.get<CommonBlockDetails>().add_object(obj); 7101 } 7102 } 7103 } 7104 } 7105 7106 void ResolveNamesVisitor::CreateGeneric(const parser::GenericSpec &x) { 7107 auto info{GenericSpecInfo{x}}; 7108 SourceName symbolName{info.symbolName()}; 7109 if (IsLogicalConstant(context(), symbolName)) { 7110 Say(symbolName, 7111 "Logical constant '%s' may not be used as a defined operator"_err_en_US); 7112 return; 7113 } 7114 GenericDetails genericDetails; 7115 Symbol *existing{nullptr}; 7116 // Check all variants of names, e.g. "operator(.ne.)" for "operator(/=)" 7117 for (const std::string &n : GetAllNames(context(), symbolName)) { 7118 if (auto iter{currScope().find(n)}; iter != currScope().end()) { 7119 existing = &*iter->second; 7120 break; 7121 } 7122 } 7123 if (existing) { 7124 Symbol &ultimate{existing->GetUltimate()}; 7125 if (const auto *existingGeneric{ultimate.detailsIf<GenericDetails>()}) { 7126 if (const auto *existingUse{existing->detailsIf<UseDetails>()}) { 7127 // Create a local copy of a use associated generic so that 7128 // it can be locally extended without corrupting the original. 7129 genericDetails.CopyFrom(*existingGeneric); 7130 AddGenericUse(genericDetails, existing->name(), existingUse->symbol()); 7131 } else if (existing == &ultimate) { 7132 // Extending an extant generic in the same scope 7133 info.Resolve(existing); 7134 return; 7135 } else { 7136 // Host association of a generic is handled in ResolveGeneric() 7137 CHECK(existing->has<HostAssocDetails>()); 7138 } 7139 } else if (ultimate.has<SubprogramDetails>() || 7140 ultimate.has<SubprogramNameDetails>()) { 7141 genericDetails.set_specific(ultimate); 7142 } else if (ultimate.has<DerivedTypeDetails>()) { 7143 genericDetails.set_derivedType(ultimate); 7144 } else { 7145 SayAlreadyDeclared(symbolName, *existing); 7146 return; 7147 } 7148 EraseSymbol(*existing); 7149 } 7150 info.Resolve(&MakeSymbol(symbolName, Attrs{}, std::move(genericDetails))); 7151 } 7152 7153 void ResolveNamesVisitor::FinishSpecificationPart( 7154 const std::list<parser::DeclarationConstruct> &decls) { 7155 badStmtFuncFound_ = false; 7156 funcResultStack().CompleteFunctionResultType(); 7157 CheckImports(); 7158 bool inModule{currScope().kind() == Scope::Kind::Module}; 7159 for (auto &pair : currScope()) { 7160 auto &symbol{*pair.second}; 7161 if (NeedsExplicitType(symbol)) { 7162 ApplyImplicitRules(symbol); 7163 } 7164 if (IsDummy(symbol) && isImplicitNoneType() && 7165 symbol.test(Symbol::Flag::Implicit) && !context().HasError(symbol)) { 7166 Say(symbol.name(), 7167 "No explicit type declared for dummy argument '%s'"_err_en_US); 7168 context().SetError(symbol); 7169 } 7170 if (symbol.has<GenericDetails>()) { 7171 CheckGenericProcedures(symbol); 7172 } 7173 if (inModule && symbol.attrs().test(Attr::EXTERNAL) && 7174 !symbol.test(Symbol::Flag::Function) && 7175 !symbol.test(Symbol::Flag::Subroutine)) { 7176 // in a module, external proc without return type is subroutine 7177 symbol.set( 7178 symbol.GetType() ? Symbol::Flag::Function : Symbol::Flag::Subroutine); 7179 } 7180 if (!symbol.has<HostAssocDetails>()) { 7181 CheckPossibleBadForwardRef(symbol); 7182 } 7183 } 7184 currScope().InstantiateDerivedTypes(); 7185 for (const auto &decl : decls) { 7186 if (const auto *statement{std::get_if< 7187 parser::Statement<common::Indirection<parser::StmtFunctionStmt>>>( 7188 &decl.u)}) { 7189 AnalyzeStmtFunctionStmt(statement->statement.value()); 7190 } 7191 } 7192 // TODO: what about instantiations in BLOCK? 7193 CheckSaveStmts(); 7194 CheckCommonBlocks(); 7195 if (!inInterfaceBlock()) { 7196 // TODO: warn for the case where the EQUIVALENCE statement is in a 7197 // procedure declaration in an interface block 7198 CheckEquivalenceSets(); 7199 } 7200 } 7201 7202 // Analyze the bodies of statement functions now that the symbols in this 7203 // specification part have been fully declared and implicitly typed. 7204 void ResolveNamesVisitor::AnalyzeStmtFunctionStmt( 7205 const parser::StmtFunctionStmt &stmtFunc) { 7206 Symbol *symbol{std::get<parser::Name>(stmtFunc.t).symbol}; 7207 if (!symbol || !symbol->has<SubprogramDetails>()) { 7208 return; 7209 } 7210 auto &details{symbol->get<SubprogramDetails>()}; 7211 auto expr{AnalyzeExpr( 7212 context(), std::get<parser::Scalar<parser::Expr>>(stmtFunc.t))}; 7213 if (!expr) { 7214 context().SetError(*symbol); 7215 return; 7216 } 7217 if (auto type{evaluate::DynamicType::From(*symbol)}) { 7218 auto converted{ConvertToType(*type, std::move(*expr))}; 7219 if (!converted) { 7220 context().SetError(*symbol); 7221 return; 7222 } 7223 details.set_stmtFunction(std::move(*converted)); 7224 } else { 7225 details.set_stmtFunction(std::move(*expr)); 7226 } 7227 } 7228 7229 void ResolveNamesVisitor::CheckImports() { 7230 auto &scope{currScope()}; 7231 switch (scope.GetImportKind()) { 7232 case common::ImportKind::None: 7233 break; 7234 case common::ImportKind::All: 7235 // C8102: all entities in host must not be hidden 7236 for (const auto &pair : scope.parent()) { 7237 auto &name{pair.first}; 7238 std::optional<SourceName> scopeName{scope.GetName()}; 7239 if (!scopeName || name != *scopeName) { 7240 CheckImport(prevImportStmt_.value(), name); 7241 } 7242 } 7243 break; 7244 case common::ImportKind::Default: 7245 case common::ImportKind::Only: 7246 // C8102: entities named in IMPORT must not be hidden 7247 for (auto &name : scope.importNames()) { 7248 CheckImport(name, name); 7249 } 7250 break; 7251 } 7252 } 7253 7254 void ResolveNamesVisitor::CheckImport( 7255 const SourceName &location, const SourceName &name) { 7256 if (auto *symbol{FindInScope(name)}) { 7257 const Symbol &ultimate{symbol->GetUltimate()}; 7258 if (&ultimate.owner() == &currScope()) { 7259 Say(location, "'%s' from host is not accessible"_err_en_US, name) 7260 .Attach(symbol->name(), "'%s' is hidden by this entity"_en_US, 7261 symbol->name()); 7262 } 7263 } 7264 } 7265 7266 bool ResolveNamesVisitor::Pre(const parser::ImplicitStmt &x) { 7267 return CheckNotInBlock("IMPLICIT") && // C1107 7268 ImplicitRulesVisitor::Pre(x); 7269 } 7270 7271 void ResolveNamesVisitor::Post(const parser::PointerObject &x) { 7272 common::visit(common::visitors{ 7273 [&](const parser::Name &x) { ResolveName(x); }, 7274 [&](const parser::StructureComponent &x) { 7275 ResolveStructureComponent(x); 7276 }, 7277 }, 7278 x.u); 7279 } 7280 void ResolveNamesVisitor::Post(const parser::AllocateObject &x) { 7281 common::visit(common::visitors{ 7282 [&](const parser::Name &x) { ResolveName(x); }, 7283 [&](const parser::StructureComponent &x) { 7284 ResolveStructureComponent(x); 7285 }, 7286 }, 7287 x.u); 7288 } 7289 7290 bool ResolveNamesVisitor::Pre(const parser::PointerAssignmentStmt &x) { 7291 const auto &dataRef{std::get<parser::DataRef>(x.t)}; 7292 const auto &bounds{std::get<parser::PointerAssignmentStmt::Bounds>(x.t)}; 7293 const auto &expr{std::get<parser::Expr>(x.t)}; 7294 ResolveDataRef(dataRef); 7295 Walk(bounds); 7296 // Resolve unrestricted specific intrinsic procedures as in "p => cos". 7297 if (const parser::Name * name{parser::Unwrap<parser::Name>(expr)}) { 7298 if (NameIsKnownOrIntrinsic(*name)) { 7299 // If the name is known because it is an object entity from a host 7300 // procedure, create a host associated symbol. 7301 if (Symbol * symbol{name->symbol}; symbol && 7302 symbol->GetUltimate().has<ObjectEntityDetails>() && 7303 IsUplevelReference(*symbol)) { 7304 MakeHostAssocSymbol(*name, *symbol); 7305 } 7306 return false; 7307 } 7308 } 7309 Walk(expr); 7310 return false; 7311 } 7312 void ResolveNamesVisitor::Post(const parser::Designator &x) { 7313 ResolveDesignator(x); 7314 } 7315 7316 void ResolveNamesVisitor::Post(const parser::ProcComponentRef &x) { 7317 ResolveStructureComponent(x.v.thing); 7318 } 7319 void ResolveNamesVisitor::Post(const parser::TypeGuardStmt &x) { 7320 DeclTypeSpecVisitor::Post(x); 7321 ConstructVisitor::Post(x); 7322 } 7323 bool ResolveNamesVisitor::Pre(const parser::StmtFunctionStmt &x) { 7324 CheckNotInBlock("STATEMENT FUNCTION"); // C1107 7325 if (HandleStmtFunction(x)) { 7326 return false; 7327 } else { 7328 // This is an array element assignment: resolve names of indices 7329 const auto &names{std::get<std::list<parser::Name>>(x.t)}; 7330 for (auto &name : names) { 7331 ResolveName(name); 7332 } 7333 return true; 7334 } 7335 } 7336 7337 bool ResolveNamesVisitor::Pre(const parser::DefinedOpName &x) { 7338 const parser::Name &name{x.v}; 7339 if (FindSymbol(name)) { 7340 // OK 7341 } else if (IsLogicalConstant(context(), name.source)) { 7342 Say(name, 7343 "Logical constant '%s' may not be used as a defined operator"_err_en_US); 7344 } else { 7345 // Resolved later in expression semantics 7346 MakePlaceholder(name, MiscDetails::Kind::TypeBoundDefinedOp); 7347 } 7348 return false; 7349 } 7350 7351 void ResolveNamesVisitor::Post(const parser::AssignStmt &x) { 7352 if (auto *name{ResolveName(std::get<parser::Name>(x.t))}) { 7353 ConvertToObjectEntity(DEREF(name->symbol)); 7354 } 7355 } 7356 void ResolveNamesVisitor::Post(const parser::AssignedGotoStmt &x) { 7357 if (auto *name{ResolveName(std::get<parser::Name>(x.t))}) { 7358 ConvertToObjectEntity(DEREF(name->symbol)); 7359 } 7360 } 7361 7362 bool ResolveNamesVisitor::Pre(const parser::ProgramUnit &x) { 7363 if (std::holds_alternative<common::Indirection<parser::CompilerDirective>>( 7364 x.u)) { 7365 // TODO: global directives 7366 return true; 7367 } 7368 auto root{ProgramTree::Build(x)}; 7369 SetScope(topScope_); 7370 ResolveSpecificationParts(root); 7371 FinishSpecificationParts(root); 7372 ResolveExecutionParts(root); 7373 ResolveAccParts(context(), x); 7374 ResolveOmpParts(context(), x); 7375 return false; 7376 } 7377 7378 // References to procedures need to record that their symbols are known 7379 // to be procedures, so that they don't get converted to objects by default. 7380 class ExecutionPartSkimmer { 7381 public: 7382 explicit ExecutionPartSkimmer(ResolveNamesVisitor &resolver) 7383 : resolver_{resolver} {} 7384 7385 void Walk(const parser::ExecutionPart *exec) { 7386 if (exec) { 7387 parser::Walk(*exec, *this); 7388 } 7389 } 7390 7391 template <typename A> bool Pre(const A &) { return true; } 7392 template <typename A> void Post(const A &) {} 7393 void Post(const parser::FunctionReference &fr) { 7394 resolver_.NoteExecutablePartCall(Symbol::Flag::Function, fr.v); 7395 } 7396 void Post(const parser::CallStmt &cs) { 7397 resolver_.NoteExecutablePartCall(Symbol::Flag::Subroutine, cs.v); 7398 } 7399 7400 private: 7401 ResolveNamesVisitor &resolver_; 7402 }; 7403 7404 // Build the scope tree and resolve names in the specification parts of this 7405 // node and its children 7406 void ResolveNamesVisitor::ResolveSpecificationParts(ProgramTree &node) { 7407 if (node.isSpecificationPartResolved()) { 7408 return; // been here already 7409 } 7410 node.set_isSpecificationPartResolved(); 7411 if (!BeginScopeForNode(node)) { 7412 return; // an error prevented scope from being created 7413 } 7414 Scope &scope{currScope()}; 7415 node.set_scope(scope); 7416 AddSubpNames(node); 7417 common::visit( 7418 [&](const auto *x) { 7419 if (x) { 7420 Walk(*x); 7421 } 7422 }, 7423 node.stmt()); 7424 Walk(node.spec()); 7425 // If this is a function, convert result to an object. This is to prevent the 7426 // result from being converted later to a function symbol if it is called 7427 // inside the function. 7428 // If the result is function pointer, then ConvertToObjectEntity will not 7429 // convert the result to an object, and calling the symbol inside the function 7430 // will result in calls to the result pointer. 7431 // A function cannot be called recursively if RESULT was not used to define a 7432 // distinct result name (15.6.2.2 point 4.). 7433 if (Symbol * symbol{scope.symbol()}) { 7434 if (auto *details{symbol->detailsIf<SubprogramDetails>()}) { 7435 if (details->isFunction()) { 7436 ConvertToObjectEntity(const_cast<Symbol &>(details->result())); 7437 } 7438 } 7439 } 7440 if (node.IsModule()) { 7441 ApplyDefaultAccess(); 7442 } 7443 for (auto &child : node.children()) { 7444 ResolveSpecificationParts(child); 7445 } 7446 ExecutionPartSkimmer{*this}.Walk(node.exec()); 7447 EndScopeForNode(node); 7448 // Ensure that every object entity has a type. 7449 for (auto &pair : *node.scope()) { 7450 ApplyImplicitRules(*pair.second); 7451 } 7452 } 7453 7454 // Add SubprogramNameDetails symbols for module and internal subprograms and 7455 // their ENTRY statements. 7456 void ResolveNamesVisitor::AddSubpNames(ProgramTree &node) { 7457 auto kind{ 7458 node.IsModule() ? SubprogramKind::Module : SubprogramKind::Internal}; 7459 for (auto &child : node.children()) { 7460 auto &symbol{MakeSymbol(child.name(), SubprogramNameDetails{kind, child})}; 7461 auto childKind{child.GetKind()}; 7462 if (childKind == ProgramTree::Kind::Function) { 7463 symbol.set(Symbol::Flag::Function); 7464 } else if (childKind == ProgramTree::Kind::Subroutine) { 7465 symbol.set(Symbol::Flag::Subroutine); 7466 } else { 7467 continue; // make ENTRY symbols only where valid 7468 } 7469 for (const auto &entryStmt : child.entryStmts()) { 7470 SubprogramNameDetails details{kind, child}; 7471 auto &symbol{ 7472 MakeSymbol(std::get<parser::Name>(entryStmt->t), std::move(details))}; 7473 symbol.set(child.GetSubpFlag()); 7474 } 7475 } 7476 for (const auto &generic : node.genericSpecs()) { 7477 if (const auto *name{std::get_if<parser::Name>(&generic->u)}) { 7478 if (currScope().find(name->source) != currScope().end()) { 7479 // If this scope has both a generic interface and a contained 7480 // subprogram with the same name, create the generic's symbol 7481 // now so that any other generics of the same name that are pulled 7482 // into scope later via USE association will properly merge instead 7483 // of raising a bogus error due a conflict with the subprogram. 7484 CreateGeneric(*generic); 7485 } 7486 } 7487 } 7488 } 7489 7490 // Push a new scope for this node or return false on error. 7491 bool ResolveNamesVisitor::BeginScopeForNode(const ProgramTree &node) { 7492 switch (node.GetKind()) { 7493 SWITCH_COVERS_ALL_CASES 7494 case ProgramTree::Kind::Program: 7495 PushScope(Scope::Kind::MainProgram, 7496 &MakeSymbol(node.name(), MainProgramDetails{})); 7497 return true; 7498 case ProgramTree::Kind::Function: 7499 case ProgramTree::Kind::Subroutine: 7500 return BeginSubprogram(node.name(), node.GetSubpFlag(), 7501 node.HasModulePrefix(), node.bindingSpec(), &node.entryStmts()); 7502 case ProgramTree::Kind::MpSubprogram: 7503 return BeginMpSubprogram(node.name()); 7504 case ProgramTree::Kind::Module: 7505 BeginModule(node.name(), false); 7506 return true; 7507 case ProgramTree::Kind::Submodule: 7508 return BeginSubmodule(node.name(), node.GetParentId()); 7509 case ProgramTree::Kind::BlockData: 7510 PushBlockDataScope(node.name()); 7511 return true; 7512 } 7513 } 7514 7515 void ResolveNamesVisitor::EndScopeForNode(const ProgramTree &node) { 7516 std::optional<parser::CharBlock> stmtSource; 7517 const std::optional<parser::LanguageBindingSpec> *binding{nullptr}; 7518 common::visit( 7519 common::visitors{ 7520 [&](const parser::Statement<parser::FunctionStmt> *stmt) { 7521 if (stmt) { 7522 stmtSource = stmt->source; 7523 if (const auto &maybeSuffix{ 7524 std::get<std::optional<parser::Suffix>>( 7525 stmt->statement.t)}) { 7526 binding = &maybeSuffix->binding; 7527 } 7528 } 7529 }, 7530 [&](const parser::Statement<parser::SubroutineStmt> *stmt) { 7531 if (stmt) { 7532 stmtSource = stmt->source; 7533 binding = &std::get<std::optional<parser::LanguageBindingSpec>>( 7534 stmt->statement.t); 7535 } 7536 }, 7537 [](const auto *) {}, 7538 }, 7539 node.stmt()); 7540 EndSubprogram(stmtSource, binding); 7541 } 7542 7543 // Some analyses and checks, such as the processing of initializers of 7544 // pointers, are deferred until all of the pertinent specification parts 7545 // have been visited. This deferred processing enables the use of forward 7546 // references in these circumstances. 7547 class DeferredCheckVisitor { 7548 public: 7549 explicit DeferredCheckVisitor(ResolveNamesVisitor &resolver) 7550 : resolver_{resolver} {} 7551 7552 template <typename A> void Walk(const A &x) { parser::Walk(x, *this); } 7553 7554 template <typename A> bool Pre(const A &) { return true; } 7555 template <typename A> void Post(const A &) {} 7556 7557 void Post(const parser::DerivedTypeStmt &x) { 7558 const auto &name{std::get<parser::Name>(x.t)}; 7559 if (Symbol * symbol{name.symbol}) { 7560 if (Scope * scope{symbol->scope()}) { 7561 if (scope->IsDerivedType()) { 7562 resolver_.PushScope(*scope); 7563 pushedScope_ = true; 7564 } 7565 } 7566 } 7567 } 7568 void Post(const parser::EndTypeStmt &) { 7569 if (pushedScope_) { 7570 resolver_.PopScope(); 7571 pushedScope_ = false; 7572 } 7573 } 7574 7575 void Post(const parser::ProcInterface &pi) { 7576 if (const auto *name{std::get_if<parser::Name>(&pi.u)}) { 7577 resolver_.CheckExplicitInterface(*name); 7578 } 7579 } 7580 bool Pre(const parser::EntityDecl &decl) { 7581 Init(std::get<parser::Name>(decl.t), 7582 std::get<std::optional<parser::Initialization>>(decl.t)); 7583 return false; 7584 } 7585 bool Pre(const parser::ComponentDecl &decl) { 7586 Init(std::get<parser::Name>(decl.t), 7587 std::get<std::optional<parser::Initialization>>(decl.t)); 7588 return false; 7589 } 7590 bool Pre(const parser::ProcDecl &decl) { 7591 if (const auto &init{ 7592 std::get<std::optional<parser::ProcPointerInit>>(decl.t)}) { 7593 resolver_.PointerInitialization(std::get<parser::Name>(decl.t), *init); 7594 } 7595 return false; 7596 } 7597 void Post(const parser::TypeBoundProcedureStmt::WithInterface &tbps) { 7598 resolver_.CheckExplicitInterface(tbps.interfaceName); 7599 } 7600 void Post(const parser::TypeBoundProcedureStmt::WithoutInterface &tbps) { 7601 if (pushedScope_) { 7602 resolver_.CheckBindings(tbps); 7603 } 7604 } 7605 7606 private: 7607 void Init(const parser::Name &name, 7608 const std::optional<parser::Initialization> &init) { 7609 if (init) { 7610 if (const auto *target{ 7611 std::get_if<parser::InitialDataTarget>(&init->u)}) { 7612 resolver_.PointerInitialization(name, *target); 7613 } 7614 } 7615 } 7616 7617 ResolveNamesVisitor &resolver_; 7618 bool pushedScope_{false}; 7619 }; 7620 7621 // Perform checks and completions that need to happen after all of 7622 // the specification parts but before any of the execution parts. 7623 void ResolveNamesVisitor::FinishSpecificationParts(const ProgramTree &node) { 7624 if (!node.scope()) { 7625 return; // error occurred creating scope 7626 } 7627 SetScope(*node.scope()); 7628 // The initializers of pointers, the default initializers of pointer 7629 // components, and non-deferred type-bound procedure bindings have not 7630 // yet been traversed. 7631 // We do that now, when any (formerly) forward references that appear 7632 // in those initializers will resolve to the right symbols without 7633 // incurring spurious errors with IMPLICIT NONE. 7634 DeferredCheckVisitor{*this}.Walk(node.spec()); 7635 DeferredCheckVisitor{*this}.Walk(node.exec()); // for BLOCK 7636 for (Scope &childScope : currScope().children()) { 7637 if (childScope.IsParameterizedDerivedTypeInstantiation()) { 7638 FinishDerivedTypeInstantiation(childScope); 7639 } 7640 } 7641 for (const auto &child : node.children()) { 7642 FinishSpecificationParts(child); 7643 } 7644 } 7645 7646 // Duplicate and fold component object pointer default initializer designators 7647 // using the actual type parameter values of each particular instantiation. 7648 // Validation is done later in declaration checking. 7649 void ResolveNamesVisitor::FinishDerivedTypeInstantiation(Scope &scope) { 7650 CHECK(scope.IsDerivedType() && !scope.symbol()); 7651 if (DerivedTypeSpec * spec{scope.derivedTypeSpec()}) { 7652 spec->Instantiate(currScope()); 7653 const Symbol &origTypeSymbol{spec->typeSymbol()}; 7654 if (const Scope * origTypeScope{origTypeSymbol.scope()}) { 7655 CHECK(origTypeScope->IsDerivedType() && 7656 origTypeScope->symbol() == &origTypeSymbol); 7657 auto &foldingContext{GetFoldingContext()}; 7658 auto restorer{foldingContext.WithPDTInstance(*spec)}; 7659 for (auto &pair : scope) { 7660 Symbol &comp{*pair.second}; 7661 const Symbol &origComp{DEREF(FindInScope(*origTypeScope, comp.name()))}; 7662 if (IsPointer(comp)) { 7663 if (auto *details{comp.detailsIf<ObjectEntityDetails>()}) { 7664 auto origDetails{origComp.get<ObjectEntityDetails>()}; 7665 if (const MaybeExpr & init{origDetails.init()}) { 7666 SomeExpr newInit{*init}; 7667 MaybeExpr folded{ 7668 evaluate::Fold(foldingContext, std::move(newInit))}; 7669 details->set_init(std::move(folded)); 7670 } 7671 } 7672 } 7673 } 7674 } 7675 } 7676 } 7677 7678 // Resolve names in the execution part of this node and its children 7679 void ResolveNamesVisitor::ResolveExecutionParts(const ProgramTree &node) { 7680 if (!node.scope()) { 7681 return; // error occurred creating scope 7682 } 7683 SetScope(*node.scope()); 7684 if (const auto *exec{node.exec()}) { 7685 Walk(*exec); 7686 } 7687 FinishNamelists(); 7688 PopScope(); // converts unclassified entities into objects 7689 for (const auto &child : node.children()) { 7690 ResolveExecutionParts(child); 7691 } 7692 } 7693 7694 void ResolveNamesVisitor::Post(const parser::Program &) { 7695 // ensure that all temps were deallocated 7696 CHECK(!attrs_); 7697 CHECK(!GetDeclTypeSpec()); 7698 } 7699 7700 // A singleton instance of the scope -> IMPLICIT rules mapping is 7701 // shared by all instances of ResolveNamesVisitor and accessed by this 7702 // pointer when the visitors (other than the top-level original) are 7703 // constructed. 7704 static ImplicitRulesMap *sharedImplicitRulesMap{nullptr}; 7705 7706 bool ResolveNames( 7707 SemanticsContext &context, const parser::Program &program, Scope &top) { 7708 ImplicitRulesMap implicitRulesMap; 7709 auto restorer{common::ScopedSet(sharedImplicitRulesMap, &implicitRulesMap)}; 7710 ResolveNamesVisitor{context, implicitRulesMap, top}.Walk(program); 7711 return !context.AnyFatalError(); 7712 } 7713 7714 // Processes a module (but not internal) function when it is referenced 7715 // in a specification expression in a sibling procedure. 7716 void ResolveSpecificationParts( 7717 SemanticsContext &context, const Symbol &subprogram) { 7718 auto originalLocation{context.location()}; 7719 ImplicitRulesMap implicitRulesMap; 7720 bool localImplicitRulesMap{false}; 7721 if (!sharedImplicitRulesMap) { 7722 sharedImplicitRulesMap = &implicitRulesMap; 7723 localImplicitRulesMap = true; 7724 } 7725 ResolveNamesVisitor visitor{ 7726 context, *sharedImplicitRulesMap, context.globalScope()}; 7727 const auto &details{subprogram.get<SubprogramNameDetails>()}; 7728 ProgramTree &node{details.node()}; 7729 const Scope &moduleScope{subprogram.owner()}; 7730 if (localImplicitRulesMap) { 7731 visitor.BeginScope(const_cast<Scope &>(moduleScope)); 7732 } else { 7733 visitor.SetScope(const_cast<Scope &>(moduleScope)); 7734 } 7735 visitor.ResolveSpecificationParts(node); 7736 context.set_location(std::move(originalLocation)); 7737 if (localImplicitRulesMap) { 7738 sharedImplicitRulesMap = nullptr; 7739 } 7740 } 7741 7742 } // namespace Fortran::semantics 7743