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