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