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