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 "definable.h" 11 #include "mod-file.h" 12 #include "pointer-assignment.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/openmp-modifiers.h" 35 #include "flang/Semantics/program-tree.h" 36 #include "flang/Semantics/scope.h" 37 #include "flang/Semantics/semantics.h" 38 #include "flang/Semantics/symbol.h" 39 #include "flang/Semantics/tools.h" 40 #include "flang/Semantics/type.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include <list> 43 #include <map> 44 #include <set> 45 #include <stack> 46 47 namespace Fortran::semantics { 48 49 using namespace parser::literals; 50 51 template <typename T> using Indirection = common::Indirection<T>; 52 using Message = parser::Message; 53 using Messages = parser::Messages; 54 using MessageFixedText = parser::MessageFixedText; 55 using MessageFormattedText = parser::MessageFormattedText; 56 57 class ResolveNamesVisitor; 58 class ScopeHandler; 59 60 // ImplicitRules maps initial character of identifier to the DeclTypeSpec 61 // representing the implicit type; std::nullopt if none. 62 // It also records the presence of IMPLICIT NONE statements. 63 // When inheritFromParent is set, defaults come from the parent rules. 64 class ImplicitRules { 65 public: 66 ImplicitRules(SemanticsContext &context, const ImplicitRules *parent) 67 : parent_{parent}, context_{context}, 68 inheritFromParent_{parent != nullptr} {} 69 bool isImplicitNoneType() const; 70 bool isImplicitNoneExternal() const; 71 void set_isImplicitNoneType(bool x) { isImplicitNoneType_ = x; } 72 void set_isImplicitNoneExternal(bool x) { isImplicitNoneExternal_ = x; } 73 void set_inheritFromParent(bool x) { inheritFromParent_ = x; } 74 // Get the implicit type for this name. May be null. 75 const DeclTypeSpec *GetType( 76 SourceName, bool respectImplicitNone = true) const; 77 // Record the implicit type for the range of characters [fromLetter, 78 // toLetter]. 79 void SetTypeMapping(const DeclTypeSpec &type, parser::Location fromLetter, 80 parser::Location toLetter); 81 82 private: 83 static char Incr(char ch); 84 85 const ImplicitRules *parent_; 86 SemanticsContext &context_; 87 bool inheritFromParent_{false}; // look in parent if not specified here 88 bool isImplicitNoneType_{ 89 context_.IsEnabled(common::LanguageFeature::ImplicitNoneTypeAlways)}; 90 bool isImplicitNoneExternal_{false}; 91 // map_ contains the mapping between letters and types that were defined 92 // by the IMPLICIT statements of the related scope. It does not contain 93 // the default Fortran mappings nor the mapping defined in parents. 94 std::map<char, common::Reference<const DeclTypeSpec>> map_; 95 96 friend llvm::raw_ostream &operator<<( 97 llvm::raw_ostream &, const ImplicitRules &); 98 friend void ShowImplicitRule( 99 llvm::raw_ostream &, const ImplicitRules &, char); 100 }; 101 102 // scope -> implicit rules for that scope 103 using ImplicitRulesMap = std::map<const Scope *, ImplicitRules>; 104 105 // Track statement source locations and save messages. 106 class MessageHandler { 107 public: 108 MessageHandler() { DIE("MessageHandler: default-constructed"); } 109 explicit MessageHandler(SemanticsContext &c) : context_{&c} {} 110 Messages &messages() { return context_->messages(); }; 111 const std::optional<SourceName> &currStmtSource() { 112 return context_->location(); 113 } 114 void set_currStmtSource(const std::optional<SourceName> &source) { 115 context_->set_location(source); 116 } 117 118 // Emit a message associated with the current statement source. 119 Message &Say(MessageFixedText &&); 120 Message &Say(MessageFormattedText &&); 121 // Emit a message about a SourceName 122 Message &Say(const SourceName &, MessageFixedText &&); 123 // Emit a formatted message associated with a source location. 124 template <typename... A> 125 Message &Say(const SourceName &source, MessageFixedText &&msg, A &&...args) { 126 return context_->Say(source, std::move(msg), std::forward<A>(args)...); 127 } 128 129 private: 130 SemanticsContext *context_; 131 }; 132 133 // Inheritance graph for the parse tree visitation classes that follow: 134 // BaseVisitor 135 // + AttrsVisitor 136 // | + DeclTypeSpecVisitor 137 // | + ImplicitRulesVisitor 138 // | + ScopeHandler ------------------+ 139 // | + ModuleVisitor -------------+ | 140 // | + GenericHandler -------+ | | 141 // | | + InterfaceVisitor | | | 142 // | +-+ SubprogramVisitor ==|==+ | | 143 // + ArraySpecVisitor | | | | 144 // + DeclarationVisitor <--------+ | | | 145 // + ConstructVisitor | | | 146 // + ResolveNamesVisitor <------+-+-+ 147 148 class BaseVisitor { 149 public: 150 BaseVisitor() { DIE("BaseVisitor: default-constructed"); } 151 BaseVisitor( 152 SemanticsContext &c, ResolveNamesVisitor &v, ImplicitRulesMap &rules) 153 : implicitRulesMap_{&rules}, this_{&v}, context_{&c}, messageHandler_{c} { 154 } 155 template <typename T> void Walk(const T &); 156 157 MessageHandler &messageHandler() { return messageHandler_; } 158 const std::optional<SourceName> &currStmtSource() { 159 return context_->location(); 160 } 161 SemanticsContext &context() const { return *context_; } 162 evaluate::FoldingContext &GetFoldingContext() const { 163 return context_->foldingContext(); 164 } 165 bool IsIntrinsic( 166 const SourceName &name, std::optional<Symbol::Flag> flag) const { 167 if (!flag) { 168 return context_->intrinsics().IsIntrinsic(name.ToString()); 169 } else if (flag == Symbol::Flag::Function) { 170 return context_->intrinsics().IsIntrinsicFunction(name.ToString()); 171 } else if (flag == Symbol::Flag::Subroutine) { 172 return context_->intrinsics().IsIntrinsicSubroutine(name.ToString()); 173 } else { 174 DIE("expected Subroutine or Function flag"); 175 } 176 } 177 178 bool InModuleFile() const { 179 return GetFoldingContext().moduleFileName().has_value(); 180 } 181 182 // Make a placeholder symbol for a Name that otherwise wouldn't have one. 183 // It is not in any scope and always has MiscDetails. 184 void MakePlaceholder(const parser::Name &, MiscDetails::Kind); 185 186 template <typename T> common::IfNoLvalue<T, T> FoldExpr(T &&expr) { 187 return evaluate::Fold(GetFoldingContext(), std::move(expr)); 188 } 189 190 template <typename T> MaybeExpr EvaluateExpr(const T &expr) { 191 return FoldExpr(AnalyzeExpr(*context_, expr)); 192 } 193 194 template <typename T> 195 MaybeExpr EvaluateNonPointerInitializer( 196 const Symbol &symbol, const T &expr, parser::CharBlock source) { 197 if (!context().HasError(symbol)) { 198 if (auto maybeExpr{AnalyzeExpr(*context_, expr)}) { 199 auto restorer{GetFoldingContext().messages().SetLocation(source)}; 200 return evaluate::NonPointerInitializationExpr( 201 symbol, std::move(*maybeExpr), GetFoldingContext()); 202 } 203 } 204 return std::nullopt; 205 } 206 207 template <typename T> MaybeIntExpr EvaluateIntExpr(const T &expr) { 208 return semantics::EvaluateIntExpr(*context_, expr); 209 } 210 211 template <typename T> 212 MaybeSubscriptIntExpr EvaluateSubscriptIntExpr(const T &expr) { 213 if (MaybeIntExpr maybeIntExpr{EvaluateIntExpr(expr)}) { 214 return FoldExpr(evaluate::ConvertToType<evaluate::SubscriptInteger>( 215 std::move(*maybeIntExpr))); 216 } else { 217 return std::nullopt; 218 } 219 } 220 221 template <typename... A> Message &Say(A &&...args) { 222 return messageHandler_.Say(std::forward<A>(args)...); 223 } 224 template <typename... A> 225 Message &Say( 226 const parser::Name &name, MessageFixedText &&text, const A &...args) { 227 return messageHandler_.Say(name.source, std::move(text), args...); 228 } 229 230 protected: 231 ImplicitRulesMap *implicitRulesMap_{nullptr}; 232 233 private: 234 ResolveNamesVisitor *this_; 235 SemanticsContext *context_; 236 MessageHandler messageHandler_; 237 }; 238 239 // Provide Post methods to collect attributes into a member variable. 240 class AttrsVisitor : public virtual BaseVisitor { 241 public: 242 bool BeginAttrs(); // always returns true 243 Attrs GetAttrs(); 244 std::optional<common::CUDADataAttr> cudaDataAttr() { return cudaDataAttr_; } 245 Attrs EndAttrs(); 246 bool SetPassNameOn(Symbol &); 247 void SetBindNameOn(Symbol &); 248 void Post(const parser::LanguageBindingSpec &); 249 bool Pre(const parser::IntentSpec &); 250 bool Pre(const parser::Pass &); 251 252 bool CheckAndSet(Attr); 253 254 // Simple case: encountering CLASSNAME causes ATTRNAME to be set. 255 #define HANDLE_ATTR_CLASS(CLASSNAME, ATTRNAME) \ 256 bool Pre(const parser::CLASSNAME &) { \ 257 CheckAndSet(Attr::ATTRNAME); \ 258 return false; \ 259 } 260 HANDLE_ATTR_CLASS(PrefixSpec::Elemental, ELEMENTAL) 261 HANDLE_ATTR_CLASS(PrefixSpec::Impure, IMPURE) 262 HANDLE_ATTR_CLASS(PrefixSpec::Module, MODULE) 263 HANDLE_ATTR_CLASS(PrefixSpec::Non_Recursive, NON_RECURSIVE) 264 HANDLE_ATTR_CLASS(PrefixSpec::Pure, PURE) 265 HANDLE_ATTR_CLASS(PrefixSpec::Recursive, RECURSIVE) 266 HANDLE_ATTR_CLASS(TypeAttrSpec::BindC, BIND_C) 267 HANDLE_ATTR_CLASS(BindAttr::Deferred, DEFERRED) 268 HANDLE_ATTR_CLASS(BindAttr::Non_Overridable, NON_OVERRIDABLE) 269 HANDLE_ATTR_CLASS(Abstract, ABSTRACT) 270 HANDLE_ATTR_CLASS(Allocatable, ALLOCATABLE) 271 HANDLE_ATTR_CLASS(Asynchronous, ASYNCHRONOUS) 272 HANDLE_ATTR_CLASS(Contiguous, CONTIGUOUS) 273 HANDLE_ATTR_CLASS(External, EXTERNAL) 274 HANDLE_ATTR_CLASS(Intrinsic, INTRINSIC) 275 HANDLE_ATTR_CLASS(NoPass, NOPASS) 276 HANDLE_ATTR_CLASS(Optional, OPTIONAL) 277 HANDLE_ATTR_CLASS(Parameter, PARAMETER) 278 HANDLE_ATTR_CLASS(Pointer, POINTER) 279 HANDLE_ATTR_CLASS(Protected, PROTECTED) 280 HANDLE_ATTR_CLASS(Save, SAVE) 281 HANDLE_ATTR_CLASS(Target, TARGET) 282 HANDLE_ATTR_CLASS(Value, VALUE) 283 HANDLE_ATTR_CLASS(Volatile, VOLATILE) 284 #undef HANDLE_ATTR_CLASS 285 bool Pre(const common::CUDADataAttr); 286 287 protected: 288 std::optional<Attrs> attrs_; 289 std::optional<common::CUDADataAttr> cudaDataAttr_; 290 291 Attr AccessSpecToAttr(const parser::AccessSpec &x) { 292 switch (x.v) { 293 case parser::AccessSpec::Kind::Public: 294 return Attr::PUBLIC; 295 case parser::AccessSpec::Kind::Private: 296 return Attr::PRIVATE; 297 } 298 llvm_unreachable("Switch covers all cases"); // suppress g++ warning 299 } 300 Attr IntentSpecToAttr(const parser::IntentSpec &x) { 301 switch (x.v) { 302 case parser::IntentSpec::Intent::In: 303 return Attr::INTENT_IN; 304 case parser::IntentSpec::Intent::Out: 305 return Attr::INTENT_OUT; 306 case parser::IntentSpec::Intent::InOut: 307 return Attr::INTENT_INOUT; 308 } 309 llvm_unreachable("Switch covers all cases"); // suppress g++ warning 310 } 311 312 private: 313 bool IsDuplicateAttr(Attr); 314 bool HaveAttrConflict(Attr, Attr, Attr); 315 bool IsConflictingAttr(Attr); 316 317 MaybeExpr bindName_; // from BIND(C, NAME="...") 318 bool isCDefined_{false}; // BIND(C, NAME="...", CDEFINED) extension 319 std::optional<SourceName> passName_; // from PASS(...) 320 }; 321 322 // Find and create types from declaration-type-spec nodes. 323 class DeclTypeSpecVisitor : public AttrsVisitor { 324 public: 325 using AttrsVisitor::Post; 326 using AttrsVisitor::Pre; 327 void Post(const parser::IntrinsicTypeSpec::DoublePrecision &); 328 void Post(const parser::IntrinsicTypeSpec::DoubleComplex &); 329 void Post(const parser::DeclarationTypeSpec::ClassStar &); 330 void Post(const parser::DeclarationTypeSpec::TypeStar &); 331 bool Pre(const parser::TypeGuardStmt &); 332 void Post(const parser::TypeGuardStmt &); 333 void Post(const parser::TypeSpec &); 334 335 // Walk the parse tree of a type spec and return the DeclTypeSpec for it. 336 template <typename T> 337 const DeclTypeSpec *ProcessTypeSpec(const T &x, bool allowForward = false) { 338 auto restorer{common::ScopedSet(state_, State{})}; 339 set_allowForwardReferenceToDerivedType(allowForward); 340 BeginDeclTypeSpec(); 341 Walk(x); 342 const auto *type{GetDeclTypeSpec()}; 343 EndDeclTypeSpec(); 344 return type; 345 } 346 347 protected: 348 struct State { 349 bool expectDeclTypeSpec{false}; // should see decl-type-spec only when true 350 const DeclTypeSpec *declTypeSpec{nullptr}; 351 struct { 352 DerivedTypeSpec *type{nullptr}; 353 DeclTypeSpec::Category category{DeclTypeSpec::TypeDerived}; 354 } derived; 355 bool allowForwardReferenceToDerivedType{false}; 356 }; 357 358 bool allowForwardReferenceToDerivedType() const { 359 return state_.allowForwardReferenceToDerivedType; 360 } 361 void set_allowForwardReferenceToDerivedType(bool yes) { 362 state_.allowForwardReferenceToDerivedType = yes; 363 } 364 365 const DeclTypeSpec *GetDeclTypeSpec(); 366 void BeginDeclTypeSpec(); 367 void EndDeclTypeSpec(); 368 void SetDeclTypeSpec(const DeclTypeSpec &); 369 void SetDeclTypeSpecCategory(DeclTypeSpec::Category); 370 DeclTypeSpec::Category GetDeclTypeSpecCategory() const { 371 return state_.derived.category; 372 } 373 KindExpr GetKindParamExpr( 374 TypeCategory, const std::optional<parser::KindSelector> &); 375 void CheckForAbstractType(const Symbol &typeSymbol); 376 377 private: 378 State state_; 379 380 void MakeNumericType(TypeCategory, int kind); 381 }; 382 383 // Visit ImplicitStmt and related parse tree nodes and updates implicit rules. 384 class ImplicitRulesVisitor : public DeclTypeSpecVisitor { 385 public: 386 using DeclTypeSpecVisitor::Post; 387 using DeclTypeSpecVisitor::Pre; 388 using ImplicitNoneNameSpec = parser::ImplicitStmt::ImplicitNoneNameSpec; 389 390 void Post(const parser::ParameterStmt &); 391 bool Pre(const parser::ImplicitStmt &); 392 bool Pre(const parser::LetterSpec &); 393 bool Pre(const parser::ImplicitSpec &); 394 void Post(const parser::ImplicitSpec &); 395 396 const DeclTypeSpec *GetType( 397 SourceName name, bool respectImplicitNoneType = true) { 398 return implicitRules_->GetType(name, respectImplicitNoneType); 399 } 400 bool isImplicitNoneType() const { 401 return implicitRules_->isImplicitNoneType(); 402 } 403 bool isImplicitNoneType(const Scope &scope) const { 404 return implicitRulesMap_->at(&scope).isImplicitNoneType(); 405 } 406 bool isImplicitNoneExternal() const { 407 return implicitRules_->isImplicitNoneExternal(); 408 } 409 void set_inheritFromParent(bool x) { 410 implicitRules_->set_inheritFromParent(x); 411 } 412 413 protected: 414 void BeginScope(const Scope &); 415 void SetScope(const Scope &); 416 417 private: 418 // implicit rules in effect for current scope 419 ImplicitRules *implicitRules_{nullptr}; 420 std::optional<SourceName> prevImplicit_; 421 std::optional<SourceName> prevImplicitNone_; 422 std::optional<SourceName> prevImplicitNoneType_; 423 std::optional<SourceName> prevParameterStmt_; 424 425 bool HandleImplicitNone(const std::list<ImplicitNoneNameSpec> &nameSpecs); 426 }; 427 428 // Track array specifications. They can occur in AttrSpec, EntityDecl, 429 // ObjectDecl, DimensionStmt, CommonBlockObject, BasedPointer, and 430 // ComponentDecl. 431 // 1. INTEGER, DIMENSION(10) :: x 432 // 2. INTEGER :: x(10) 433 // 3. ALLOCATABLE :: x(:) 434 // 4. DIMENSION :: x(10) 435 // 5. COMMON x(10) 436 // 6. POINTER(p,x(10)) 437 class ArraySpecVisitor : public virtual BaseVisitor { 438 public: 439 void Post(const parser::ArraySpec &); 440 void Post(const parser::ComponentArraySpec &); 441 void Post(const parser::CoarraySpec &); 442 void Post(const parser::AttrSpec &) { PostAttrSpec(); } 443 void Post(const parser::ComponentAttrSpec &) { PostAttrSpec(); } 444 445 protected: 446 const ArraySpec &arraySpec(); 447 void set_arraySpec(const ArraySpec arraySpec) { arraySpec_ = arraySpec; } 448 const ArraySpec &coarraySpec(); 449 void BeginArraySpec(); 450 void EndArraySpec(); 451 void ClearArraySpec() { arraySpec_.clear(); } 452 void ClearCoarraySpec() { coarraySpec_.clear(); } 453 454 private: 455 // arraySpec_/coarraySpec_ are populated from any ArraySpec/CoarraySpec 456 ArraySpec arraySpec_; 457 ArraySpec coarraySpec_; 458 // When an ArraySpec is under an AttrSpec or ComponentAttrSpec, it is moved 459 // into attrArraySpec_ 460 ArraySpec attrArraySpec_; 461 ArraySpec attrCoarraySpec_; 462 463 void PostAttrSpec(); 464 }; 465 466 // Manages a stack of function result information. We defer the processing 467 // of a type specification that appears in the prefix of a FUNCTION statement 468 // until the function result variable appears in the specification part 469 // or the end of the specification part. This allows for forward references 470 // in the type specification to resolve to local names. 471 class FuncResultStack { 472 public: 473 explicit FuncResultStack(ScopeHandler &scopeHandler) 474 : scopeHandler_{scopeHandler} {} 475 ~FuncResultStack(); 476 477 struct FuncInfo { 478 FuncInfo(const Scope &s, SourceName at) : scope{s}, source{at} {} 479 const Scope &scope; 480 SourceName source; 481 // Parse tree of the type specification in the FUNCTION prefix 482 const parser::DeclarationTypeSpec *parsedType{nullptr}; 483 // Name of the function RESULT in the FUNCTION suffix, if any 484 const parser::Name *resultName{nullptr}; 485 // Result symbol 486 Symbol *resultSymbol{nullptr}; 487 bool inFunctionStmt{false}; // true between Pre/Post of FunctionStmt 488 }; 489 490 // Completes the definition of the top function's result. 491 void CompleteFunctionResultType(); 492 // Completes the definition of a symbol if it is the top function's result. 493 void CompleteTypeIfFunctionResult(Symbol &); 494 495 FuncInfo *Top() { return stack_.empty() ? nullptr : &stack_.back(); } 496 FuncInfo &Push(const Scope &scope, SourceName at) { 497 return stack_.emplace_back(scope, at); 498 } 499 void Pop(); 500 501 private: 502 ScopeHandler &scopeHandler_; 503 std::vector<FuncInfo> stack_; 504 }; 505 506 // Manage a stack of Scopes 507 class ScopeHandler : public ImplicitRulesVisitor { 508 public: 509 using ImplicitRulesVisitor::Post; 510 using ImplicitRulesVisitor::Pre; 511 512 Scope &currScope() { return DEREF(currScope_); } 513 // The enclosing host procedure if current scope is in an internal procedure 514 Scope *GetHostProcedure(); 515 // The innermost enclosing program unit scope, ignoring BLOCK and other 516 // construct scopes. 517 Scope &InclusiveScope(); 518 // The enclosing scope, skipping derived types. 519 Scope &NonDerivedTypeScope(); 520 521 // Create a new scope and push it on the scope stack. 522 void PushScope(Scope::Kind kind, Symbol *symbol); 523 void PushScope(Scope &scope); 524 void PopScope(); 525 void SetScope(Scope &); 526 527 template <typename T> bool Pre(const parser::Statement<T> &x) { 528 messageHandler().set_currStmtSource(x.source); 529 currScope_->AddSourceRange(x.source); 530 return true; 531 } 532 template <typename T> void Post(const parser::Statement<T> &) { 533 messageHandler().set_currStmtSource(std::nullopt); 534 } 535 536 // Special messages: already declared; referencing symbol's declaration; 537 // about a type; two names & locations 538 void SayAlreadyDeclared(const parser::Name &, Symbol &); 539 void SayAlreadyDeclared(const SourceName &, Symbol &); 540 void SayAlreadyDeclared(const SourceName &, const SourceName &); 541 void SayWithReason( 542 const parser::Name &, Symbol &, MessageFixedText &&, Message &&); 543 template <typename... A> 544 Message &SayWithDecl( 545 const parser::Name &, Symbol &, MessageFixedText &&, A &&...args); 546 void SayLocalMustBeVariable(const parser::Name &, Symbol &); 547 Message &SayDerivedType( 548 const SourceName &, MessageFixedText &&, const Scope &); 549 Message &Say2(const SourceName &, MessageFixedText &&, const SourceName &, 550 MessageFixedText &&); 551 Message &Say2( 552 const SourceName &, MessageFixedText &&, Symbol &, MessageFixedText &&); 553 Message &Say2( 554 const parser::Name &, MessageFixedText &&, Symbol &, MessageFixedText &&); 555 556 // Search for symbol by name in current, parent derived type, and 557 // containing scopes 558 Symbol *FindSymbol(const parser::Name &); 559 Symbol *FindSymbol(const Scope &, const parser::Name &); 560 // Search for name only in scope, not in enclosing scopes. 561 Symbol *FindInScope(const Scope &, const parser::Name &); 562 Symbol *FindInScope(const Scope &, const SourceName &); 563 template <typename T> Symbol *FindInScope(const T &name) { 564 return FindInScope(currScope(), name); 565 } 566 // Search for name in a derived type scope and its parents. 567 Symbol *FindInTypeOrParents(const Scope &, const parser::Name &); 568 Symbol *FindInTypeOrParents(const parser::Name &); 569 Symbol *FindInScopeOrBlockConstructs(const Scope &, SourceName); 570 Symbol *FindSeparateModuleProcedureInterface(const parser::Name &); 571 void EraseSymbol(const parser::Name &); 572 void EraseSymbol(const Symbol &symbol) { currScope().erase(symbol.name()); } 573 // Make a new symbol with the name and attrs of an existing one 574 Symbol &CopySymbol(const SourceName &, const Symbol &); 575 576 // Make symbols in the current or named scope 577 Symbol &MakeSymbol(Scope &, const SourceName &, Attrs); 578 Symbol &MakeSymbol(const SourceName &, Attrs = Attrs{}); 579 Symbol &MakeSymbol(const parser::Name &, Attrs = Attrs{}); 580 Symbol &MakeHostAssocSymbol(const parser::Name &, const Symbol &); 581 582 template <typename D> 583 common::IfNoLvalue<Symbol &, D> MakeSymbol( 584 const parser::Name &name, D &&details) { 585 return MakeSymbol(name, Attrs{}, std::move(details)); 586 } 587 588 template <typename D> 589 common::IfNoLvalue<Symbol &, D> MakeSymbol( 590 const parser::Name &name, const Attrs &attrs, D &&details) { 591 return Resolve(name, MakeSymbol(name.source, attrs, std::move(details))); 592 } 593 594 template <typename D> 595 common::IfNoLvalue<Symbol &, D> MakeSymbol( 596 const SourceName &name, const Attrs &attrs, D &&details) { 597 // Note: don't use FindSymbol here. If this is a derived type scope, 598 // we want to detect whether the name is already declared as a component. 599 auto *symbol{FindInScope(name)}; 600 if (!symbol) { 601 symbol = &MakeSymbol(name, attrs); 602 symbol->set_details(std::move(details)); 603 return *symbol; 604 } 605 if constexpr (std::is_same_v<DerivedTypeDetails, D>) { 606 if (auto *d{symbol->detailsIf<GenericDetails>()}) { 607 if (!d->specific()) { 608 // derived type with same name as a generic 609 auto *derivedType{d->derivedType()}; 610 if (!derivedType) { 611 derivedType = 612 &currScope().MakeSymbol(name, attrs, std::move(details)); 613 d->set_derivedType(*derivedType); 614 } else if (derivedType->CanReplaceDetails(details)) { 615 // was forward-referenced 616 CheckDuplicatedAttrs(name, *symbol, attrs); 617 SetExplicitAttrs(*derivedType, attrs); 618 derivedType->set_details(std::move(details)); 619 } else { 620 SayAlreadyDeclared(name, *derivedType); 621 } 622 return *derivedType; 623 } 624 } 625 } else if constexpr (std::is_same_v<ProcEntityDetails, D>) { 626 if (auto *d{symbol->detailsIf<GenericDetails>()}) { 627 if (!d->derivedType()) { 628 // procedure pointer with same name as a generic 629 auto *specific{d->specific()}; 630 if (!specific) { 631 specific = &currScope().MakeSymbol(name, attrs, std::move(details)); 632 d->set_specific(*specific); 633 } else { 634 SayAlreadyDeclared(name, *specific); 635 } 636 return *specific; 637 } 638 } 639 } 640 if (symbol->CanReplaceDetails(details)) { 641 // update the existing symbol 642 CheckDuplicatedAttrs(name, *symbol, attrs); 643 SetExplicitAttrs(*symbol, attrs); 644 if constexpr (std::is_same_v<SubprogramDetails, D>) { 645 // Dummy argument defined by explicit interface? 646 details.set_isDummy(IsDummy(*symbol)); 647 } 648 symbol->set_details(std::move(details)); 649 return *symbol; 650 } else if constexpr (std::is_same_v<UnknownDetails, D>) { 651 CheckDuplicatedAttrs(name, *symbol, attrs); 652 SetExplicitAttrs(*symbol, attrs); 653 return *symbol; 654 } else { 655 if (!CheckPossibleBadForwardRef(*symbol)) { 656 if (name.empty() && symbol->name().empty()) { 657 // report the error elsewhere 658 return *symbol; 659 } 660 Symbol &errSym{*symbol}; 661 if (auto *d{symbol->detailsIf<GenericDetails>()}) { 662 if (d->specific()) { 663 errSym = *d->specific(); 664 } else if (d->derivedType()) { 665 errSym = *d->derivedType(); 666 } 667 } 668 SayAlreadyDeclared(name, errSym); 669 } 670 // replace the old symbol with a new one with correct details 671 EraseSymbol(*symbol); 672 auto &result{MakeSymbol(name, attrs, std::move(details))}; 673 context().SetError(result); 674 return result; 675 } 676 } 677 678 void MakeExternal(Symbol &); 679 680 // C815 duplicated attribute checking; returns false on error 681 bool CheckDuplicatedAttr(SourceName, Symbol &, Attr); 682 bool CheckDuplicatedAttrs(SourceName, Symbol &, Attrs); 683 684 void SetExplicitAttr(Symbol &symbol, Attr attr) const { 685 symbol.attrs().set(attr); 686 symbol.implicitAttrs().reset(attr); 687 } 688 void SetExplicitAttrs(Symbol &symbol, Attrs attrs) const { 689 symbol.attrs() |= attrs; 690 symbol.implicitAttrs() &= ~attrs; 691 } 692 void SetImplicitAttr(Symbol &symbol, Attr attr) const { 693 symbol.attrs().set(attr); 694 symbol.implicitAttrs().set(attr); 695 } 696 void SetCUDADataAttr( 697 SourceName, Symbol &, std::optional<common::CUDADataAttr>); 698 699 protected: 700 FuncResultStack &funcResultStack() { return funcResultStack_; } 701 702 // Apply the implicit type rules to this symbol. 703 void ApplyImplicitRules(Symbol &, bool allowForwardReference = false); 704 bool ImplicitlyTypeForwardRef(Symbol &); 705 void AcquireIntrinsicProcedureFlags(Symbol &); 706 const DeclTypeSpec *GetImplicitType( 707 Symbol &, bool respectImplicitNoneType = true); 708 void CheckEntryDummyUse(SourceName, Symbol *); 709 bool ConvertToObjectEntity(Symbol &); 710 bool ConvertToProcEntity(Symbol &, std::optional<SourceName> = std::nullopt); 711 712 const DeclTypeSpec &MakeNumericType( 713 TypeCategory, const std::optional<parser::KindSelector> &); 714 const DeclTypeSpec &MakeNumericType(TypeCategory, int); 715 const DeclTypeSpec &MakeLogicalType( 716 const std::optional<parser::KindSelector> &); 717 const DeclTypeSpec &MakeLogicalType(int); 718 void NotePossibleBadForwardRef(const parser::Name &); 719 std::optional<SourceName> HadForwardRef(const Symbol &) const; 720 bool CheckPossibleBadForwardRef(const Symbol &); 721 722 bool inSpecificationPart_{false}; 723 bool deferImplicitTyping_{false}; 724 bool skipImplicitTyping_{false}; 725 bool inEquivalenceStmt_{false}; 726 727 // Some information is collected from a specification part for deferred 728 // processing in DeclarationPartVisitor functions (e.g., CheckSaveStmts()) 729 // that are called by ResolveNamesVisitor::FinishSpecificationPart(). Since 730 // specification parts can nest (e.g., INTERFACE bodies), the collected 731 // information that is not contained in the scope needs to be packaged 732 // and restorable. 733 struct SpecificationPartState { 734 std::set<SourceName> forwardRefs; 735 // Collect equivalence sets and process at end of specification part 736 std::vector<const std::list<parser::EquivalenceObject> *> equivalenceSets; 737 // Names of all common block objects in the scope 738 std::set<SourceName> commonBlockObjects; 739 // Info about SAVE statements and attributes in current scope 740 struct { 741 std::optional<SourceName> saveAll; // "SAVE" without entity list 742 std::set<SourceName> entities; // names of entities with save attr 743 std::set<SourceName> commons; // names of common blocks with save attr 744 } saveInfo; 745 } specPartState_; 746 747 // Some declaration processing can and should be deferred to 748 // ResolveExecutionParts() to avoid prematurely creating implicitly-typed 749 // local symbols that should be host associations. 750 struct DeferredDeclarationState { 751 // The content of each namelist group 752 std::list<const parser::NamelistStmt::Group *> namelistGroups; 753 }; 754 DeferredDeclarationState *GetDeferredDeclarationState(bool add = false) { 755 if (!add && deferred_.find(&currScope()) == deferred_.end()) { 756 return nullptr; 757 } else { 758 return &deferred_.emplace(&currScope(), DeferredDeclarationState{}) 759 .first->second; 760 } 761 } 762 763 void SkipImplicitTyping(bool skip) { 764 deferImplicitTyping_ = skipImplicitTyping_ = skip; 765 } 766 767 private: 768 Scope *currScope_{nullptr}; 769 FuncResultStack funcResultStack_{*this}; 770 std::map<Scope *, DeferredDeclarationState> deferred_; 771 }; 772 773 class ModuleVisitor : public virtual ScopeHandler { 774 public: 775 bool Pre(const parser::AccessStmt &); 776 bool Pre(const parser::Only &); 777 bool Pre(const parser::Rename::Names &); 778 bool Pre(const parser::Rename::Operators &); 779 bool Pre(const parser::UseStmt &); 780 void Post(const parser::UseStmt &); 781 782 void BeginModule(const parser::Name &, bool isSubmodule); 783 bool BeginSubmodule(const parser::Name &, const parser::ParentIdentifier &); 784 void ApplyDefaultAccess(); 785 Symbol &AddGenericUse(GenericDetails &, const SourceName &, const Symbol &); 786 void AddAndCheckModuleUse(SourceName, bool isIntrinsic); 787 void CollectUseRenames(const parser::UseStmt &); 788 void ClearUseRenames() { useRenames_.clear(); } 789 void ClearUseOnly() { useOnly_.clear(); } 790 void ClearModuleUses() { 791 intrinsicUses_.clear(); 792 nonIntrinsicUses_.clear(); 793 } 794 795 private: 796 // The location of the last AccessStmt without access-ids, if any. 797 std::optional<SourceName> prevAccessStmt_; 798 // The scope of the module during a UseStmt 799 Scope *useModuleScope_{nullptr}; 800 // Names that have appeared in a rename clause of USE statements 801 std::set<std::pair<SourceName, SourceName>> useRenames_; 802 // Names that have appeared in an ONLY clause of a USE statement 803 std::set<std::pair<SourceName, Scope *>> useOnly_; 804 // Intrinsic and non-intrinsic (explicit or not) module names that 805 // have appeared in USE statements; used for C1406 warnings. 806 std::set<SourceName> intrinsicUses_; 807 std::set<SourceName> nonIntrinsicUses_; 808 809 Symbol &SetAccess(const SourceName &, Attr attr, Symbol * = nullptr); 810 // A rename in a USE statement: local => use 811 struct SymbolRename { 812 Symbol *local{nullptr}; 813 Symbol *use{nullptr}; 814 }; 815 // Record a use from useModuleScope_ of use Name/Symbol as local Name/Symbol 816 SymbolRename AddUse(const SourceName &localName, const SourceName &useName); 817 SymbolRename AddUse(const SourceName &, const SourceName &, Symbol *); 818 void DoAddUse( 819 SourceName, SourceName, Symbol &localSymbol, const Symbol &useSymbol); 820 void AddUse(const GenericSpecInfo &); 821 // Record a name appearing as the target of a USE rename clause 822 void AddUseRename(SourceName name, SourceName moduleName) { 823 useRenames_.emplace(std::make_pair(name, moduleName)); 824 } 825 bool IsUseRenamed(const SourceName &name) const { 826 return useModuleScope_ && useModuleScope_->symbol() && 827 useRenames_.find({name, useModuleScope_->symbol()->name()}) != 828 useRenames_.end(); 829 } 830 // Record a name appearing in a USE ONLY clause 831 void AddUseOnly(const SourceName &name) { 832 useOnly_.emplace(std::make_pair(name, useModuleScope_)); 833 } 834 bool IsUseOnly(const SourceName &name) const { 835 return useOnly_.find({name, useModuleScope_}) != useOnly_.end(); 836 } 837 Scope *FindModule(const parser::Name &, std::optional<bool> isIntrinsic, 838 Scope *ancestor = nullptr); 839 }; 840 841 class GenericHandler : public virtual ScopeHandler { 842 protected: 843 using ProcedureKind = parser::ProcedureStmt::Kind; 844 void ResolveSpecificsInGeneric(Symbol &, bool isEndOfSpecificationPart); 845 void DeclaredPossibleSpecificProc(Symbol &); 846 847 // Mappings of generics to their as-yet specific proc names and kinds 848 using SpecificProcMapType = 849 std::multimap<Symbol *, std::pair<const parser::Name *, ProcedureKind>>; 850 SpecificProcMapType specificsForGenericProcs_; 851 // inversion of SpecificProcMapType: maps pending proc names to generics 852 using GenericProcMapType = std::multimap<SourceName, Symbol *>; 853 GenericProcMapType genericsForSpecificProcs_; 854 }; 855 856 class InterfaceVisitor : public virtual ScopeHandler, 857 public virtual GenericHandler { 858 public: 859 bool Pre(const parser::InterfaceStmt &); 860 void Post(const parser::InterfaceStmt &); 861 void Post(const parser::EndInterfaceStmt &); 862 bool Pre(const parser::GenericSpec &); 863 bool Pre(const parser::ProcedureStmt &); 864 bool Pre(const parser::GenericStmt &); 865 void Post(const parser::GenericStmt &); 866 867 bool inInterfaceBlock() const; 868 bool isGeneric() const; 869 bool isAbstract() const; 870 871 protected: 872 Symbol &GetGenericSymbol() { return DEREF(genericInfo_.top().symbol); } 873 // Add to generic the symbol for the subprogram with the same name 874 void CheckGenericProcedures(Symbol &); 875 876 private: 877 // A new GenericInfo is pushed for each interface block and generic stmt 878 struct GenericInfo { 879 GenericInfo(bool isInterface, bool isAbstract = false) 880 : isInterface{isInterface}, isAbstract{isAbstract} {} 881 bool isInterface; // in interface block 882 bool isAbstract; // in abstract interface block 883 Symbol *symbol{nullptr}; // the generic symbol being defined 884 }; 885 std::stack<GenericInfo> genericInfo_; 886 const GenericInfo &GetGenericInfo() const { return genericInfo_.top(); } 887 void SetGenericSymbol(Symbol &symbol) { genericInfo_.top().symbol = &symbol; } 888 void AddSpecificProcs(const std::list<parser::Name> &, ProcedureKind); 889 void ResolveNewSpecifics(); 890 }; 891 892 class SubprogramVisitor : public virtual ScopeHandler, public InterfaceVisitor { 893 public: 894 bool HandleStmtFunction(const parser::StmtFunctionStmt &); 895 bool Pre(const parser::SubroutineStmt &); 896 bool Pre(const parser::FunctionStmt &); 897 void Post(const parser::FunctionStmt &); 898 bool Pre(const parser::EntryStmt &); 899 void Post(const parser::EntryStmt &); 900 bool Pre(const parser::InterfaceBody::Subroutine &); 901 void Post(const parser::InterfaceBody::Subroutine &); 902 bool Pre(const parser::InterfaceBody::Function &); 903 void Post(const parser::InterfaceBody::Function &); 904 bool Pre(const parser::Suffix &); 905 bool Pre(const parser::PrefixSpec &); 906 bool Pre(const parser::PrefixSpec::Attributes &); 907 void Post(const parser::PrefixSpec::Launch_Bounds &); 908 void Post(const parser::PrefixSpec::Cluster_Dims &); 909 910 bool BeginSubprogram(const parser::Name &, Symbol::Flag, 911 bool hasModulePrefix = false, 912 const parser::LanguageBindingSpec * = nullptr, 913 const ProgramTree::EntryStmtList * = nullptr); 914 bool BeginMpSubprogram(const parser::Name &); 915 void PushBlockDataScope(const parser::Name &); 916 void EndSubprogram(std::optional<parser::CharBlock> stmtSource = std::nullopt, 917 const std::optional<parser::LanguageBindingSpec> * = nullptr, 918 const ProgramTree::EntryStmtList * = nullptr); 919 920 protected: 921 // Set when we see a stmt function that is really an array element assignment 922 bool misparsedStmtFuncFound_{false}; 923 924 private: 925 // Edits an existing symbol created for earlier calls to a subprogram or ENTRY 926 // so that it can be replaced by a later definition. 927 bool HandlePreviousCalls(const parser::Name &, Symbol &, Symbol::Flag); 928 void CheckExtantProc(const parser::Name &, Symbol::Flag); 929 // Create a subprogram symbol in the current scope and push a new scope. 930 Symbol &PushSubprogramScope(const parser::Name &, Symbol::Flag, 931 const parser::LanguageBindingSpec * = nullptr, 932 bool hasModulePrefix = false); 933 Symbol *GetSpecificFromGeneric(const parser::Name &); 934 Symbol &PostSubprogramStmt(); 935 void CreateDummyArgument(SubprogramDetails &, const parser::Name &); 936 void CreateEntry(const parser::EntryStmt &stmt, Symbol &subprogram); 937 void PostEntryStmt(const parser::EntryStmt &stmt); 938 void HandleLanguageBinding(Symbol *, 939 std::optional<parser::CharBlock> stmtSource, 940 const std::optional<parser::LanguageBindingSpec> *); 941 }; 942 943 class DeclarationVisitor : public ArraySpecVisitor, 944 public virtual GenericHandler { 945 public: 946 using ArraySpecVisitor::Post; 947 using ScopeHandler::Post; 948 using ScopeHandler::Pre; 949 950 bool Pre(const parser::Initialization &); 951 void Post(const parser::EntityDecl &); 952 void Post(const parser::ObjectDecl &); 953 void Post(const parser::PointerDecl &); 954 bool Pre(const parser::BindStmt &) { return BeginAttrs(); } 955 void Post(const parser::BindStmt &) { EndAttrs(); } 956 bool Pre(const parser::BindEntity &); 957 bool Pre(const parser::OldParameterStmt &); 958 bool Pre(const parser::NamedConstantDef &); 959 bool Pre(const parser::NamedConstant &); 960 void Post(const parser::EnumDef &); 961 bool Pre(const parser::Enumerator &); 962 bool Pre(const parser::AccessSpec &); 963 bool Pre(const parser::AsynchronousStmt &); 964 bool Pre(const parser::ContiguousStmt &); 965 bool Pre(const parser::ExternalStmt &); 966 bool Pre(const parser::IntentStmt &); 967 bool Pre(const parser::IntrinsicStmt &); 968 bool Pre(const parser::OptionalStmt &); 969 bool Pre(const parser::ProtectedStmt &); 970 bool Pre(const parser::ValueStmt &); 971 bool Pre(const parser::VolatileStmt &); 972 bool Pre(const parser::AllocatableStmt &) { 973 objectDeclAttr_ = Attr::ALLOCATABLE; 974 return true; 975 } 976 void Post(const parser::AllocatableStmt &) { objectDeclAttr_ = std::nullopt; } 977 bool Pre(const parser::TargetStmt &) { 978 objectDeclAttr_ = Attr::TARGET; 979 return true; 980 } 981 bool Pre(const parser::CUDAAttributesStmt &); 982 void Post(const parser::TargetStmt &) { objectDeclAttr_ = std::nullopt; } 983 void Post(const parser::DimensionStmt::Declaration &); 984 void Post(const parser::CodimensionDecl &); 985 bool Pre(const parser::TypeDeclarationStmt &); 986 void Post(const parser::TypeDeclarationStmt &); 987 void Post(const parser::IntegerTypeSpec &); 988 void Post(const parser::UnsignedTypeSpec &); 989 void Post(const parser::IntrinsicTypeSpec::Real &); 990 void Post(const parser::IntrinsicTypeSpec::Complex &); 991 void Post(const parser::IntrinsicTypeSpec::Logical &); 992 void Post(const parser::IntrinsicTypeSpec::Character &); 993 void Post(const parser::CharSelector::LengthAndKind &); 994 void Post(const parser::CharLength &); 995 void Post(const parser::LengthSelector &); 996 bool Pre(const parser::KindParam &); 997 bool Pre(const parser::VectorTypeSpec &); 998 void Post(const parser::VectorTypeSpec &); 999 bool Pre(const parser::DeclarationTypeSpec::Type &); 1000 void Post(const parser::DeclarationTypeSpec::Type &); 1001 bool Pre(const parser::DeclarationTypeSpec::Class &); 1002 void Post(const parser::DeclarationTypeSpec::Class &); 1003 void Post(const parser::DeclarationTypeSpec::Record &); 1004 void Post(const parser::DerivedTypeSpec &); 1005 bool Pre(const parser::DerivedTypeDef &); 1006 bool Pre(const parser::DerivedTypeStmt &); 1007 void Post(const parser::DerivedTypeStmt &); 1008 bool Pre(const parser::TypeParamDefStmt &) { return BeginDecl(); } 1009 void Post(const parser::TypeParamDefStmt &); 1010 bool Pre(const parser::TypeAttrSpec::Extends &); 1011 bool Pre(const parser::PrivateStmt &); 1012 bool Pre(const parser::SequenceStmt &); 1013 bool Pre(const parser::ComponentDefStmt &) { return BeginDecl(); } 1014 void Post(const parser::ComponentDefStmt &) { EndDecl(); } 1015 void Post(const parser::ComponentDecl &); 1016 void Post(const parser::FillDecl &); 1017 bool Pre(const parser::ProcedureDeclarationStmt &); 1018 void Post(const parser::ProcedureDeclarationStmt &); 1019 bool Pre(const parser::DataComponentDefStmt &); // returns false 1020 bool Pre(const parser::ProcComponentDefStmt &); 1021 void Post(const parser::ProcComponentDefStmt &); 1022 bool Pre(const parser::ProcPointerInit &); 1023 void Post(const parser::ProcInterface &); 1024 void Post(const parser::ProcDecl &); 1025 bool Pre(const parser::TypeBoundProcedurePart &); 1026 void Post(const parser::TypeBoundProcedurePart &); 1027 void Post(const parser::ContainsStmt &); 1028 bool Pre(const parser::TypeBoundProcBinding &) { return BeginAttrs(); } 1029 void Post(const parser::TypeBoundProcBinding &) { EndAttrs(); } 1030 void Post(const parser::TypeBoundProcedureStmt::WithoutInterface &); 1031 void Post(const parser::TypeBoundProcedureStmt::WithInterface &); 1032 bool Pre(const parser::FinalProcedureStmt &); 1033 bool Pre(const parser::TypeBoundGenericStmt &); 1034 bool Pre(const parser::StructureDef &); // returns false 1035 bool Pre(const parser::Union::UnionStmt &); 1036 bool Pre(const parser::StructureField &); 1037 void Post(const parser::StructureField &); 1038 bool Pre(const parser::AllocateStmt &); 1039 void Post(const parser::AllocateStmt &); 1040 bool Pre(const parser::StructureConstructor &); 1041 bool Pre(const parser::NamelistStmt::Group &); 1042 bool Pre(const parser::IoControlSpec &); 1043 bool Pre(const parser::CommonStmt::Block &); 1044 bool Pre(const parser::CommonBlockObject &); 1045 void Post(const parser::CommonBlockObject &); 1046 bool Pre(const parser::EquivalenceStmt &); 1047 bool Pre(const parser::SaveStmt &); 1048 bool Pre(const parser::BasedPointer &); 1049 void Post(const parser::BasedPointer &); 1050 1051 void PointerInitialization( 1052 const parser::Name &, const parser::InitialDataTarget &); 1053 void PointerInitialization( 1054 const parser::Name &, const parser::ProcPointerInit &); 1055 void NonPointerInitialization( 1056 const parser::Name &, const parser::ConstantExpr &); 1057 void CheckExplicitInterface(const parser::Name &); 1058 void CheckBindings(const parser::TypeBoundProcedureStmt::WithoutInterface &); 1059 1060 const parser::Name *ResolveDesignator(const parser::Designator &); 1061 int GetVectorElementKind( 1062 TypeCategory category, const std::optional<parser::KindSelector> &kind); 1063 1064 protected: 1065 bool BeginDecl(); 1066 void EndDecl(); 1067 Symbol &DeclareObjectEntity(const parser::Name &, Attrs = Attrs{}); 1068 // Make sure that there's an entity in an enclosing scope called Name 1069 Symbol &FindOrDeclareEnclosingEntity(const parser::Name &); 1070 // Declare a LOCAL/LOCAL_INIT/REDUCE entity while setting a locality flag. If 1071 // there isn't a type specified it comes from the entity in the containing 1072 // scope, or implicit rules. 1073 void DeclareLocalEntity(const parser::Name &, Symbol::Flag); 1074 // Declare a statement entity (i.e., an implied DO loop index for 1075 // a DATA statement or an array constructor). If there isn't an explict 1076 // type specified, implicit rules apply. Return pointer to the new symbol, 1077 // or nullptr on error. 1078 Symbol *DeclareStatementEntity(const parser::DoVariable &, 1079 const std::optional<parser::IntegerTypeSpec> &); 1080 Symbol &MakeCommonBlockSymbol(const parser::Name &); 1081 Symbol &MakeCommonBlockSymbol(const std::optional<parser::Name> &); 1082 bool CheckUseError(const parser::Name &); 1083 void CheckAccessibility(const SourceName &, bool, Symbol &); 1084 void CheckCommonBlocks(); 1085 void CheckSaveStmts(); 1086 void CheckEquivalenceSets(); 1087 bool CheckNotInBlock(const char *); 1088 bool NameIsKnownOrIntrinsic(const parser::Name &); 1089 void FinishNamelists(); 1090 1091 // Each of these returns a pointer to a resolved Name (i.e. with symbol) 1092 // or nullptr in case of error. 1093 const parser::Name *ResolveStructureComponent( 1094 const parser::StructureComponent &); 1095 const parser::Name *ResolveDataRef(const parser::DataRef &); 1096 const parser::Name *ResolveName(const parser::Name &); 1097 bool PassesSharedLocalityChecks(const parser::Name &name, Symbol &symbol); 1098 Symbol *NoteInterfaceName(const parser::Name &); 1099 bool IsUplevelReference(const Symbol &); 1100 1101 std::optional<SourceName> BeginCheckOnIndexUseInOwnBounds( 1102 const parser::DoVariable &name) { 1103 std::optional<SourceName> result{checkIndexUseInOwnBounds_}; 1104 checkIndexUseInOwnBounds_ = name.thing.thing.source; 1105 return result; 1106 } 1107 void EndCheckOnIndexUseInOwnBounds(const std::optional<SourceName> &restore) { 1108 checkIndexUseInOwnBounds_ = restore; 1109 } 1110 void NoteScalarSpecificationArgument(const Symbol &symbol) { 1111 mustBeScalar_.emplace(symbol); 1112 } 1113 // Declare an object or procedure entity. 1114 // T is one of: EntityDetails, ObjectEntityDetails, ProcEntityDetails 1115 template <typename T> 1116 Symbol &DeclareEntity(const parser::Name &name, Attrs attrs) { 1117 Symbol &symbol{MakeSymbol(name, attrs)}; 1118 if (context().HasError(symbol) || symbol.has<T>()) { 1119 return symbol; // OK or error already reported 1120 } else if (symbol.has<UnknownDetails>()) { 1121 symbol.set_details(T{}); 1122 return symbol; 1123 } else if (auto *details{symbol.detailsIf<EntityDetails>()}) { 1124 symbol.set_details(T{std::move(*details)}); 1125 return symbol; 1126 } else if (std::is_same_v<EntityDetails, T> && 1127 (symbol.has<ObjectEntityDetails>() || 1128 symbol.has<ProcEntityDetails>())) { 1129 return symbol; // OK 1130 } else if (auto *details{symbol.detailsIf<UseDetails>()}) { 1131 Say(name.source, 1132 "'%s' is use-associated from module '%s' and cannot be re-declared"_err_en_US, 1133 name.source, GetUsedModule(*details).name()); 1134 } else if (auto *details{symbol.detailsIf<SubprogramNameDetails>()}) { 1135 if (details->kind() == SubprogramKind::Module) { 1136 Say2(name, 1137 "Declaration of '%s' conflicts with its use as module procedure"_err_en_US, 1138 symbol, "Module procedure definition"_en_US); 1139 } else if (details->kind() == SubprogramKind::Internal) { 1140 Say2(name, 1141 "Declaration of '%s' conflicts with its use as internal procedure"_err_en_US, 1142 symbol, "Internal procedure definition"_en_US); 1143 } else { 1144 DIE("unexpected kind"); 1145 } 1146 } else if (std::is_same_v<ObjectEntityDetails, T> && 1147 symbol.has<ProcEntityDetails>()) { 1148 SayWithDecl( 1149 name, symbol, "'%s' is already declared as a procedure"_err_en_US); 1150 } else if (std::is_same_v<ProcEntityDetails, T> && 1151 symbol.has<ObjectEntityDetails>()) { 1152 if (FindCommonBlockContaining(symbol)) { 1153 SayWithDecl(name, symbol, 1154 "'%s' may not be a procedure as it is in a COMMON block"_err_en_US); 1155 } else { 1156 SayWithDecl( 1157 name, symbol, "'%s' is already declared as an object"_err_en_US); 1158 } 1159 } else if (!CheckPossibleBadForwardRef(symbol)) { 1160 SayAlreadyDeclared(name, symbol); 1161 } 1162 context().SetError(symbol); 1163 return symbol; 1164 } 1165 1166 private: 1167 // The attribute corresponding to the statement containing an ObjectDecl 1168 std::optional<Attr> objectDeclAttr_; 1169 // Info about current character type while walking DeclTypeSpec. 1170 // Also captures any "*length" specifier on an individual declaration. 1171 struct { 1172 std::optional<ParamValue> length; 1173 std::optional<KindExpr> kind; 1174 } charInfo_; 1175 // Info about current derived type or STRUCTURE while walking 1176 // DerivedTypeDef / StructureDef 1177 struct { 1178 const parser::Name *extends{nullptr}; // EXTENDS(name) 1179 bool privateComps{false}; // components are private by default 1180 bool privateBindings{false}; // bindings are private by default 1181 bool sawContains{false}; // currently processing bindings 1182 bool sequence{false}; // is a sequence type 1183 const Symbol *type{nullptr}; // derived type being defined 1184 bool isStructure{false}; // is a DEC STRUCTURE 1185 } derivedTypeInfo_; 1186 // In a ProcedureDeclarationStmt or ProcComponentDefStmt, this is 1187 // the interface name, if any. 1188 const parser::Name *interfaceName_{nullptr}; 1189 // Map type-bound generic to binding names of its specific bindings 1190 std::multimap<Symbol *, const parser::Name *> genericBindings_; 1191 // Info about current ENUM 1192 struct EnumeratorState { 1193 // Enum value must hold inside a C_INT (7.6.2). 1194 std::optional<int> value{0}; 1195 } enumerationState_; 1196 // Set for OldParameterStmt processing 1197 bool inOldStyleParameterStmt_{false}; 1198 // Set when walking DATA & array constructor implied DO loop bounds 1199 // to warn about use of the implied DO intex therein. 1200 std::optional<SourceName> checkIndexUseInOwnBounds_; 1201 bool isVectorType_{false}; 1202 UnorderedSymbolSet mustBeScalar_; 1203 1204 bool HandleAttributeStmt(Attr, const std::list<parser::Name> &); 1205 Symbol &HandleAttributeStmt(Attr, const parser::Name &); 1206 Symbol &DeclareUnknownEntity(const parser::Name &, Attrs); 1207 Symbol &DeclareProcEntity( 1208 const parser::Name &, Attrs, const Symbol *interface); 1209 void SetType(const parser::Name &, const DeclTypeSpec &); 1210 std::optional<DerivedTypeSpec> ResolveDerivedType(const parser::Name &); 1211 std::optional<DerivedTypeSpec> ResolveExtendsType( 1212 const parser::Name &, const parser::Name *); 1213 Symbol *MakeTypeSymbol(const SourceName &, Details &&); 1214 Symbol *MakeTypeSymbol(const parser::Name &, Details &&); 1215 bool OkToAddComponent(const parser::Name &, const Symbol *extends = nullptr); 1216 ParamValue GetParamValue( 1217 const parser::TypeParamValue &, common::TypeParamAttr attr); 1218 void CheckCommonBlockDerivedType( 1219 const SourceName &, const Symbol &, UnorderedSymbolSet &); 1220 Attrs HandleSaveName(const SourceName &, Attrs); 1221 void AddSaveName(std::set<SourceName> &, const SourceName &); 1222 bool HandleUnrestrictedSpecificIntrinsicFunction(const parser::Name &); 1223 const parser::Name *FindComponent(const parser::Name *, const parser::Name &); 1224 void Initialization(const parser::Name &, const parser::Initialization &, 1225 bool inComponentDecl); 1226 bool PassesLocalityChecks( 1227 const parser::Name &name, Symbol &symbol, Symbol::Flag flag); 1228 bool CheckForHostAssociatedImplicit(const parser::Name &); 1229 bool HasCycle(const Symbol &, const Symbol *interface); 1230 bool MustBeScalar(const Symbol &symbol) const { 1231 return mustBeScalar_.find(symbol) != mustBeScalar_.end(); 1232 } 1233 void DeclareIntrinsic(const parser::Name &); 1234 }; 1235 1236 // Resolve construct entities and statement entities. 1237 // Check that construct names don't conflict with other names. 1238 class ConstructVisitor : public virtual DeclarationVisitor { 1239 public: 1240 bool Pre(const parser::ConcurrentHeader &); 1241 bool Pre(const parser::LocalitySpec::Local &); 1242 bool Pre(const parser::LocalitySpec::LocalInit &); 1243 bool Pre(const parser::LocalitySpec::Reduce &); 1244 bool Pre(const parser::LocalitySpec::Shared &); 1245 bool Pre(const parser::AcSpec &); 1246 bool Pre(const parser::AcImpliedDo &); 1247 bool Pre(const parser::DataImpliedDo &); 1248 bool Pre(const parser::DataIDoObject &); 1249 bool Pre(const parser::DataStmtObject &); 1250 bool Pre(const parser::DataStmtValue &); 1251 bool Pre(const parser::DoConstruct &); 1252 void Post(const parser::DoConstruct &); 1253 bool Pre(const parser::ForallConstruct &); 1254 void Post(const parser::ForallConstruct &); 1255 bool Pre(const parser::ForallStmt &); 1256 void Post(const parser::ForallStmt &); 1257 bool Pre(const parser::BlockConstruct &); 1258 void Post(const parser::Selector &); 1259 void Post(const parser::AssociateStmt &); 1260 void Post(const parser::EndAssociateStmt &); 1261 bool Pre(const parser::Association &); 1262 void Post(const parser::SelectTypeStmt &); 1263 void Post(const parser::SelectRankStmt &); 1264 bool Pre(const parser::SelectTypeConstruct &); 1265 void Post(const parser::SelectTypeConstruct &); 1266 bool Pre(const parser::SelectTypeConstruct::TypeCase &); 1267 void Post(const parser::SelectTypeConstruct::TypeCase &); 1268 // Creates Block scopes with neither symbol name nor symbol details. 1269 bool Pre(const parser::SelectRankConstruct::RankCase &); 1270 void Post(const parser::SelectRankConstruct::RankCase &); 1271 bool Pre(const parser::TypeGuardStmt::Guard &); 1272 void Post(const parser::TypeGuardStmt::Guard &); 1273 void Post(const parser::SelectRankCaseStmt::Rank &); 1274 bool Pre(const parser::ChangeTeamStmt &); 1275 void Post(const parser::EndChangeTeamStmt &); 1276 void Post(const parser::CoarrayAssociation &); 1277 1278 // Definitions of construct names 1279 bool Pre(const parser::WhereConstructStmt &x) { return CheckDef(x.t); } 1280 bool Pre(const parser::ForallConstructStmt &x) { return CheckDef(x.t); } 1281 bool Pre(const parser::CriticalStmt &x) { return CheckDef(x.t); } 1282 bool Pre(const parser::LabelDoStmt &) { 1283 return false; // error recovery 1284 } 1285 bool Pre(const parser::NonLabelDoStmt &x) { return CheckDef(x.t); } 1286 bool Pre(const parser::IfThenStmt &x) { return CheckDef(x.t); } 1287 bool Pre(const parser::SelectCaseStmt &x) { return CheckDef(x.t); } 1288 bool Pre(const parser::SelectRankConstruct &); 1289 void Post(const parser::SelectRankConstruct &); 1290 bool Pre(const parser::SelectRankStmt &x) { 1291 return CheckDef(std::get<0>(x.t)); 1292 } 1293 bool Pre(const parser::SelectTypeStmt &x) { 1294 return CheckDef(std::get<0>(x.t)); 1295 } 1296 1297 // References to construct names 1298 void Post(const parser::MaskedElsewhereStmt &x) { CheckRef(x.t); } 1299 void Post(const parser::ElsewhereStmt &x) { CheckRef(x.v); } 1300 void Post(const parser::EndWhereStmt &x) { CheckRef(x.v); } 1301 void Post(const parser::EndForallStmt &x) { CheckRef(x.v); } 1302 void Post(const parser::EndCriticalStmt &x) { CheckRef(x.v); } 1303 void Post(const parser::EndDoStmt &x) { CheckRef(x.v); } 1304 void Post(const parser::ElseIfStmt &x) { CheckRef(x.t); } 1305 void Post(const parser::ElseStmt &x) { CheckRef(x.v); } 1306 void Post(const parser::EndIfStmt &x) { CheckRef(x.v); } 1307 void Post(const parser::CaseStmt &x) { CheckRef(x.t); } 1308 void Post(const parser::EndSelectStmt &x) { CheckRef(x.v); } 1309 void Post(const parser::SelectRankCaseStmt &x) { CheckRef(x.t); } 1310 void Post(const parser::TypeGuardStmt &x) { CheckRef(x.t); } 1311 void Post(const parser::CycleStmt &x) { CheckRef(x.v); } 1312 void Post(const parser::ExitStmt &x) { CheckRef(x.v); } 1313 1314 void HandleImpliedAsynchronousInScope(const parser::Block &); 1315 1316 private: 1317 // R1105 selector -> expr | variable 1318 // expr is set in either case unless there were errors 1319 struct Selector { 1320 Selector() {} 1321 Selector(const SourceName &source, MaybeExpr &&expr) 1322 : source{source}, expr{std::move(expr)} {} 1323 operator bool() const { return expr.has_value(); } 1324 parser::CharBlock source; 1325 MaybeExpr expr; 1326 }; 1327 // association -> [associate-name =>] selector 1328 struct Association { 1329 const parser::Name *name{nullptr}; 1330 Selector selector; 1331 }; 1332 std::vector<Association> associationStack_; 1333 Association *currentAssociation_{nullptr}; 1334 1335 template <typename T> bool CheckDef(const T &t) { 1336 return CheckDef(std::get<std::optional<parser::Name>>(t)); 1337 } 1338 template <typename T> void CheckRef(const T &t) { 1339 CheckRef(std::get<std::optional<parser::Name>>(t)); 1340 } 1341 bool CheckDef(const std::optional<parser::Name> &); 1342 void CheckRef(const std::optional<parser::Name> &); 1343 const DeclTypeSpec &ToDeclTypeSpec(evaluate::DynamicType &&); 1344 const DeclTypeSpec &ToDeclTypeSpec( 1345 evaluate::DynamicType &&, MaybeSubscriptIntExpr &&length); 1346 Symbol *MakeAssocEntity(); 1347 void SetTypeFromAssociation(Symbol &); 1348 void SetAttrsFromAssociation(Symbol &); 1349 Selector ResolveSelector(const parser::Selector &); 1350 void ResolveIndexName(const parser::ConcurrentControl &control); 1351 void SetCurrentAssociation(std::size_t n); 1352 Association &GetCurrentAssociation(); 1353 void PushAssociation(); 1354 void PopAssociation(std::size_t count = 1); 1355 }; 1356 1357 // Create scopes for OpenACC constructs 1358 class AccVisitor : public virtual DeclarationVisitor { 1359 public: 1360 void AddAccSourceRange(const parser::CharBlock &); 1361 1362 static bool NeedsScope(const parser::OpenACCBlockConstruct &); 1363 1364 bool Pre(const parser::OpenACCBlockConstruct &); 1365 void Post(const parser::OpenACCBlockConstruct &); 1366 bool Pre(const parser::OpenACCCombinedConstruct &); 1367 void Post(const parser::OpenACCCombinedConstruct &); 1368 bool Pre(const parser::AccBeginBlockDirective &x) { 1369 AddAccSourceRange(x.source); 1370 return true; 1371 } 1372 void Post(const parser::AccBeginBlockDirective &) { 1373 messageHandler().set_currStmtSource(std::nullopt); 1374 } 1375 bool Pre(const parser::AccEndBlockDirective &x) { 1376 AddAccSourceRange(x.source); 1377 return true; 1378 } 1379 void Post(const parser::AccEndBlockDirective &) { 1380 messageHandler().set_currStmtSource(std::nullopt); 1381 } 1382 bool Pre(const parser::AccBeginLoopDirective &x) { 1383 AddAccSourceRange(x.source); 1384 return true; 1385 } 1386 void Post(const parser::AccBeginLoopDirective &x) { 1387 messageHandler().set_currStmtSource(std::nullopt); 1388 } 1389 }; 1390 1391 bool AccVisitor::NeedsScope(const parser::OpenACCBlockConstruct &x) { 1392 const auto &beginBlockDir{std::get<parser::AccBeginBlockDirective>(x.t)}; 1393 const auto &beginDir{std::get<parser::AccBlockDirective>(beginBlockDir.t)}; 1394 switch (beginDir.v) { 1395 case llvm::acc::Directive::ACCD_data: 1396 case llvm::acc::Directive::ACCD_host_data: 1397 case llvm::acc::Directive::ACCD_kernels: 1398 case llvm::acc::Directive::ACCD_parallel: 1399 case llvm::acc::Directive::ACCD_serial: 1400 return true; 1401 default: 1402 return false; 1403 } 1404 } 1405 1406 void AccVisitor::AddAccSourceRange(const parser::CharBlock &source) { 1407 messageHandler().set_currStmtSource(source); 1408 currScope().AddSourceRange(source); 1409 } 1410 1411 bool AccVisitor::Pre(const parser::OpenACCBlockConstruct &x) { 1412 if (NeedsScope(x)) { 1413 PushScope(Scope::Kind::OpenACCConstruct, nullptr); 1414 } 1415 return true; 1416 } 1417 1418 void AccVisitor::Post(const parser::OpenACCBlockConstruct &x) { 1419 if (NeedsScope(x)) { 1420 PopScope(); 1421 } 1422 } 1423 1424 bool AccVisitor::Pre(const parser::OpenACCCombinedConstruct &x) { 1425 PushScope(Scope::Kind::OpenACCConstruct, nullptr); 1426 return true; 1427 } 1428 1429 void AccVisitor::Post(const parser::OpenACCCombinedConstruct &x) { PopScope(); } 1430 1431 // Create scopes for OpenMP constructs 1432 class OmpVisitor : public virtual DeclarationVisitor { 1433 public: 1434 void AddOmpSourceRange(const parser::CharBlock &); 1435 1436 static bool NeedsScope(const parser::OpenMPBlockConstruct &); 1437 static bool NeedsScope(const parser::OmpClause &); 1438 1439 bool Pre(const parser::OpenMPRequiresConstruct &x) { 1440 AddOmpSourceRange(x.source); 1441 return true; 1442 } 1443 bool Pre(const parser::OmpSimpleStandaloneDirective &x) { 1444 AddOmpSourceRange(x.source); 1445 return true; 1446 } 1447 bool Pre(const parser::OpenMPBlockConstruct &); 1448 void Post(const parser::OpenMPBlockConstruct &); 1449 bool Pre(const parser::OmpBeginBlockDirective &x) { 1450 AddOmpSourceRange(x.source); 1451 return true; 1452 } 1453 void Post(const parser::OmpBeginBlockDirective &) { 1454 messageHandler().set_currStmtSource(std::nullopt); 1455 } 1456 bool Pre(const parser::OmpEndBlockDirective &x) { 1457 AddOmpSourceRange(x.source); 1458 return true; 1459 } 1460 void Post(const parser::OmpEndBlockDirective &) { 1461 messageHandler().set_currStmtSource(std::nullopt); 1462 } 1463 1464 bool Pre(const parser::OpenMPLoopConstruct &) { 1465 PushScope(Scope::Kind::OtherConstruct, nullptr); 1466 return true; 1467 } 1468 void Post(const parser::OpenMPLoopConstruct &) { PopScope(); } 1469 bool Pre(const parser::OmpBeginLoopDirective &x) { 1470 AddOmpSourceRange(x.source); 1471 return true; 1472 } 1473 1474 bool Pre(const parser::OpenMPDeclareMapperConstruct &); 1475 1476 bool Pre(const parser::OmpMapClause &); 1477 1478 void Post(const parser::OmpBeginLoopDirective &) { 1479 messageHandler().set_currStmtSource(std::nullopt); 1480 } 1481 bool Pre(const parser::OmpEndLoopDirective &x) { 1482 AddOmpSourceRange(x.source); 1483 return true; 1484 } 1485 void Post(const parser::OmpEndLoopDirective &) { 1486 messageHandler().set_currStmtSource(std::nullopt); 1487 } 1488 1489 bool Pre(const parser::OpenMPSectionsConstruct &) { 1490 PushScope(Scope::Kind::OtherConstruct, nullptr); 1491 return true; 1492 } 1493 void Post(const parser::OpenMPSectionsConstruct &) { PopScope(); } 1494 bool Pre(const parser::OmpBeginSectionsDirective &x) { 1495 AddOmpSourceRange(x.source); 1496 return true; 1497 } 1498 void Post(const parser::OmpBeginSectionsDirective &) { 1499 messageHandler().set_currStmtSource(std::nullopt); 1500 } 1501 bool Pre(const parser::OmpEndSectionsDirective &x) { 1502 AddOmpSourceRange(x.source); 1503 return true; 1504 } 1505 void Post(const parser::OmpEndSectionsDirective &) { 1506 messageHandler().set_currStmtSource(std::nullopt); 1507 } 1508 bool Pre(const parser::OmpCriticalDirective &x) { 1509 AddOmpSourceRange(x.source); 1510 return true; 1511 } 1512 void Post(const parser::OmpCriticalDirective &) { 1513 messageHandler().set_currStmtSource(std::nullopt); 1514 } 1515 bool Pre(const parser::OmpEndCriticalDirective &x) { 1516 AddOmpSourceRange(x.source); 1517 return true; 1518 } 1519 void Post(const parser::OmpEndCriticalDirective &) { 1520 messageHandler().set_currStmtSource(std::nullopt); 1521 } 1522 bool Pre(const parser::OpenMPThreadprivate &) { 1523 SkipImplicitTyping(true); 1524 return true; 1525 } 1526 void Post(const parser::OpenMPThreadprivate &) { SkipImplicitTyping(false); } 1527 bool Pre(const parser::OpenMPDeclareTargetConstruct &) { 1528 SkipImplicitTyping(true); 1529 return true; 1530 } 1531 void Post(const parser::OpenMPDeclareTargetConstruct &) { 1532 SkipImplicitTyping(false); 1533 } 1534 bool Pre(const parser::OpenMPDeclarativeAllocate &) { 1535 SkipImplicitTyping(true); 1536 return true; 1537 } 1538 void Post(const parser::OpenMPDeclarativeAllocate &) { 1539 SkipImplicitTyping(false); 1540 } 1541 bool Pre(const parser::OpenMPDeclarativeConstruct &x) { 1542 AddOmpSourceRange(x.source); 1543 return true; 1544 } 1545 void Post(const parser::OpenMPDeclarativeConstruct &) { 1546 messageHandler().set_currStmtSource(std::nullopt); 1547 } 1548 bool Pre(const parser::OpenMPDepobjConstruct &x) { 1549 AddOmpSourceRange(x.source); 1550 return true; 1551 } 1552 void Post(const parser::OpenMPDepobjConstruct &x) { 1553 messageHandler().set_currStmtSource(std::nullopt); 1554 } 1555 bool Pre(const parser::OpenMPAtomicConstruct &x) { 1556 return common::visit(common::visitors{[&](const auto &u) -> bool { 1557 AddOmpSourceRange(u.source); 1558 return true; 1559 }}, 1560 x.u); 1561 } 1562 void Post(const parser::OpenMPAtomicConstruct &) { 1563 messageHandler().set_currStmtSource(std::nullopt); 1564 } 1565 bool Pre(const parser::OmpClause &x) { 1566 if (NeedsScope(x)) { 1567 PushScope(Scope::Kind::OtherClause, nullptr); 1568 } 1569 return true; 1570 } 1571 void Post(const parser::OmpClause &x) { 1572 if (NeedsScope(x)) { 1573 PopScope(); 1574 } 1575 } 1576 }; 1577 1578 bool OmpVisitor::NeedsScope(const parser::OpenMPBlockConstruct &x) { 1579 const auto &beginBlockDir{std::get<parser::OmpBeginBlockDirective>(x.t)}; 1580 const auto &beginDir{std::get<parser::OmpBlockDirective>(beginBlockDir.t)}; 1581 switch (beginDir.v) { 1582 case llvm::omp::Directive::OMPD_master: 1583 case llvm::omp::Directive::OMPD_ordered: 1584 case llvm::omp::Directive::OMPD_taskgroup: 1585 return false; 1586 default: 1587 return true; 1588 } 1589 } 1590 1591 bool OmpVisitor::NeedsScope(const parser::OmpClause &x) { 1592 // Iterators contain declarations, whose scope extends until the end 1593 // the clause. 1594 return llvm::omp::canHaveIterator(x.Id()); 1595 } 1596 1597 void OmpVisitor::AddOmpSourceRange(const parser::CharBlock &source) { 1598 messageHandler().set_currStmtSource(source); 1599 currScope().AddSourceRange(source); 1600 } 1601 1602 bool OmpVisitor::Pre(const parser::OpenMPBlockConstruct &x) { 1603 if (NeedsScope(x)) { 1604 PushScope(Scope::Kind::OtherConstruct, nullptr); 1605 } 1606 return true; 1607 } 1608 1609 void OmpVisitor::Post(const parser::OpenMPBlockConstruct &x) { 1610 if (NeedsScope(x)) { 1611 PopScope(); 1612 } 1613 } 1614 1615 // This "manually" walks the tree of the construct, because we need 1616 // to resolve the type before the map clauses are processed - when 1617 // just following the natural flow, the map clauses gets processed before 1618 // the type has been fully processed. 1619 bool OmpVisitor::Pre(const parser::OpenMPDeclareMapperConstruct &x) { 1620 AddOmpSourceRange(x.source); 1621 BeginDeclTypeSpec(); 1622 const auto &spec{std::get<parser::OmpDeclareMapperSpecifier>(x.t)}; 1623 Symbol *mapperSym{nullptr}; 1624 if (const auto &mapperName{std::get<std::optional<parser::Name>>(spec.t)}) { 1625 mapperSym = 1626 &MakeSymbol(*mapperName, MiscDetails{MiscDetails::Kind::ConstructName}); 1627 mapperName->symbol = mapperSym; 1628 } else { 1629 const parser::CharBlock defaultName{"default", 7}; 1630 mapperSym = &MakeSymbol( 1631 defaultName, Attrs{}, MiscDetails{MiscDetails::Kind::ConstructName}); 1632 } 1633 1634 PushScope(Scope::Kind::OtherConstruct, nullptr); 1635 Walk(std::get<parser::TypeSpec>(spec.t)); 1636 const auto &varName{std::get<parser::ObjectName>(spec.t)}; 1637 DeclareObjectEntity(varName); 1638 1639 Walk(std::get<parser::OmpClauseList>(x.t)); 1640 1641 EndDeclTypeSpec(); 1642 PopScope(); 1643 return false; 1644 } 1645 1646 bool OmpVisitor::Pre(const parser::OmpMapClause &x) { 1647 auto &mods{OmpGetModifiers(x)}; 1648 if (auto *mapper{OmpGetUniqueModifier<parser::OmpMapper>(mods)}) { 1649 if (auto *symbol{FindSymbol(currScope(), mapper->v)}) { 1650 // TODO: Do we need a specific flag or type here, to distinghuish against 1651 // other ConstructName things? Leaving this for the full implementation 1652 // of mapper lowering. 1653 auto *misc{symbol->detailsIf<MiscDetails>()}; 1654 if (!misc || misc->kind() != MiscDetails::Kind::ConstructName) 1655 context().Say(mapper->v.source, 1656 "Name '%s' should be a mapper name"_err_en_US, mapper->v.source); 1657 else 1658 mapper->v.symbol = symbol; 1659 } else { 1660 mapper->v.symbol = 1661 &MakeSymbol(mapper->v, MiscDetails{MiscDetails::Kind::ConstructName}); 1662 // TODO: When completing the implementation, we probably want to error if 1663 // the symbol is not declared, but right now, testing that the TODO for 1664 // OmpMapClause happens is obscured by the TODO for declare mapper, so 1665 // leaving this out. Remove the above line once the declare mapper is 1666 // implemented. context().Say(mapper->v.source, "'%s' not 1667 // declared"_err_en_US, mapper->v.source); 1668 } 1669 } 1670 return true; 1671 } 1672 1673 // Walk the parse tree and resolve names to symbols. 1674 class ResolveNamesVisitor : public virtual ScopeHandler, 1675 public ModuleVisitor, 1676 public SubprogramVisitor, 1677 public ConstructVisitor, 1678 public OmpVisitor, 1679 public AccVisitor { 1680 public: 1681 using AccVisitor::Post; 1682 using AccVisitor::Pre; 1683 using ArraySpecVisitor::Post; 1684 using ConstructVisitor::Post; 1685 using ConstructVisitor::Pre; 1686 using DeclarationVisitor::Post; 1687 using DeclarationVisitor::Pre; 1688 using ImplicitRulesVisitor::Post; 1689 using ImplicitRulesVisitor::Pre; 1690 using InterfaceVisitor::Post; 1691 using InterfaceVisitor::Pre; 1692 using ModuleVisitor::Post; 1693 using ModuleVisitor::Pre; 1694 using OmpVisitor::Post; 1695 using OmpVisitor::Pre; 1696 using ScopeHandler::Post; 1697 using ScopeHandler::Pre; 1698 using SubprogramVisitor::Post; 1699 using SubprogramVisitor::Pre; 1700 1701 ResolveNamesVisitor( 1702 SemanticsContext &context, ImplicitRulesMap &rules, Scope &top) 1703 : BaseVisitor{context, *this, rules}, topScope_{top} { 1704 PushScope(top); 1705 } 1706 1707 Scope &topScope() const { return topScope_; } 1708 1709 // Default action for a parse tree node is to visit children. 1710 template <typename T> bool Pre(const T &) { return true; } 1711 template <typename T> void Post(const T &) {} 1712 1713 bool Pre(const parser::SpecificationPart &); 1714 bool Pre(const parser::Program &); 1715 void Post(const parser::Program &); 1716 bool Pre(const parser::ImplicitStmt &); 1717 void Post(const parser::PointerObject &); 1718 void Post(const parser::AllocateObject &); 1719 bool Pre(const parser::PointerAssignmentStmt &); 1720 void Post(const parser::Designator &); 1721 void Post(const parser::SubstringInquiry &); 1722 template <typename A, typename B> 1723 void Post(const parser::LoopBounds<A, B> &x) { 1724 ResolveName(*parser::Unwrap<parser::Name>(x.name)); 1725 } 1726 void Post(const parser::ProcComponentRef &); 1727 bool Pre(const parser::FunctionReference &); 1728 bool Pre(const parser::CallStmt &); 1729 bool Pre(const parser::ImportStmt &); 1730 void Post(const parser::TypeGuardStmt &); 1731 bool Pre(const parser::StmtFunctionStmt &); 1732 bool Pre(const parser::DefinedOpName &); 1733 bool Pre(const parser::ProgramUnit &); 1734 void Post(const parser::AssignStmt &); 1735 void Post(const parser::AssignedGotoStmt &); 1736 void Post(const parser::CompilerDirective &); 1737 1738 // These nodes should never be reached: they are handled in ProgramUnit 1739 bool Pre(const parser::MainProgram &) { 1740 llvm_unreachable("This node is handled in ProgramUnit"); 1741 } 1742 bool Pre(const parser::FunctionSubprogram &) { 1743 llvm_unreachable("This node is handled in ProgramUnit"); 1744 } 1745 bool Pre(const parser::SubroutineSubprogram &) { 1746 llvm_unreachable("This node is handled in ProgramUnit"); 1747 } 1748 bool Pre(const parser::SeparateModuleSubprogram &) { 1749 llvm_unreachable("This node is handled in ProgramUnit"); 1750 } 1751 bool Pre(const parser::Module &) { 1752 llvm_unreachable("This node is handled in ProgramUnit"); 1753 } 1754 bool Pre(const parser::Submodule &) { 1755 llvm_unreachable("This node is handled in ProgramUnit"); 1756 } 1757 bool Pre(const parser::BlockData &) { 1758 llvm_unreachable("This node is handled in ProgramUnit"); 1759 } 1760 1761 void NoteExecutablePartCall(Symbol::Flag, SourceName, bool hasCUDAChevrons); 1762 1763 friend void ResolveSpecificationParts(SemanticsContext &, const Symbol &); 1764 1765 private: 1766 // Kind of procedure we are expecting to see in a ProcedureDesignator 1767 std::optional<Symbol::Flag> expectedProcFlag_; 1768 std::optional<SourceName> prevImportStmt_; 1769 Scope &topScope_; 1770 1771 void PreSpecificationConstruct(const parser::SpecificationConstruct &); 1772 void CreateCommonBlockSymbols(const parser::CommonStmt &); 1773 void CreateObjectSymbols(const std::list<parser::ObjectDecl> &, Attr); 1774 void CreateGeneric(const parser::GenericSpec &); 1775 void FinishSpecificationPart(const std::list<parser::DeclarationConstruct> &); 1776 void AnalyzeStmtFunctionStmt(const parser::StmtFunctionStmt &); 1777 void CheckImports(); 1778 void CheckImport(const SourceName &, const SourceName &); 1779 void HandleCall(Symbol::Flag, const parser::Call &); 1780 void HandleProcedureName(Symbol::Flag, const parser::Name &); 1781 bool CheckImplicitNoneExternal(const SourceName &, const Symbol &); 1782 bool SetProcFlag(const parser::Name &, Symbol &, Symbol::Flag); 1783 void ResolveSpecificationParts(ProgramTree &); 1784 void AddSubpNames(ProgramTree &); 1785 bool BeginScopeForNode(const ProgramTree &); 1786 void EndScopeForNode(const ProgramTree &); 1787 void FinishSpecificationParts(const ProgramTree &); 1788 void FinishExecutionParts(const ProgramTree &); 1789 void FinishDerivedTypeInstantiation(Scope &); 1790 void ResolveExecutionParts(const ProgramTree &); 1791 void UseCUDABuiltinNames(); 1792 void HandleDerivedTypesInImplicitStmts(const parser::ImplicitPart &, 1793 const std::list<parser::DeclarationConstruct> &); 1794 }; 1795 1796 // ImplicitRules implementation 1797 1798 bool ImplicitRules::isImplicitNoneType() const { 1799 if (isImplicitNoneType_) { 1800 return true; 1801 } else if (map_.empty() && inheritFromParent_) { 1802 return parent_->isImplicitNoneType(); 1803 } else { 1804 return false; // default if not specified 1805 } 1806 } 1807 1808 bool ImplicitRules::isImplicitNoneExternal() const { 1809 if (isImplicitNoneExternal_) { 1810 return true; 1811 } else if (inheritFromParent_) { 1812 return parent_->isImplicitNoneExternal(); 1813 } else { 1814 return false; // default if not specified 1815 } 1816 } 1817 1818 const DeclTypeSpec *ImplicitRules::GetType( 1819 SourceName name, bool respectImplicitNoneType) const { 1820 char ch{name.begin()[0]}; 1821 if (isImplicitNoneType_ && respectImplicitNoneType) { 1822 return nullptr; 1823 } else if (auto it{map_.find(ch)}; it != map_.end()) { 1824 return &*it->second; 1825 } else if (inheritFromParent_) { 1826 return parent_->GetType(name, respectImplicitNoneType); 1827 } else if (ch >= 'i' && ch <= 'n') { 1828 return &context_.MakeNumericType(TypeCategory::Integer); 1829 } else if (ch >= 'a' && ch <= 'z') { 1830 return &context_.MakeNumericType(TypeCategory::Real); 1831 } else { 1832 return nullptr; 1833 } 1834 } 1835 1836 void ImplicitRules::SetTypeMapping(const DeclTypeSpec &type, 1837 parser::Location fromLetter, parser::Location toLetter) { 1838 for (char ch = *fromLetter; ch; ch = ImplicitRules::Incr(ch)) { 1839 auto res{map_.emplace(ch, type)}; 1840 if (!res.second) { 1841 context_.Say(parser::CharBlock{fromLetter}, 1842 "More than one implicit type specified for '%c'"_err_en_US, ch); 1843 } 1844 if (ch == *toLetter) { 1845 break; 1846 } 1847 } 1848 } 1849 1850 // Return the next char after ch in a way that works for ASCII or EBCDIC. 1851 // Return '\0' for the char after 'z'. 1852 char ImplicitRules::Incr(char ch) { 1853 switch (ch) { 1854 case 'i': 1855 return 'j'; 1856 case 'r': 1857 return 's'; 1858 case 'z': 1859 return '\0'; 1860 default: 1861 return ch + 1; 1862 } 1863 } 1864 1865 llvm::raw_ostream &operator<<( 1866 llvm::raw_ostream &o, const ImplicitRules &implicitRules) { 1867 o << "ImplicitRules:\n"; 1868 for (char ch = 'a'; ch; ch = ImplicitRules::Incr(ch)) { 1869 ShowImplicitRule(o, implicitRules, ch); 1870 } 1871 ShowImplicitRule(o, implicitRules, '_'); 1872 ShowImplicitRule(o, implicitRules, '$'); 1873 ShowImplicitRule(o, implicitRules, '@'); 1874 return o; 1875 } 1876 void ShowImplicitRule( 1877 llvm::raw_ostream &o, const ImplicitRules &implicitRules, char ch) { 1878 auto it{implicitRules.map_.find(ch)}; 1879 if (it != implicitRules.map_.end()) { 1880 o << " " << ch << ": " << *it->second << '\n'; 1881 } 1882 } 1883 1884 template <typename T> void BaseVisitor::Walk(const T &x) { 1885 parser::Walk(x, *this_); 1886 } 1887 1888 void BaseVisitor::MakePlaceholder( 1889 const parser::Name &name, MiscDetails::Kind kind) { 1890 if (!name.symbol) { 1891 name.symbol = &context_->globalScope().MakeSymbol( 1892 name.source, Attrs{}, MiscDetails{kind}); 1893 } 1894 } 1895 1896 // AttrsVisitor implementation 1897 1898 bool AttrsVisitor::BeginAttrs() { 1899 CHECK(!attrs_ && !cudaDataAttr_); 1900 attrs_ = Attrs{}; 1901 return true; 1902 } 1903 Attrs AttrsVisitor::GetAttrs() { 1904 CHECK(attrs_); 1905 return *attrs_; 1906 } 1907 Attrs AttrsVisitor::EndAttrs() { 1908 Attrs result{GetAttrs()}; 1909 attrs_.reset(); 1910 cudaDataAttr_.reset(); 1911 passName_ = std::nullopt; 1912 bindName_.reset(); 1913 isCDefined_ = false; 1914 return result; 1915 } 1916 1917 bool AttrsVisitor::SetPassNameOn(Symbol &symbol) { 1918 if (!passName_) { 1919 return false; 1920 } 1921 common::visit(common::visitors{ 1922 [&](ProcEntityDetails &x) { x.set_passName(*passName_); }, 1923 [&](ProcBindingDetails &x) { x.set_passName(*passName_); }, 1924 [](auto &) { common::die("unexpected pass name"); }, 1925 }, 1926 symbol.details()); 1927 return true; 1928 } 1929 1930 void AttrsVisitor::SetBindNameOn(Symbol &symbol) { 1931 if ((!attrs_ || !attrs_->test(Attr::BIND_C)) && 1932 !symbol.attrs().test(Attr::BIND_C)) { 1933 return; 1934 } 1935 symbol.SetIsCDefined(isCDefined_); 1936 std::optional<std::string> label{ 1937 evaluate::GetScalarConstantValue<evaluate::Ascii>(bindName_)}; 1938 // 18.9.2(2): discard leading and trailing blanks 1939 if (label) { 1940 symbol.SetIsExplicitBindName(true); 1941 auto first{label->find_first_not_of(" ")}; 1942 if (first == std::string::npos) { 1943 // Empty NAME= means no binding at all (18.10.2p2) 1944 return; 1945 } 1946 auto last{label->find_last_not_of(" ")}; 1947 label = label->substr(first, last - first + 1); 1948 } else if (symbol.GetIsExplicitBindName()) { 1949 // don't try to override explicit binding name with default 1950 return; 1951 } else if (ClassifyProcedure(symbol) == ProcedureDefinitionClass::Internal) { 1952 // BIND(C) does not give an implicit binding label to internal procedures. 1953 return; 1954 } else { 1955 label = symbol.name().ToString(); 1956 } 1957 // Checks whether a symbol has two Bind names. 1958 std::string oldBindName; 1959 if (const auto *bindName{symbol.GetBindName()}) { 1960 oldBindName = *bindName; 1961 } 1962 symbol.SetBindName(std::move(*label)); 1963 if (!oldBindName.empty()) { 1964 if (const std::string * newBindName{symbol.GetBindName()}) { 1965 if (oldBindName != *newBindName) { 1966 Say(symbol.name(), 1967 "The entity '%s' has multiple BIND names ('%s' and '%s')"_err_en_US, 1968 symbol.name(), oldBindName, *newBindName); 1969 } 1970 } 1971 } 1972 } 1973 1974 void AttrsVisitor::Post(const parser::LanguageBindingSpec &x) { 1975 if (CheckAndSet(Attr::BIND_C)) { 1976 if (const auto &name{ 1977 std::get<std::optional<parser::ScalarDefaultCharConstantExpr>>( 1978 x.t)}) { 1979 bindName_ = EvaluateExpr(*name); 1980 } 1981 isCDefined_ = std::get<bool>(x.t); 1982 } 1983 } 1984 bool AttrsVisitor::Pre(const parser::IntentSpec &x) { 1985 CheckAndSet(IntentSpecToAttr(x)); 1986 return false; 1987 } 1988 bool AttrsVisitor::Pre(const parser::Pass &x) { 1989 if (CheckAndSet(Attr::PASS)) { 1990 if (x.v) { 1991 passName_ = x.v->source; 1992 MakePlaceholder(*x.v, MiscDetails::Kind::PassName); 1993 } 1994 } 1995 return false; 1996 } 1997 1998 // C730, C743, C755, C778, C1543 say no attribute or prefix repetitions 1999 bool AttrsVisitor::IsDuplicateAttr(Attr attrName) { 2000 CHECK(attrs_); 2001 if (attrs_->test(attrName)) { 2002 context().Warn(common::LanguageFeature::RedundantAttribute, 2003 currStmtSource().value(), 2004 "Attribute '%s' cannot be used more than once"_warn_en_US, 2005 AttrToString(attrName)); 2006 return true; 2007 } 2008 return false; 2009 } 2010 2011 // See if attrName violates a constraint cause by a conflict. attr1 and attr2 2012 // name attributes that cannot be used on the same declaration 2013 bool AttrsVisitor::HaveAttrConflict(Attr attrName, Attr attr1, Attr attr2) { 2014 CHECK(attrs_); 2015 if ((attrName == attr1 && attrs_->test(attr2)) || 2016 (attrName == attr2 && attrs_->test(attr1))) { 2017 Say(currStmtSource().value(), 2018 "Attributes '%s' and '%s' conflict with each other"_err_en_US, 2019 AttrToString(attr1), AttrToString(attr2)); 2020 return true; 2021 } 2022 return false; 2023 } 2024 // C759, C1543 2025 bool AttrsVisitor::IsConflictingAttr(Attr attrName) { 2026 return HaveAttrConflict(attrName, Attr::INTENT_IN, Attr::INTENT_INOUT) || 2027 HaveAttrConflict(attrName, Attr::INTENT_IN, Attr::INTENT_OUT) || 2028 HaveAttrConflict(attrName, Attr::INTENT_INOUT, Attr::INTENT_OUT) || 2029 HaveAttrConflict(attrName, Attr::PASS, Attr::NOPASS) || // C781 2030 HaveAttrConflict(attrName, Attr::PURE, Attr::IMPURE) || 2031 HaveAttrConflict(attrName, Attr::PUBLIC, Attr::PRIVATE) || 2032 HaveAttrConflict(attrName, Attr::RECURSIVE, Attr::NON_RECURSIVE); 2033 } 2034 bool AttrsVisitor::CheckAndSet(Attr attrName) { 2035 if (IsConflictingAttr(attrName) || IsDuplicateAttr(attrName)) { 2036 return false; 2037 } 2038 attrs_->set(attrName); 2039 return true; 2040 } 2041 bool AttrsVisitor::Pre(const common::CUDADataAttr x) { 2042 if (cudaDataAttr_.value_or(x) != x) { 2043 Say(currStmtSource().value(), 2044 "CUDA data attributes '%s' and '%s' may not both be specified"_err_en_US, 2045 common::EnumToString(*cudaDataAttr_), common::EnumToString(x)); 2046 } 2047 cudaDataAttr_ = x; 2048 return false; 2049 } 2050 2051 // DeclTypeSpecVisitor implementation 2052 2053 const DeclTypeSpec *DeclTypeSpecVisitor::GetDeclTypeSpec() { 2054 return state_.declTypeSpec; 2055 } 2056 2057 void DeclTypeSpecVisitor::BeginDeclTypeSpec() { 2058 CHECK(!state_.expectDeclTypeSpec); 2059 CHECK(!state_.declTypeSpec); 2060 state_.expectDeclTypeSpec = true; 2061 } 2062 void DeclTypeSpecVisitor::EndDeclTypeSpec() { 2063 CHECK(state_.expectDeclTypeSpec); 2064 state_ = {}; 2065 } 2066 2067 void DeclTypeSpecVisitor::SetDeclTypeSpecCategory( 2068 DeclTypeSpec::Category category) { 2069 CHECK(state_.expectDeclTypeSpec); 2070 state_.derived.category = category; 2071 } 2072 2073 bool DeclTypeSpecVisitor::Pre(const parser::TypeGuardStmt &) { 2074 BeginDeclTypeSpec(); 2075 return true; 2076 } 2077 void DeclTypeSpecVisitor::Post(const parser::TypeGuardStmt &) { 2078 EndDeclTypeSpec(); 2079 } 2080 2081 void DeclTypeSpecVisitor::Post(const parser::TypeSpec &typeSpec) { 2082 // Record the resolved DeclTypeSpec in the parse tree for use by 2083 // expression semantics if the DeclTypeSpec is a valid TypeSpec. 2084 // The grammar ensures that it's an intrinsic or derived type spec, 2085 // not TYPE(*) or CLASS(*) or CLASS(T). 2086 if (const DeclTypeSpec * spec{state_.declTypeSpec}) { 2087 switch (spec->category()) { 2088 case DeclTypeSpec::Numeric: 2089 case DeclTypeSpec::Logical: 2090 case DeclTypeSpec::Character: 2091 typeSpec.declTypeSpec = spec; 2092 break; 2093 case DeclTypeSpec::TypeDerived: 2094 if (const DerivedTypeSpec * derived{spec->AsDerived()}) { 2095 CheckForAbstractType(derived->typeSymbol()); // C703 2096 typeSpec.declTypeSpec = spec; 2097 } 2098 break; 2099 default: 2100 CRASH_NO_CASE; 2101 } 2102 } 2103 } 2104 2105 void DeclTypeSpecVisitor::Post( 2106 const parser::IntrinsicTypeSpec::DoublePrecision &) { 2107 MakeNumericType(TypeCategory::Real, context().doublePrecisionKind()); 2108 } 2109 void DeclTypeSpecVisitor::Post( 2110 const parser::IntrinsicTypeSpec::DoubleComplex &) { 2111 MakeNumericType(TypeCategory::Complex, context().doublePrecisionKind()); 2112 } 2113 void DeclTypeSpecVisitor::MakeNumericType(TypeCategory category, int kind) { 2114 SetDeclTypeSpec(context().MakeNumericType(category, kind)); 2115 } 2116 2117 void DeclTypeSpecVisitor::CheckForAbstractType(const Symbol &typeSymbol) { 2118 if (typeSymbol.attrs().test(Attr::ABSTRACT)) { 2119 Say("ABSTRACT derived type may not be used here"_err_en_US); 2120 } 2121 } 2122 2123 void DeclTypeSpecVisitor::Post(const parser::DeclarationTypeSpec::ClassStar &) { 2124 SetDeclTypeSpec(context().globalScope().MakeClassStarType()); 2125 } 2126 void DeclTypeSpecVisitor::Post(const parser::DeclarationTypeSpec::TypeStar &) { 2127 SetDeclTypeSpec(context().globalScope().MakeTypeStarType()); 2128 } 2129 2130 // Check that we're expecting to see a DeclTypeSpec (and haven't seen one yet) 2131 // and save it in state_.declTypeSpec. 2132 void DeclTypeSpecVisitor::SetDeclTypeSpec(const DeclTypeSpec &declTypeSpec) { 2133 CHECK(state_.expectDeclTypeSpec); 2134 CHECK(!state_.declTypeSpec); 2135 state_.declTypeSpec = &declTypeSpec; 2136 } 2137 2138 KindExpr DeclTypeSpecVisitor::GetKindParamExpr( 2139 TypeCategory category, const std::optional<parser::KindSelector> &kind) { 2140 return AnalyzeKindSelector(context(), category, kind); 2141 } 2142 2143 // MessageHandler implementation 2144 2145 Message &MessageHandler::Say(MessageFixedText &&msg) { 2146 return context_->Say(currStmtSource().value(), std::move(msg)); 2147 } 2148 Message &MessageHandler::Say(MessageFormattedText &&msg) { 2149 return context_->Say(currStmtSource().value(), std::move(msg)); 2150 } 2151 Message &MessageHandler::Say(const SourceName &name, MessageFixedText &&msg) { 2152 return Say(name, std::move(msg), name); 2153 } 2154 2155 // ImplicitRulesVisitor implementation 2156 2157 void ImplicitRulesVisitor::Post(const parser::ParameterStmt &) { 2158 prevParameterStmt_ = currStmtSource(); 2159 } 2160 2161 bool ImplicitRulesVisitor::Pre(const parser::ImplicitStmt &x) { 2162 bool result{ 2163 common::visit(common::visitors{ 2164 [&](const std::list<ImplicitNoneNameSpec> &y) { 2165 return HandleImplicitNone(y); 2166 }, 2167 [&](const std::list<parser::ImplicitSpec> &) { 2168 if (prevImplicitNoneType_) { 2169 Say("IMPLICIT statement after IMPLICIT NONE or " 2170 "IMPLICIT NONE(TYPE) statement"_err_en_US); 2171 return false; 2172 } 2173 implicitRules_->set_isImplicitNoneType(false); 2174 return true; 2175 }, 2176 }, 2177 x.u)}; 2178 prevImplicit_ = currStmtSource(); 2179 return result; 2180 } 2181 2182 bool ImplicitRulesVisitor::Pre(const parser::LetterSpec &x) { 2183 auto loLoc{std::get<parser::Location>(x.t)}; 2184 auto hiLoc{loLoc}; 2185 if (auto hiLocOpt{std::get<std::optional<parser::Location>>(x.t)}) { 2186 hiLoc = *hiLocOpt; 2187 if (*hiLoc < *loLoc) { 2188 Say(hiLoc, "'%s' does not follow '%s' alphabetically"_err_en_US, 2189 std::string(hiLoc, 1), std::string(loLoc, 1)); 2190 return false; 2191 } 2192 } 2193 implicitRules_->SetTypeMapping(*GetDeclTypeSpec(), loLoc, hiLoc); 2194 return false; 2195 } 2196 2197 bool ImplicitRulesVisitor::Pre(const parser::ImplicitSpec &) { 2198 BeginDeclTypeSpec(); 2199 set_allowForwardReferenceToDerivedType(true); 2200 return true; 2201 } 2202 2203 void ImplicitRulesVisitor::Post(const parser::ImplicitSpec &) { 2204 set_allowForwardReferenceToDerivedType(false); 2205 EndDeclTypeSpec(); 2206 } 2207 2208 void ImplicitRulesVisitor::SetScope(const Scope &scope) { 2209 implicitRules_ = &DEREF(implicitRulesMap_).at(&scope); 2210 prevImplicit_ = std::nullopt; 2211 prevImplicitNone_ = std::nullopt; 2212 prevImplicitNoneType_ = std::nullopt; 2213 prevParameterStmt_ = std::nullopt; 2214 } 2215 void ImplicitRulesVisitor::BeginScope(const Scope &scope) { 2216 // find or create implicit rules for this scope 2217 DEREF(implicitRulesMap_).try_emplace(&scope, context(), implicitRules_); 2218 SetScope(scope); 2219 } 2220 2221 // TODO: for all of these errors, reference previous statement too 2222 bool ImplicitRulesVisitor::HandleImplicitNone( 2223 const std::list<ImplicitNoneNameSpec> &nameSpecs) { 2224 if (prevImplicitNone_) { 2225 Say("More than one IMPLICIT NONE statement"_err_en_US); 2226 Say(*prevImplicitNone_, "Previous IMPLICIT NONE statement"_en_US); 2227 return false; 2228 } 2229 if (prevParameterStmt_) { 2230 Say("IMPLICIT NONE statement after PARAMETER statement"_err_en_US); 2231 return false; 2232 } 2233 prevImplicitNone_ = currStmtSource(); 2234 bool implicitNoneTypeNever{ 2235 context().IsEnabled(common::LanguageFeature::ImplicitNoneTypeNever)}; 2236 if (nameSpecs.empty()) { 2237 if (!implicitNoneTypeNever) { 2238 prevImplicitNoneType_ = currStmtSource(); 2239 implicitRules_->set_isImplicitNoneType(true); 2240 if (prevImplicit_) { 2241 Say("IMPLICIT NONE statement after IMPLICIT statement"_err_en_US); 2242 return false; 2243 } 2244 } 2245 } else { 2246 int sawType{0}; 2247 int sawExternal{0}; 2248 for (const auto noneSpec : nameSpecs) { 2249 switch (noneSpec) { 2250 case ImplicitNoneNameSpec::External: 2251 implicitRules_->set_isImplicitNoneExternal(true); 2252 ++sawExternal; 2253 break; 2254 case ImplicitNoneNameSpec::Type: 2255 if (!implicitNoneTypeNever) { 2256 prevImplicitNoneType_ = currStmtSource(); 2257 implicitRules_->set_isImplicitNoneType(true); 2258 if (prevImplicit_) { 2259 Say("IMPLICIT NONE(TYPE) after IMPLICIT statement"_err_en_US); 2260 return false; 2261 } 2262 ++sawType; 2263 } 2264 break; 2265 } 2266 } 2267 if (sawType > 1) { 2268 Say("TYPE specified more than once in IMPLICIT NONE statement"_err_en_US); 2269 return false; 2270 } 2271 if (sawExternal > 1) { 2272 Say("EXTERNAL specified more than once in IMPLICIT NONE statement"_err_en_US); 2273 return false; 2274 } 2275 } 2276 return true; 2277 } 2278 2279 // ArraySpecVisitor implementation 2280 2281 void ArraySpecVisitor::Post(const parser::ArraySpec &x) { 2282 CHECK(arraySpec_.empty()); 2283 arraySpec_ = AnalyzeArraySpec(context(), x); 2284 } 2285 void ArraySpecVisitor::Post(const parser::ComponentArraySpec &x) { 2286 CHECK(arraySpec_.empty()); 2287 arraySpec_ = AnalyzeArraySpec(context(), x); 2288 } 2289 void ArraySpecVisitor::Post(const parser::CoarraySpec &x) { 2290 CHECK(coarraySpec_.empty()); 2291 coarraySpec_ = AnalyzeCoarraySpec(context(), x); 2292 } 2293 2294 const ArraySpec &ArraySpecVisitor::arraySpec() { 2295 return !arraySpec_.empty() ? arraySpec_ : attrArraySpec_; 2296 } 2297 const ArraySpec &ArraySpecVisitor::coarraySpec() { 2298 return !coarraySpec_.empty() ? coarraySpec_ : attrCoarraySpec_; 2299 } 2300 void ArraySpecVisitor::BeginArraySpec() { 2301 CHECK(arraySpec_.empty()); 2302 CHECK(coarraySpec_.empty()); 2303 CHECK(attrArraySpec_.empty()); 2304 CHECK(attrCoarraySpec_.empty()); 2305 } 2306 void ArraySpecVisitor::EndArraySpec() { 2307 CHECK(arraySpec_.empty()); 2308 CHECK(coarraySpec_.empty()); 2309 attrArraySpec_.clear(); 2310 attrCoarraySpec_.clear(); 2311 } 2312 void ArraySpecVisitor::PostAttrSpec() { 2313 // Save dimension/codimension from attrs so we can process array/coarray-spec 2314 // on the entity-decl 2315 if (!arraySpec_.empty()) { 2316 if (attrArraySpec_.empty()) { 2317 attrArraySpec_ = arraySpec_; 2318 arraySpec_.clear(); 2319 } else { 2320 Say(currStmtSource().value(), 2321 "Attribute 'DIMENSION' cannot be used more than once"_err_en_US); 2322 } 2323 } 2324 if (!coarraySpec_.empty()) { 2325 if (attrCoarraySpec_.empty()) { 2326 attrCoarraySpec_ = coarraySpec_; 2327 coarraySpec_.clear(); 2328 } else { 2329 Say(currStmtSource().value(), 2330 "Attribute 'CODIMENSION' cannot be used more than once"_err_en_US); 2331 } 2332 } 2333 } 2334 2335 // FuncResultStack implementation 2336 2337 FuncResultStack::~FuncResultStack() { CHECK(stack_.empty()); } 2338 2339 void FuncResultStack::CompleteFunctionResultType() { 2340 // If the function has a type in the prefix, process it now. 2341 FuncInfo *info{Top()}; 2342 if (info && &info->scope == &scopeHandler_.currScope()) { 2343 if (info->parsedType && info->resultSymbol) { 2344 scopeHandler_.messageHandler().set_currStmtSource(info->source); 2345 if (const auto *type{ 2346 scopeHandler_.ProcessTypeSpec(*info->parsedType, true)}) { 2347 Symbol &symbol{*info->resultSymbol}; 2348 if (!scopeHandler_.context().HasError(symbol)) { 2349 if (symbol.GetType()) { 2350 scopeHandler_.Say(symbol.name(), 2351 "Function cannot have both an explicit type prefix and a RESULT suffix"_err_en_US); 2352 scopeHandler_.context().SetError(symbol); 2353 } else { 2354 symbol.SetType(*type); 2355 } 2356 } 2357 } 2358 info->parsedType = nullptr; 2359 } 2360 } 2361 } 2362 2363 // Called from ConvertTo{Object/Proc}Entity to cope with any appearance 2364 // of the function result in a specification expression. 2365 void FuncResultStack::CompleteTypeIfFunctionResult(Symbol &symbol) { 2366 if (FuncInfo * info{Top()}) { 2367 if (info->resultSymbol == &symbol) { 2368 CompleteFunctionResultType(); 2369 } 2370 } 2371 } 2372 2373 void FuncResultStack::Pop() { 2374 if (!stack_.empty() && &stack_.back().scope == &scopeHandler_.currScope()) { 2375 stack_.pop_back(); 2376 } 2377 } 2378 2379 // ScopeHandler implementation 2380 2381 void ScopeHandler::SayAlreadyDeclared(const parser::Name &name, Symbol &prev) { 2382 SayAlreadyDeclared(name.source, prev); 2383 } 2384 void ScopeHandler::SayAlreadyDeclared(const SourceName &name, Symbol &prev) { 2385 if (context().HasError(prev)) { 2386 // don't report another error about prev 2387 } else { 2388 if (const auto *details{prev.detailsIf<UseDetails>()}) { 2389 Say(name, "'%s' is already declared in this scoping unit"_err_en_US) 2390 .Attach(details->location(), 2391 "It is use-associated with '%s' in module '%s'"_en_US, 2392 details->symbol().name(), GetUsedModule(*details).name()); 2393 } else { 2394 SayAlreadyDeclared(name, prev.name()); 2395 } 2396 context().SetError(prev); 2397 } 2398 } 2399 void ScopeHandler::SayAlreadyDeclared( 2400 const SourceName &name1, const SourceName &name2) { 2401 if (name1.begin() < name2.begin()) { 2402 SayAlreadyDeclared(name2, name1); 2403 } else { 2404 Say(name1, "'%s' is already declared in this scoping unit"_err_en_US) 2405 .Attach(name2, "Previous declaration of '%s'"_en_US, name2); 2406 } 2407 } 2408 2409 void ScopeHandler::SayWithReason(const parser::Name &name, Symbol &symbol, 2410 MessageFixedText &&msg1, Message &&msg2) { 2411 bool isFatal{msg1.IsFatal()}; 2412 Say(name, std::move(msg1), symbol.name()).Attach(std::move(msg2)); 2413 context().SetError(symbol, isFatal); 2414 } 2415 2416 template <typename... A> 2417 Message &ScopeHandler::SayWithDecl(const parser::Name &name, Symbol &symbol, 2418 MessageFixedText &&msg, A &&...args) { 2419 auto &message{ 2420 Say(name.source, std::move(msg), symbol.name(), std::forward<A>(args)...) 2421 .Attach(symbol.name(), 2422 symbol.test(Symbol::Flag::Implicit) 2423 ? "Implicit declaration of '%s'"_en_US 2424 : "Declaration of '%s'"_en_US, 2425 name.source)}; 2426 if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}) { 2427 if (auto usedAsProc{proc->usedAsProcedureHere()}) { 2428 if (usedAsProc->begin() != symbol.name().begin()) { 2429 message.Attach(*usedAsProc, "Referenced as a procedure"_en_US); 2430 } 2431 } 2432 } 2433 return message; 2434 } 2435 2436 void ScopeHandler::SayLocalMustBeVariable( 2437 const parser::Name &name, Symbol &symbol) { 2438 SayWithDecl(name, symbol, 2439 "The name '%s' must be a variable to appear" 2440 " in a locality-spec"_err_en_US); 2441 } 2442 2443 Message &ScopeHandler::SayDerivedType( 2444 const SourceName &name, MessageFixedText &&msg, const Scope &type) { 2445 const Symbol &typeSymbol{DEREF(type.GetSymbol())}; 2446 return Say(name, std::move(msg), name, typeSymbol.name()) 2447 .Attach(typeSymbol.name(), "Declaration of derived type '%s'"_en_US, 2448 typeSymbol.name()); 2449 } 2450 Message &ScopeHandler::Say2(const SourceName &name1, MessageFixedText &&msg1, 2451 const SourceName &name2, MessageFixedText &&msg2) { 2452 return Say(name1, std::move(msg1)).Attach(name2, std::move(msg2), name2); 2453 } 2454 Message &ScopeHandler::Say2(const SourceName &name, MessageFixedText &&msg1, 2455 Symbol &symbol, MessageFixedText &&msg2) { 2456 bool isFatal{msg1.IsFatal()}; 2457 Message &result{Say2(name, std::move(msg1), symbol.name(), std::move(msg2))}; 2458 context().SetError(symbol, isFatal); 2459 return result; 2460 } 2461 Message &ScopeHandler::Say2(const parser::Name &name, MessageFixedText &&msg1, 2462 Symbol &symbol, MessageFixedText &&msg2) { 2463 bool isFatal{msg1.IsFatal()}; 2464 Message &result{ 2465 Say2(name.source, std::move(msg1), symbol.name(), std::move(msg2))}; 2466 context().SetError(symbol, isFatal); 2467 return result; 2468 } 2469 2470 // This is essentially GetProgramUnitContaining(), but it can return 2471 // a mutable Scope &, it ignores statement functions, and it fails 2472 // gracefully for error recovery (returning the original Scope). 2473 template <typename T> static T &GetInclusiveScope(T &scope) { 2474 for (T *s{&scope}; !s->IsGlobal(); s = &s->parent()) { 2475 switch (s->kind()) { 2476 case Scope::Kind::Module: 2477 case Scope::Kind::MainProgram: 2478 case Scope::Kind::Subprogram: 2479 case Scope::Kind::BlockData: 2480 if (!s->IsStmtFunction()) { 2481 return *s; 2482 } 2483 break; 2484 default:; 2485 } 2486 } 2487 return scope; 2488 } 2489 2490 Scope &ScopeHandler::InclusiveScope() { return GetInclusiveScope(currScope()); } 2491 2492 Scope *ScopeHandler::GetHostProcedure() { 2493 Scope &parent{InclusiveScope().parent()}; 2494 switch (parent.kind()) { 2495 case Scope::Kind::Subprogram: 2496 return &parent; 2497 case Scope::Kind::MainProgram: 2498 return &parent; 2499 default: 2500 return nullptr; 2501 } 2502 } 2503 2504 Scope &ScopeHandler::NonDerivedTypeScope() { 2505 return currScope_->IsDerivedType() ? currScope_->parent() : *currScope_; 2506 } 2507 2508 void ScopeHandler::PushScope(Scope::Kind kind, Symbol *symbol) { 2509 PushScope(currScope().MakeScope(kind, symbol)); 2510 } 2511 void ScopeHandler::PushScope(Scope &scope) { 2512 currScope_ = &scope; 2513 auto kind{currScope_->kind()}; 2514 if (kind != Scope::Kind::BlockConstruct && 2515 kind != Scope::Kind::OtherConstruct && kind != Scope::Kind::OtherClause) { 2516 BeginScope(scope); 2517 } 2518 // The name of a module or submodule cannot be "used" in its scope, 2519 // as we read 19.3.1(2), so we allow the name to be used as a local 2520 // identifier in the module or submodule too. Same with programs 2521 // (14.1(3)) and BLOCK DATA. 2522 if (!currScope_->IsDerivedType() && kind != Scope::Kind::Module && 2523 kind != Scope::Kind::MainProgram && kind != Scope::Kind::BlockData) { 2524 if (auto *symbol{scope.symbol()}) { 2525 // Create a dummy symbol so we can't create another one with the same 2526 // name. It might already be there if we previously pushed the scope. 2527 SourceName name{symbol->name()}; 2528 if (!FindInScope(scope, name)) { 2529 auto &newSymbol{MakeSymbol(name)}; 2530 if (kind == Scope::Kind::Subprogram) { 2531 // Allow for recursive references. If this symbol is a function 2532 // without an explicit RESULT(), this new symbol will be discarded 2533 // and replaced with an object of the same name. 2534 newSymbol.set_details(HostAssocDetails{*symbol}); 2535 } else { 2536 newSymbol.set_details(MiscDetails{MiscDetails::Kind::ScopeName}); 2537 } 2538 } 2539 } 2540 } 2541 } 2542 void ScopeHandler::PopScope() { 2543 CHECK(currScope_ && !currScope_->IsGlobal()); 2544 // Entities that are not yet classified as objects or procedures are now 2545 // assumed to be objects. 2546 // TODO: Statement functions 2547 for (auto &pair : currScope()) { 2548 ConvertToObjectEntity(*pair.second); 2549 } 2550 funcResultStack_.Pop(); 2551 // If popping back into a global scope, pop back to the main global scope. 2552 SetScope(currScope_->parent().IsGlobal() ? context().globalScope() 2553 : currScope_->parent()); 2554 } 2555 void ScopeHandler::SetScope(Scope &scope) { 2556 currScope_ = &scope; 2557 ImplicitRulesVisitor::SetScope(InclusiveScope()); 2558 } 2559 2560 Symbol *ScopeHandler::FindSymbol(const parser::Name &name) { 2561 return FindSymbol(currScope(), name); 2562 } 2563 Symbol *ScopeHandler::FindSymbol(const Scope &scope, const parser::Name &name) { 2564 if (scope.IsDerivedType()) { 2565 if (Symbol * symbol{scope.FindComponent(name.source)}) { 2566 if (symbol->has<TypeParamDetails>()) { 2567 return Resolve(name, symbol); 2568 } 2569 } 2570 return FindSymbol(scope.parent(), name); 2571 } else { 2572 // In EQUIVALENCE statements only resolve names in the local scope, see 2573 // 19.5.1.4, paragraph 2, item (10) 2574 return Resolve(name, 2575 inEquivalenceStmt_ ? FindInScope(scope, name) 2576 : scope.FindSymbol(name.source)); 2577 } 2578 } 2579 2580 Symbol &ScopeHandler::MakeSymbol( 2581 Scope &scope, const SourceName &name, Attrs attrs) { 2582 if (Symbol * symbol{FindInScope(scope, name)}) { 2583 CheckDuplicatedAttrs(name, *symbol, attrs); 2584 SetExplicitAttrs(*symbol, attrs); 2585 return *symbol; 2586 } else { 2587 const auto pair{scope.try_emplace(name, attrs, UnknownDetails{})}; 2588 CHECK(pair.second); // name was not found, so must be able to add 2589 return *pair.first->second; 2590 } 2591 } 2592 Symbol &ScopeHandler::MakeSymbol(const SourceName &name, Attrs attrs) { 2593 return MakeSymbol(currScope(), name, attrs); 2594 } 2595 Symbol &ScopeHandler::MakeSymbol(const parser::Name &name, Attrs attrs) { 2596 return Resolve(name, MakeSymbol(name.source, attrs)); 2597 } 2598 Symbol &ScopeHandler::MakeHostAssocSymbol( 2599 const parser::Name &name, const Symbol &hostSymbol) { 2600 Symbol &symbol{*NonDerivedTypeScope() 2601 .try_emplace(name.source, HostAssocDetails{hostSymbol}) 2602 .first->second}; 2603 name.symbol = &symbol; 2604 symbol.attrs() = hostSymbol.attrs(); // TODO: except PRIVATE, PUBLIC? 2605 // These attributes can be redundantly reapplied without error 2606 // on the host-associated name, at most once (C815). 2607 symbol.implicitAttrs() = 2608 symbol.attrs() & Attrs{Attr::ASYNCHRONOUS, Attr::VOLATILE}; 2609 // SAVE statement in the inner scope will create a new symbol. 2610 // If the host variable is used via host association, 2611 // we have to propagate whether SAVE is implicit in the host scope. 2612 // Otherwise, verifications that do not allow explicit SAVE 2613 // attribute would fail. 2614 symbol.implicitAttrs() |= hostSymbol.implicitAttrs() & Attrs{Attr::SAVE}; 2615 symbol.flags() = hostSymbol.flags(); 2616 return symbol; 2617 } 2618 Symbol &ScopeHandler::CopySymbol(const SourceName &name, const Symbol &symbol) { 2619 CHECK(!FindInScope(name)); 2620 return MakeSymbol(currScope(), name, symbol.attrs()); 2621 } 2622 2623 // Look for name only in scope, not in enclosing scopes. 2624 2625 Symbol *ScopeHandler::FindInScope( 2626 const Scope &scope, const parser::Name &name) { 2627 return Resolve(name, FindInScope(scope, name.source)); 2628 } 2629 Symbol *ScopeHandler::FindInScope(const Scope &scope, const SourceName &name) { 2630 // all variants of names, e.g. "operator(.ne.)" for "operator(/=)" 2631 for (const std::string &n : GetAllNames(context(), name)) { 2632 auto it{scope.find(SourceName{n})}; 2633 if (it != scope.end()) { 2634 return &*it->second; 2635 } 2636 } 2637 return nullptr; 2638 } 2639 2640 // Find a component or type parameter by name in a derived type or its parents. 2641 Symbol *ScopeHandler::FindInTypeOrParents( 2642 const Scope &scope, const parser::Name &name) { 2643 return Resolve(name, scope.FindComponent(name.source)); 2644 } 2645 Symbol *ScopeHandler::FindInTypeOrParents(const parser::Name &name) { 2646 return FindInTypeOrParents(currScope(), name); 2647 } 2648 Symbol *ScopeHandler::FindInScopeOrBlockConstructs( 2649 const Scope &scope, SourceName name) { 2650 if (Symbol * symbol{FindInScope(scope, name)}) { 2651 return symbol; 2652 } 2653 for (const Scope &child : scope.children()) { 2654 if (child.kind() == Scope::Kind::BlockConstruct) { 2655 if (Symbol * symbol{FindInScopeOrBlockConstructs(child, name)}) { 2656 return symbol; 2657 } 2658 } 2659 } 2660 return nullptr; 2661 } 2662 2663 void ScopeHandler::EraseSymbol(const parser::Name &name) { 2664 currScope().erase(name.source); 2665 name.symbol = nullptr; 2666 } 2667 2668 static bool NeedsType(const Symbol &symbol) { 2669 return !symbol.GetType() && 2670 common::visit(common::visitors{ 2671 [](const EntityDetails &) { return true; }, 2672 [](const ObjectEntityDetails &) { return true; }, 2673 [](const AssocEntityDetails &) { return true; }, 2674 [&](const ProcEntityDetails &p) { 2675 return symbol.test(Symbol::Flag::Function) && 2676 !symbol.attrs().test(Attr::INTRINSIC) && 2677 !p.type() && !p.procInterface(); 2678 }, 2679 [](const auto &) { return false; }, 2680 }, 2681 symbol.details()); 2682 } 2683 2684 void ScopeHandler::ApplyImplicitRules( 2685 Symbol &symbol, bool allowForwardReference) { 2686 funcResultStack_.CompleteTypeIfFunctionResult(symbol); 2687 if (context().HasError(symbol) || !NeedsType(symbol)) { 2688 return; 2689 } 2690 if (const DeclTypeSpec * type{GetImplicitType(symbol)}) { 2691 if (!skipImplicitTyping_) { 2692 symbol.set(Symbol::Flag::Implicit); 2693 symbol.SetType(*type); 2694 } 2695 return; 2696 } 2697 if (symbol.has<ProcEntityDetails>() && !symbol.attrs().test(Attr::EXTERNAL)) { 2698 std::optional<Symbol::Flag> functionOrSubroutineFlag; 2699 if (symbol.test(Symbol::Flag::Function)) { 2700 functionOrSubroutineFlag = Symbol::Flag::Function; 2701 } else if (symbol.test(Symbol::Flag::Subroutine)) { 2702 functionOrSubroutineFlag = Symbol::Flag::Subroutine; 2703 } 2704 if (IsIntrinsic(symbol.name(), functionOrSubroutineFlag)) { 2705 // type will be determined in expression semantics 2706 AcquireIntrinsicProcedureFlags(symbol); 2707 return; 2708 } 2709 } 2710 if (allowForwardReference && ImplicitlyTypeForwardRef(symbol)) { 2711 return; 2712 } 2713 if (const auto *entity{symbol.detailsIf<EntityDetails>()}; 2714 entity && entity->isDummy()) { 2715 // Dummy argument, no declaration or reference; if it turns 2716 // out to be a subroutine, it's fine, and if it is a function 2717 // or object, it'll be caught later. 2718 return; 2719 } 2720 if (deferImplicitTyping_) { 2721 return; 2722 } 2723 if (!context().HasError(symbol)) { 2724 Say(symbol.name(), "No explicit type declared for '%s'"_err_en_US); 2725 context().SetError(symbol); 2726 } 2727 } 2728 2729 // Extension: Allow forward references to scalar integer dummy arguments 2730 // or variables in COMMON to appear in specification expressions under 2731 // IMPLICIT NONE(TYPE) when what would otherwise have been their implicit 2732 // type is default INTEGER. 2733 bool ScopeHandler::ImplicitlyTypeForwardRef(Symbol &symbol) { 2734 if (!inSpecificationPart_ || context().HasError(symbol) || 2735 !(IsDummy(symbol) || FindCommonBlockContaining(symbol)) || 2736 symbol.Rank() != 0 || 2737 !context().languageFeatures().IsEnabled( 2738 common::LanguageFeature::ForwardRefImplicitNone)) { 2739 return false; 2740 } 2741 const DeclTypeSpec *type{ 2742 GetImplicitType(symbol, false /*ignore IMPLICIT NONE*/)}; 2743 if (!type || !type->IsNumeric(TypeCategory::Integer)) { 2744 return false; 2745 } 2746 auto kind{evaluate::ToInt64(type->numericTypeSpec().kind())}; 2747 if (!kind || *kind != context().GetDefaultKind(TypeCategory::Integer)) { 2748 return false; 2749 } 2750 if (!ConvertToObjectEntity(symbol)) { 2751 return false; 2752 } 2753 // TODO: check no INTENT(OUT) if dummy? 2754 context().Warn(common::LanguageFeature::ForwardRefImplicitNone, symbol.name(), 2755 "'%s' was used without (or before) being explicitly typed"_warn_en_US, 2756 symbol.name()); 2757 symbol.set(Symbol::Flag::Implicit); 2758 symbol.SetType(*type); 2759 return true; 2760 } 2761 2762 // Ensure that the symbol for an intrinsic procedure is marked with 2763 // the INTRINSIC attribute. Also set PURE &/or ELEMENTAL as 2764 // appropriate. 2765 void ScopeHandler::AcquireIntrinsicProcedureFlags(Symbol &symbol) { 2766 SetImplicitAttr(symbol, Attr::INTRINSIC); 2767 switch (context().intrinsics().GetIntrinsicClass(symbol.name().ToString())) { 2768 case evaluate::IntrinsicClass::elementalFunction: 2769 case evaluate::IntrinsicClass::elementalSubroutine: 2770 SetExplicitAttr(symbol, Attr::ELEMENTAL); 2771 SetExplicitAttr(symbol, Attr::PURE); 2772 break; 2773 case evaluate::IntrinsicClass::impureSubroutine: 2774 break; 2775 default: 2776 SetExplicitAttr(symbol, Attr::PURE); 2777 } 2778 } 2779 2780 const DeclTypeSpec *ScopeHandler::GetImplicitType( 2781 Symbol &symbol, bool respectImplicitNoneType) { 2782 const Scope *scope{&symbol.owner()}; 2783 if (scope->IsGlobal()) { 2784 scope = &currScope(); 2785 } 2786 scope = &GetInclusiveScope(*scope); 2787 const auto *type{implicitRulesMap_->at(scope).GetType( 2788 symbol.name(), respectImplicitNoneType)}; 2789 if (type) { 2790 if (const DerivedTypeSpec * derived{type->AsDerived()}) { 2791 // Resolve any forward-referenced derived type; a quick no-op else. 2792 auto &instantiatable{*const_cast<DerivedTypeSpec *>(derived)}; 2793 instantiatable.Instantiate(currScope()); 2794 } 2795 } 2796 return type; 2797 } 2798 2799 void ScopeHandler::CheckEntryDummyUse(SourceName source, Symbol *symbol) { 2800 if (!inSpecificationPart_ && symbol && 2801 symbol->test(Symbol::Flag::EntryDummyArgument)) { 2802 Say(source, 2803 "Dummy argument '%s' may not be used before its ENTRY statement"_err_en_US, 2804 symbol->name()); 2805 symbol->set(Symbol::Flag::EntryDummyArgument, false); 2806 } 2807 } 2808 2809 // Convert symbol to be a ObjectEntity or return false if it can't be. 2810 bool ScopeHandler::ConvertToObjectEntity(Symbol &symbol) { 2811 if (symbol.has<ObjectEntityDetails>()) { 2812 // nothing to do 2813 } else if (symbol.has<UnknownDetails>()) { 2814 // These are attributes that a name could have picked up from 2815 // an attribute statement or type declaration statement. 2816 if (symbol.attrs().HasAny({Attr::EXTERNAL, Attr::INTRINSIC})) { 2817 return false; 2818 } 2819 symbol.set_details(ObjectEntityDetails{}); 2820 } else if (auto *details{symbol.detailsIf<EntityDetails>()}) { 2821 if (symbol.attrs().HasAny({Attr::EXTERNAL, Attr::INTRINSIC})) { 2822 return false; 2823 } 2824 funcResultStack_.CompleteTypeIfFunctionResult(symbol); 2825 symbol.set_details(ObjectEntityDetails{std::move(*details)}); 2826 } else if (auto *useDetails{symbol.detailsIf<UseDetails>()}) { 2827 return useDetails->symbol().has<ObjectEntityDetails>(); 2828 } else if (auto *hostDetails{symbol.detailsIf<HostAssocDetails>()}) { 2829 return hostDetails->symbol().has<ObjectEntityDetails>(); 2830 } else { 2831 return false; 2832 } 2833 return true; 2834 } 2835 // Convert symbol to be a ProcEntity or return false if it can't be. 2836 bool ScopeHandler::ConvertToProcEntity( 2837 Symbol &symbol, std::optional<SourceName> usedHere) { 2838 if (symbol.has<ProcEntityDetails>()) { 2839 } else if (symbol.has<UnknownDetails>()) { 2840 symbol.set_details(ProcEntityDetails{}); 2841 } else if (auto *details{symbol.detailsIf<EntityDetails>()}) { 2842 if (IsFunctionResult(symbol) && 2843 !(IsPointer(symbol) && symbol.attrs().test(Attr::EXTERNAL))) { 2844 // Don't turn function result into a procedure pointer unless both 2845 // POINTER and EXTERNAL 2846 return false; 2847 } 2848 funcResultStack_.CompleteTypeIfFunctionResult(symbol); 2849 symbol.set_details(ProcEntityDetails{std::move(*details)}); 2850 if (symbol.GetType() && !symbol.test(Symbol::Flag::Implicit)) { 2851 CHECK(!symbol.test(Symbol::Flag::Subroutine)); 2852 symbol.set(Symbol::Flag::Function); 2853 } 2854 } else if (auto *useDetails{symbol.detailsIf<UseDetails>()}) { 2855 return useDetails->symbol().has<ProcEntityDetails>(); 2856 } else if (auto *hostDetails{symbol.detailsIf<HostAssocDetails>()}) { 2857 return hostDetails->symbol().has<ProcEntityDetails>(); 2858 } else { 2859 return false; 2860 } 2861 auto &proc{symbol.get<ProcEntityDetails>()}; 2862 if (usedHere && !proc.usedAsProcedureHere()) { 2863 proc.set_usedAsProcedureHere(*usedHere); 2864 } 2865 return true; 2866 } 2867 2868 const DeclTypeSpec &ScopeHandler::MakeNumericType( 2869 TypeCategory category, const std::optional<parser::KindSelector> &kind) { 2870 KindExpr value{GetKindParamExpr(category, kind)}; 2871 if (auto known{evaluate::ToInt64(value)}) { 2872 return MakeNumericType(category, static_cast<int>(*known)); 2873 } else { 2874 return currScope_->MakeNumericType(category, std::move(value)); 2875 } 2876 } 2877 2878 const DeclTypeSpec &ScopeHandler::MakeNumericType( 2879 TypeCategory category, int kind) { 2880 return context().MakeNumericType(category, kind); 2881 } 2882 2883 const DeclTypeSpec &ScopeHandler::MakeLogicalType( 2884 const std::optional<parser::KindSelector> &kind) { 2885 KindExpr value{GetKindParamExpr(TypeCategory::Logical, kind)}; 2886 if (auto known{evaluate::ToInt64(value)}) { 2887 return MakeLogicalType(static_cast<int>(*known)); 2888 } else { 2889 return currScope_->MakeLogicalType(std::move(value)); 2890 } 2891 } 2892 2893 const DeclTypeSpec &ScopeHandler::MakeLogicalType(int kind) { 2894 return context().MakeLogicalType(kind); 2895 } 2896 2897 void ScopeHandler::NotePossibleBadForwardRef(const parser::Name &name) { 2898 if (inSpecificationPart_ && !deferImplicitTyping_ && name.symbol) { 2899 auto kind{currScope().kind()}; 2900 if ((kind == Scope::Kind::Subprogram && !currScope().IsStmtFunction()) || 2901 kind == Scope::Kind::BlockConstruct) { 2902 bool isHostAssociated{&name.symbol->owner() == &currScope() 2903 ? name.symbol->has<HostAssocDetails>() 2904 : name.symbol->owner().Contains(currScope())}; 2905 if (isHostAssociated) { 2906 specPartState_.forwardRefs.insert(name.source); 2907 } 2908 } 2909 } 2910 } 2911 2912 std::optional<SourceName> ScopeHandler::HadForwardRef( 2913 const Symbol &symbol) const { 2914 auto iter{specPartState_.forwardRefs.find(symbol.name())}; 2915 if (iter != specPartState_.forwardRefs.end()) { 2916 return *iter; 2917 } 2918 return std::nullopt; 2919 } 2920 2921 bool ScopeHandler::CheckPossibleBadForwardRef(const Symbol &symbol) { 2922 if (!context().HasError(symbol)) { 2923 if (auto fwdRef{HadForwardRef(symbol)}) { 2924 const Symbol *outer{symbol.owner().FindSymbol(symbol.name())}; 2925 if (outer && symbol.has<UseDetails>() && 2926 &symbol.GetUltimate() == &outer->GetUltimate()) { 2927 // e.g. IMPORT of host's USE association 2928 return false; 2929 } 2930 Say(*fwdRef, 2931 "Forward reference to '%s' is not allowed in the same specification part"_err_en_US, 2932 *fwdRef) 2933 .Attach(symbol.name(), "Later declaration of '%s'"_en_US, *fwdRef); 2934 context().SetError(symbol); 2935 return true; 2936 } 2937 if ((IsDummy(symbol) || FindCommonBlockContaining(symbol)) && 2938 isImplicitNoneType() && symbol.test(Symbol::Flag::Implicit) && 2939 !context().HasError(symbol)) { 2940 // Dummy or COMMON was implicitly typed despite IMPLICIT NONE(TYPE) in 2941 // ApplyImplicitRules() due to use in a specification expression, 2942 // and no explicit type declaration appeared later. 2943 Say(symbol.name(), "No explicit type declared for '%s'"_err_en_US); 2944 context().SetError(symbol); 2945 return true; 2946 } 2947 } 2948 return false; 2949 } 2950 2951 void ScopeHandler::MakeExternal(Symbol &symbol) { 2952 if (!symbol.attrs().test(Attr::EXTERNAL)) { 2953 SetImplicitAttr(symbol, Attr::EXTERNAL); 2954 if (symbol.attrs().test(Attr::INTRINSIC)) { // C840 2955 Say(symbol.name(), 2956 "Symbol '%s' cannot have both EXTERNAL and INTRINSIC attributes"_err_en_US, 2957 symbol.name()); 2958 } 2959 } 2960 } 2961 2962 bool ScopeHandler::CheckDuplicatedAttr( 2963 SourceName name, Symbol &symbol, Attr attr) { 2964 if (attr == Attr::SAVE) { 2965 // checked elsewhere 2966 } else if (symbol.attrs().test(attr)) { // C815 2967 if (symbol.implicitAttrs().test(attr)) { 2968 // Implied attribute is now confirmed explicitly 2969 symbol.implicitAttrs().reset(attr); 2970 } else { 2971 Say(name, "%s attribute was already specified on '%s'"_err_en_US, 2972 EnumToString(attr), name); 2973 return false; 2974 } 2975 } 2976 return true; 2977 } 2978 2979 bool ScopeHandler::CheckDuplicatedAttrs( 2980 SourceName name, Symbol &symbol, Attrs attrs) { 2981 bool ok{true}; 2982 attrs.IterateOverMembers( 2983 [&](Attr x) { ok &= CheckDuplicatedAttr(name, symbol, x); }); 2984 return ok; 2985 } 2986 2987 void ScopeHandler::SetCUDADataAttr(SourceName source, Symbol &symbol, 2988 std::optional<common::CUDADataAttr> attr) { 2989 if (attr) { 2990 ConvertToObjectEntity(symbol); 2991 if (auto *object{symbol.detailsIf<ObjectEntityDetails>()}) { 2992 if (*attr != object->cudaDataAttr().value_or(*attr)) { 2993 Say(source, 2994 "'%s' already has another CUDA data attribute ('%s')"_err_en_US, 2995 symbol.name(), 2996 std::string{common::EnumToString(*object->cudaDataAttr())}.c_str()); 2997 } else { 2998 object->set_cudaDataAttr(attr); 2999 } 3000 } else { 3001 Say(source, 3002 "'%s' is not an object and may not have a CUDA data attribute"_err_en_US, 3003 symbol.name()); 3004 } 3005 } 3006 } 3007 3008 // ModuleVisitor implementation 3009 3010 bool ModuleVisitor::Pre(const parser::Only &x) { 3011 common::visit(common::visitors{ 3012 [&](const Indirection<parser::GenericSpec> &generic) { 3013 GenericSpecInfo genericSpecInfo{generic.value()}; 3014 AddUseOnly(genericSpecInfo.symbolName()); 3015 AddUse(genericSpecInfo); 3016 }, 3017 [&](const parser::Name &name) { 3018 AddUseOnly(name.source); 3019 Resolve(name, AddUse(name.source, name.source).use); 3020 }, 3021 [&](const parser::Rename &rename) { Walk(rename); }, 3022 }, 3023 x.u); 3024 return false; 3025 } 3026 3027 void ModuleVisitor::CollectUseRenames(const parser::UseStmt &useStmt) { 3028 auto doRename{[&](const parser::Rename &rename) { 3029 if (const auto *names{std::get_if<parser::Rename::Names>(&rename.u)}) { 3030 AddUseRename(std::get<1>(names->t).source, useStmt.moduleName.source); 3031 } 3032 }}; 3033 common::visit( 3034 common::visitors{ 3035 [&](const std::list<parser::Rename> &renames) { 3036 for (const auto &rename : renames) { 3037 doRename(rename); 3038 } 3039 }, 3040 [&](const std::list<parser::Only> &onlys) { 3041 for (const auto &only : onlys) { 3042 if (const auto *rename{std::get_if<parser::Rename>(&only.u)}) { 3043 doRename(*rename); 3044 } 3045 } 3046 }, 3047 }, 3048 useStmt.u); 3049 } 3050 3051 bool ModuleVisitor::Pre(const parser::Rename::Names &x) { 3052 const auto &localName{std::get<0>(x.t)}; 3053 const auto &useName{std::get<1>(x.t)}; 3054 SymbolRename rename{AddUse(localName.source, useName.source)}; 3055 Resolve(useName, rename.use); 3056 Resolve(localName, rename.local); 3057 return false; 3058 } 3059 bool ModuleVisitor::Pre(const parser::Rename::Operators &x) { 3060 const parser::DefinedOpName &local{std::get<0>(x.t)}; 3061 const parser::DefinedOpName &use{std::get<1>(x.t)}; 3062 GenericSpecInfo localInfo{local}; 3063 GenericSpecInfo useInfo{use}; 3064 if (IsIntrinsicOperator(context(), local.v.source)) { 3065 Say(local.v, 3066 "Intrinsic operator '%s' may not be used as a defined operator"_err_en_US); 3067 } else if (IsLogicalConstant(context(), local.v.source)) { 3068 Say(local.v, 3069 "Logical constant '%s' may not be used as a defined operator"_err_en_US); 3070 } else { 3071 SymbolRename rename{AddUse(localInfo.symbolName(), useInfo.symbolName())}; 3072 useInfo.Resolve(rename.use); 3073 localInfo.Resolve(rename.local); 3074 } 3075 return false; 3076 } 3077 3078 // Set useModuleScope_ to the Scope of the module being used. 3079 bool ModuleVisitor::Pre(const parser::UseStmt &x) { 3080 std::optional<bool> isIntrinsic; 3081 if (x.nature) { 3082 isIntrinsic = *x.nature == parser::UseStmt::ModuleNature::Intrinsic; 3083 } else if (currScope().IsModule() && currScope().symbol() && 3084 currScope().symbol()->attrs().test(Attr::INTRINSIC)) { 3085 // Intrinsic modules USE only other intrinsic modules 3086 isIntrinsic = true; 3087 } 3088 useModuleScope_ = FindModule(x.moduleName, isIntrinsic); 3089 if (!useModuleScope_) { 3090 return false; 3091 } 3092 AddAndCheckModuleUse(x.moduleName.source, 3093 useModuleScope_->parent().kind() == Scope::Kind::IntrinsicModules); 3094 // use the name from this source file 3095 useModuleScope_->symbol()->ReplaceName(x.moduleName.source); 3096 return true; 3097 } 3098 3099 void ModuleVisitor::Post(const parser::UseStmt &x) { 3100 if (const auto *list{std::get_if<std::list<parser::Rename>>(&x.u)}) { 3101 // Not a use-only: collect the names that were used in renames, 3102 // then add a use for each public name that was not renamed. 3103 std::set<SourceName> useNames; 3104 for (const auto &rename : *list) { 3105 common::visit(common::visitors{ 3106 [&](const parser::Rename::Names &names) { 3107 useNames.insert(std::get<1>(names.t).source); 3108 }, 3109 [&](const parser::Rename::Operators &ops) { 3110 useNames.insert(std::get<1>(ops.t).v.source); 3111 }, 3112 }, 3113 rename.u); 3114 } 3115 for (const auto &[name, symbol] : *useModuleScope_) { 3116 if (symbol->attrs().test(Attr::PUBLIC) && !IsUseRenamed(symbol->name()) && 3117 (!symbol->implicitAttrs().test(Attr::INTRINSIC) || 3118 symbol->has<UseDetails>()) && 3119 !symbol->has<MiscDetails>() && useNames.count(name) == 0) { 3120 SourceName location{x.moduleName.source}; 3121 if (auto *localSymbol{FindInScope(name)}) { 3122 DoAddUse(location, localSymbol->name(), *localSymbol, *symbol); 3123 } else { 3124 DoAddUse(location, location, CopySymbol(name, *symbol), *symbol); 3125 } 3126 } 3127 } 3128 } 3129 useModuleScope_ = nullptr; 3130 } 3131 3132 ModuleVisitor::SymbolRename ModuleVisitor::AddUse( 3133 const SourceName &localName, const SourceName &useName) { 3134 return AddUse(localName, useName, FindInScope(*useModuleScope_, useName)); 3135 } 3136 3137 ModuleVisitor::SymbolRename ModuleVisitor::AddUse( 3138 const SourceName &localName, const SourceName &useName, Symbol *useSymbol) { 3139 if (!useModuleScope_) { 3140 return {}; // error occurred finding module 3141 } 3142 if (!useSymbol) { 3143 Say(useName, "'%s' not found in module '%s'"_err_en_US, MakeOpName(useName), 3144 useModuleScope_->GetName().value()); 3145 return {}; 3146 } 3147 if (useSymbol->attrs().test(Attr::PRIVATE) && 3148 !FindModuleFileContaining(currScope())) { 3149 // Privacy is not enforced in module files so that generic interfaces 3150 // can be resolved to private specific procedures in specification 3151 // expressions. 3152 Say(useName, "'%s' is PRIVATE in '%s'"_err_en_US, MakeOpName(useName), 3153 useModuleScope_->GetName().value()); 3154 return {}; 3155 } 3156 auto &localSymbol{MakeSymbol(localName)}; 3157 DoAddUse(useName, localName, localSymbol, *useSymbol); 3158 return {&localSymbol, useSymbol}; 3159 } 3160 3161 // symbol must be either a Use or a Generic formed by merging two uses. 3162 // Convert it to a UseError with this additional location. 3163 static bool ConvertToUseError( 3164 Symbol &symbol, const SourceName &location, const Scope &module) { 3165 if (auto *ued{symbol.detailsIf<UseErrorDetails>()}) { 3166 ued->add_occurrence(location, module); 3167 return true; 3168 } 3169 const auto *useDetails{symbol.detailsIf<UseDetails>()}; 3170 if (!useDetails) { 3171 if (auto *genericDetails{symbol.detailsIf<GenericDetails>()}) { 3172 if (!genericDetails->uses().empty()) { 3173 useDetails = &genericDetails->uses().at(0)->get<UseDetails>(); 3174 } 3175 } 3176 } 3177 if (useDetails) { 3178 symbol.set_details( 3179 UseErrorDetails{*useDetails}.add_occurrence(location, module)); 3180 return true; 3181 } else { 3182 return false; 3183 } 3184 } 3185 3186 void ModuleVisitor::DoAddUse(SourceName location, SourceName localName, 3187 Symbol &originalLocal, const Symbol &useSymbol) { 3188 Symbol *localSymbol{&originalLocal}; 3189 if (auto *details{localSymbol->detailsIf<UseErrorDetails>()}) { 3190 details->add_occurrence(location, *useModuleScope_); 3191 return; 3192 } 3193 const Symbol &useUltimate{useSymbol.GetUltimate()}; 3194 const auto *useGeneric{useUltimate.detailsIf<GenericDetails>()}; 3195 if (localSymbol->has<UnknownDetails>()) { 3196 if (useGeneric && 3197 ((useGeneric->specific() && 3198 IsProcedurePointer(*useGeneric->specific())) || 3199 (useGeneric->derivedType() && 3200 useUltimate.name() != localSymbol->name()))) { 3201 // We are use-associating a generic that either shadows a procedure 3202 // pointer or shadows a derived type with a distinct name. 3203 // Local references that might be made to the procedure pointer should 3204 // use a UseDetails symbol for proper data addressing, and a derived 3205 // type needs to be in scope with its local name. So create an 3206 // empty local generic now into which the use-associated generic may 3207 // be copied. 3208 localSymbol->set_details(GenericDetails{}); 3209 localSymbol->get<GenericDetails>().set_kind(useGeneric->kind()); 3210 } else { // just create UseDetails 3211 localSymbol->set_details(UseDetails{localName, useSymbol}); 3212 localSymbol->attrs() = 3213 useSymbol.attrs() & ~Attrs{Attr::PUBLIC, Attr::PRIVATE, Attr::SAVE}; 3214 localSymbol->implicitAttrs() = 3215 localSymbol->attrs() & Attrs{Attr::ASYNCHRONOUS, Attr::VOLATILE}; 3216 localSymbol->flags() = useSymbol.flags(); 3217 return; 3218 } 3219 } 3220 3221 Symbol &localUltimate{localSymbol->GetUltimate()}; 3222 if (&localUltimate == &useUltimate) { 3223 // use-associating the same symbol again -- ok 3224 return; 3225 } 3226 3227 // There are many possible combinations of symbol types that could arrive 3228 // with the same (local) name vie USE association from distinct modules. 3229 // Fortran allows a generic interface to share its name with a derived type, 3230 // or with the name of a non-generic procedure (which should be one of the 3231 // generic's specific procedures). Implementing all these possibilities is 3232 // complicated. 3233 // Error cases are converted into UseErrorDetails symbols to trigger error 3234 // messages when/if bad combinations are actually used later in the program. 3235 // The error cases are: 3236 // - two distinct derived types 3237 // - two distinct non-generic procedures 3238 // - a generic and a non-generic that is not already one of its specifics 3239 // - anything other than a derived type, non-generic procedure, or 3240 // generic procedure being combined with something other than an 3241 // prior USE association of itself 3242 auto *localGeneric{localUltimate.detailsIf<GenericDetails>()}; 3243 Symbol *localDerivedType{nullptr}; 3244 if (localUltimate.has<DerivedTypeDetails>()) { 3245 localDerivedType = &localUltimate; 3246 } else if (localGeneric) { 3247 if (auto *dt{localGeneric->derivedType()}; 3248 dt && !dt->attrs().test(Attr::PRIVATE)) { 3249 localDerivedType = dt; 3250 } 3251 } 3252 const Symbol *useDerivedType{nullptr}; 3253 if (useUltimate.has<DerivedTypeDetails>()) { 3254 useDerivedType = &useUltimate; 3255 } else if (useGeneric) { 3256 if (const auto *dt{useGeneric->derivedType()}; 3257 dt && !dt->attrs().test(Attr::PRIVATE)) { 3258 useDerivedType = dt; 3259 } 3260 } 3261 3262 Symbol *localProcedure{nullptr}; 3263 if (localGeneric) { 3264 if (localGeneric->specific() && 3265 !localGeneric->specific()->attrs().test(Attr::PRIVATE)) { 3266 localProcedure = localGeneric->specific(); 3267 } 3268 } else if (IsProcedure(localUltimate)) { 3269 localProcedure = &localUltimate; 3270 } 3271 const Symbol *useProcedure{nullptr}; 3272 if (useGeneric) { 3273 if (useGeneric->specific() && 3274 !useGeneric->specific()->attrs().test(Attr::PRIVATE)) { 3275 useProcedure = useGeneric->specific(); 3276 } 3277 } else if (IsProcedure(useUltimate)) { 3278 useProcedure = &useUltimate; 3279 } 3280 3281 // Creates a UseErrorDetails symbol in the current scope for a 3282 // current UseDetails symbol, but leaves the UseDetails in the 3283 // scope's name map. 3284 auto CreateLocalUseError{[&]() { 3285 EraseSymbol(*localSymbol); 3286 CHECK(localSymbol->has<UseDetails>()); 3287 UseErrorDetails details{localSymbol->get<UseDetails>()}; 3288 details.add_occurrence(location, *useModuleScope_); 3289 Symbol *newSymbol{&MakeSymbol(localName, Attrs{}, std::move(details))}; 3290 // Restore *localSymbol in currScope 3291 auto iter{currScope().find(localName)}; 3292 CHECK(iter != currScope().end() && &*iter->second == newSymbol); 3293 iter->second = MutableSymbolRef{*localSymbol}; 3294 return newSymbol; 3295 }}; 3296 3297 // When two derived types arrived, try to combine them. 3298 const Symbol *combinedDerivedType{nullptr}; 3299 if (!useDerivedType) { 3300 combinedDerivedType = localDerivedType; 3301 } else if (!localDerivedType) { 3302 if (useDerivedType->name() == localName) { 3303 combinedDerivedType = useDerivedType; 3304 } else { 3305 combinedDerivedType = 3306 &currScope().MakeSymbol(localSymbol->name(), useDerivedType->attrs(), 3307 UseDetails{localSymbol->name(), *useDerivedType}); 3308 } 3309 } else if (&localDerivedType->GetUltimate() == 3310 &useDerivedType->GetUltimate()) { 3311 combinedDerivedType = localDerivedType; 3312 } else { 3313 const Scope *localScope{localDerivedType->GetUltimate().scope()}; 3314 const Scope *useScope{useDerivedType->GetUltimate().scope()}; 3315 if (localScope && useScope && localScope->derivedTypeSpec() && 3316 useScope->derivedTypeSpec() && 3317 evaluate::AreSameDerivedType( 3318 *localScope->derivedTypeSpec(), *useScope->derivedTypeSpec())) { 3319 combinedDerivedType = localDerivedType; 3320 } else { 3321 // Create a local UseErrorDetails for the ambiguous derived type 3322 if (localGeneric) { 3323 combinedDerivedType = CreateLocalUseError(); 3324 } else { 3325 ConvertToUseError(*localSymbol, location, *useModuleScope_); 3326 localDerivedType = nullptr; 3327 localGeneric = nullptr; 3328 combinedDerivedType = localSymbol; 3329 } 3330 } 3331 if (!localGeneric && !useGeneric) { 3332 return; // both symbols are derived types; done 3333 } 3334 } 3335 3336 auto AreSameProcedure{[&](const Symbol &p1, const Symbol &p2) { 3337 if (&p1 == &p2) { 3338 return true; 3339 } else if (p1.name() != p2.name()) { 3340 return false; 3341 } else if (p1.attrs().test(Attr::INTRINSIC) || 3342 p2.attrs().test(Attr::INTRINSIC)) { 3343 return p1.attrs().test(Attr::INTRINSIC) && 3344 p2.attrs().test(Attr::INTRINSIC); 3345 } else if (!IsProcedure(p1) || !IsProcedure(p2)) { 3346 return false; 3347 } else if (IsPointer(p1) || IsPointer(p2)) { 3348 return false; 3349 } else if (const auto *subp{p1.detailsIf<SubprogramDetails>()}; 3350 subp && !subp->isInterface()) { 3351 return false; // defined in module, not an external 3352 } else if (const auto *subp{p2.detailsIf<SubprogramDetails>()}; 3353 subp && !subp->isInterface()) { 3354 return false; // defined in module, not an external 3355 } else { 3356 // Both are external interfaces, perhaps to the same procedure 3357 auto class1{ClassifyProcedure(p1)}; 3358 auto class2{ClassifyProcedure(p2)}; 3359 if (class1 == ProcedureDefinitionClass::External && 3360 class2 == ProcedureDefinitionClass::External) { 3361 auto chars1{evaluate::characteristics::Procedure::Characterize( 3362 p1, GetFoldingContext())}; 3363 auto chars2{evaluate::characteristics::Procedure::Characterize( 3364 p2, GetFoldingContext())}; 3365 // same procedure interface defined identically in two modules? 3366 return chars1 && chars2 && *chars1 == *chars2; 3367 } else { 3368 return false; 3369 } 3370 } 3371 }}; 3372 3373 // When two non-generic procedures arrived, try to combine them. 3374 const Symbol *combinedProcedure{nullptr}; 3375 if (!localProcedure) { 3376 combinedProcedure = useProcedure; 3377 } else if (!useProcedure) { 3378 combinedProcedure = localProcedure; 3379 } else { 3380 if (AreSameProcedure( 3381 localProcedure->GetUltimate(), useProcedure->GetUltimate())) { 3382 if (!localGeneric && !useGeneric) { 3383 return; // both symbols are non-generic procedures 3384 } 3385 combinedProcedure = localProcedure; 3386 } 3387 } 3388 3389 // Prepare to merge generics 3390 bool cantCombine{false}; 3391 if (localGeneric) { 3392 if (useGeneric || useDerivedType) { 3393 } else if (&useUltimate == &BypassGeneric(localUltimate).GetUltimate()) { 3394 return; // nothing to do; used subprogram is local's specific 3395 } else if (useUltimate.attrs().test(Attr::INTRINSIC) && 3396 useUltimate.name() == localSymbol->name()) { 3397 return; // local generic can extend intrinsic 3398 } else { 3399 for (const auto &ref : localGeneric->specificProcs()) { 3400 if (&ref->GetUltimate() == &useUltimate) { 3401 return; // used non-generic is already a specific of local generic 3402 } 3403 } 3404 cantCombine = true; 3405 } 3406 } else if (useGeneric) { 3407 if (localDerivedType) { 3408 } else if (&localUltimate == &BypassGeneric(useUltimate).GetUltimate() || 3409 (localSymbol->attrs().test(Attr::INTRINSIC) && 3410 localUltimate.name() == useUltimate.name())) { 3411 // Local is the specific of the used generic or an intrinsic with the 3412 // same name; replace it. 3413 EraseSymbol(*localSymbol); 3414 Symbol &newSymbol{MakeSymbol(localName, 3415 useUltimate.attrs() & ~Attrs{Attr::PUBLIC, Attr::PRIVATE}, 3416 UseDetails{localName, useUltimate})}; 3417 newSymbol.flags() = useSymbol.flags(); 3418 return; 3419 } else { 3420 for (const auto &ref : useGeneric->specificProcs()) { 3421 if (&ref->GetUltimate() == &localUltimate) { 3422 return; // local non-generic is already a specific of used generic 3423 } 3424 } 3425 cantCombine = true; 3426 } 3427 } else { 3428 cantCombine = true; 3429 } 3430 3431 // If symbols are not combinable, create a use error. 3432 if (cantCombine) { 3433 if (!ConvertToUseError(*localSymbol, location, *useModuleScope_)) { 3434 Say(location, 3435 "Cannot use-associate '%s'; it is already declared in this scope"_err_en_US, 3436 localName) 3437 .Attach(localSymbol->name(), "Previous declaration of '%s'"_en_US, 3438 localName); 3439 } 3440 return; 3441 } 3442 3443 // At this point, there must be at least one generic interface. 3444 CHECK(localGeneric || (useGeneric && (localDerivedType || localProcedure))); 3445 3446 // Ensure that a use-associated specific procedure that is a procedure 3447 // pointer is properly represented as a USE association of an entity. 3448 if (IsProcedurePointer(useProcedure)) { 3449 Symbol &combined{currScope().MakeSymbol(localSymbol->name(), 3450 useProcedure->attrs(), UseDetails{localName, *useProcedure})}; 3451 combined.flags() |= useProcedure->flags(); 3452 combinedProcedure = &combined; 3453 } 3454 3455 if (localGeneric) { 3456 // Create a local copy of a previously use-associated generic so that 3457 // it can be locally extended without corrupting the original. 3458 if (localSymbol->has<UseDetails>()) { 3459 GenericDetails generic; 3460 generic.CopyFrom(DEREF(localGeneric)); 3461 EraseSymbol(*localSymbol); 3462 Symbol &newSymbol{MakeSymbol( 3463 localSymbol->name(), localSymbol->attrs(), std::move(generic))}; 3464 newSymbol.flags() = localSymbol->flags(); 3465 localGeneric = &newSymbol.get<GenericDetails>(); 3466 localGeneric->AddUse(*localSymbol); 3467 localSymbol = &newSymbol; 3468 } 3469 if (useGeneric) { 3470 // Combine two use-associated generics 3471 localSymbol->attrs() = 3472 useSymbol.attrs() & ~Attrs{Attr::PUBLIC, Attr::PRIVATE}; 3473 localSymbol->flags() = useSymbol.flags(); 3474 AddGenericUse(*localGeneric, localName, useUltimate); 3475 localGeneric->clear_derivedType(); 3476 localGeneric->CopyFrom(*useGeneric); 3477 } 3478 localGeneric->clear_derivedType(); 3479 if (combinedDerivedType) { 3480 localGeneric->set_derivedType(*const_cast<Symbol *>(combinedDerivedType)); 3481 } 3482 localGeneric->clear_specific(); 3483 if (combinedProcedure) { 3484 localGeneric->set_specific(*const_cast<Symbol *>(combinedProcedure)); 3485 } 3486 } else { 3487 CHECK(localSymbol->has<UseDetails>()); 3488 // Create a local copy of the use-associated generic, then extend it 3489 // with the combined derived type &/or non-generic procedure. 3490 GenericDetails generic; 3491 generic.CopyFrom(*useGeneric); 3492 EraseSymbol(*localSymbol); 3493 Symbol &newSymbol{MakeSymbol(localName, 3494 useUltimate.attrs() & ~Attrs{Attr::PUBLIC, Attr::PRIVATE}, 3495 std::move(generic))}; 3496 newSymbol.flags() = useUltimate.flags(); 3497 auto &newUseGeneric{newSymbol.get<GenericDetails>()}; 3498 AddGenericUse(newUseGeneric, localName, useUltimate); 3499 newUseGeneric.AddUse(*localSymbol); 3500 if (combinedDerivedType) { 3501 if (const auto *oldDT{newUseGeneric.derivedType()}) { 3502 CHECK(&oldDT->GetUltimate() == &combinedDerivedType->GetUltimate()); 3503 } else { 3504 newUseGeneric.set_derivedType( 3505 *const_cast<Symbol *>(combinedDerivedType)); 3506 } 3507 } 3508 if (combinedProcedure) { 3509 newUseGeneric.set_specific(*const_cast<Symbol *>(combinedProcedure)); 3510 } 3511 } 3512 } 3513 3514 void ModuleVisitor::AddUse(const GenericSpecInfo &info) { 3515 if (useModuleScope_) { 3516 const auto &name{info.symbolName()}; 3517 auto rename{AddUse(name, name, FindInScope(*useModuleScope_, name))}; 3518 info.Resolve(rename.use); 3519 } 3520 } 3521 3522 // Create a UseDetails symbol for this USE and add it to generic 3523 Symbol &ModuleVisitor::AddGenericUse( 3524 GenericDetails &generic, const SourceName &name, const Symbol &useSymbol) { 3525 Symbol &newSymbol{ 3526 currScope().MakeSymbol(name, {}, UseDetails{name, useSymbol})}; 3527 generic.AddUse(newSymbol); 3528 return newSymbol; 3529 } 3530 3531 // Enforce F'2023 C1406 as a warning 3532 void ModuleVisitor::AddAndCheckModuleUse(SourceName name, bool isIntrinsic) { 3533 if (isIntrinsic) { 3534 if (auto iter{nonIntrinsicUses_.find(name)}; 3535 iter != nonIntrinsicUses_.end()) { 3536 if (auto *msg{context().Warn(common::LanguageFeature::MiscUseExtensions, 3537 name, 3538 "Should not USE the intrinsic module '%s' in the same scope as a USE of the non-intrinsic module"_port_en_US, 3539 name)}) { 3540 msg->Attach(*iter, "Previous USE of '%s'"_en_US, *iter); 3541 } 3542 } 3543 intrinsicUses_.insert(name); 3544 } else { 3545 if (auto iter{intrinsicUses_.find(name)}; iter != intrinsicUses_.end()) { 3546 if (auto *msg{context().Warn(common::LanguageFeature::MiscUseExtensions, 3547 name, 3548 "Should not USE the non-intrinsic module '%s' in the same scope as a USE of the intrinsic module"_port_en_US, 3549 name)}) { 3550 msg->Attach(*iter, "Previous USE of '%s'"_en_US, *iter); 3551 } 3552 } 3553 nonIntrinsicUses_.insert(name); 3554 } 3555 } 3556 3557 bool ModuleVisitor::BeginSubmodule( 3558 const parser::Name &name, const parser::ParentIdentifier &parentId) { 3559 const auto &ancestorName{std::get<parser::Name>(parentId.t)}; 3560 Scope *parentScope{nullptr}; 3561 Scope *ancestor{FindModule(ancestorName, false /*not intrinsic*/)}; 3562 if (ancestor) { 3563 if (const auto &parentName{ 3564 std::get<std::optional<parser::Name>>(parentId.t)}) { 3565 parentScope = FindModule(*parentName, false /*not intrinsic*/, ancestor); 3566 } else { 3567 parentScope = ancestor; 3568 } 3569 } 3570 if (parentScope) { 3571 PushScope(*parentScope); 3572 } else { 3573 // Error recovery: there's no ancestor scope, so create a dummy one to 3574 // hold the submodule's scope. 3575 SourceName dummyName{context().GetTempName(currScope())}; 3576 Symbol &dummySymbol{MakeSymbol(dummyName, Attrs{}, ModuleDetails{false})}; 3577 PushScope(Scope::Kind::Module, &dummySymbol); 3578 parentScope = &currScope(); 3579 } 3580 BeginModule(name, true); 3581 set_inheritFromParent(false); // submodules don't inherit parents' implicits 3582 if (ancestor && !ancestor->AddSubmodule(name.source, currScope())) { 3583 Say(name, "Module '%s' already has a submodule named '%s'"_err_en_US, 3584 ancestorName.source, name.source); 3585 } 3586 return true; 3587 } 3588 3589 void ModuleVisitor::BeginModule(const parser::Name &name, bool isSubmodule) { 3590 // Submodule symbols are not visible in their parents' scopes. 3591 Symbol &symbol{isSubmodule ? Resolve(name, 3592 currScope().MakeSymbol(name.source, Attrs{}, 3593 ModuleDetails{true})) 3594 : MakeSymbol(name, ModuleDetails{false})}; 3595 auto &details{symbol.get<ModuleDetails>()}; 3596 PushScope(Scope::Kind::Module, &symbol); 3597 details.set_scope(&currScope()); 3598 prevAccessStmt_ = std::nullopt; 3599 } 3600 3601 // Find a module or submodule by name and return its scope. 3602 // If ancestor is present, look for a submodule of that ancestor module. 3603 // May have to read a .mod file to find it. 3604 // If an error occurs, report it and return nullptr. 3605 Scope *ModuleVisitor::FindModule(const parser::Name &name, 3606 std::optional<bool> isIntrinsic, Scope *ancestor) { 3607 ModFileReader reader{context()}; 3608 Scope *scope{ 3609 reader.Read(name.source, isIntrinsic, ancestor, /*silent=*/false)}; 3610 if (!scope) { 3611 return nullptr; 3612 } 3613 if (DoesScopeContain(scope, currScope())) { // 14.2.2(1) 3614 Say(name, "Module '%s' cannot USE itself"_err_en_US); 3615 } 3616 Resolve(name, scope->symbol()); 3617 return scope; 3618 } 3619 3620 void ModuleVisitor::ApplyDefaultAccess() { 3621 const auto *moduleDetails{ 3622 DEREF(currScope().symbol()).detailsIf<ModuleDetails>()}; 3623 CHECK(moduleDetails); 3624 Attr defaultAttr{ 3625 DEREF(moduleDetails).isDefaultPrivate() ? Attr::PRIVATE : Attr::PUBLIC}; 3626 for (auto &pair : currScope()) { 3627 Symbol &symbol{*pair.second}; 3628 if (!symbol.attrs().HasAny({Attr::PUBLIC, Attr::PRIVATE})) { 3629 Attr attr{defaultAttr}; 3630 if (auto *generic{symbol.detailsIf<GenericDetails>()}) { 3631 if (generic->derivedType()) { 3632 // If a generic interface has a derived type of the same 3633 // name that has an explicit accessibility attribute, then 3634 // the generic must have the same accessibility. 3635 if (generic->derivedType()->attrs().test(Attr::PUBLIC)) { 3636 attr = Attr::PUBLIC; 3637 } else if (generic->derivedType()->attrs().test(Attr::PRIVATE)) { 3638 attr = Attr::PRIVATE; 3639 } 3640 } 3641 } 3642 SetImplicitAttr(symbol, attr); 3643 } 3644 } 3645 } 3646 3647 // InterfaceVistor implementation 3648 3649 bool InterfaceVisitor::Pre(const parser::InterfaceStmt &x) { 3650 bool isAbstract{std::holds_alternative<parser::Abstract>(x.u)}; 3651 genericInfo_.emplace(/*isInterface*/ true, isAbstract); 3652 return BeginAttrs(); 3653 } 3654 3655 void InterfaceVisitor::Post(const parser::InterfaceStmt &) { EndAttrs(); } 3656 3657 void InterfaceVisitor::Post(const parser::EndInterfaceStmt &) { 3658 ResolveNewSpecifics(); 3659 genericInfo_.pop(); 3660 } 3661 3662 // Create a symbol in genericSymbol_ for this GenericSpec. 3663 bool InterfaceVisitor::Pre(const parser::GenericSpec &x) { 3664 if (auto *symbol{FindInScope(GenericSpecInfo{x}.symbolName())}) { 3665 SetGenericSymbol(*symbol); 3666 } 3667 return false; 3668 } 3669 3670 bool InterfaceVisitor::Pre(const parser::ProcedureStmt &x) { 3671 if (!isGeneric()) { 3672 Say("A PROCEDURE statement is only allowed in a generic interface block"_err_en_US); 3673 } else { 3674 auto kind{std::get<parser::ProcedureStmt::Kind>(x.t)}; 3675 const auto &names{std::get<std::list<parser::Name>>(x.t)}; 3676 AddSpecificProcs(names, kind); 3677 } 3678 return false; 3679 } 3680 3681 bool InterfaceVisitor::Pre(const parser::GenericStmt &) { 3682 genericInfo_.emplace(/*isInterface*/ false); 3683 return BeginAttrs(); 3684 } 3685 void InterfaceVisitor::Post(const parser::GenericStmt &x) { 3686 auto attrs{EndAttrs()}; 3687 if (Symbol * symbol{GetGenericInfo().symbol}) { 3688 SetExplicitAttrs(*symbol, attrs); 3689 } 3690 const auto &names{std::get<std::list<parser::Name>>(x.t)}; 3691 AddSpecificProcs(names, ProcedureKind::Procedure); 3692 ResolveNewSpecifics(); 3693 genericInfo_.pop(); 3694 } 3695 3696 bool InterfaceVisitor::inInterfaceBlock() const { 3697 return !genericInfo_.empty() && GetGenericInfo().isInterface; 3698 } 3699 bool InterfaceVisitor::isGeneric() const { 3700 return !genericInfo_.empty() && GetGenericInfo().symbol; 3701 } 3702 bool InterfaceVisitor::isAbstract() const { 3703 return !genericInfo_.empty() && GetGenericInfo().isAbstract; 3704 } 3705 3706 void InterfaceVisitor::AddSpecificProcs( 3707 const std::list<parser::Name> &names, ProcedureKind kind) { 3708 if (Symbol * symbol{GetGenericInfo().symbol}; 3709 symbol && symbol->has<GenericDetails>()) { 3710 for (const auto &name : names) { 3711 specificsForGenericProcs_.emplace(symbol, std::make_pair(&name, kind)); 3712 genericsForSpecificProcs_.emplace(name.source, symbol); 3713 } 3714 } 3715 } 3716 3717 // By now we should have seen all specific procedures referenced by name in 3718 // this generic interface. Resolve those names to symbols. 3719 void GenericHandler::ResolveSpecificsInGeneric( 3720 Symbol &generic, bool isEndOfSpecificationPart) { 3721 auto &details{generic.get<GenericDetails>()}; 3722 UnorderedSymbolSet symbolsSeen; 3723 for (const Symbol &symbol : details.specificProcs()) { 3724 symbolsSeen.insert(symbol.GetUltimate()); 3725 } 3726 auto range{specificsForGenericProcs_.equal_range(&generic)}; 3727 SpecificProcMapType retain; 3728 for (auto it{range.first}; it != range.second; ++it) { 3729 const parser::Name *name{it->second.first}; 3730 auto kind{it->second.second}; 3731 const Symbol *symbol{isEndOfSpecificationPart 3732 ? FindSymbol(*name) 3733 : FindInScope(generic.owner(), *name)}; 3734 ProcedureDefinitionClass defClass{ProcedureDefinitionClass::None}; 3735 const Symbol *specific{symbol}; 3736 const Symbol *ultimate{nullptr}; 3737 if (symbol) { 3738 // Subtlety: when *symbol is a use- or host-association, the specific 3739 // procedure that is recorded in the GenericDetails below must be *symbol, 3740 // not the specific procedure shadowed by a generic, because that specific 3741 // procedure may be a symbol from another module and its name unavailable 3742 // to emit to a module file. 3743 const Symbol &bypassed{BypassGeneric(*symbol)}; 3744 if (symbol == &symbol->GetUltimate()) { 3745 specific = &bypassed; 3746 } 3747 ultimate = &bypassed.GetUltimate(); 3748 defClass = ClassifyProcedure(*ultimate); 3749 } 3750 std::optional<MessageFixedText> error; 3751 if (defClass == ProcedureDefinitionClass::Module) { 3752 // ok 3753 } else if (kind == ProcedureKind::ModuleProcedure) { 3754 error = "'%s' is not a module procedure"_err_en_US; 3755 } else { 3756 switch (defClass) { 3757 case ProcedureDefinitionClass::Intrinsic: 3758 case ProcedureDefinitionClass::External: 3759 case ProcedureDefinitionClass::Internal: 3760 case ProcedureDefinitionClass::Dummy: 3761 case ProcedureDefinitionClass::Pointer: 3762 break; 3763 case ProcedureDefinitionClass::None: 3764 error = "'%s' is not a procedure"_err_en_US; 3765 break; 3766 default: 3767 error = 3768 "'%s' is not a procedure that can appear in a generic interface"_err_en_US; 3769 break; 3770 } 3771 } 3772 if (error) { 3773 if (isEndOfSpecificationPart) { 3774 Say(*name, std::move(*error)); 3775 } else { 3776 // possible forward reference, catch it later 3777 retain.emplace(&generic, std::make_pair(name, kind)); 3778 } 3779 } else if (!ultimate) { 3780 } else if (symbolsSeen.insert(*ultimate).second /*true if added*/) { 3781 // When a specific procedure is a USE association, that association 3782 // is saved in the generic's specifics, not its ultimate symbol, 3783 // so that module file output of interfaces can distinguish them. 3784 details.AddSpecificProc(*specific, name->source); 3785 } else if (specific == ultimate) { 3786 Say(name->source, 3787 "Procedure '%s' is already specified in generic '%s'"_err_en_US, 3788 name->source, MakeOpName(generic.name())); 3789 } else { 3790 Say(name->source, 3791 "Procedure '%s' from module '%s' is already specified in generic '%s'"_err_en_US, 3792 ultimate->name(), ultimate->owner().GetName().value(), 3793 MakeOpName(generic.name())); 3794 } 3795 } 3796 specificsForGenericProcs_.erase(range.first, range.second); 3797 specificsForGenericProcs_.merge(std::move(retain)); 3798 } 3799 3800 void GenericHandler::DeclaredPossibleSpecificProc(Symbol &proc) { 3801 auto range{genericsForSpecificProcs_.equal_range(proc.name())}; 3802 for (auto iter{range.first}; iter != range.second; ++iter) { 3803 ResolveSpecificsInGeneric(*iter->second, false); 3804 } 3805 } 3806 3807 void InterfaceVisitor::ResolveNewSpecifics() { 3808 if (Symbol * generic{genericInfo_.top().symbol}; 3809 generic && generic->has<GenericDetails>()) { 3810 ResolveSpecificsInGeneric(*generic, false); 3811 } 3812 } 3813 3814 // Mixed interfaces are allowed by the standard. 3815 // If there is a derived type with the same name, they must all be functions. 3816 void InterfaceVisitor::CheckGenericProcedures(Symbol &generic) { 3817 ResolveSpecificsInGeneric(generic, true); 3818 auto &details{generic.get<GenericDetails>()}; 3819 if (auto *proc{details.CheckSpecific()}) { 3820 context().Warn(common::UsageWarning::HomonymousSpecific, 3821 proc->name().begin() > generic.name().begin() ? proc->name() 3822 : generic.name(), 3823 "'%s' should not be the name of both a generic interface and a procedure unless it is a specific procedure of the generic"_warn_en_US, 3824 generic.name()); 3825 } 3826 auto &specifics{details.specificProcs()}; 3827 if (specifics.empty()) { 3828 if (details.derivedType()) { 3829 generic.set(Symbol::Flag::Function); 3830 } 3831 return; 3832 } 3833 const Symbol *function{nullptr}; 3834 const Symbol *subroutine{nullptr}; 3835 for (const Symbol &specific : specifics) { 3836 if (!function && specific.test(Symbol::Flag::Function)) { 3837 function = &specific; 3838 } else if (!subroutine && specific.test(Symbol::Flag::Subroutine)) { 3839 subroutine = &specific; 3840 if (details.derivedType() && 3841 context().ShouldWarn( 3842 common::LanguageFeature::SubroutineAndFunctionSpecifics) && 3843 !InModuleFile()) { 3844 SayDerivedType(generic.name(), 3845 "Generic interface '%s' should only contain functions due to derived type with same name"_warn_en_US, 3846 *details.derivedType()->GetUltimate().scope()) 3847 .set_languageFeature( 3848 common::LanguageFeature::SubroutineAndFunctionSpecifics); 3849 } 3850 } 3851 if (function && subroutine) { // F'2023 C1514 3852 if (auto *msg{context().Warn( 3853 common::LanguageFeature::SubroutineAndFunctionSpecifics, 3854 generic.name(), 3855 "Generic interface '%s' has both a function and a subroutine"_warn_en_US, 3856 generic.name())}) { 3857 msg->Attach(function->name(), "Function declaration"_en_US) 3858 .Attach(subroutine->name(), "Subroutine declaration"_en_US); 3859 } 3860 break; 3861 } 3862 } 3863 if (function && !subroutine) { 3864 generic.set(Symbol::Flag::Function); 3865 } else if (subroutine && !function) { 3866 generic.set(Symbol::Flag::Subroutine); 3867 } 3868 } 3869 3870 // SubprogramVisitor implementation 3871 3872 // Return false if it is actually an assignment statement. 3873 bool SubprogramVisitor::HandleStmtFunction(const parser::StmtFunctionStmt &x) { 3874 const auto &name{std::get<parser::Name>(x.t)}; 3875 const DeclTypeSpec *resultType{nullptr}; 3876 // Look up name: provides return type or tells us if it's an array 3877 if (auto *symbol{FindSymbol(name)}) { 3878 Symbol &ultimate{symbol->GetUltimate()}; 3879 if (ultimate.has<ObjectEntityDetails>() || 3880 ultimate.has<AssocEntityDetails>() || 3881 CouldBeDataPointerValuedFunction(&ultimate) || 3882 (&symbol->owner() == &currScope() && IsFunctionResult(*symbol))) { 3883 misparsedStmtFuncFound_ = true; 3884 return false; 3885 } 3886 if (IsHostAssociated(*symbol, currScope())) { 3887 context().Warn(common::LanguageFeature::StatementFunctionExtensions, 3888 name.source, 3889 "Name '%s' from host scope should have a type declaration before its local statement function definition"_port_en_US, 3890 name.source); 3891 MakeSymbol(name, Attrs{}, UnknownDetails{}); 3892 } else if (auto *entity{ultimate.detailsIf<EntityDetails>()}; 3893 entity && !ultimate.has<ProcEntityDetails>()) { 3894 resultType = entity->type(); 3895 ultimate.details() = UnknownDetails{}; // will be replaced below 3896 } else { 3897 misparsedStmtFuncFound_ = true; 3898 } 3899 } 3900 if (misparsedStmtFuncFound_) { 3901 Say(name, 3902 "'%s' has not been declared as an array or pointer-valued function"_err_en_US); 3903 return false; 3904 } 3905 auto &symbol{PushSubprogramScope(name, Symbol::Flag::Function)}; 3906 symbol.set(Symbol::Flag::StmtFunction); 3907 EraseSymbol(symbol); // removes symbol added by PushSubprogramScope 3908 auto &details{symbol.get<SubprogramDetails>()}; 3909 for (const auto &dummyName : std::get<std::list<parser::Name>>(x.t)) { 3910 ObjectEntityDetails dummyDetails{true}; 3911 if (auto *dummySymbol{FindInScope(currScope().parent(), dummyName)}) { 3912 if (auto *d{dummySymbol->GetType()}) { 3913 dummyDetails.set_type(*d); 3914 } 3915 } 3916 Symbol &dummy{MakeSymbol(dummyName, std::move(dummyDetails))}; 3917 ApplyImplicitRules(dummy); 3918 details.add_dummyArg(dummy); 3919 } 3920 ObjectEntityDetails resultDetails; 3921 if (resultType) { 3922 resultDetails.set_type(*resultType); 3923 } 3924 resultDetails.set_funcResult(true); 3925 Symbol &result{MakeSymbol(name, std::move(resultDetails))}; 3926 result.flags().set(Symbol::Flag::StmtFunction); 3927 ApplyImplicitRules(result); 3928 details.set_result(result); 3929 // The analysis of the expression that constitutes the body of the 3930 // statement function is deferred to FinishSpecificationPart() so that 3931 // all declarations and implicit typing are complete. 3932 PopScope(); 3933 return true; 3934 } 3935 3936 bool SubprogramVisitor::Pre(const parser::Suffix &suffix) { 3937 if (suffix.resultName) { 3938 if (IsFunction(currScope())) { 3939 if (FuncResultStack::FuncInfo * info{funcResultStack().Top()}) { 3940 if (info->inFunctionStmt) { 3941 info->resultName = &suffix.resultName.value(); 3942 } else { 3943 // will check the result name in Post(EntryStmt) 3944 } 3945 } 3946 } else { 3947 Message &msg{Say(*suffix.resultName, 3948 "RESULT(%s) may appear only in a function"_err_en_US)}; 3949 if (const Symbol * subprogram{InclusiveScope().symbol()}) { 3950 msg.Attach(subprogram->name(), "Containing subprogram"_en_US); 3951 } 3952 } 3953 } 3954 // LanguageBindingSpec deferred to Post(EntryStmt) or, for FunctionStmt, 3955 // all the way to EndSubprogram(). 3956 return false; 3957 } 3958 3959 bool SubprogramVisitor::Pre(const parser::PrefixSpec &x) { 3960 // Save this to process after UseStmt and ImplicitPart 3961 if (const auto *parsedType{std::get_if<parser::DeclarationTypeSpec>(&x.u)}) { 3962 if (FuncResultStack::FuncInfo * info{funcResultStack().Top()}) { 3963 if (info->parsedType) { // C1543 3964 Say(currStmtSource().value_or(info->source), 3965 "FUNCTION prefix cannot specify the type more than once"_err_en_US); 3966 } else { 3967 info->parsedType = parsedType; 3968 if (auto at{currStmtSource()}) { 3969 info->source = *at; 3970 } 3971 } 3972 } else { 3973 Say(currStmtSource().value(), 3974 "SUBROUTINE prefix cannot specify a type"_err_en_US); 3975 } 3976 return false; 3977 } else { 3978 return true; 3979 } 3980 } 3981 3982 bool SubprogramVisitor::Pre(const parser::PrefixSpec::Attributes &attrs) { 3983 if (auto *subp{currScope().symbol() 3984 ? currScope().symbol()->detailsIf<SubprogramDetails>() 3985 : nullptr}) { 3986 for (auto attr : attrs.v) { 3987 if (auto current{subp->cudaSubprogramAttrs()}) { 3988 if (attr == *current || 3989 (*current == common::CUDASubprogramAttrs::HostDevice && 3990 (attr == common::CUDASubprogramAttrs::Host || 3991 attr == common::CUDASubprogramAttrs::Device))) { 3992 context().Warn(common::LanguageFeature::RedundantAttribute, 3993 currStmtSource().value(), 3994 "ATTRIBUTES(%s) appears more than once"_warn_en_US, 3995 common::EnumToString(attr)); 3996 } else if ((attr == common::CUDASubprogramAttrs::Host || 3997 attr == common::CUDASubprogramAttrs::Device) && 3998 (*current == common::CUDASubprogramAttrs::Host || 3999 *current == common::CUDASubprogramAttrs::Device || 4000 *current == common::CUDASubprogramAttrs::HostDevice)) { 4001 // HOST,DEVICE or DEVICE,HOST -> HostDevice 4002 subp->set_cudaSubprogramAttrs( 4003 common::CUDASubprogramAttrs::HostDevice); 4004 } else { 4005 Say(currStmtSource().value(), 4006 "ATTRIBUTES(%s) conflicts with earlier ATTRIBUTES(%s)"_err_en_US, 4007 common::EnumToString(attr), common::EnumToString(*current)); 4008 } 4009 } else { 4010 subp->set_cudaSubprogramAttrs(attr); 4011 } 4012 } 4013 if (auto attrs{subp->cudaSubprogramAttrs()}) { 4014 if (*attrs == common::CUDASubprogramAttrs::Global || 4015 *attrs == common::CUDASubprogramAttrs::Device) { 4016 const Scope &scope{currScope()}; 4017 const Scope *mod{FindModuleContaining(scope)}; 4018 if (mod && mod->GetName().value() == "cudadevice") { 4019 return false; 4020 } 4021 // Implicitly USE the cudadevice module by copying its symbols in the 4022 // current scope. 4023 const Scope &cudaDeviceScope{context().GetCUDADeviceScope()}; 4024 for (auto sym : cudaDeviceScope.GetSymbols()) { 4025 if (!currScope().FindSymbol(sym->name())) { 4026 auto &localSymbol{MakeSymbol( 4027 sym->name(), Attrs{}, UseDetails{sym->name(), *sym})}; 4028 localSymbol.flags() = sym->flags(); 4029 } 4030 } 4031 } 4032 } 4033 } 4034 return false; 4035 } 4036 4037 void SubprogramVisitor::Post(const parser::PrefixSpec::Launch_Bounds &x) { 4038 std::vector<std::int64_t> bounds; 4039 bool ok{true}; 4040 for (const auto &sicx : x.v) { 4041 if (auto value{evaluate::ToInt64(EvaluateExpr(sicx))}) { 4042 bounds.push_back(*value); 4043 } else { 4044 ok = false; 4045 } 4046 } 4047 if (!ok || bounds.size() < 2 || bounds.size() > 3) { 4048 Say(currStmtSource().value(), 4049 "Operands of LAUNCH_BOUNDS() must be 2 or 3 integer constants"_err_en_US); 4050 } else if (auto *subp{currScope().symbol() 4051 ? currScope().symbol()->detailsIf<SubprogramDetails>() 4052 : nullptr}) { 4053 if (subp->cudaLaunchBounds().empty()) { 4054 subp->set_cudaLaunchBounds(std::move(bounds)); 4055 } else { 4056 Say(currStmtSource().value(), 4057 "LAUNCH_BOUNDS() may only appear once"_err_en_US); 4058 } 4059 } 4060 } 4061 4062 void SubprogramVisitor::Post(const parser::PrefixSpec::Cluster_Dims &x) { 4063 std::vector<std::int64_t> dims; 4064 bool ok{true}; 4065 for (const auto &sicx : x.v) { 4066 if (auto value{evaluate::ToInt64(EvaluateExpr(sicx))}) { 4067 dims.push_back(*value); 4068 } else { 4069 ok = false; 4070 } 4071 } 4072 if (!ok || dims.size() != 3) { 4073 Say(currStmtSource().value(), 4074 "Operands of CLUSTER_DIMS() must be three integer constants"_err_en_US); 4075 } else if (auto *subp{currScope().symbol() 4076 ? currScope().symbol()->detailsIf<SubprogramDetails>() 4077 : nullptr}) { 4078 if (subp->cudaClusterDims().empty()) { 4079 subp->set_cudaClusterDims(std::move(dims)); 4080 } else { 4081 Say(currStmtSource().value(), 4082 "CLUSTER_DIMS() may only appear once"_err_en_US); 4083 } 4084 } 4085 } 4086 4087 static bool HasModulePrefix(const std::list<parser::PrefixSpec> &prefixes) { 4088 for (const auto &prefix : prefixes) { 4089 if (std::holds_alternative<parser::PrefixSpec::Module>(prefix.u)) { 4090 return true; 4091 } 4092 } 4093 return false; 4094 } 4095 4096 bool SubprogramVisitor::Pre(const parser::InterfaceBody::Subroutine &x) { 4097 const auto &stmtTuple{ 4098 std::get<parser::Statement<parser::SubroutineStmt>>(x.t).statement.t}; 4099 return BeginSubprogram(std::get<parser::Name>(stmtTuple), 4100 Symbol::Flag::Subroutine, 4101 HasModulePrefix(std::get<std::list<parser::PrefixSpec>>(stmtTuple))); 4102 } 4103 void SubprogramVisitor::Post(const parser::InterfaceBody::Subroutine &x) { 4104 const auto &stmt{std::get<parser::Statement<parser::SubroutineStmt>>(x.t)}; 4105 EndSubprogram(stmt.source, 4106 &std::get<std::optional<parser::LanguageBindingSpec>>(stmt.statement.t)); 4107 } 4108 bool SubprogramVisitor::Pre(const parser::InterfaceBody::Function &x) { 4109 const auto &stmtTuple{ 4110 std::get<parser::Statement<parser::FunctionStmt>>(x.t).statement.t}; 4111 return BeginSubprogram(std::get<parser::Name>(stmtTuple), 4112 Symbol::Flag::Function, 4113 HasModulePrefix(std::get<std::list<parser::PrefixSpec>>(stmtTuple))); 4114 } 4115 void SubprogramVisitor::Post(const parser::InterfaceBody::Function &x) { 4116 const auto &stmt{std::get<parser::Statement<parser::FunctionStmt>>(x.t)}; 4117 const auto &maybeSuffix{ 4118 std::get<std::optional<parser::Suffix>>(stmt.statement.t)}; 4119 EndSubprogram(stmt.source, maybeSuffix ? &maybeSuffix->binding : nullptr); 4120 } 4121 4122 bool SubprogramVisitor::Pre(const parser::SubroutineStmt &stmt) { 4123 BeginAttrs(); 4124 Walk(std::get<std::list<parser::PrefixSpec>>(stmt.t)); 4125 Walk(std::get<parser::Name>(stmt.t)); 4126 Walk(std::get<std::list<parser::DummyArg>>(stmt.t)); 4127 // Don't traverse the LanguageBindingSpec now; it's deferred to EndSubprogram. 4128 Symbol &symbol{PostSubprogramStmt()}; 4129 SubprogramDetails &details{symbol.get<SubprogramDetails>()}; 4130 for (const auto &dummyArg : std::get<std::list<parser::DummyArg>>(stmt.t)) { 4131 if (const auto *dummyName{std::get_if<parser::Name>(&dummyArg.u)}) { 4132 CreateDummyArgument(details, *dummyName); 4133 } else { 4134 details.add_alternateReturn(); 4135 } 4136 } 4137 return false; 4138 } 4139 bool SubprogramVisitor::Pre(const parser::FunctionStmt &) { 4140 FuncResultStack::FuncInfo &info{DEREF(funcResultStack().Top())}; 4141 CHECK(!info.inFunctionStmt); 4142 info.inFunctionStmt = true; 4143 if (auto at{currStmtSource()}) { 4144 info.source = *at; 4145 } 4146 return BeginAttrs(); 4147 } 4148 bool SubprogramVisitor::Pre(const parser::EntryStmt &) { return BeginAttrs(); } 4149 4150 void SubprogramVisitor::Post(const parser::FunctionStmt &stmt) { 4151 const auto &name{std::get<parser::Name>(stmt.t)}; 4152 Symbol &symbol{PostSubprogramStmt()}; 4153 SubprogramDetails &details{symbol.get<SubprogramDetails>()}; 4154 for (const auto &dummyName : std::get<std::list<parser::Name>>(stmt.t)) { 4155 CreateDummyArgument(details, dummyName); 4156 } 4157 const parser::Name *funcResultName; 4158 FuncResultStack::FuncInfo &info{DEREF(funcResultStack().Top())}; 4159 CHECK(info.inFunctionStmt); 4160 info.inFunctionStmt = false; 4161 bool distinctResultName{ 4162 info.resultName && info.resultName->source != name.source}; 4163 if (distinctResultName) { 4164 // Note that RESULT is ignored if it has the same name as the function. 4165 // The symbol created by PushScope() is retained as a place-holder 4166 // for error detection. 4167 funcResultName = info.resultName; 4168 } else { 4169 EraseSymbol(name); // was added by PushScope() 4170 funcResultName = &name; 4171 } 4172 if (details.isFunction()) { 4173 CHECK(context().HasError(currScope().symbol())); 4174 } else { 4175 // RESULT(x) can be the same explicitly-named RESULT(x) as an ENTRY 4176 // statement. 4177 Symbol *result{nullptr}; 4178 if (distinctResultName) { 4179 if (auto iter{currScope().find(funcResultName->source)}; 4180 iter != currScope().end()) { 4181 Symbol &entryResult{*iter->second}; 4182 if (IsFunctionResult(entryResult)) { 4183 result = &entryResult; 4184 } 4185 } 4186 } 4187 if (result) { 4188 Resolve(*funcResultName, *result); 4189 } else { 4190 // add function result to function scope 4191 EntityDetails funcResultDetails; 4192 funcResultDetails.set_funcResult(true); 4193 result = &MakeSymbol(*funcResultName, std::move(funcResultDetails)); 4194 } 4195 info.resultSymbol = result; 4196 details.set_result(*result); 4197 } 4198 // C1560. 4199 if (info.resultName && !distinctResultName) { 4200 context().Warn(common::UsageWarning::HomonymousResult, 4201 info.resultName->source, 4202 "The function name should not appear in RESULT; references to '%s' " 4203 "inside the function will be considered as references to the " 4204 "result only"_warn_en_US, 4205 name.source); 4206 // RESULT name was ignored above, the only side effect from doing so will be 4207 // the inability to make recursive calls. The related parser::Name is still 4208 // resolved to the created function result symbol because every parser::Name 4209 // should be resolved to avoid internal errors. 4210 Resolve(*info.resultName, info.resultSymbol); 4211 } 4212 name.symbol = &symbol; // must not be function result symbol 4213 // Clear the RESULT() name now in case an ENTRY statement in the implicit-part 4214 // has a RESULT() suffix. 4215 info.resultName = nullptr; 4216 } 4217 4218 Symbol &SubprogramVisitor::PostSubprogramStmt() { 4219 Symbol &symbol{*currScope().symbol()}; 4220 SetExplicitAttrs(symbol, EndAttrs()); 4221 if (symbol.attrs().test(Attr::MODULE)) { 4222 symbol.attrs().set(Attr::EXTERNAL, false); 4223 symbol.implicitAttrs().set(Attr::EXTERNAL, false); 4224 } 4225 return symbol; 4226 } 4227 4228 void SubprogramVisitor::Post(const parser::EntryStmt &stmt) { 4229 if (const auto &suffix{std::get<std::optional<parser::Suffix>>(stmt.t)}) { 4230 Walk(suffix->binding); 4231 } 4232 PostEntryStmt(stmt); 4233 EndAttrs(); 4234 } 4235 4236 void SubprogramVisitor::CreateDummyArgument( 4237 SubprogramDetails &details, const parser::Name &name) { 4238 Symbol *dummy{FindInScope(name)}; 4239 if (dummy) { 4240 if (IsDummy(*dummy)) { 4241 if (dummy->test(Symbol::Flag::EntryDummyArgument)) { 4242 dummy->set(Symbol::Flag::EntryDummyArgument, false); 4243 } else { 4244 Say(name, 4245 "'%s' appears more than once as a dummy argument name in this subprogram"_err_en_US, 4246 name.source); 4247 return; 4248 } 4249 } else { 4250 SayWithDecl(name, *dummy, 4251 "'%s' may not appear as a dummy argument name in this subprogram"_err_en_US); 4252 return; 4253 } 4254 } else { 4255 dummy = &MakeSymbol(name, EntityDetails{true}); 4256 } 4257 details.add_dummyArg(DEREF(dummy)); 4258 } 4259 4260 void SubprogramVisitor::CreateEntry( 4261 const parser::EntryStmt &stmt, Symbol &subprogram) { 4262 const auto &entryName{std::get<parser::Name>(stmt.t)}; 4263 Scope &outer{currScope().parent()}; 4264 Symbol::Flag subpFlag{subprogram.test(Symbol::Flag::Function) 4265 ? Symbol::Flag::Function 4266 : Symbol::Flag::Subroutine}; 4267 Attrs attrs; 4268 const auto &suffix{std::get<std::optional<parser::Suffix>>(stmt.t)}; 4269 bool hasGlobalBindingName{outer.IsGlobal() && suffix && suffix->binding && 4270 std::get<std::optional<parser::ScalarDefaultCharConstantExpr>>( 4271 suffix->binding->t) 4272 .has_value()}; 4273 if (!hasGlobalBindingName) { 4274 if (Symbol * extant{FindSymbol(outer, entryName)}) { 4275 if (!HandlePreviousCalls(entryName, *extant, subpFlag)) { 4276 if (outer.IsTopLevel()) { 4277 Say2(entryName, 4278 "'%s' is already defined as a global identifier"_err_en_US, 4279 *extant, "Previous definition of '%s'"_en_US); 4280 } else { 4281 SayAlreadyDeclared(entryName, *extant); 4282 } 4283 return; 4284 } 4285 attrs = extant->attrs(); 4286 } 4287 } 4288 std::optional<SourceName> distinctResultName; 4289 if (suffix && suffix->resultName && 4290 suffix->resultName->source != entryName.source) { 4291 distinctResultName = suffix->resultName->source; 4292 } 4293 if (outer.IsModule() && !attrs.test(Attr::PRIVATE)) { 4294 attrs.set(Attr::PUBLIC); 4295 } 4296 Symbol *entrySymbol{nullptr}; 4297 if (hasGlobalBindingName) { 4298 // Hide the entry's symbol in a new anonymous global scope so 4299 // that its name doesn't clash with anything. 4300 Symbol &symbol{MakeSymbol(outer, context().GetTempName(outer), Attrs{})}; 4301 symbol.set_details(MiscDetails{MiscDetails::Kind::ScopeName}); 4302 Scope &hidden{outer.MakeScope(Scope::Kind::Global, &symbol)}; 4303 entrySymbol = &MakeSymbol(hidden, entryName.source, attrs); 4304 } else { 4305 entrySymbol = FindInScope(outer, entryName.source); 4306 if (entrySymbol) { 4307 if (auto *generic{entrySymbol->detailsIf<GenericDetails>()}) { 4308 if (auto *specific{generic->specific()}) { 4309 // Forward reference to ENTRY from a generic interface 4310 entrySymbol = specific; 4311 CheckDuplicatedAttrs(entryName.source, *entrySymbol, attrs); 4312 SetExplicitAttrs(*entrySymbol, attrs); 4313 } 4314 } 4315 } else { 4316 entrySymbol = &MakeSymbol(outer, entryName.source, attrs); 4317 } 4318 } 4319 SubprogramDetails entryDetails; 4320 entryDetails.set_entryScope(currScope()); 4321 entrySymbol->set(subpFlag); 4322 if (subpFlag == Symbol::Flag::Function) { 4323 Symbol *result{nullptr}; 4324 EntityDetails resultDetails; 4325 resultDetails.set_funcResult(true); 4326 if (distinctResultName) { 4327 // An explicit RESULT() can also be an explicit RESULT() 4328 // of the function or another ENTRY. 4329 if (auto iter{currScope().find(suffix->resultName->source)}; 4330 iter != currScope().end()) { 4331 result = &*iter->second; 4332 } 4333 if (!result) { 4334 result = 4335 &MakeSymbol(*distinctResultName, Attrs{}, std::move(resultDetails)); 4336 } else if (!result->has<EntityDetails>()) { 4337 Say(*distinctResultName, 4338 "ENTRY cannot have RESULT(%s) that is not a variable"_err_en_US, 4339 *distinctResultName) 4340 .Attach(result->name(), "Existing declaration of '%s'"_en_US, 4341 result->name()); 4342 result = nullptr; 4343 } 4344 if (result) { 4345 Resolve(*suffix->resultName, *result); 4346 } 4347 } else { 4348 result = &MakeSymbol(entryName.source, Attrs{}, std::move(resultDetails)); 4349 } 4350 if (result) { 4351 entryDetails.set_result(*result); 4352 } 4353 } 4354 if (subpFlag == Symbol::Flag::Subroutine || distinctResultName) { 4355 Symbol &assoc{MakeSymbol(entryName.source)}; 4356 assoc.set_details(HostAssocDetails{*entrySymbol}); 4357 assoc.set(Symbol::Flag::Subroutine); 4358 } 4359 Resolve(entryName, *entrySymbol); 4360 std::set<SourceName> dummies; 4361 for (const auto &dummyArg : std::get<std::list<parser::DummyArg>>(stmt.t)) { 4362 if (const auto *dummyName{std::get_if<parser::Name>(&dummyArg.u)}) { 4363 auto pair{dummies.insert(dummyName->source)}; 4364 if (!pair.second) { 4365 Say(*dummyName, 4366 "'%s' appears more than once as a dummy argument name in this ENTRY statement"_err_en_US, 4367 dummyName->source); 4368 continue; 4369 } 4370 Symbol *dummy{FindInScope(*dummyName)}; 4371 if (dummy) { 4372 if (!IsDummy(*dummy)) { 4373 evaluate::AttachDeclaration( 4374 Say(*dummyName, 4375 "'%s' may not appear as a dummy argument name in this ENTRY statement"_err_en_US, 4376 dummyName->source), 4377 *dummy); 4378 continue; 4379 } 4380 } else { 4381 dummy = &MakeSymbol(*dummyName, EntityDetails{true}); 4382 dummy->set(Symbol::Flag::EntryDummyArgument); 4383 } 4384 entryDetails.add_dummyArg(DEREF(dummy)); 4385 } else if (subpFlag == Symbol::Flag::Function) { // C1573 4386 Say(entryName, 4387 "ENTRY in a function may not have an alternate return dummy argument"_err_en_US); 4388 break; 4389 } else { 4390 entryDetails.add_alternateReturn(); 4391 } 4392 } 4393 entrySymbol->set_details(std::move(entryDetails)); 4394 } 4395 4396 void SubprogramVisitor::PostEntryStmt(const parser::EntryStmt &stmt) { 4397 // The entry symbol should have already been created and resolved 4398 // in CreateEntry(), called by BeginSubprogram(), with one exception (below). 4399 const auto &name{std::get<parser::Name>(stmt.t)}; 4400 Scope &inclusiveScope{InclusiveScope()}; 4401 if (!name.symbol) { 4402 if (inclusiveScope.kind() != Scope::Kind::Subprogram) { 4403 Say(name.source, 4404 "ENTRY '%s' may appear only in a subroutine or function"_err_en_US, 4405 name.source); 4406 } else if (FindSeparateModuleSubprogramInterface(inclusiveScope.symbol())) { 4407 Say(name.source, 4408 "ENTRY '%s' may not appear in a separate module procedure"_err_en_US, 4409 name.source); 4410 } else { 4411 // C1571 - entry is nested, so was not put into the program tree; error 4412 // is emitted from MiscChecker in semantics.cpp. 4413 } 4414 return; 4415 } 4416 Symbol &entrySymbol{*name.symbol}; 4417 if (context().HasError(entrySymbol)) { 4418 return; 4419 } 4420 if (!entrySymbol.has<SubprogramDetails>()) { 4421 SayAlreadyDeclared(name, entrySymbol); 4422 return; 4423 } 4424 SubprogramDetails &entryDetails{entrySymbol.get<SubprogramDetails>()}; 4425 CHECK(entryDetails.entryScope() == &inclusiveScope); 4426 SetCUDADataAttr(name.source, entrySymbol, cudaDataAttr()); 4427 entrySymbol.attrs() |= GetAttrs(); 4428 SetBindNameOn(entrySymbol); 4429 for (const auto &dummyArg : std::get<std::list<parser::DummyArg>>(stmt.t)) { 4430 if (const auto *dummyName{std::get_if<parser::Name>(&dummyArg.u)}) { 4431 if (Symbol * dummy{FindInScope(*dummyName)}) { 4432 if (dummy->test(Symbol::Flag::EntryDummyArgument)) { 4433 const auto *subp{dummy->detailsIf<SubprogramDetails>()}; 4434 if (subp && subp->isInterface()) { // ok 4435 } else if (!dummy->has<EntityDetails>() && 4436 !dummy->has<ObjectEntityDetails>() && 4437 !dummy->has<ProcEntityDetails>()) { 4438 SayWithDecl(*dummyName, *dummy, 4439 "ENTRY dummy argument '%s' was previously declared as an item that may not be used as a dummy argument"_err_en_US); 4440 } 4441 dummy->set(Symbol::Flag::EntryDummyArgument, false); 4442 } 4443 } 4444 } 4445 } 4446 } 4447 4448 Symbol *ScopeHandler::FindSeparateModuleProcedureInterface( 4449 const parser::Name &name) { 4450 auto *symbol{FindSymbol(name)}; 4451 if (symbol && symbol->has<SubprogramNameDetails>()) { 4452 const Scope *parent{nullptr}; 4453 if (currScope().IsSubmodule()) { 4454 parent = currScope().symbol()->get<ModuleDetails>().parent(); 4455 } 4456 symbol = parent ? FindSymbol(*parent, name) : nullptr; 4457 } 4458 if (symbol) { 4459 if (auto *generic{symbol->detailsIf<GenericDetails>()}) { 4460 symbol = generic->specific(); 4461 } 4462 } 4463 if (const Symbol * defnIface{FindSeparateModuleSubprogramInterface(symbol)}) { 4464 // Error recovery in case of multiple definitions 4465 symbol = const_cast<Symbol *>(defnIface); 4466 } 4467 if (!IsSeparateModuleProcedureInterface(symbol)) { 4468 Say(name, "'%s' was not declared a separate module procedure"_err_en_US); 4469 symbol = nullptr; 4470 } 4471 return symbol; 4472 } 4473 4474 // A subprogram declared with MODULE PROCEDURE 4475 bool SubprogramVisitor::BeginMpSubprogram(const parser::Name &name) { 4476 Symbol *symbol{FindSeparateModuleProcedureInterface(name)}; 4477 if (!symbol) { 4478 return false; 4479 } 4480 if (symbol->owner() == currScope() && symbol->scope()) { 4481 // This is a MODULE PROCEDURE whose interface appears in its host. 4482 // Convert the module procedure's interface into a subprogram. 4483 SetScope(DEREF(symbol->scope())); 4484 symbol->get<SubprogramDetails>().set_isInterface(false); 4485 name.symbol = symbol; 4486 } else { 4487 // Copy the interface into a new subprogram scope. 4488 EraseSymbol(name); 4489 Symbol &newSymbol{MakeSymbol(name, SubprogramDetails{})}; 4490 PushScope(Scope::Kind::Subprogram, &newSymbol); 4491 auto &newSubprogram{newSymbol.get<SubprogramDetails>()}; 4492 newSubprogram.set_moduleInterface(*symbol); 4493 auto &subprogram{symbol->get<SubprogramDetails>()}; 4494 if (const auto *name{subprogram.bindName()}) { 4495 newSubprogram.set_bindName(std::string{*name}); 4496 } 4497 newSymbol.attrs() |= symbol->attrs(); 4498 newSymbol.set(symbol->test(Symbol::Flag::Subroutine) 4499 ? Symbol::Flag::Subroutine 4500 : Symbol::Flag::Function); 4501 MapSubprogramToNewSymbols(*symbol, newSymbol, currScope()); 4502 } 4503 return true; 4504 } 4505 4506 // A subprogram or interface declared with SUBROUTINE or FUNCTION 4507 bool SubprogramVisitor::BeginSubprogram(const parser::Name &name, 4508 Symbol::Flag subpFlag, bool hasModulePrefix, 4509 const parser::LanguageBindingSpec *bindingSpec, 4510 const ProgramTree::EntryStmtList *entryStmts) { 4511 bool isValid{true}; 4512 if (hasModulePrefix && !currScope().IsModule() && 4513 !currScope().IsSubmodule()) { // C1547 4514 Say(name, 4515 "'%s' is a MODULE procedure which must be declared within a " 4516 "MODULE or SUBMODULE"_err_en_US); 4517 // Don't return here because it can be useful to have the scope set for 4518 // other semantic checks run before we print the errors 4519 isValid = false; 4520 } 4521 Symbol *moduleInterface{nullptr}; 4522 if (isValid && hasModulePrefix && !inInterfaceBlock()) { 4523 moduleInterface = FindSeparateModuleProcedureInterface(name); 4524 if (moduleInterface && &moduleInterface->owner() == &currScope()) { 4525 // Subprogram is MODULE FUNCTION or MODULE SUBROUTINE with an interface 4526 // previously defined in the same scope. 4527 if (GenericDetails * 4528 generic{DEREF(FindSymbol(name)).detailsIf<GenericDetails>()}) { 4529 generic->clear_specific(); 4530 name.symbol = nullptr; 4531 } else { 4532 EraseSymbol(name); 4533 } 4534 } 4535 } 4536 Symbol &newSymbol{ 4537 PushSubprogramScope(name, subpFlag, bindingSpec, hasModulePrefix)}; 4538 if (moduleInterface) { 4539 newSymbol.get<SubprogramDetails>().set_moduleInterface(*moduleInterface); 4540 if (moduleInterface->attrs().test(Attr::PRIVATE)) { 4541 SetImplicitAttr(newSymbol, Attr::PRIVATE); 4542 } else if (moduleInterface->attrs().test(Attr::PUBLIC)) { 4543 SetImplicitAttr(newSymbol, Attr::PUBLIC); 4544 } 4545 } 4546 if (entryStmts) { 4547 for (const auto &ref : *entryStmts) { 4548 CreateEntry(*ref, newSymbol); 4549 } 4550 } 4551 return true; 4552 } 4553 4554 void SubprogramVisitor::HandleLanguageBinding(Symbol *symbol, 4555 std::optional<parser::CharBlock> stmtSource, 4556 const std::optional<parser::LanguageBindingSpec> *binding) { 4557 if (binding && *binding && symbol) { 4558 // Finally process the BIND(C,NAME=name) now that symbols in the name 4559 // expression will resolve to local names if needed. 4560 auto flagRestorer{common::ScopedSet(inSpecificationPart_, false)}; 4561 auto originalStmtSource{messageHandler().currStmtSource()}; 4562 messageHandler().set_currStmtSource(stmtSource); 4563 BeginAttrs(); 4564 Walk(**binding); 4565 SetBindNameOn(*symbol); 4566 symbol->attrs() |= EndAttrs(); 4567 messageHandler().set_currStmtSource(originalStmtSource); 4568 } 4569 } 4570 4571 void SubprogramVisitor::EndSubprogram( 4572 std::optional<parser::CharBlock> stmtSource, 4573 const std::optional<parser::LanguageBindingSpec> *binding, 4574 const ProgramTree::EntryStmtList *entryStmts) { 4575 HandleLanguageBinding(currScope().symbol(), stmtSource, binding); 4576 if (entryStmts) { 4577 for (const auto &ref : *entryStmts) { 4578 const parser::EntryStmt &entryStmt{*ref}; 4579 if (const auto &suffix{ 4580 std::get<std::optional<parser::Suffix>>(entryStmt.t)}) { 4581 const auto &name{std::get<parser::Name>(entryStmt.t)}; 4582 HandleLanguageBinding(name.symbol, name.source, &suffix->binding); 4583 } 4584 } 4585 } 4586 if (inInterfaceBlock() && currScope().symbol()) { 4587 DeclaredPossibleSpecificProc(*currScope().symbol()); 4588 } 4589 PopScope(); 4590 } 4591 4592 bool SubprogramVisitor::HandlePreviousCalls( 4593 const parser::Name &name, Symbol &symbol, Symbol::Flag subpFlag) { 4594 // If the extant symbol is a generic, check its homonymous specific 4595 // procedure instead if it has one. 4596 if (auto *generic{symbol.detailsIf<GenericDetails>()}) { 4597 return generic->specific() && 4598 HandlePreviousCalls(name, *generic->specific(), subpFlag); 4599 } else if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}; proc && 4600 !proc->isDummy() && 4601 !symbol.attrs().HasAny(Attrs{Attr::INTRINSIC, Attr::POINTER})) { 4602 // There's a symbol created for previous calls to this subprogram or 4603 // ENTRY's name. We have to replace that symbol in situ to avoid the 4604 // obligation to rewrite symbol pointers in the parse tree. 4605 if (!symbol.test(subpFlag)) { 4606 auto other{subpFlag == Symbol::Flag::Subroutine 4607 ? Symbol::Flag::Function 4608 : Symbol::Flag::Subroutine}; 4609 // External statements issue an explicit EXTERNAL attribute. 4610 if (symbol.attrs().test(Attr::EXTERNAL) && 4611 !symbol.implicitAttrs().test(Attr::EXTERNAL)) { 4612 // Warn if external statement previously declared. 4613 context().Warn(common::LanguageFeature::RedundantAttribute, name.source, 4614 "EXTERNAL attribute was already specified on '%s'"_warn_en_US, 4615 name.source); 4616 } else if (symbol.test(other)) { 4617 Say2(name, 4618 subpFlag == Symbol::Flag::Function 4619 ? "'%s' was previously called as a subroutine"_err_en_US 4620 : "'%s' was previously called as a function"_err_en_US, 4621 symbol, "Previous call of '%s'"_en_US); 4622 } else { 4623 symbol.set(subpFlag); 4624 } 4625 } 4626 EntityDetails entity; 4627 if (proc->type()) { 4628 entity.set_type(*proc->type()); 4629 } 4630 symbol.details() = std::move(entity); 4631 return true; 4632 } else { 4633 return symbol.has<UnknownDetails>() || symbol.has<SubprogramNameDetails>(); 4634 } 4635 } 4636 4637 void SubprogramVisitor::CheckExtantProc( 4638 const parser::Name &name, Symbol::Flag subpFlag) { 4639 if (auto *prev{FindSymbol(name)}) { 4640 if (IsDummy(*prev)) { 4641 } else if (auto *entity{prev->detailsIf<EntityDetails>()}; 4642 IsPointer(*prev) && entity && !entity->type()) { 4643 // POINTER attribute set before interface 4644 } else if (inInterfaceBlock() && currScope() != prev->owner()) { 4645 // Procedures in an INTERFACE block do not resolve to symbols 4646 // in scopes between the global scope and the current scope. 4647 } else if (!HandlePreviousCalls(name, *prev, subpFlag)) { 4648 SayAlreadyDeclared(name, *prev); 4649 } 4650 } 4651 } 4652 4653 Symbol &SubprogramVisitor::PushSubprogramScope(const parser::Name &name, 4654 Symbol::Flag subpFlag, const parser::LanguageBindingSpec *bindingSpec, 4655 bool hasModulePrefix) { 4656 Symbol *symbol{GetSpecificFromGeneric(name)}; 4657 if (!symbol) { 4658 if (bindingSpec && currScope().IsGlobal() && 4659 std::get<std::optional<parser::ScalarDefaultCharConstantExpr>>( 4660 bindingSpec->t) 4661 .has_value()) { 4662 // Create this new top-level subprogram with a binding label 4663 // in a new global scope, so that its symbol's name won't clash 4664 // with another symbol that has a distinct binding label. 4665 PushScope(Scope::Kind::Global, 4666 &MakeSymbol(context().GetTempName(currScope()), Attrs{}, 4667 MiscDetails{MiscDetails::Kind::ScopeName})); 4668 } 4669 CheckExtantProc(name, subpFlag); 4670 symbol = &MakeSymbol(name, SubprogramDetails{}); 4671 } 4672 symbol->ReplaceName(name.source); 4673 symbol->set(subpFlag); 4674 PushScope(Scope::Kind::Subprogram, symbol); 4675 if (subpFlag == Symbol::Flag::Function) { 4676 funcResultStack().Push(currScope(), name.source); 4677 } 4678 if (inInterfaceBlock()) { 4679 auto &details{symbol->get<SubprogramDetails>()}; 4680 details.set_isInterface(); 4681 if (isAbstract()) { 4682 SetExplicitAttr(*symbol, Attr::ABSTRACT); 4683 } else if (hasModulePrefix) { 4684 SetExplicitAttr(*symbol, Attr::MODULE); 4685 } else { 4686 MakeExternal(*symbol); 4687 } 4688 if (isGeneric()) { 4689 Symbol &genericSymbol{GetGenericSymbol()}; 4690 if (auto *details{genericSymbol.detailsIf<GenericDetails>()}) { 4691 details->AddSpecificProc(*symbol, name.source); 4692 } else { 4693 CHECK(context().HasError(genericSymbol)); 4694 } 4695 } 4696 set_inheritFromParent(false); // interfaces don't inherit, even if MODULE 4697 } 4698 if (Symbol * found{FindSymbol(name)}; 4699 found && found->has<HostAssocDetails>()) { 4700 found->set(subpFlag); // PushScope() created symbol 4701 } 4702 return *symbol; 4703 } 4704 4705 void SubprogramVisitor::PushBlockDataScope(const parser::Name &name) { 4706 if (auto *prev{FindSymbol(name)}) { 4707 if (prev->attrs().test(Attr::EXTERNAL) && prev->has<ProcEntityDetails>()) { 4708 if (prev->test(Symbol::Flag::Subroutine) || 4709 prev->test(Symbol::Flag::Function)) { 4710 Say2(name, "BLOCK DATA '%s' has been called"_err_en_US, *prev, 4711 "Previous call of '%s'"_en_US); 4712 } 4713 EraseSymbol(name); 4714 } 4715 } 4716 if (name.source.empty()) { 4717 // Don't let unnamed BLOCK DATA conflict with unnamed PROGRAM 4718 PushScope(Scope::Kind::BlockData, nullptr); 4719 } else { 4720 PushScope(Scope::Kind::BlockData, &MakeSymbol(name, SubprogramDetails{})); 4721 } 4722 } 4723 4724 // If name is a generic, return specific subprogram with the same name. 4725 Symbol *SubprogramVisitor::GetSpecificFromGeneric(const parser::Name &name) { 4726 // Search for the name but don't resolve it 4727 if (auto *symbol{currScope().FindSymbol(name.source)}) { 4728 if (symbol->has<SubprogramNameDetails>()) { 4729 if (inInterfaceBlock()) { 4730 // Subtle: clear any MODULE flag so that the new interface 4731 // symbol doesn't inherit it and ruin the ability to check it. 4732 symbol->attrs().reset(Attr::MODULE); 4733 } 4734 } else if (auto *details{symbol->detailsIf<GenericDetails>()}) { 4735 // found generic, want specific procedure 4736 auto *specific{details->specific()}; 4737 Attrs moduleAttr; 4738 if (inInterfaceBlock()) { 4739 if (specific) { 4740 // Defining an interface in a generic of the same name which is 4741 // already shadowing another procedure. In some cases, the shadowed 4742 // procedure is about to be replaced. 4743 if (specific->has<SubprogramNameDetails>() && 4744 specific->attrs().test(Attr::MODULE)) { 4745 // The shadowed procedure is a separate module procedure that is 4746 // actually defined later in this (sub)module. 4747 // Define its interface now as a new symbol. 4748 moduleAttr.set(Attr::MODULE); 4749 specific = nullptr; 4750 } else if (&specific->owner() != &symbol->owner()) { 4751 // The shadowed procedure was from an enclosing scope and will be 4752 // overridden by this interface definition. 4753 specific = nullptr; 4754 } 4755 if (!specific) { 4756 details->clear_specific(); 4757 } 4758 } else if (const auto *dType{details->derivedType()}) { 4759 if (&dType->owner() != &symbol->owner()) { 4760 // The shadowed derived type was from an enclosing scope and 4761 // will be overridden by this interface definition. 4762 details->clear_derivedType(); 4763 } 4764 } 4765 } 4766 if (!specific) { 4767 specific = &currScope().MakeSymbol( 4768 name.source, std::move(moduleAttr), SubprogramDetails{}); 4769 if (details->derivedType()) { 4770 // A specific procedure with the same name as a derived type 4771 SayAlreadyDeclared(name, *details->derivedType()); 4772 } else { 4773 details->set_specific(Resolve(name, *specific)); 4774 } 4775 } else if (isGeneric()) { 4776 SayAlreadyDeclared(name, *specific); 4777 } 4778 if (specific->has<SubprogramNameDetails>()) { 4779 specific->set_details(Details{SubprogramDetails{}}); 4780 } 4781 return specific; 4782 } 4783 } 4784 return nullptr; 4785 } 4786 4787 // DeclarationVisitor implementation 4788 4789 bool DeclarationVisitor::BeginDecl() { 4790 BeginDeclTypeSpec(); 4791 BeginArraySpec(); 4792 return BeginAttrs(); 4793 } 4794 void DeclarationVisitor::EndDecl() { 4795 EndDeclTypeSpec(); 4796 EndArraySpec(); 4797 EndAttrs(); 4798 } 4799 4800 bool DeclarationVisitor::CheckUseError(const parser::Name &name) { 4801 return HadUseError(context(), name.source, name.symbol); 4802 } 4803 4804 // Report error if accessibility of symbol doesn't match isPrivate. 4805 void DeclarationVisitor::CheckAccessibility( 4806 const SourceName &name, bool isPrivate, Symbol &symbol) { 4807 if (symbol.attrs().test(Attr::PRIVATE) != isPrivate) { 4808 Say2(name, 4809 "'%s' does not have the same accessibility as its previous declaration"_err_en_US, 4810 symbol, "Previous declaration of '%s'"_en_US); 4811 } 4812 } 4813 4814 bool DeclarationVisitor::Pre(const parser::TypeDeclarationStmt &x) { 4815 BeginDecl(); 4816 // If INTRINSIC appears as an attr-spec, handle it now as if the 4817 // names had appeared on an INTRINSIC attribute statement beforehand. 4818 for (const auto &attr : std::get<std::list<parser::AttrSpec>>(x.t)) { 4819 if (std::holds_alternative<parser::Intrinsic>(attr.u)) { 4820 for (const auto &decl : std::get<std::list<parser::EntityDecl>>(x.t)) { 4821 DeclareIntrinsic(parser::GetFirstName(decl)); 4822 } 4823 break; 4824 } 4825 } 4826 return true; 4827 } 4828 void DeclarationVisitor::Post(const parser::TypeDeclarationStmt &) { 4829 EndDecl(); 4830 } 4831 4832 void DeclarationVisitor::Post(const parser::DimensionStmt::Declaration &x) { 4833 DeclareObjectEntity(std::get<parser::Name>(x.t)); 4834 } 4835 void DeclarationVisitor::Post(const parser::CodimensionDecl &x) { 4836 DeclareObjectEntity(std::get<parser::Name>(x.t)); 4837 } 4838 4839 bool DeclarationVisitor::Pre(const parser::Initialization &) { 4840 // Defer inspection of initializers to Initialization() so that the 4841 // symbol being initialized will be available within the initialization 4842 // expression. 4843 return false; 4844 } 4845 4846 void DeclarationVisitor::Post(const parser::EntityDecl &x) { 4847 const auto &name{std::get<parser::ObjectName>(x.t)}; 4848 Attrs attrs{attrs_ ? HandleSaveName(name.source, *attrs_) : Attrs{}}; 4849 attrs.set(Attr::INTRINSIC, false); // dealt with in Pre(TypeDeclarationStmt) 4850 Symbol &symbol{DeclareUnknownEntity(name, attrs)}; 4851 symbol.ReplaceName(name.source); 4852 SetCUDADataAttr(name.source, symbol, cudaDataAttr()); 4853 if (const auto &init{std::get<std::optional<parser::Initialization>>(x.t)}) { 4854 ConvertToObjectEntity(symbol) || ConvertToProcEntity(symbol); 4855 symbol.set( 4856 Symbol::Flag::EntryDummyArgument, false); // forestall excessive errors 4857 Initialization(name, *init, false); 4858 } else if (attrs.test(Attr::PARAMETER)) { // C882, C883 4859 Say(name, "Missing initialization for parameter '%s'"_err_en_US); 4860 } 4861 if (auto *scopeSymbol{currScope().symbol()}) { 4862 if (auto *details{scopeSymbol->detailsIf<DerivedTypeDetails>()}) { 4863 if (details->isDECStructure()) { 4864 details->add_component(symbol); 4865 } 4866 } 4867 } 4868 } 4869 4870 void DeclarationVisitor::Post(const parser::PointerDecl &x) { 4871 const auto &name{std::get<parser::Name>(x.t)}; 4872 if (const auto &deferredShapeSpecs{ 4873 std::get<std::optional<parser::DeferredShapeSpecList>>(x.t)}) { 4874 CHECK(arraySpec().empty()); 4875 BeginArraySpec(); 4876 set_arraySpec(AnalyzeDeferredShapeSpecList(context(), *deferredShapeSpecs)); 4877 Symbol &symbol{DeclareObjectEntity(name, Attrs{Attr::POINTER})}; 4878 symbol.ReplaceName(name.source); 4879 EndArraySpec(); 4880 } else { 4881 if (const auto *symbol{FindInScope(name)}) { 4882 const auto *subp{symbol->detailsIf<SubprogramDetails>()}; 4883 if (!symbol->has<UseDetails>() && // error caught elsewhere 4884 !symbol->has<ObjectEntityDetails>() && 4885 !symbol->has<ProcEntityDetails>() && 4886 !symbol->CanReplaceDetails(ObjectEntityDetails{}) && 4887 !symbol->CanReplaceDetails(ProcEntityDetails{}) && 4888 !(subp && subp->isInterface())) { 4889 Say(name, "'%s' cannot have the POINTER attribute"_err_en_US); 4890 } 4891 } 4892 HandleAttributeStmt(Attr::POINTER, std::get<parser::Name>(x.t)); 4893 } 4894 } 4895 4896 bool DeclarationVisitor::Pre(const parser::BindEntity &x) { 4897 auto kind{std::get<parser::BindEntity::Kind>(x.t)}; 4898 auto &name{std::get<parser::Name>(x.t)}; 4899 Symbol *symbol; 4900 if (kind == parser::BindEntity::Kind::Object) { 4901 symbol = &HandleAttributeStmt(Attr::BIND_C, name); 4902 } else { 4903 symbol = &MakeCommonBlockSymbol(name); 4904 SetExplicitAttr(*symbol, Attr::BIND_C); 4905 } 4906 // 8.6.4(1) 4907 // Some entities such as named constant or module name need to checked 4908 // elsewhere. This is to skip the ICE caused by setting Bind name for non-name 4909 // things such as data type and also checks for procedures. 4910 if (symbol->has<CommonBlockDetails>() || symbol->has<ObjectEntityDetails>() || 4911 symbol->has<EntityDetails>()) { 4912 SetBindNameOn(*symbol); 4913 } else { 4914 Say(name, 4915 "Only variable and named common block can be in BIND statement"_err_en_US); 4916 } 4917 return false; 4918 } 4919 bool DeclarationVisitor::Pre(const parser::OldParameterStmt &x) { 4920 inOldStyleParameterStmt_ = true; 4921 Walk(x.v); 4922 inOldStyleParameterStmt_ = false; 4923 return false; 4924 } 4925 bool DeclarationVisitor::Pre(const parser::NamedConstantDef &x) { 4926 auto &name{std::get<parser::NamedConstant>(x.t).v}; 4927 auto &symbol{HandleAttributeStmt(Attr::PARAMETER, name)}; 4928 ConvertToObjectEntity(symbol); 4929 auto *details{symbol.detailsIf<ObjectEntityDetails>()}; 4930 if (!details || symbol.test(Symbol::Flag::CrayPointer) || 4931 symbol.test(Symbol::Flag::CrayPointee)) { 4932 SayWithDecl( 4933 name, symbol, "PARAMETER attribute not allowed on '%s'"_err_en_US); 4934 return false; 4935 } 4936 const auto &expr{std::get<parser::ConstantExpr>(x.t)}; 4937 if (details->init() || symbol.test(Symbol::Flag::InDataStmt)) { 4938 Say(name, "Named constant '%s' already has a value"_err_en_US); 4939 } 4940 if (inOldStyleParameterStmt_) { 4941 // non-standard extension PARAMETER statement (no parentheses) 4942 Walk(expr); 4943 auto folded{EvaluateExpr(expr)}; 4944 if (details->type()) { 4945 SayWithDecl(name, symbol, 4946 "Alternative style PARAMETER '%s' must not already have an explicit type"_err_en_US); 4947 } else if (folded) { 4948 auto at{expr.thing.value().source}; 4949 if (evaluate::IsActuallyConstant(*folded)) { 4950 if (const auto *type{currScope().GetType(*folded)}) { 4951 if (type->IsPolymorphic()) { 4952 Say(at, "The expression must not be polymorphic"_err_en_US); 4953 } else if (auto shape{ToArraySpec( 4954 GetFoldingContext(), evaluate::GetShape(*folded))}) { 4955 // The type of the named constant is assumed from the expression. 4956 details->set_type(*type); 4957 details->set_init(std::move(*folded)); 4958 details->set_shape(std::move(*shape)); 4959 } else { 4960 Say(at, "The expression must have constant shape"_err_en_US); 4961 } 4962 } else { 4963 Say(at, "The expression must have a known type"_err_en_US); 4964 } 4965 } else { 4966 Say(at, "The expression must be a constant of known type"_err_en_US); 4967 } 4968 } 4969 } else { 4970 // standard-conforming PARAMETER statement (with parentheses) 4971 ApplyImplicitRules(symbol); 4972 Walk(expr); 4973 if (auto converted{EvaluateNonPointerInitializer( 4974 symbol, expr, expr.thing.value().source)}) { 4975 details->set_init(std::move(*converted)); 4976 } 4977 } 4978 return false; 4979 } 4980 bool DeclarationVisitor::Pre(const parser::NamedConstant &x) { 4981 const parser::Name &name{x.v}; 4982 if (!FindSymbol(name)) { 4983 Say(name, "Named constant '%s' not found"_err_en_US); 4984 } else { 4985 CheckUseError(name); 4986 } 4987 return false; 4988 } 4989 4990 bool DeclarationVisitor::Pre(const parser::Enumerator &enumerator) { 4991 const parser::Name &name{std::get<parser::NamedConstant>(enumerator.t).v}; 4992 Symbol *symbol{FindInScope(name)}; 4993 if (symbol && !symbol->has<UnknownDetails>()) { 4994 // Contrary to named constants appearing in a PARAMETER statement, 4995 // enumerator names should not have their type, dimension or any other 4996 // attributes defined before they are declared in the enumerator statement, 4997 // with the exception of accessibility. 4998 // This is not explicitly forbidden by the standard, but they are scalars 4999 // which type is left for the compiler to chose, so do not let users try to 5000 // tamper with that. 5001 SayAlreadyDeclared(name, *symbol); 5002 symbol = nullptr; 5003 } else { 5004 // Enumerators are treated as PARAMETER (section 7.6 paragraph (4)) 5005 symbol = &MakeSymbol(name, Attrs{Attr::PARAMETER}, ObjectEntityDetails{}); 5006 symbol->SetType(context().MakeNumericType( 5007 TypeCategory::Integer, evaluate::CInteger::kind)); 5008 } 5009 5010 if (auto &init{std::get<std::optional<parser::ScalarIntConstantExpr>>( 5011 enumerator.t)}) { 5012 Walk(*init); // Resolve names in expression before evaluation. 5013 if (auto value{EvaluateInt64(context(), *init)}) { 5014 // Cast all init expressions to C_INT so that they can then be 5015 // safely incremented (see 7.6 Note 2). 5016 enumerationState_.value = static_cast<int>(*value); 5017 } else { 5018 Say(name, 5019 "Enumerator value could not be computed " 5020 "from the given expression"_err_en_US); 5021 // Prevent resolution of next enumerators value 5022 enumerationState_.value = std::nullopt; 5023 } 5024 } 5025 5026 if (symbol) { 5027 if (enumerationState_.value) { 5028 symbol->get<ObjectEntityDetails>().set_init(SomeExpr{ 5029 evaluate::Expr<evaluate::CInteger>{*enumerationState_.value}}); 5030 } else { 5031 context().SetError(*symbol); 5032 } 5033 } 5034 5035 if (enumerationState_.value) { 5036 (*enumerationState_.value)++; 5037 } 5038 return false; 5039 } 5040 5041 void DeclarationVisitor::Post(const parser::EnumDef &) { 5042 enumerationState_ = EnumeratorState{}; 5043 } 5044 5045 bool DeclarationVisitor::Pre(const parser::AccessSpec &x) { 5046 Attr attr{AccessSpecToAttr(x)}; 5047 if (!NonDerivedTypeScope().IsModule()) { // C817 5048 Say(currStmtSource().value(), 5049 "%s attribute may only appear in the specification part of a module"_err_en_US, 5050 EnumToString(attr)); 5051 } 5052 CheckAndSet(attr); 5053 return false; 5054 } 5055 5056 bool DeclarationVisitor::Pre(const parser::AsynchronousStmt &x) { 5057 return HandleAttributeStmt(Attr::ASYNCHRONOUS, x.v); 5058 } 5059 bool DeclarationVisitor::Pre(const parser::ContiguousStmt &x) { 5060 return HandleAttributeStmt(Attr::CONTIGUOUS, x.v); 5061 } 5062 bool DeclarationVisitor::Pre(const parser::ExternalStmt &x) { 5063 HandleAttributeStmt(Attr::EXTERNAL, x.v); 5064 for (const auto &name : x.v) { 5065 auto *symbol{FindSymbol(name)}; 5066 if (!ConvertToProcEntity(DEREF(symbol), name.source)) { 5067 // Check if previous symbol is an interface. 5068 if (auto *details{symbol->detailsIf<SubprogramDetails>()}) { 5069 if (details->isInterface()) { 5070 // Warn if interface previously declared. 5071 context().Warn(common::LanguageFeature::RedundantAttribute, 5072 name.source, 5073 "EXTERNAL attribute was already specified on '%s'"_warn_en_US, 5074 name.source); 5075 } 5076 } else { 5077 SayWithDecl( 5078 name, *symbol, "EXTERNAL attribute not allowed on '%s'"_err_en_US); 5079 } 5080 } else if (symbol->attrs().test(Attr::INTRINSIC)) { // C840 5081 Say(symbol->name(), 5082 "Symbol '%s' cannot have both INTRINSIC and EXTERNAL attributes"_err_en_US, 5083 symbol->name()); 5084 } 5085 } 5086 return false; 5087 } 5088 bool DeclarationVisitor::Pre(const parser::IntentStmt &x) { 5089 auto &intentSpec{std::get<parser::IntentSpec>(x.t)}; 5090 auto &names{std::get<std::list<parser::Name>>(x.t)}; 5091 return CheckNotInBlock("INTENT") && // C1107 5092 HandleAttributeStmt(IntentSpecToAttr(intentSpec), names); 5093 } 5094 bool DeclarationVisitor::Pre(const parser::IntrinsicStmt &x) { 5095 for (const auto &name : x.v) { 5096 DeclareIntrinsic(name); 5097 } 5098 return false; 5099 } 5100 void DeclarationVisitor::DeclareIntrinsic(const parser::Name &name) { 5101 HandleAttributeStmt(Attr::INTRINSIC, name); 5102 if (!IsIntrinsic(name.source, std::nullopt)) { 5103 Say(name.source, "'%s' is not a known intrinsic procedure"_err_en_US); 5104 } 5105 auto &symbol{DEREF(FindSymbol(name))}; 5106 if (symbol.has<GenericDetails>()) { 5107 // Generic interface is extending intrinsic; ok 5108 } else if (!ConvertToProcEntity(symbol, name.source)) { 5109 SayWithDecl( 5110 name, symbol, "INTRINSIC attribute not allowed on '%s'"_err_en_US); 5111 } else if (symbol.attrs().test(Attr::EXTERNAL)) { // C840 5112 Say(symbol.name(), 5113 "Symbol '%s' cannot have both EXTERNAL and INTRINSIC attributes"_err_en_US, 5114 symbol.name()); 5115 } else { 5116 if (symbol.GetType()) { 5117 // These warnings are worded so that they should make sense in either 5118 // order. 5119 if (auto *msg{context().Warn( 5120 common::UsageWarning::IgnoredIntrinsicFunctionType, symbol.name(), 5121 "Explicit type declaration ignored for intrinsic function '%s'"_warn_en_US, 5122 symbol.name())}) { 5123 msg->Attach(name.source, 5124 "INTRINSIC statement for explicitly-typed '%s'"_en_US, name.source); 5125 } 5126 } 5127 if (!symbol.test(Symbol::Flag::Function) && 5128 !symbol.test(Symbol::Flag::Subroutine)) { 5129 if (context().intrinsics().IsIntrinsicFunction(name.source.ToString())) { 5130 symbol.set(Symbol::Flag::Function); 5131 } else if (context().intrinsics().IsIntrinsicSubroutine( 5132 name.source.ToString())) { 5133 symbol.set(Symbol::Flag::Subroutine); 5134 } 5135 } 5136 } 5137 } 5138 bool DeclarationVisitor::Pre(const parser::OptionalStmt &x) { 5139 return CheckNotInBlock("OPTIONAL") && // C1107 5140 HandleAttributeStmt(Attr::OPTIONAL, x.v); 5141 } 5142 bool DeclarationVisitor::Pre(const parser::ProtectedStmt &x) { 5143 return HandleAttributeStmt(Attr::PROTECTED, x.v); 5144 } 5145 bool DeclarationVisitor::Pre(const parser::ValueStmt &x) { 5146 return CheckNotInBlock("VALUE") && // C1107 5147 HandleAttributeStmt(Attr::VALUE, x.v); 5148 } 5149 bool DeclarationVisitor::Pre(const parser::VolatileStmt &x) { 5150 return HandleAttributeStmt(Attr::VOLATILE, x.v); 5151 } 5152 bool DeclarationVisitor::Pre(const parser::CUDAAttributesStmt &x) { 5153 auto attr{std::get<common::CUDADataAttr>(x.t)}; 5154 for (const auto &name : std::get<std::list<parser::Name>>(x.t)) { 5155 auto *symbol{FindInScope(name)}; 5156 if (symbol && symbol->has<UseDetails>()) { 5157 Say(currStmtSource().value(), 5158 "Cannot apply CUDA data attribute to use-associated '%s'"_err_en_US, 5159 name.source); 5160 } else { 5161 if (!symbol) { 5162 symbol = &MakeSymbol(name, ObjectEntityDetails{}); 5163 } 5164 SetCUDADataAttr(name.source, *symbol, attr); 5165 } 5166 } 5167 return false; 5168 } 5169 // Handle a statement that sets an attribute on a list of names. 5170 bool DeclarationVisitor::HandleAttributeStmt( 5171 Attr attr, const std::list<parser::Name> &names) { 5172 for (const auto &name : names) { 5173 HandleAttributeStmt(attr, name); 5174 } 5175 return false; 5176 } 5177 Symbol &DeclarationVisitor::HandleAttributeStmt( 5178 Attr attr, const parser::Name &name) { 5179 auto *symbol{FindInScope(name)}; 5180 if (attr == Attr::ASYNCHRONOUS || attr == Attr::VOLATILE) { 5181 // these can be set on a symbol that is host-assoc or use-assoc 5182 if (!symbol && 5183 (currScope().kind() == Scope::Kind::Subprogram || 5184 currScope().kind() == Scope::Kind::BlockConstruct)) { 5185 if (auto *hostSymbol{FindSymbol(name)}) { 5186 symbol = &MakeHostAssocSymbol(name, *hostSymbol); 5187 } 5188 } 5189 } else if (symbol && symbol->has<UseDetails>()) { 5190 if (symbol->GetUltimate().attrs().test(attr)) { 5191 context().Warn(common::LanguageFeature::RedundantAttribute, 5192 currStmtSource().value(), 5193 "Use-associated '%s' already has '%s' attribute"_warn_en_US, 5194 name.source, EnumToString(attr)); 5195 } else { 5196 Say(currStmtSource().value(), 5197 "Cannot change %s attribute on use-associated '%s'"_err_en_US, 5198 EnumToString(attr), name.source); 5199 } 5200 return *symbol; 5201 } 5202 if (!symbol) { 5203 symbol = &MakeSymbol(name, EntityDetails{}); 5204 } 5205 if (CheckDuplicatedAttr(name.source, *symbol, attr)) { 5206 HandleSaveName(name.source, Attrs{attr}); 5207 SetExplicitAttr(*symbol, attr); 5208 } 5209 return *symbol; 5210 } 5211 // C1107 5212 bool DeclarationVisitor::CheckNotInBlock(const char *stmt) { 5213 if (currScope().kind() == Scope::Kind::BlockConstruct) { 5214 Say(MessageFormattedText{ 5215 "%s statement is not allowed in a BLOCK construct"_err_en_US, stmt}); 5216 return false; 5217 } else { 5218 return true; 5219 } 5220 } 5221 5222 void DeclarationVisitor::Post(const parser::ObjectDecl &x) { 5223 CHECK(objectDeclAttr_); 5224 const auto &name{std::get<parser::ObjectName>(x.t)}; 5225 DeclareObjectEntity(name, Attrs{*objectDeclAttr_}); 5226 } 5227 5228 // Declare an entity not yet known to be an object or proc. 5229 Symbol &DeclarationVisitor::DeclareUnknownEntity( 5230 const parser::Name &name, Attrs attrs) { 5231 if (!arraySpec().empty() || !coarraySpec().empty()) { 5232 return DeclareObjectEntity(name, attrs); 5233 } else { 5234 Symbol &symbol{DeclareEntity<EntityDetails>(name, attrs)}; 5235 if (auto *type{GetDeclTypeSpec()}) { 5236 SetType(name, *type); 5237 } 5238 charInfo_.length.reset(); 5239 if (symbol.attrs().test(Attr::EXTERNAL)) { 5240 ConvertToProcEntity(symbol); 5241 } else if (symbol.attrs().HasAny(Attrs{Attr::ALLOCATABLE, 5242 Attr::ASYNCHRONOUS, Attr::CONTIGUOUS, Attr::PARAMETER, 5243 Attr::SAVE, Attr::TARGET, Attr::VALUE, Attr::VOLATILE})) { 5244 ConvertToObjectEntity(symbol); 5245 } 5246 if (attrs.test(Attr::BIND_C)) { 5247 SetBindNameOn(symbol); 5248 } 5249 return symbol; 5250 } 5251 } 5252 5253 bool DeclarationVisitor::HasCycle( 5254 const Symbol &procSymbol, const Symbol *interface) { 5255 SourceOrderedSymbolSet procsInCycle; 5256 procsInCycle.insert(procSymbol); 5257 while (interface) { 5258 if (procsInCycle.count(*interface) > 0) { 5259 for (const auto &procInCycle : procsInCycle) { 5260 Say(procInCycle->name(), 5261 "The interface for procedure '%s' is recursively defined"_err_en_US, 5262 procInCycle->name()); 5263 context().SetError(*procInCycle); 5264 } 5265 return true; 5266 } else if (const auto *procDetails{ 5267 interface->detailsIf<ProcEntityDetails>()}) { 5268 procsInCycle.insert(*interface); 5269 interface = procDetails->procInterface(); 5270 } else { 5271 break; 5272 } 5273 } 5274 return false; 5275 } 5276 5277 Symbol &DeclarationVisitor::DeclareProcEntity( 5278 const parser::Name &name, Attrs attrs, const Symbol *interface) { 5279 Symbol *proc{nullptr}; 5280 if (auto *extant{FindInScope(name)}) { 5281 if (auto *d{extant->detailsIf<GenericDetails>()}; d && !d->derivedType()) { 5282 // procedure pointer with same name as a generic 5283 if (auto *specific{d->specific()}) { 5284 SayAlreadyDeclared(name, *specific); 5285 } else { 5286 // Create the ProcEntityDetails symbol in the scope as the "specific()" 5287 // symbol behind an existing GenericDetails symbol of the same name. 5288 proc = &Resolve(name, 5289 currScope().MakeSymbol(name.source, attrs, ProcEntityDetails{})); 5290 d->set_specific(*proc); 5291 } 5292 } 5293 } 5294 Symbol &symbol{proc ? *proc : DeclareEntity<ProcEntityDetails>(name, attrs)}; 5295 if (auto *details{symbol.detailsIf<ProcEntityDetails>()}) { 5296 if (context().HasError(symbol)) { 5297 } else if (HasCycle(symbol, interface)) { 5298 return symbol; 5299 } else if (interface && (details->procInterface() || details->type())) { 5300 SayWithDecl(name, symbol, 5301 "The interface for procedure '%s' has already been declared"_err_en_US); 5302 context().SetError(symbol); 5303 } else if (interface) { 5304 details->set_procInterfaces( 5305 *interface, BypassGeneric(interface->GetUltimate())); 5306 if (interface->test(Symbol::Flag::Function)) { 5307 symbol.set(Symbol::Flag::Function); 5308 } else if (interface->test(Symbol::Flag::Subroutine)) { 5309 symbol.set(Symbol::Flag::Subroutine); 5310 } 5311 } else if (auto *type{GetDeclTypeSpec()}) { 5312 SetType(name, *type); 5313 symbol.set(Symbol::Flag::Function); 5314 } 5315 SetBindNameOn(symbol); 5316 SetPassNameOn(symbol); 5317 } 5318 return symbol; 5319 } 5320 5321 Symbol &DeclarationVisitor::DeclareObjectEntity( 5322 const parser::Name &name, Attrs attrs) { 5323 Symbol &symbol{DeclareEntity<ObjectEntityDetails>(name, attrs)}; 5324 if (auto *details{symbol.detailsIf<ObjectEntityDetails>()}) { 5325 if (auto *type{GetDeclTypeSpec()}) { 5326 SetType(name, *type); 5327 } 5328 if (!arraySpec().empty()) { 5329 if (details->IsArray()) { 5330 if (!context().HasError(symbol)) { 5331 Say(name, 5332 "The dimensions of '%s' have already been declared"_err_en_US); 5333 context().SetError(symbol); 5334 } 5335 } else if (MustBeScalar(symbol)) { 5336 context().Warn(common::UsageWarning::PreviousScalarUse, name.source, 5337 "'%s' appeared earlier as a scalar actual argument to a specification function"_warn_en_US, 5338 name.source); 5339 } else if (details->init() || symbol.test(Symbol::Flag::InDataStmt)) { 5340 Say(name, "'%s' was initialized earlier as a scalar"_err_en_US); 5341 } else { 5342 details->set_shape(arraySpec()); 5343 } 5344 } 5345 if (!coarraySpec().empty()) { 5346 if (details->IsCoarray()) { 5347 if (!context().HasError(symbol)) { 5348 Say(name, 5349 "The codimensions of '%s' have already been declared"_err_en_US); 5350 context().SetError(symbol); 5351 } 5352 } else { 5353 details->set_coshape(coarraySpec()); 5354 } 5355 } 5356 SetBindNameOn(symbol); 5357 } 5358 ClearArraySpec(); 5359 ClearCoarraySpec(); 5360 charInfo_.length.reset(); 5361 return symbol; 5362 } 5363 5364 void DeclarationVisitor::Post(const parser::IntegerTypeSpec &x) { 5365 if (!isVectorType_) { 5366 SetDeclTypeSpec(MakeNumericType(TypeCategory::Integer, x.v)); 5367 } 5368 } 5369 void DeclarationVisitor::Post(const parser::UnsignedTypeSpec &x) { 5370 if (!isVectorType_) { 5371 if (!context().IsEnabled(common::LanguageFeature::Unsigned) && 5372 !context().AnyFatalError()) { 5373 context().Say("-funsigned is required to enable UNSIGNED type"_err_en_US); 5374 } 5375 SetDeclTypeSpec(MakeNumericType(TypeCategory::Unsigned, x.v)); 5376 } 5377 } 5378 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Real &x) { 5379 if (!isVectorType_) { 5380 SetDeclTypeSpec(MakeNumericType(TypeCategory::Real, x.kind)); 5381 } 5382 } 5383 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Complex &x) { 5384 SetDeclTypeSpec(MakeNumericType(TypeCategory::Complex, x.kind)); 5385 } 5386 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Logical &x) { 5387 SetDeclTypeSpec(MakeLogicalType(x.kind)); 5388 } 5389 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Character &) { 5390 if (!charInfo_.length) { 5391 charInfo_.length = ParamValue{1, common::TypeParamAttr::Len}; 5392 } 5393 if (!charInfo_.kind) { 5394 charInfo_.kind = 5395 KindExpr{context().GetDefaultKind(TypeCategory::Character)}; 5396 } 5397 SetDeclTypeSpec(currScope().MakeCharacterType( 5398 std::move(*charInfo_.length), std::move(*charInfo_.kind))); 5399 charInfo_ = {}; 5400 } 5401 void DeclarationVisitor::Post(const parser::CharSelector::LengthAndKind &x) { 5402 charInfo_.kind = EvaluateSubscriptIntExpr(x.kind); 5403 std::optional<std::int64_t> intKind{ToInt64(charInfo_.kind)}; 5404 if (intKind && 5405 !context().targetCharacteristics().IsTypeEnabled( 5406 TypeCategory::Character, *intKind)) { // C715, C719 5407 Say(currStmtSource().value(), 5408 "KIND value (%jd) not valid for CHARACTER"_err_en_US, *intKind); 5409 charInfo_.kind = std::nullopt; // prevent further errors 5410 } 5411 if (x.length) { 5412 charInfo_.length = GetParamValue(*x.length, common::TypeParamAttr::Len); 5413 } 5414 } 5415 void DeclarationVisitor::Post(const parser::CharLength &x) { 5416 if (const auto *length{std::get_if<std::uint64_t>(&x.u)}) { 5417 charInfo_.length = ParamValue{ 5418 static_cast<ConstantSubscript>(*length), common::TypeParamAttr::Len}; 5419 } else { 5420 charInfo_.length = GetParamValue( 5421 std::get<parser::TypeParamValue>(x.u), common::TypeParamAttr::Len); 5422 } 5423 } 5424 void DeclarationVisitor::Post(const parser::LengthSelector &x) { 5425 if (const auto *param{std::get_if<parser::TypeParamValue>(&x.u)}) { 5426 charInfo_.length = GetParamValue(*param, common::TypeParamAttr::Len); 5427 } 5428 } 5429 5430 bool DeclarationVisitor::Pre(const parser::KindParam &x) { 5431 if (const auto *kind{std::get_if< 5432 parser::Scalar<parser::Integer<parser::Constant<parser::Name>>>>( 5433 &x.u)}) { 5434 const parser::Name &name{kind->thing.thing.thing}; 5435 if (!FindSymbol(name)) { 5436 Say(name, "Parameter '%s' not found"_err_en_US); 5437 } 5438 } 5439 return false; 5440 } 5441 5442 int DeclarationVisitor::GetVectorElementKind( 5443 TypeCategory category, const std::optional<parser::KindSelector> &kind) { 5444 KindExpr value{GetKindParamExpr(category, kind)}; 5445 if (auto known{evaluate::ToInt64(value)}) { 5446 return static_cast<int>(*known); 5447 } 5448 common::die("Vector element kind must be known at compile-time"); 5449 } 5450 5451 bool DeclarationVisitor::Pre(const parser::VectorTypeSpec &) { 5452 // PowerPC vector types are allowed only on Power architectures. 5453 if (!currScope().context().targetCharacteristics().isPPC()) { 5454 Say(currStmtSource().value(), 5455 "Vector type is only supported for PowerPC"_err_en_US); 5456 isVectorType_ = false; 5457 return false; 5458 } 5459 isVectorType_ = true; 5460 return true; 5461 } 5462 // Create semantic::DerivedTypeSpec for Vector types here. 5463 void DeclarationVisitor::Post(const parser::VectorTypeSpec &x) { 5464 llvm::StringRef typeName; 5465 llvm::SmallVector<ParamValue> typeParams; 5466 DerivedTypeSpec::Category vectorCategory; 5467 5468 isVectorType_ = false; 5469 common::visit( 5470 common::visitors{ 5471 [&](const parser::IntrinsicVectorTypeSpec &y) { 5472 vectorCategory = DerivedTypeSpec::Category::IntrinsicVector; 5473 int vecElemKind = 0; 5474 typeName = "__builtin_ppc_intrinsic_vector"; 5475 common::visit( 5476 common::visitors{ 5477 [&](const parser::IntegerTypeSpec &z) { 5478 vecElemKind = GetVectorElementKind( 5479 TypeCategory::Integer, std::move(z.v)); 5480 typeParams.push_back(ParamValue( 5481 static_cast<common::ConstantSubscript>( 5482 common::VectorElementCategory::Integer), 5483 common::TypeParamAttr::Kind)); 5484 }, 5485 [&](const parser::IntrinsicTypeSpec::Real &z) { 5486 vecElemKind = GetVectorElementKind( 5487 TypeCategory::Real, std::move(z.kind)); 5488 typeParams.push_back( 5489 ParamValue(static_cast<common::ConstantSubscript>( 5490 common::VectorElementCategory::Real), 5491 common::TypeParamAttr::Kind)); 5492 }, 5493 [&](const parser::UnsignedTypeSpec &z) { 5494 vecElemKind = GetVectorElementKind( 5495 TypeCategory::Integer, std::move(z.v)); 5496 typeParams.push_back(ParamValue( 5497 static_cast<common::ConstantSubscript>( 5498 common::VectorElementCategory::Unsigned), 5499 common::TypeParamAttr::Kind)); 5500 }, 5501 }, 5502 y.v.u); 5503 typeParams.push_back( 5504 ParamValue(static_cast<common::ConstantSubscript>(vecElemKind), 5505 common::TypeParamAttr::Kind)); 5506 }, 5507 [&](const parser::VectorTypeSpec::PairVectorTypeSpec &y) { 5508 vectorCategory = DerivedTypeSpec::Category::PairVector; 5509 typeName = "__builtin_ppc_pair_vector"; 5510 }, 5511 [&](const parser::VectorTypeSpec::QuadVectorTypeSpec &y) { 5512 vectorCategory = DerivedTypeSpec::Category::QuadVector; 5513 typeName = "__builtin_ppc_quad_vector"; 5514 }, 5515 }, 5516 x.u); 5517 5518 auto ppcBuiltinTypesScope = currScope().context().GetPPCBuiltinTypesScope(); 5519 if (!ppcBuiltinTypesScope) { 5520 common::die("INTERNAL: The __ppc_types module was not found "); 5521 } 5522 5523 auto iter{ppcBuiltinTypesScope->find( 5524 semantics::SourceName{typeName.data(), typeName.size()})}; 5525 if (iter == ppcBuiltinTypesScope->cend()) { 5526 common::die("INTERNAL: The __ppc_types module does not define " 5527 "the type '%s'", 5528 typeName.data()); 5529 } 5530 5531 const semantics::Symbol &typeSymbol{*iter->second}; 5532 DerivedTypeSpec vectorDerivedType{typeName.data(), typeSymbol}; 5533 vectorDerivedType.set_category(vectorCategory); 5534 if (typeParams.size()) { 5535 vectorDerivedType.AddRawParamValue(nullptr, std::move(typeParams[0])); 5536 vectorDerivedType.AddRawParamValue(nullptr, std::move(typeParams[1])); 5537 vectorDerivedType.CookParameters(GetFoldingContext()); 5538 } 5539 5540 if (const DeclTypeSpec * 5541 extant{ppcBuiltinTypesScope->FindInstantiatedDerivedType( 5542 vectorDerivedType, DeclTypeSpec::Category::TypeDerived)}) { 5543 // This derived type and parameter expressions (if any) are already present 5544 // in the __ppc_intrinsics scope. 5545 SetDeclTypeSpec(*extant); 5546 } else { 5547 DeclTypeSpec &type{ppcBuiltinTypesScope->MakeDerivedType( 5548 DeclTypeSpec::Category::TypeDerived, std::move(vectorDerivedType))}; 5549 DerivedTypeSpec &derived{type.derivedTypeSpec()}; 5550 auto restorer{ 5551 GetFoldingContext().messages().SetLocation(currStmtSource().value())}; 5552 derived.Instantiate(*ppcBuiltinTypesScope); 5553 SetDeclTypeSpec(type); 5554 } 5555 } 5556 5557 bool DeclarationVisitor::Pre(const parser::DeclarationTypeSpec::Type &) { 5558 CHECK(GetDeclTypeSpecCategory() == DeclTypeSpec::Category::TypeDerived); 5559 return true; 5560 } 5561 5562 void DeclarationVisitor::Post(const parser::DeclarationTypeSpec::Type &type) { 5563 const parser::Name &derivedName{std::get<parser::Name>(type.derived.t)}; 5564 if (const Symbol * derivedSymbol{derivedName.symbol}) { 5565 CheckForAbstractType(*derivedSymbol); // C706 5566 } 5567 } 5568 5569 bool DeclarationVisitor::Pre(const parser::DeclarationTypeSpec::Class &) { 5570 SetDeclTypeSpecCategory(DeclTypeSpec::Category::ClassDerived); 5571 return true; 5572 } 5573 5574 void DeclarationVisitor::Post( 5575 const parser::DeclarationTypeSpec::Class &parsedClass) { 5576 const auto &typeName{std::get<parser::Name>(parsedClass.derived.t)}; 5577 if (auto spec{ResolveDerivedType(typeName)}; 5578 spec && !IsExtensibleType(&*spec)) { // C705 5579 SayWithDecl(typeName, *typeName.symbol, 5580 "Non-extensible derived type '%s' may not be used with CLASS" 5581 " keyword"_err_en_US); 5582 } 5583 } 5584 5585 void DeclarationVisitor::Post(const parser::DerivedTypeSpec &x) { 5586 const auto &typeName{std::get<parser::Name>(x.t)}; 5587 auto spec{ResolveDerivedType(typeName)}; 5588 if (!spec) { 5589 return; 5590 } 5591 bool seenAnyName{false}; 5592 for (const auto &typeParamSpec : 5593 std::get<std::list<parser::TypeParamSpec>>(x.t)) { 5594 const auto &optKeyword{ 5595 std::get<std::optional<parser::Keyword>>(typeParamSpec.t)}; 5596 std::optional<SourceName> name; 5597 if (optKeyword) { 5598 seenAnyName = true; 5599 name = optKeyword->v.source; 5600 } else if (seenAnyName) { 5601 Say(typeName.source, "Type parameter value must have a name"_err_en_US); 5602 continue; 5603 } 5604 const auto &value{std::get<parser::TypeParamValue>(typeParamSpec.t)}; 5605 // The expressions in a derived type specifier whose values define 5606 // non-defaulted type parameters are evaluated (folded) in the enclosing 5607 // scope. The KIND/LEN distinction is resolved later in 5608 // DerivedTypeSpec::CookParameters(). 5609 ParamValue param{GetParamValue(value, common::TypeParamAttr::Kind)}; 5610 if (!param.isExplicit() || param.GetExplicit()) { 5611 spec->AddRawParamValue( 5612 common::GetPtrFromOptional(optKeyword), std::move(param)); 5613 } 5614 } 5615 // The DerivedTypeSpec *spec is used initially as a search key. 5616 // If it turns out to have the same name and actual parameter 5617 // value expressions as another DerivedTypeSpec in the current 5618 // scope does, then we'll use that extant spec; otherwise, when this 5619 // spec is distinct from all derived types previously instantiated 5620 // in the current scope, this spec will be moved into that collection. 5621 const auto &dtDetails{spec->typeSymbol().get<DerivedTypeDetails>()}; 5622 auto category{GetDeclTypeSpecCategory()}; 5623 if (dtDetails.isForwardReferenced()) { 5624 DeclTypeSpec &type{currScope().MakeDerivedType(category, std::move(*spec))}; 5625 SetDeclTypeSpec(type); 5626 return; 5627 } 5628 // Normalize parameters to produce a better search key. 5629 spec->CookParameters(GetFoldingContext()); 5630 if (!spec->MightBeParameterized()) { 5631 spec->EvaluateParameters(context()); 5632 } 5633 if (const DeclTypeSpec * 5634 extant{currScope().FindInstantiatedDerivedType(*spec, category)}) { 5635 // This derived type and parameter expressions (if any) are already present 5636 // in this scope. 5637 SetDeclTypeSpec(*extant); 5638 } else { 5639 DeclTypeSpec &type{currScope().MakeDerivedType(category, std::move(*spec))}; 5640 DerivedTypeSpec &derived{type.derivedTypeSpec()}; 5641 if (derived.MightBeParameterized() && 5642 currScope().IsParameterizedDerivedType()) { 5643 // Defer instantiation; use the derived type's definition's scope. 5644 derived.set_scope(DEREF(spec->typeSymbol().scope())); 5645 } else if (&currScope() == spec->typeSymbol().scope()) { 5646 // Direct recursive use of a type in the definition of one of its 5647 // components: defer instantiation 5648 } else { 5649 auto restorer{ 5650 GetFoldingContext().messages().SetLocation(currStmtSource().value())}; 5651 derived.Instantiate(currScope()); 5652 } 5653 SetDeclTypeSpec(type); 5654 } 5655 // Capture the DerivedTypeSpec in the parse tree for use in building 5656 // structure constructor expressions. 5657 x.derivedTypeSpec = &GetDeclTypeSpec()->derivedTypeSpec(); 5658 } 5659 5660 void DeclarationVisitor::Post(const parser::DeclarationTypeSpec::Record &rec) { 5661 const auto &typeName{rec.v}; 5662 if (auto spec{ResolveDerivedType(typeName)}) { 5663 spec->CookParameters(GetFoldingContext()); 5664 spec->EvaluateParameters(context()); 5665 if (const DeclTypeSpec * 5666 extant{currScope().FindInstantiatedDerivedType( 5667 *spec, DeclTypeSpec::TypeDerived)}) { 5668 SetDeclTypeSpec(*extant); 5669 } else { 5670 Say(typeName.source, "%s is not a known STRUCTURE"_err_en_US, 5671 typeName.source); 5672 } 5673 } 5674 } 5675 5676 // The descendents of DerivedTypeDef in the parse tree are visited directly 5677 // in this Pre() routine so that recursive use of the derived type can be 5678 // supported in the components. 5679 bool DeclarationVisitor::Pre(const parser::DerivedTypeDef &x) { 5680 auto &stmt{std::get<parser::Statement<parser::DerivedTypeStmt>>(x.t)}; 5681 Walk(stmt); 5682 Walk(std::get<std::list<parser::Statement<parser::TypeParamDefStmt>>>(x.t)); 5683 auto &scope{currScope()}; 5684 CHECK(scope.symbol()); 5685 CHECK(scope.symbol()->scope() == &scope); 5686 auto &details{scope.symbol()->get<DerivedTypeDetails>()}; 5687 for (auto ¶mName : std::get<std::list<parser::Name>>(stmt.statement.t)) { 5688 if (auto *symbol{FindInScope(scope, paramName)}) { 5689 if (auto *details{symbol->detailsIf<TypeParamDetails>()}) { 5690 if (!details->attr()) { 5691 Say(paramName, 5692 "No definition found for type parameter '%s'"_err_en_US); // C742 5693 } 5694 } 5695 } 5696 } 5697 Walk(std::get<std::list<parser::Statement<parser::PrivateOrSequence>>>(x.t)); 5698 const auto &componentDefs{ 5699 std::get<std::list<parser::Statement<parser::ComponentDefStmt>>>(x.t)}; 5700 Walk(componentDefs); 5701 if (derivedTypeInfo_.sequence) { 5702 details.set_sequence(true); 5703 if (componentDefs.empty()) { 5704 // F'2023 C745 - not enforced by any compiler 5705 context().Warn(common::LanguageFeature::EmptySequenceType, stmt.source, 5706 "A sequence type should have at least one component"_warn_en_US); 5707 } 5708 if (!details.paramDeclOrder().empty()) { // C740 5709 Say(stmt.source, 5710 "A sequence type may not have type parameters"_err_en_US); 5711 } 5712 if (derivedTypeInfo_.extends) { // C735 5713 Say(stmt.source, 5714 "A sequence type may not have the EXTENDS attribute"_err_en_US); 5715 } 5716 } 5717 Walk(std::get<std::optional<parser::TypeBoundProcedurePart>>(x.t)); 5718 Walk(std::get<parser::Statement<parser::EndTypeStmt>>(x.t)); 5719 details.set_isForwardReferenced(false); 5720 derivedTypeInfo_ = {}; 5721 PopScope(); 5722 return false; 5723 } 5724 5725 bool DeclarationVisitor::Pre(const parser::DerivedTypeStmt &) { 5726 return BeginAttrs(); 5727 } 5728 void DeclarationVisitor::Post(const parser::DerivedTypeStmt &x) { 5729 auto &name{std::get<parser::Name>(x.t)}; 5730 // Resolve the EXTENDS() clause before creating the derived 5731 // type's symbol to foil attempts to recursively extend a type. 5732 auto *extendsName{derivedTypeInfo_.extends}; 5733 std::optional<DerivedTypeSpec> extendsType{ 5734 ResolveExtendsType(name, extendsName)}; 5735 DerivedTypeDetails derivedTypeDetails; 5736 // Catch any premature structure constructors within the definition 5737 derivedTypeDetails.set_isForwardReferenced(true); 5738 auto &symbol{MakeSymbol(name, GetAttrs(), std::move(derivedTypeDetails))}; 5739 symbol.ReplaceName(name.source); 5740 derivedTypeInfo_.type = &symbol; 5741 PushScope(Scope::Kind::DerivedType, &symbol); 5742 if (extendsType) { 5743 // Declare the "parent component"; private if the type is. 5744 // Any symbol stored in the EXTENDS() clause is temporarily 5745 // hidden so that a new symbol can be created for the parent 5746 // component without producing spurious errors about already 5747 // existing. 5748 const Symbol &extendsSymbol{extendsType->typeSymbol()}; 5749 auto restorer{common::ScopedSet(extendsName->symbol, nullptr)}; 5750 if (OkToAddComponent(*extendsName, &extendsSymbol)) { 5751 auto &comp{DeclareEntity<ObjectEntityDetails>(*extendsName, Attrs{})}; 5752 comp.attrs().set( 5753 Attr::PRIVATE, extendsSymbol.attrs().test(Attr::PRIVATE)); 5754 comp.implicitAttrs().set( 5755 Attr::PRIVATE, extendsSymbol.implicitAttrs().test(Attr::PRIVATE)); 5756 comp.set(Symbol::Flag::ParentComp); 5757 DeclTypeSpec &type{currScope().MakeDerivedType( 5758 DeclTypeSpec::TypeDerived, std::move(*extendsType))}; 5759 type.derivedTypeSpec().set_scope(DEREF(extendsSymbol.scope())); 5760 comp.SetType(type); 5761 DerivedTypeDetails &details{symbol.get<DerivedTypeDetails>()}; 5762 details.add_component(comp); 5763 } 5764 } 5765 // Create symbols now for type parameters so that they shadow names 5766 // from the enclosing specification part. 5767 if (auto *details{symbol.detailsIf<DerivedTypeDetails>()}) { 5768 for (const auto &name : std::get<std::list<parser::Name>>(x.t)) { 5769 if (Symbol * symbol{MakeTypeSymbol(name, TypeParamDetails{})}) { 5770 details->add_paramNameOrder(*symbol); 5771 } 5772 } 5773 } 5774 EndAttrs(); 5775 } 5776 5777 void DeclarationVisitor::Post(const parser::TypeParamDefStmt &x) { 5778 auto *type{GetDeclTypeSpec()}; 5779 DerivedTypeDetails *derivedDetails{nullptr}; 5780 if (Symbol * dtSym{currScope().symbol()}) { 5781 derivedDetails = dtSym->detailsIf<DerivedTypeDetails>(); 5782 } 5783 auto attr{std::get<common::TypeParamAttr>(x.t)}; 5784 for (auto &decl : std::get<std::list<parser::TypeParamDecl>>(x.t)) { 5785 auto &name{std::get<parser::Name>(decl.t)}; 5786 if (Symbol * symbol{FindInScope(currScope(), name)}) { 5787 if (auto *paramDetails{symbol->detailsIf<TypeParamDetails>()}) { 5788 if (!paramDetails->attr()) { 5789 paramDetails->set_attr(attr); 5790 SetType(name, *type); 5791 if (auto &init{std::get<std::optional<parser::ScalarIntConstantExpr>>( 5792 decl.t)}) { 5793 if (auto maybeExpr{AnalyzeExpr(context(), *init)}) { 5794 if (auto *intExpr{std::get_if<SomeIntExpr>(&maybeExpr->u)}) { 5795 paramDetails->set_init(std::move(*intExpr)); 5796 } 5797 } 5798 } 5799 if (derivedDetails) { 5800 derivedDetails->add_paramDeclOrder(*symbol); 5801 } 5802 } else { 5803 Say(name, 5804 "Type parameter '%s' was already declared in this derived type"_err_en_US); 5805 } 5806 } 5807 } else { 5808 Say(name, "'%s' is not a parameter of this derived type"_err_en_US); 5809 } 5810 } 5811 EndDecl(); 5812 } 5813 bool DeclarationVisitor::Pre(const parser::TypeAttrSpec::Extends &x) { 5814 if (derivedTypeInfo_.extends) { 5815 Say(currStmtSource().value(), 5816 "Attribute 'EXTENDS' cannot be used more than once"_err_en_US); 5817 } else { 5818 derivedTypeInfo_.extends = &x.v; 5819 } 5820 return false; 5821 } 5822 5823 bool DeclarationVisitor::Pre(const parser::PrivateStmt &) { 5824 if (!currScope().parent().IsModule()) { 5825 Say("PRIVATE is only allowed in a derived type that is" 5826 " in a module"_err_en_US); // C766 5827 } else if (derivedTypeInfo_.sawContains) { 5828 derivedTypeInfo_.privateBindings = true; 5829 } else if (!derivedTypeInfo_.privateComps) { 5830 derivedTypeInfo_.privateComps = true; 5831 } else { // C738 5832 context().Warn(common::LanguageFeature::RedundantAttribute, 5833 "PRIVATE should not appear more than once in derived type components"_warn_en_US); 5834 } 5835 return false; 5836 } 5837 bool DeclarationVisitor::Pre(const parser::SequenceStmt &) { 5838 if (derivedTypeInfo_.sequence) { // C738 5839 context().Warn(common::LanguageFeature::RedundantAttribute, 5840 "SEQUENCE should not appear more than once in derived type components"_warn_en_US); 5841 } 5842 derivedTypeInfo_.sequence = true; 5843 return false; 5844 } 5845 void DeclarationVisitor::Post(const parser::ComponentDecl &x) { 5846 const auto &name{std::get<parser::Name>(x.t)}; 5847 auto attrs{GetAttrs()}; 5848 if (derivedTypeInfo_.privateComps && 5849 !attrs.HasAny({Attr::PUBLIC, Attr::PRIVATE})) { 5850 attrs.set(Attr::PRIVATE); 5851 } 5852 if (const auto *declType{GetDeclTypeSpec()}) { 5853 if (const auto *derived{declType->AsDerived()}) { 5854 if (!attrs.HasAny({Attr::POINTER, Attr::ALLOCATABLE})) { 5855 if (derivedTypeInfo_.type == &derived->typeSymbol()) { // C744 5856 Say("Recursive use of the derived type requires " 5857 "POINTER or ALLOCATABLE"_err_en_US); 5858 } 5859 } 5860 // TODO: This would be more appropriate in CheckDerivedType() 5861 if (auto it{FindCoarrayUltimateComponent(*derived)}) { // C748 5862 std::string ultimateName{it.BuildResultDesignatorName()}; 5863 // Strip off the leading "%" 5864 if (ultimateName.length() > 1) { 5865 ultimateName.erase(0, 1); 5866 if (attrs.HasAny({Attr::POINTER, Attr::ALLOCATABLE})) { 5867 evaluate::AttachDeclaration( 5868 Say(name.source, 5869 "A component with a POINTER or ALLOCATABLE attribute may " 5870 "not " 5871 "be of a type with a coarray ultimate component (named " 5872 "'%s')"_err_en_US, 5873 ultimateName), 5874 derived->typeSymbol()); 5875 } 5876 if (!arraySpec().empty() || !coarraySpec().empty()) { 5877 evaluate::AttachDeclaration( 5878 Say(name.source, 5879 "An array or coarray component may not be of a type with a " 5880 "coarray ultimate component (named '%s')"_err_en_US, 5881 ultimateName), 5882 derived->typeSymbol()); 5883 } 5884 } 5885 } 5886 } 5887 } 5888 if (OkToAddComponent(name)) { 5889 auto &symbol{DeclareObjectEntity(name, attrs)}; 5890 SetCUDADataAttr(name.source, symbol, cudaDataAttr()); 5891 if (symbol.has<ObjectEntityDetails>()) { 5892 if (auto &init{std::get<std::optional<parser::Initialization>>(x.t)}) { 5893 Initialization(name, *init, true); 5894 } 5895 } 5896 currScope().symbol()->get<DerivedTypeDetails>().add_component(symbol); 5897 } 5898 ClearArraySpec(); 5899 ClearCoarraySpec(); 5900 } 5901 void DeclarationVisitor::Post(const parser::FillDecl &x) { 5902 // Replace "%FILL" with a distinct generated name 5903 const auto &name{std::get<parser::Name>(x.t)}; 5904 const_cast<SourceName &>(name.source) = context().GetTempName(currScope()); 5905 if (OkToAddComponent(name)) { 5906 auto &symbol{DeclareObjectEntity(name, GetAttrs())}; 5907 currScope().symbol()->get<DerivedTypeDetails>().add_component(symbol); 5908 } 5909 ClearArraySpec(); 5910 } 5911 bool DeclarationVisitor::Pre(const parser::ProcedureDeclarationStmt &x) { 5912 CHECK(!interfaceName_); 5913 const auto &procAttrSpec{std::get<std::list<parser::ProcAttrSpec>>(x.t)}; 5914 for (const parser::ProcAttrSpec &procAttr : procAttrSpec) { 5915 if (auto *bindC{std::get_if<parser::LanguageBindingSpec>(&procAttr.u)}) { 5916 if (std::get<std::optional<parser::ScalarDefaultCharConstantExpr>>( 5917 bindC->t) 5918 .has_value()) { 5919 if (std::get<std::list<parser::ProcDecl>>(x.t).size() > 1) { 5920 Say(context().location().value(), 5921 "A procedure declaration statement with a binding name may not declare multiple procedures"_err_en_US); 5922 } 5923 break; 5924 } 5925 } 5926 } 5927 return BeginDecl(); 5928 } 5929 void DeclarationVisitor::Post(const parser::ProcedureDeclarationStmt &) { 5930 interfaceName_ = nullptr; 5931 EndDecl(); 5932 } 5933 bool DeclarationVisitor::Pre(const parser::DataComponentDefStmt &x) { 5934 // Overrides parse tree traversal so as to handle attributes first, 5935 // so POINTER & ALLOCATABLE enable forward references to derived types. 5936 Walk(std::get<std::list<parser::ComponentAttrSpec>>(x.t)); 5937 set_allowForwardReferenceToDerivedType( 5938 GetAttrs().HasAny({Attr::POINTER, Attr::ALLOCATABLE})); 5939 Walk(std::get<parser::DeclarationTypeSpec>(x.t)); 5940 set_allowForwardReferenceToDerivedType(false); 5941 if (derivedTypeInfo_.sequence) { // C740 5942 if (const auto *declType{GetDeclTypeSpec()}) { 5943 if (!declType->AsIntrinsic() && !declType->IsSequenceType() && 5944 !InModuleFile()) { 5945 if (GetAttrs().test(Attr::POINTER) && 5946 context().IsEnabled(common::LanguageFeature::PointerInSeqType)) { 5947 context().Warn(common::LanguageFeature::PointerInSeqType, 5948 "A sequence type data component that is a pointer to a non-sequence type is not standard"_port_en_US); 5949 } else { 5950 Say("A sequence type data component must either be of an intrinsic type or a derived sequence type"_err_en_US); 5951 } 5952 } 5953 } 5954 } 5955 Walk(std::get<std::list<parser::ComponentOrFill>>(x.t)); 5956 return false; 5957 } 5958 bool DeclarationVisitor::Pre(const parser::ProcComponentDefStmt &) { 5959 CHECK(!interfaceName_); 5960 return true; 5961 } 5962 void DeclarationVisitor::Post(const parser::ProcComponentDefStmt &) { 5963 interfaceName_ = nullptr; 5964 } 5965 bool DeclarationVisitor::Pre(const parser::ProcPointerInit &x) { 5966 if (auto *name{std::get_if<parser::Name>(&x.u)}) { 5967 return !NameIsKnownOrIntrinsic(*name) && !CheckUseError(*name); 5968 } else { 5969 const auto &null{DEREF(std::get_if<parser::NullInit>(&x.u))}; 5970 Walk(null); 5971 if (auto nullInit{EvaluateExpr(null)}) { 5972 if (!evaluate::IsNullPointer(*nullInit)) { 5973 Say(null.v.value().source, 5974 "Procedure pointer initializer must be a name or intrinsic NULL()"_err_en_US); 5975 } 5976 } 5977 return false; 5978 } 5979 } 5980 void DeclarationVisitor::Post(const parser::ProcInterface &x) { 5981 if (auto *name{std::get_if<parser::Name>(&x.u)}) { 5982 interfaceName_ = name; 5983 NoteInterfaceName(*name); 5984 } 5985 } 5986 void DeclarationVisitor::Post(const parser::ProcDecl &x) { 5987 const auto &name{std::get<parser::Name>(x.t)}; 5988 // Don't use BypassGeneric or GetUltimate on this symbol, they can 5989 // lead to unusable names in module files. 5990 const Symbol *procInterface{ 5991 interfaceName_ ? interfaceName_->symbol : nullptr}; 5992 auto attrs{HandleSaveName(name.source, GetAttrs())}; 5993 DerivedTypeDetails *dtDetails{nullptr}; 5994 if (Symbol * symbol{currScope().symbol()}) { 5995 dtDetails = symbol->detailsIf<DerivedTypeDetails>(); 5996 } 5997 if (!dtDetails) { 5998 attrs.set(Attr::EXTERNAL); 5999 } 6000 Symbol &symbol{DeclareProcEntity(name, attrs, procInterface)}; 6001 SetCUDADataAttr(name.source, symbol, cudaDataAttr()); // for error 6002 symbol.ReplaceName(name.source); 6003 if (dtDetails) { 6004 dtDetails->add_component(symbol); 6005 } 6006 DeclaredPossibleSpecificProc(symbol); 6007 } 6008 6009 bool DeclarationVisitor::Pre(const parser::TypeBoundProcedurePart &) { 6010 derivedTypeInfo_.sawContains = true; 6011 return true; 6012 } 6013 6014 // Resolve binding names from type-bound generics, saved in genericBindings_. 6015 void DeclarationVisitor::Post(const parser::TypeBoundProcedurePart &) { 6016 // track specifics seen for the current generic to detect duplicates: 6017 const Symbol *currGeneric{nullptr}; 6018 std::set<SourceName> specifics; 6019 for (const auto &[generic, bindingName] : genericBindings_) { 6020 if (generic != currGeneric) { 6021 currGeneric = generic; 6022 specifics.clear(); 6023 } 6024 auto [it, inserted]{specifics.insert(bindingName->source)}; 6025 if (!inserted) { 6026 Say(*bindingName, // C773 6027 "Binding name '%s' was already specified for generic '%s'"_err_en_US, 6028 bindingName->source, generic->name()) 6029 .Attach(*it, "Previous specification of '%s'"_en_US, *it); 6030 continue; 6031 } 6032 auto *symbol{FindInTypeOrParents(*bindingName)}; 6033 if (!symbol) { 6034 Say(*bindingName, // C772 6035 "Binding name '%s' not found in this derived type"_err_en_US); 6036 } else if (!symbol->has<ProcBindingDetails>()) { 6037 SayWithDecl(*bindingName, *symbol, // C772 6038 "'%s' is not the name of a specific binding of this type"_err_en_US); 6039 } else { 6040 generic->get<GenericDetails>().AddSpecificProc( 6041 *symbol, bindingName->source); 6042 } 6043 } 6044 genericBindings_.clear(); 6045 } 6046 6047 void DeclarationVisitor::Post(const parser::ContainsStmt &) { 6048 if (derivedTypeInfo_.sequence) { 6049 Say("A sequence type may not have a CONTAINS statement"_err_en_US); // C740 6050 } 6051 } 6052 6053 void DeclarationVisitor::Post( 6054 const parser::TypeBoundProcedureStmt::WithoutInterface &x) { 6055 if (GetAttrs().test(Attr::DEFERRED)) { // C783 6056 Say("DEFERRED is only allowed when an interface-name is provided"_err_en_US); 6057 } 6058 for (auto &declaration : x.declarations) { 6059 auto &bindingName{std::get<parser::Name>(declaration.t)}; 6060 auto &optName{std::get<std::optional<parser::Name>>(declaration.t)}; 6061 const parser::Name &procedureName{optName ? *optName : bindingName}; 6062 Symbol *procedure{FindSymbol(procedureName)}; 6063 if (!procedure) { 6064 procedure = NoteInterfaceName(procedureName); 6065 } 6066 if (procedure) { 6067 const Symbol &bindTo{BypassGeneric(*procedure)}; 6068 if (auto *s{MakeTypeSymbol(bindingName, ProcBindingDetails{bindTo})}) { 6069 SetPassNameOn(*s); 6070 if (GetAttrs().test(Attr::DEFERRED)) { 6071 context().SetError(*s); 6072 } 6073 } 6074 } 6075 } 6076 } 6077 6078 void DeclarationVisitor::CheckBindings( 6079 const parser::TypeBoundProcedureStmt::WithoutInterface &tbps) { 6080 CHECK(currScope().IsDerivedType()); 6081 for (auto &declaration : tbps.declarations) { 6082 auto &bindingName{std::get<parser::Name>(declaration.t)}; 6083 if (Symbol * binding{FindInScope(bindingName)}) { 6084 if (auto *details{binding->detailsIf<ProcBindingDetails>()}) { 6085 const Symbol &ultimate{details->symbol().GetUltimate()}; 6086 const Symbol &procedure{BypassGeneric(ultimate)}; 6087 if (&procedure != &ultimate) { 6088 details->ReplaceSymbol(procedure); 6089 } 6090 if (!CanBeTypeBoundProc(procedure)) { 6091 if (details->symbol().name() != binding->name()) { 6092 Say(binding->name(), 6093 "The binding of '%s' ('%s') must be either an accessible " 6094 "module procedure or an external procedure with " 6095 "an explicit interface"_err_en_US, 6096 binding->name(), details->symbol().name()); 6097 } else { 6098 Say(binding->name(), 6099 "'%s' must be either an accessible module procedure " 6100 "or an external procedure with an explicit interface"_err_en_US, 6101 binding->name()); 6102 } 6103 context().SetError(*binding); 6104 } 6105 } 6106 } 6107 } 6108 } 6109 6110 void DeclarationVisitor::Post( 6111 const parser::TypeBoundProcedureStmt::WithInterface &x) { 6112 if (!GetAttrs().test(Attr::DEFERRED)) { // C783 6113 Say("DEFERRED is required when an interface-name is provided"_err_en_US); 6114 } 6115 if (Symbol * interface{NoteInterfaceName(x.interfaceName)}) { 6116 for (auto &bindingName : x.bindingNames) { 6117 if (auto *s{ 6118 MakeTypeSymbol(bindingName, ProcBindingDetails{*interface})}) { 6119 SetPassNameOn(*s); 6120 if (!GetAttrs().test(Attr::DEFERRED)) { 6121 context().SetError(*s); 6122 } 6123 } 6124 } 6125 } 6126 } 6127 6128 bool DeclarationVisitor::Pre(const parser::FinalProcedureStmt &x) { 6129 if (currScope().IsDerivedType() && currScope().symbol()) { 6130 if (auto *details{currScope().symbol()->detailsIf<DerivedTypeDetails>()}) { 6131 for (const auto &subrName : x.v) { 6132 Symbol *symbol{FindSymbol(subrName)}; 6133 if (!symbol) { 6134 // FINAL procedures must be module subroutines 6135 symbol = &MakeSymbol( 6136 currScope().parent(), subrName.source, Attrs{Attr::MODULE}); 6137 Resolve(subrName, symbol); 6138 symbol->set_details(ProcEntityDetails{}); 6139 symbol->set(Symbol::Flag::Subroutine); 6140 } 6141 if (auto pair{details->finals().emplace(subrName.source, *symbol)}; 6142 !pair.second) { // C787 6143 Say(subrName.source, 6144 "FINAL subroutine '%s' already appeared in this derived type"_err_en_US, 6145 subrName.source) 6146 .Attach(pair.first->first, 6147 "earlier appearance of this FINAL subroutine"_en_US); 6148 } 6149 } 6150 } 6151 } 6152 return false; 6153 } 6154 6155 bool DeclarationVisitor::Pre(const parser::TypeBoundGenericStmt &x) { 6156 const auto &accessSpec{std::get<std::optional<parser::AccessSpec>>(x.t)}; 6157 const auto &genericSpec{std::get<Indirection<parser::GenericSpec>>(x.t)}; 6158 const auto &bindingNames{std::get<std::list<parser::Name>>(x.t)}; 6159 GenericSpecInfo info{genericSpec.value()}; 6160 SourceName symbolName{info.symbolName()}; 6161 bool isPrivate{accessSpec ? accessSpec->v == parser::AccessSpec::Kind::Private 6162 : derivedTypeInfo_.privateBindings}; 6163 auto *genericSymbol{FindInScope(symbolName)}; 6164 if (genericSymbol) { 6165 if (!genericSymbol->has<GenericDetails>()) { 6166 genericSymbol = nullptr; // MakeTypeSymbol will report the error below 6167 } 6168 } else { 6169 // look in ancestor types for a generic of the same name 6170 for (const auto &name : GetAllNames(context(), symbolName)) { 6171 if (Symbol * inherited{currScope().FindComponent(SourceName{name})}) { 6172 if (inherited->has<GenericDetails>()) { 6173 CheckAccessibility(symbolName, isPrivate, *inherited); // C771 6174 } else { 6175 Say(symbolName, 6176 "Type bound generic procedure '%s' may not have the same name as a non-generic symbol inherited from an ancestor type"_err_en_US) 6177 .Attach(inherited->name(), "Inherited symbol"_en_US); 6178 } 6179 break; 6180 } 6181 } 6182 } 6183 if (genericSymbol) { 6184 CheckAccessibility(symbolName, isPrivate, *genericSymbol); // C771 6185 } else { 6186 genericSymbol = MakeTypeSymbol(symbolName, GenericDetails{}); 6187 if (!genericSymbol) { 6188 return false; 6189 } 6190 if (isPrivate) { 6191 SetExplicitAttr(*genericSymbol, Attr::PRIVATE); 6192 } 6193 } 6194 for (const parser::Name &bindingName : bindingNames) { 6195 genericBindings_.emplace(genericSymbol, &bindingName); 6196 } 6197 info.Resolve(genericSymbol); 6198 return false; 6199 } 6200 6201 // DEC STRUCTUREs are handled thus to allow for nested definitions. 6202 bool DeclarationVisitor::Pre(const parser::StructureDef &def) { 6203 const auto &structureStatement{ 6204 std::get<parser::Statement<parser::StructureStmt>>(def.t)}; 6205 auto saveDerivedTypeInfo{derivedTypeInfo_}; 6206 derivedTypeInfo_ = {}; 6207 derivedTypeInfo_.isStructure = true; 6208 derivedTypeInfo_.sequence = true; 6209 Scope *previousStructure{nullptr}; 6210 if (saveDerivedTypeInfo.isStructure) { 6211 previousStructure = &currScope(); 6212 PopScope(); 6213 } 6214 const parser::StructureStmt &structStmt{structureStatement.statement}; 6215 const auto &name{std::get<std::optional<parser::Name>>(structStmt.t)}; 6216 if (!name) { 6217 // Construct a distinct generated name for an anonymous structure 6218 auto &mutableName{const_cast<std::optional<parser::Name> &>(name)}; 6219 mutableName.emplace( 6220 parser::Name{context().GetTempName(currScope()), nullptr}); 6221 } 6222 auto &symbol{MakeSymbol(*name, DerivedTypeDetails{})}; 6223 symbol.ReplaceName(name->source); 6224 symbol.get<DerivedTypeDetails>().set_sequence(true); 6225 symbol.get<DerivedTypeDetails>().set_isDECStructure(true); 6226 derivedTypeInfo_.type = &symbol; 6227 PushScope(Scope::Kind::DerivedType, &symbol); 6228 const auto &fields{std::get<std::list<parser::StructureField>>(def.t)}; 6229 Walk(fields); 6230 PopScope(); 6231 // Complete the definition 6232 DerivedTypeSpec derivedTypeSpec{symbol.name(), symbol}; 6233 derivedTypeSpec.set_scope(DEREF(symbol.scope())); 6234 derivedTypeSpec.CookParameters(GetFoldingContext()); 6235 derivedTypeSpec.EvaluateParameters(context()); 6236 DeclTypeSpec &type{currScope().MakeDerivedType( 6237 DeclTypeSpec::TypeDerived, std::move(derivedTypeSpec))}; 6238 type.derivedTypeSpec().Instantiate(currScope()); 6239 // Restore previous structure definition context, if any 6240 derivedTypeInfo_ = saveDerivedTypeInfo; 6241 if (previousStructure) { 6242 PushScope(*previousStructure); 6243 } 6244 // Handle any entity declarations on the STRUCTURE statement 6245 const auto &decls{std::get<std::list<parser::EntityDecl>>(structStmt.t)}; 6246 if (!decls.empty()) { 6247 BeginDecl(); 6248 SetDeclTypeSpec(type); 6249 Walk(decls); 6250 EndDecl(); 6251 } 6252 return false; 6253 } 6254 6255 bool DeclarationVisitor::Pre(const parser::Union::UnionStmt &) { 6256 Say("support for UNION"_todo_en_US); // TODO 6257 return true; 6258 } 6259 6260 bool DeclarationVisitor::Pre(const parser::StructureField &x) { 6261 if (std::holds_alternative<parser::Statement<parser::DataComponentDefStmt>>( 6262 x.u)) { 6263 BeginDecl(); 6264 } 6265 return true; 6266 } 6267 6268 void DeclarationVisitor::Post(const parser::StructureField &x) { 6269 if (std::holds_alternative<parser::Statement<parser::DataComponentDefStmt>>( 6270 x.u)) { 6271 EndDecl(); 6272 } 6273 } 6274 6275 bool DeclarationVisitor::Pre(const parser::AllocateStmt &) { 6276 BeginDeclTypeSpec(); 6277 return true; 6278 } 6279 void DeclarationVisitor::Post(const parser::AllocateStmt &) { 6280 EndDeclTypeSpec(); 6281 } 6282 6283 bool DeclarationVisitor::Pre(const parser::StructureConstructor &x) { 6284 auto &parsedType{std::get<parser::DerivedTypeSpec>(x.t)}; 6285 const DeclTypeSpec *type{ProcessTypeSpec(parsedType)}; 6286 if (!type) { 6287 return false; 6288 } 6289 const DerivedTypeSpec *spec{type->AsDerived()}; 6290 const Scope *typeScope{spec ? spec->scope() : nullptr}; 6291 if (!typeScope) { 6292 return false; 6293 } 6294 6295 // N.B C7102 is implicitly enforced by having inaccessible types not 6296 // being found in resolution. 6297 // More constraints are enforced in expression.cpp so that they 6298 // can apply to structure constructors that have been converted 6299 // from misparsed function references. 6300 for (const auto &component : 6301 std::get<std::list<parser::ComponentSpec>>(x.t)) { 6302 // Visit the component spec expression, but not the keyword, since 6303 // we need to resolve its symbol in the scope of the derived type. 6304 Walk(std::get<parser::ComponentDataSource>(component.t)); 6305 if (const auto &kw{std::get<std::optional<parser::Keyword>>(component.t)}) { 6306 FindInTypeOrParents(*typeScope, kw->v); 6307 } 6308 } 6309 return false; 6310 } 6311 6312 bool DeclarationVisitor::Pre(const parser::BasedPointer &) { 6313 BeginArraySpec(); 6314 return true; 6315 } 6316 6317 void DeclarationVisitor::Post(const parser::BasedPointer &bp) { 6318 const parser::ObjectName &pointerName{std::get<0>(bp.t)}; 6319 auto *pointer{FindSymbol(pointerName)}; 6320 if (!pointer) { 6321 pointer = &MakeSymbol(pointerName, ObjectEntityDetails{}); 6322 } else if (!ConvertToObjectEntity(*pointer)) { 6323 SayWithDecl(pointerName, *pointer, "'%s' is not a variable"_err_en_US); 6324 } else if (IsNamedConstant(*pointer)) { 6325 SayWithDecl(pointerName, *pointer, 6326 "'%s' is a named constant and may not be a Cray pointer"_err_en_US); 6327 } else if (pointer->Rank() > 0) { 6328 SayWithDecl( 6329 pointerName, *pointer, "Cray pointer '%s' must be a scalar"_err_en_US); 6330 } else if (pointer->test(Symbol::Flag::CrayPointee)) { 6331 Say(pointerName, 6332 "'%s' cannot be a Cray pointer as it is already a Cray pointee"_err_en_US); 6333 } 6334 pointer->set(Symbol::Flag::CrayPointer); 6335 const DeclTypeSpec &pointerType{MakeNumericType( 6336 TypeCategory::Integer, context().defaultKinds().subscriptIntegerKind())}; 6337 const auto *type{pointer->GetType()}; 6338 if (!type) { 6339 pointer->SetType(pointerType); 6340 } else if (*type != pointerType) { 6341 Say(pointerName.source, "Cray pointer '%s' must have type %s"_err_en_US, 6342 pointerName.source, pointerType.AsFortran()); 6343 } 6344 const parser::ObjectName &pointeeName{std::get<1>(bp.t)}; 6345 DeclareObjectEntity(pointeeName); 6346 if (Symbol * pointee{pointeeName.symbol}) { 6347 if (!ConvertToObjectEntity(*pointee)) { 6348 return; 6349 } 6350 if (IsNamedConstant(*pointee)) { 6351 Say(pointeeName, 6352 "'%s' is a named constant and may not be a Cray pointee"_err_en_US); 6353 return; 6354 } 6355 if (pointee->test(Symbol::Flag::CrayPointer)) { 6356 Say(pointeeName, 6357 "'%s' cannot be a Cray pointee as it is already a Cray pointer"_err_en_US); 6358 } else if (pointee->test(Symbol::Flag::CrayPointee)) { 6359 Say(pointeeName, "'%s' was already declared as a Cray pointee"_err_en_US); 6360 } else { 6361 pointee->set(Symbol::Flag::CrayPointee); 6362 } 6363 if (const auto *pointeeType{pointee->GetType()}) { 6364 if (const auto *derived{pointeeType->AsDerived()}) { 6365 if (!IsSequenceOrBindCType(derived)) { 6366 context().Warn(common::LanguageFeature::NonSequenceCrayPointee, 6367 pointeeName.source, 6368 "Type of Cray pointee '%s' is a derived type that is neither SEQUENCE nor BIND(C)"_warn_en_US, 6369 pointeeName.source); 6370 } 6371 } 6372 } 6373 currScope().add_crayPointer(pointeeName.source, *pointer); 6374 } 6375 } 6376 6377 bool DeclarationVisitor::Pre(const parser::NamelistStmt::Group &x) { 6378 if (!CheckNotInBlock("NAMELIST")) { // C1107 6379 return false; 6380 } 6381 const auto &groupName{std::get<parser::Name>(x.t)}; 6382 auto *groupSymbol{FindInScope(groupName)}; 6383 if (!groupSymbol || !groupSymbol->has<NamelistDetails>()) { 6384 groupSymbol = &MakeSymbol(groupName, NamelistDetails{}); 6385 groupSymbol->ReplaceName(groupName.source); 6386 } 6387 // Name resolution of group items is deferred to FinishNamelists() 6388 // so that host association is handled correctly. 6389 GetDeferredDeclarationState(true)->namelistGroups.emplace_back(&x); 6390 return false; 6391 } 6392 6393 void DeclarationVisitor::FinishNamelists() { 6394 if (auto *deferred{GetDeferredDeclarationState()}) { 6395 for (const parser::NamelistStmt::Group *group : deferred->namelistGroups) { 6396 if (auto *groupSymbol{FindInScope(std::get<parser::Name>(group->t))}) { 6397 if (auto *details{groupSymbol->detailsIf<NamelistDetails>()}) { 6398 for (const auto &name : std::get<std::list<parser::Name>>(group->t)) { 6399 auto *symbol{FindSymbol(name)}; 6400 if (!symbol) { 6401 symbol = &MakeSymbol(name, ObjectEntityDetails{}); 6402 ApplyImplicitRules(*symbol); 6403 } else if (!ConvertToObjectEntity(symbol->GetUltimate())) { 6404 SayWithDecl(name, *symbol, "'%s' is not a variable"_err_en_US); 6405 context().SetError(*groupSymbol); 6406 } 6407 symbol->GetUltimate().set(Symbol::Flag::InNamelist); 6408 details->add_object(*symbol); 6409 } 6410 } 6411 } 6412 } 6413 deferred->namelistGroups.clear(); 6414 } 6415 } 6416 6417 bool DeclarationVisitor::Pre(const parser::IoControlSpec &x) { 6418 if (const auto *name{std::get_if<parser::Name>(&x.u)}) { 6419 auto *symbol{FindSymbol(*name)}; 6420 if (!symbol) { 6421 Say(*name, "Namelist group '%s' not found"_err_en_US); 6422 } else if (!symbol->GetUltimate().has<NamelistDetails>()) { 6423 SayWithDecl( 6424 *name, *symbol, "'%s' is not the name of a namelist group"_err_en_US); 6425 } 6426 } 6427 return true; 6428 } 6429 6430 bool DeclarationVisitor::Pre(const parser::CommonStmt::Block &x) { 6431 CheckNotInBlock("COMMON"); // C1107 6432 return true; 6433 } 6434 6435 bool DeclarationVisitor::Pre(const parser::CommonBlockObject &) { 6436 BeginArraySpec(); 6437 return true; 6438 } 6439 6440 void DeclarationVisitor::Post(const parser::CommonBlockObject &x) { 6441 const auto &name{std::get<parser::Name>(x.t)}; 6442 DeclareObjectEntity(name); 6443 auto pair{specPartState_.commonBlockObjects.insert(name.source)}; 6444 if (!pair.second) { 6445 const SourceName &prev{*pair.first}; 6446 Say2(name.source, "'%s' is already in a COMMON block"_err_en_US, prev, 6447 "Previous occurrence of '%s' in a COMMON block"_en_US); 6448 } 6449 } 6450 6451 bool DeclarationVisitor::Pre(const parser::EquivalenceStmt &x) { 6452 // save equivalence sets to be processed after specification part 6453 if (CheckNotInBlock("EQUIVALENCE")) { // C1107 6454 for (const std::list<parser::EquivalenceObject> &set : x.v) { 6455 specPartState_.equivalenceSets.push_back(&set); 6456 } 6457 } 6458 return false; // don't implicitly declare names yet 6459 } 6460 6461 void DeclarationVisitor::CheckEquivalenceSets() { 6462 EquivalenceSets equivSets{context()}; 6463 inEquivalenceStmt_ = true; 6464 for (const auto *set : specPartState_.equivalenceSets) { 6465 const auto &source{set->front().v.value().source}; 6466 if (set->size() <= 1) { // R871 6467 Say(source, "Equivalence set must have more than one object"_err_en_US); 6468 } 6469 for (const parser::EquivalenceObject &object : *set) { 6470 const auto &designator{object.v.value()}; 6471 // The designator was not resolved when it was encountered, so do it now. 6472 // AnalyzeExpr causes array sections to be changed to substrings as needed 6473 Walk(designator); 6474 if (AnalyzeExpr(context(), designator)) { 6475 equivSets.AddToSet(designator); 6476 } 6477 } 6478 equivSets.FinishSet(source); 6479 } 6480 inEquivalenceStmt_ = false; 6481 for (auto &set : equivSets.sets()) { 6482 if (!set.empty()) { 6483 currScope().add_equivalenceSet(std::move(set)); 6484 } 6485 } 6486 specPartState_.equivalenceSets.clear(); 6487 } 6488 6489 bool DeclarationVisitor::Pre(const parser::SaveStmt &x) { 6490 if (x.v.empty()) { 6491 specPartState_.saveInfo.saveAll = currStmtSource(); 6492 currScope().set_hasSAVE(); 6493 } else { 6494 for (const parser::SavedEntity &y : x.v) { 6495 auto kind{std::get<parser::SavedEntity::Kind>(y.t)}; 6496 const auto &name{std::get<parser::Name>(y.t)}; 6497 if (kind == parser::SavedEntity::Kind::Common) { 6498 MakeCommonBlockSymbol(name); 6499 AddSaveName(specPartState_.saveInfo.commons, name.source); 6500 } else { 6501 HandleAttributeStmt(Attr::SAVE, name); 6502 } 6503 } 6504 } 6505 return false; 6506 } 6507 6508 void DeclarationVisitor::CheckSaveStmts() { 6509 for (const SourceName &name : specPartState_.saveInfo.entities) { 6510 auto *symbol{FindInScope(name)}; 6511 if (!symbol) { 6512 // error was reported 6513 } else if (specPartState_.saveInfo.saveAll) { 6514 // C889 - note that pgi, ifort, xlf do not enforce this constraint 6515 if (context().ShouldWarn(common::LanguageFeature::RedundantAttribute)) { 6516 Say2(name, 6517 "Explicit SAVE of '%s' is redundant due to global SAVE statement"_warn_en_US, 6518 *specPartState_.saveInfo.saveAll, "Global SAVE statement"_en_US) 6519 .set_languageFeature(common::LanguageFeature::RedundantAttribute); 6520 } 6521 } else if (!IsSaved(*symbol)) { 6522 SetExplicitAttr(*symbol, Attr::SAVE); 6523 } 6524 } 6525 for (const SourceName &name : specPartState_.saveInfo.commons) { 6526 if (auto *symbol{currScope().FindCommonBlock(name)}) { 6527 auto &objects{symbol->get<CommonBlockDetails>().objects()}; 6528 if (objects.empty()) { 6529 if (currScope().kind() != Scope::Kind::BlockConstruct) { 6530 Say(name, 6531 "'%s' appears as a COMMON block in a SAVE statement but not in" 6532 " a COMMON statement"_err_en_US); 6533 } else { // C1108 6534 Say(name, 6535 "SAVE statement in BLOCK construct may not contain a" 6536 " common block name '%s'"_err_en_US); 6537 } 6538 } else { 6539 for (auto &object : symbol->get<CommonBlockDetails>().objects()) { 6540 if (!IsSaved(*object)) { 6541 SetImplicitAttr(*object, Attr::SAVE); 6542 } 6543 } 6544 } 6545 } 6546 } 6547 specPartState_.saveInfo = {}; 6548 } 6549 6550 // Record SAVEd names in specPartState_.saveInfo.entities. 6551 Attrs DeclarationVisitor::HandleSaveName(const SourceName &name, Attrs attrs) { 6552 if (attrs.test(Attr::SAVE)) { 6553 AddSaveName(specPartState_.saveInfo.entities, name); 6554 } 6555 return attrs; 6556 } 6557 6558 // Record a name in a set of those to be saved. 6559 void DeclarationVisitor::AddSaveName( 6560 std::set<SourceName> &set, const SourceName &name) { 6561 auto pair{set.insert(name)}; 6562 if (!pair.second && 6563 context().ShouldWarn(common::LanguageFeature::RedundantAttribute)) { 6564 Say2(name, "SAVE attribute was already specified on '%s'"_warn_en_US, 6565 *pair.first, "Previous specification of SAVE attribute"_en_US) 6566 .set_languageFeature(common::LanguageFeature::RedundantAttribute); 6567 } 6568 } 6569 6570 // Check types of common block objects, now that they are known. 6571 void DeclarationVisitor::CheckCommonBlocks() { 6572 // check for empty common blocks 6573 for (const auto &pair : currScope().commonBlocks()) { 6574 const auto &symbol{*pair.second}; 6575 if (symbol.get<CommonBlockDetails>().objects().empty() && 6576 symbol.attrs().test(Attr::BIND_C)) { 6577 Say(symbol.name(), 6578 "'%s' appears as a COMMON block in a BIND statement but not in" 6579 " a COMMON statement"_err_en_US); 6580 } 6581 } 6582 // check objects in common blocks 6583 for (const auto &name : specPartState_.commonBlockObjects) { 6584 const auto *symbol{currScope().FindSymbol(name)}; 6585 if (!symbol) { 6586 continue; 6587 } 6588 const auto &attrs{symbol->attrs()}; 6589 if (attrs.test(Attr::ALLOCATABLE)) { 6590 Say(name, 6591 "ALLOCATABLE object '%s' may not appear in a COMMON block"_err_en_US); 6592 } else if (attrs.test(Attr::BIND_C)) { 6593 Say(name, 6594 "Variable '%s' with BIND attribute may not appear in a COMMON block"_err_en_US); 6595 } else if (IsNamedConstant(*symbol)) { 6596 Say(name, 6597 "A named constant '%s' may not appear in a COMMON block"_err_en_US); 6598 } else if (IsDummy(*symbol)) { 6599 Say(name, 6600 "Dummy argument '%s' may not appear in a COMMON block"_err_en_US); 6601 } else if (symbol->IsFuncResult()) { 6602 Say(name, 6603 "Function result '%s' may not appear in a COMMON block"_err_en_US); 6604 } else if (const DeclTypeSpec * type{symbol->GetType()}) { 6605 if (type->category() == DeclTypeSpec::ClassStar) { 6606 Say(name, 6607 "Unlimited polymorphic pointer '%s' may not appear in a COMMON block"_err_en_US); 6608 } else if (const auto *derived{type->AsDerived()}) { 6609 if (!IsSequenceOrBindCType(derived)) { 6610 Say(name, 6611 "Derived type '%s' in COMMON block must have the BIND or" 6612 " SEQUENCE attribute"_err_en_US); 6613 } 6614 UnorderedSymbolSet typeSet; 6615 CheckCommonBlockDerivedType(name, derived->typeSymbol(), typeSet); 6616 } 6617 } 6618 } 6619 specPartState_.commonBlockObjects = {}; 6620 } 6621 6622 Symbol &DeclarationVisitor::MakeCommonBlockSymbol(const parser::Name &name) { 6623 return Resolve(name, currScope().MakeCommonBlock(name.source)); 6624 } 6625 Symbol &DeclarationVisitor::MakeCommonBlockSymbol( 6626 const std::optional<parser::Name> &name) { 6627 if (name) { 6628 return MakeCommonBlockSymbol(*name); 6629 } else { 6630 return MakeCommonBlockSymbol(parser::Name{}); 6631 } 6632 } 6633 6634 bool DeclarationVisitor::NameIsKnownOrIntrinsic(const parser::Name &name) { 6635 return FindSymbol(name) || HandleUnrestrictedSpecificIntrinsicFunction(name); 6636 } 6637 6638 // Check if this derived type can be in a COMMON block. 6639 void DeclarationVisitor::CheckCommonBlockDerivedType(const SourceName &name, 6640 const Symbol &typeSymbol, UnorderedSymbolSet &typeSet) { 6641 if (auto iter{typeSet.find(SymbolRef{typeSymbol})}; iter != typeSet.end()) { 6642 return; 6643 } 6644 typeSet.emplace(typeSymbol); 6645 if (const auto *scope{typeSymbol.scope()}) { 6646 for (const auto &pair : *scope) { 6647 const Symbol &component{*pair.second}; 6648 if (component.attrs().test(Attr::ALLOCATABLE)) { 6649 Say2(name, 6650 "Derived type variable '%s' may not appear in a COMMON block" 6651 " due to ALLOCATABLE component"_err_en_US, 6652 component.name(), "Component with ALLOCATABLE attribute"_en_US); 6653 return; 6654 } 6655 const auto *details{component.detailsIf<ObjectEntityDetails>()}; 6656 if (component.test(Symbol::Flag::InDataStmt) || 6657 (details && details->init())) { 6658 Say2(name, 6659 "Derived type variable '%s' may not appear in a COMMON block due to component with default initialization"_err_en_US, 6660 component.name(), "Component with default initialization"_en_US); 6661 return; 6662 } 6663 if (details) { 6664 if (const auto *type{details->type()}) { 6665 if (const auto *derived{type->AsDerived()}) { 6666 const Symbol &derivedTypeSymbol{derived->typeSymbol()}; 6667 CheckCommonBlockDerivedType(name, derivedTypeSymbol, typeSet); 6668 } 6669 } 6670 } 6671 } 6672 } 6673 } 6674 6675 bool DeclarationVisitor::HandleUnrestrictedSpecificIntrinsicFunction( 6676 const parser::Name &name) { 6677 if (auto interface{context().intrinsics().IsSpecificIntrinsicFunction( 6678 name.source.ToString())}) { 6679 // Unrestricted specific intrinsic function names (e.g., "cos") 6680 // are acceptable as procedure interfaces. The presence of the 6681 // INTRINSIC flag will cause this symbol to have a complete interface 6682 // recreated for it later on demand, but capturing its result type here 6683 // will make GetType() return a correct result without having to 6684 // probe the intrinsics table again. 6685 Symbol &symbol{MakeSymbol(InclusiveScope(), name.source, Attrs{})}; 6686 SetImplicitAttr(symbol, Attr::INTRINSIC); 6687 CHECK(interface->functionResult.has_value()); 6688 evaluate::DynamicType dyType{ 6689 DEREF(interface->functionResult->GetTypeAndShape()).type()}; 6690 CHECK(common::IsNumericTypeCategory(dyType.category())); 6691 const DeclTypeSpec &typeSpec{ 6692 MakeNumericType(dyType.category(), dyType.kind())}; 6693 ProcEntityDetails details; 6694 details.set_type(typeSpec); 6695 symbol.set_details(std::move(details)); 6696 symbol.set(Symbol::Flag::Function); 6697 if (interface->IsElemental()) { 6698 SetExplicitAttr(symbol, Attr::ELEMENTAL); 6699 } 6700 if (interface->IsPure()) { 6701 SetExplicitAttr(symbol, Attr::PURE); 6702 } 6703 Resolve(name, symbol); 6704 return true; 6705 } else { 6706 return false; 6707 } 6708 } 6709 6710 // Checks for all locality-specs: LOCAL, LOCAL_INIT, and SHARED 6711 bool DeclarationVisitor::PassesSharedLocalityChecks( 6712 const parser::Name &name, Symbol &symbol) { 6713 if (!IsVariableName(symbol)) { 6714 SayLocalMustBeVariable(name, symbol); // C1124 6715 return false; 6716 } 6717 if (symbol.owner() == currScope()) { // C1125 and C1126 6718 SayAlreadyDeclared(name, symbol); 6719 return false; 6720 } 6721 return true; 6722 } 6723 6724 // Checks for locality-specs LOCAL, LOCAL_INIT, and REDUCE 6725 bool DeclarationVisitor::PassesLocalityChecks( 6726 const parser::Name &name, Symbol &symbol, Symbol::Flag flag) { 6727 bool isReduce{flag == Symbol::Flag::LocalityReduce}; 6728 const char *specName{ 6729 flag == Symbol::Flag::LocalityLocalInit ? "LOCAL_INIT" : "LOCAL"}; 6730 if (IsAllocatable(symbol) && !isReduce) { // F'2023 C1130 6731 SayWithDecl(name, symbol, 6732 "ALLOCATABLE variable '%s' not allowed in a %s locality-spec"_err_en_US, 6733 specName); 6734 return false; 6735 } 6736 if (IsOptional(symbol)) { // F'2023 C1130-C1131 6737 SayWithDecl(name, symbol, 6738 "OPTIONAL argument '%s' not allowed in a locality-spec"_err_en_US); 6739 return false; 6740 } 6741 if (IsIntentIn(symbol)) { // F'2023 C1130-C1131 6742 SayWithDecl(name, symbol, 6743 "INTENT IN argument '%s' not allowed in a locality-spec"_err_en_US); 6744 return false; 6745 } 6746 if (IsFinalizable(symbol) && !isReduce) { // F'2023 C1130 6747 SayWithDecl(name, symbol, 6748 "Finalizable variable '%s' not allowed in a %s locality-spec"_err_en_US, 6749 specName); 6750 return false; 6751 } 6752 if (evaluate::IsCoarray(symbol) && !isReduce) { // F'2023 C1130 6753 SayWithDecl(name, symbol, 6754 "Coarray '%s' not allowed in a %s locality-spec"_err_en_US, specName); 6755 return false; 6756 } 6757 if (const DeclTypeSpec * type{symbol.GetType()}) { 6758 if (type->IsPolymorphic() && IsDummy(symbol) && !IsPointer(symbol) && 6759 !isReduce) { // F'2023 C1130 6760 SayWithDecl(name, symbol, 6761 "Nonpointer polymorphic argument '%s' not allowed in a %s locality-spec"_err_en_US, 6762 specName); 6763 return false; 6764 } 6765 } 6766 if (symbol.attrs().test(Attr::ASYNCHRONOUS) && isReduce) { // F'2023 C1131 6767 SayWithDecl(name, symbol, 6768 "ASYNCHRONOUS variable '%s' not allowed in a REDUCE locality-spec"_err_en_US); 6769 return false; 6770 } 6771 if (symbol.attrs().test(Attr::VOLATILE) && isReduce) { // F'2023 C1131 6772 SayWithDecl(name, symbol, 6773 "VOLATILE variable '%s' not allowed in a REDUCE locality-spec"_err_en_US); 6774 return false; 6775 } 6776 if (IsAssumedSizeArray(symbol)) { // F'2023 C1130-C1131 6777 SayWithDecl(name, symbol, 6778 "Assumed size array '%s' not allowed in a locality-spec"_err_en_US); 6779 return false; 6780 } 6781 if (std::optional<Message> whyNot{WhyNotDefinable( 6782 name.source, currScope(), DefinabilityFlags{}, symbol)}) { 6783 SayWithReason(name, symbol, 6784 "'%s' may not appear in a locality-spec because it is not definable"_err_en_US, 6785 std::move(whyNot->set_severity(parser::Severity::Because))); 6786 return false; 6787 } 6788 return PassesSharedLocalityChecks(name, symbol); 6789 } 6790 6791 Symbol &DeclarationVisitor::FindOrDeclareEnclosingEntity( 6792 const parser::Name &name) { 6793 Symbol *prev{FindSymbol(name)}; 6794 if (!prev) { 6795 // Declare the name as an object in the enclosing scope so that 6796 // the name can't be repurposed there later as something else. 6797 prev = &MakeSymbol(InclusiveScope(), name.source, Attrs{}); 6798 ConvertToObjectEntity(*prev); 6799 ApplyImplicitRules(*prev); 6800 } 6801 return *prev; 6802 } 6803 6804 void DeclarationVisitor::DeclareLocalEntity( 6805 const parser::Name &name, Symbol::Flag flag) { 6806 Symbol &prev{FindOrDeclareEnclosingEntity(name)}; 6807 if (PassesLocalityChecks(name, prev, flag)) { 6808 if (auto *symbol{&MakeHostAssocSymbol(name, prev)}) { 6809 symbol->set(flag); 6810 } 6811 } 6812 } 6813 6814 Symbol *DeclarationVisitor::DeclareStatementEntity( 6815 const parser::DoVariable &doVar, 6816 const std::optional<parser::IntegerTypeSpec> &type) { 6817 const parser::Name &name{doVar.thing.thing}; 6818 const DeclTypeSpec *declTypeSpec{nullptr}; 6819 if (auto *prev{FindSymbol(name)}) { 6820 if (prev->owner() == currScope()) { 6821 SayAlreadyDeclared(name, *prev); 6822 return nullptr; 6823 } 6824 name.symbol = nullptr; 6825 // F'2023 19.4 p5 ambiguous rule about outer declarations 6826 declTypeSpec = prev->GetType(); 6827 } 6828 Symbol &symbol{DeclareEntity<ObjectEntityDetails>(name, {})}; 6829 if (!symbol.has<ObjectEntityDetails>()) { 6830 return nullptr; // error was reported in DeclareEntity 6831 } 6832 if (type) { 6833 declTypeSpec = ProcessTypeSpec(*type); 6834 } 6835 if (declTypeSpec) { 6836 // Subtlety: Don't let a "*length" specifier (if any is pending) affect the 6837 // declaration of this implied DO loop control variable. 6838 auto restorer{ 6839 common::ScopedSet(charInfo_.length, std::optional<ParamValue>{})}; 6840 SetType(name, *declTypeSpec); 6841 } else { 6842 ApplyImplicitRules(symbol); 6843 } 6844 return Resolve(name, &symbol); 6845 } 6846 6847 // Set the type of an entity or report an error. 6848 void DeclarationVisitor::SetType( 6849 const parser::Name &name, const DeclTypeSpec &type) { 6850 CHECK(name.symbol); 6851 auto &symbol{*name.symbol}; 6852 if (charInfo_.length) { // Declaration has "*length" (R723) 6853 auto length{std::move(*charInfo_.length)}; 6854 charInfo_.length.reset(); 6855 if (type.category() == DeclTypeSpec::Character) { 6856 auto kind{type.characterTypeSpec().kind()}; 6857 // Recurse with correct type. 6858 SetType(name, 6859 currScope().MakeCharacterType(std::move(length), std::move(kind))); 6860 return; 6861 } else { // C753 6862 Say(name, 6863 "A length specifier cannot be used to declare the non-character entity '%s'"_err_en_US); 6864 } 6865 } 6866 if (auto *proc{symbol.detailsIf<ProcEntityDetails>()}) { 6867 if (proc->procInterface()) { 6868 Say(name, 6869 "'%s' has an explicit interface and may not also have a type"_err_en_US); 6870 context().SetError(symbol); 6871 return; 6872 } 6873 } 6874 auto *prevType{symbol.GetType()}; 6875 if (!prevType) { 6876 if (symbol.test(Symbol::Flag::InDataStmt) && isImplicitNoneType()) { 6877 context().Warn(common::LanguageFeature::ForwardRefImplicitNoneData, 6878 name.source, 6879 "'%s' appeared in a DATA statement before its type was declared under IMPLICIT NONE(TYPE)"_port_en_US, 6880 name.source); 6881 } 6882 symbol.SetType(type); 6883 } else if (symbol.has<UseDetails>()) { 6884 // error recovery case, redeclaration of use-associated name 6885 } else if (HadForwardRef(symbol)) { 6886 // error recovery after use of host-associated name 6887 } else if (!symbol.test(Symbol::Flag::Implicit)) { 6888 SayWithDecl( 6889 name, symbol, "The type of '%s' has already been declared"_err_en_US); 6890 context().SetError(symbol); 6891 } else if (type != *prevType) { 6892 SayWithDecl(name, symbol, 6893 "The type of '%s' has already been implicitly declared"_err_en_US); 6894 context().SetError(symbol); 6895 } else { 6896 symbol.set(Symbol::Flag::Implicit, false); 6897 } 6898 } 6899 6900 std::optional<DerivedTypeSpec> DeclarationVisitor::ResolveDerivedType( 6901 const parser::Name &name) { 6902 Scope &outer{NonDerivedTypeScope()}; 6903 Symbol *symbol{FindSymbol(outer, name)}; 6904 Symbol *ultimate{symbol ? &symbol->GetUltimate() : nullptr}; 6905 auto *generic{ultimate ? ultimate->detailsIf<GenericDetails>() : nullptr}; 6906 if (generic) { 6907 if (Symbol * genDT{generic->derivedType()}) { 6908 symbol = genDT; 6909 generic = nullptr; 6910 } 6911 } 6912 if (!symbol || symbol->has<UnknownDetails>() || 6913 (generic && &ultimate->owner() == &outer)) { 6914 if (allowForwardReferenceToDerivedType()) { 6915 if (!symbol) { 6916 symbol = &MakeSymbol(outer, name.source, Attrs{}); 6917 Resolve(name, *symbol); 6918 } else if (generic) { 6919 // forward ref to type with later homonymous generic 6920 symbol = &outer.MakeSymbol(name.source, Attrs{}, UnknownDetails{}); 6921 generic->set_derivedType(*symbol); 6922 name.symbol = symbol; 6923 } 6924 DerivedTypeDetails details; 6925 details.set_isForwardReferenced(true); 6926 symbol->set_details(std::move(details)); 6927 } else { // C732 6928 Say(name, "Derived type '%s' not found"_err_en_US); 6929 return std::nullopt; 6930 } 6931 } else if (&DEREF(symbol).owner() != &outer && 6932 !ultimate->has<GenericDetails>()) { 6933 // Prevent a later declaration in this scope of a host-associated 6934 // type name. 6935 outer.add_importName(name.source); 6936 } 6937 if (CheckUseError(name)) { 6938 return std::nullopt; 6939 } else if (symbol->GetUltimate().has<DerivedTypeDetails>()) { 6940 return DerivedTypeSpec{name.source, *symbol}; 6941 } else { 6942 Say(name, "'%s' is not a derived type"_err_en_US); 6943 return std::nullopt; 6944 } 6945 } 6946 6947 std::optional<DerivedTypeSpec> DeclarationVisitor::ResolveExtendsType( 6948 const parser::Name &typeName, const parser::Name *extendsName) { 6949 if (extendsName) { 6950 if (typeName.source == extendsName->source) { 6951 Say(extendsName->source, 6952 "Derived type '%s' cannot extend itself"_err_en_US); 6953 } else if (auto dtSpec{ResolveDerivedType(*extendsName)}) { 6954 if (!dtSpec->IsForwardReferenced()) { 6955 return dtSpec; 6956 } 6957 Say(typeName.source, 6958 "Derived type '%s' cannot extend type '%s' that has not yet been defined"_err_en_US, 6959 typeName.source, extendsName->source); 6960 } 6961 } 6962 return std::nullopt; 6963 } 6964 6965 Symbol *DeclarationVisitor::NoteInterfaceName(const parser::Name &name) { 6966 // The symbol is checked later by CheckExplicitInterface() and 6967 // CheckBindings(). It can be a forward reference. 6968 if (!NameIsKnownOrIntrinsic(name)) { 6969 Symbol &symbol{MakeSymbol(InclusiveScope(), name.source, Attrs{})}; 6970 Resolve(name, symbol); 6971 } 6972 return name.symbol; 6973 } 6974 6975 void DeclarationVisitor::CheckExplicitInterface(const parser::Name &name) { 6976 if (const Symbol * symbol{name.symbol}) { 6977 const Symbol &ultimate{symbol->GetUltimate()}; 6978 if (!context().HasError(*symbol) && !context().HasError(ultimate) && 6979 !BypassGeneric(ultimate).HasExplicitInterface()) { 6980 Say(name, 6981 "'%s' must be an abstract interface or a procedure with an explicit interface"_err_en_US, 6982 symbol->name()); 6983 } 6984 } 6985 } 6986 6987 // Create a symbol for a type parameter, component, or procedure binding in 6988 // the current derived type scope. Return false on error. 6989 Symbol *DeclarationVisitor::MakeTypeSymbol( 6990 const parser::Name &name, Details &&details) { 6991 return Resolve(name, MakeTypeSymbol(name.source, std::move(details))); 6992 } 6993 Symbol *DeclarationVisitor::MakeTypeSymbol( 6994 const SourceName &name, Details &&details) { 6995 Scope &derivedType{currScope()}; 6996 CHECK(derivedType.IsDerivedType()); 6997 if (auto *symbol{FindInScope(derivedType, name)}) { // C742 6998 Say2(name, 6999 "Type parameter, component, or procedure binding '%s'" 7000 " already defined in this type"_err_en_US, 7001 *symbol, "Previous definition of '%s'"_en_US); 7002 return nullptr; 7003 } else { 7004 auto attrs{GetAttrs()}; 7005 // Apply binding-private-stmt if present and this is a procedure binding 7006 if (derivedTypeInfo_.privateBindings && 7007 !attrs.HasAny({Attr::PUBLIC, Attr::PRIVATE}) && 7008 std::holds_alternative<ProcBindingDetails>(details)) { 7009 attrs.set(Attr::PRIVATE); 7010 } 7011 Symbol &result{MakeSymbol(name, attrs, std::move(details))}; 7012 SetCUDADataAttr(name, result, cudaDataAttr()); 7013 return &result; 7014 } 7015 } 7016 7017 // Return true if it is ok to declare this component in the current scope. 7018 // Otherwise, emit an error and return false. 7019 bool DeclarationVisitor::OkToAddComponent( 7020 const parser::Name &name, const Symbol *extends) { 7021 for (const Scope *scope{&currScope()}; scope;) { 7022 CHECK(scope->IsDerivedType()); 7023 if (auto *prev{FindInScope(*scope, name.source)}) { 7024 std::optional<parser::MessageFixedText> msg; 7025 std::optional<common::UsageWarning> warning; 7026 if (context().HasError(*prev)) { // don't pile on 7027 } else if (extends) { 7028 msg = "Type cannot be extended as it has a component named" 7029 " '%s'"_err_en_US; 7030 } else if (CheckAccessibleSymbol(currScope(), *prev)) { 7031 // inaccessible component -- redeclaration is ok 7032 if (context().ShouldWarn( 7033 common::UsageWarning::RedeclaredInaccessibleComponent)) { 7034 msg = 7035 "Component '%s' is inaccessibly declared in or as a parent of this derived type"_warn_en_US; 7036 warning = common::UsageWarning::RedeclaredInaccessibleComponent; 7037 } 7038 } else if (prev->test(Symbol::Flag::ParentComp)) { 7039 msg = 7040 "'%s' is a parent type of this type and so cannot be a component"_err_en_US; 7041 } else if (scope == &currScope()) { 7042 msg = 7043 "Component '%s' is already declared in this derived type"_err_en_US; 7044 } else { 7045 msg = 7046 "Component '%s' is already declared in a parent of this derived type"_err_en_US; 7047 } 7048 if (msg) { 7049 auto &said{Say2(name, std::move(*msg), *prev, 7050 "Previous declaration of '%s'"_en_US)}; 7051 if (msg->severity() == parser::Severity::Error) { 7052 Resolve(name, *prev); 7053 return false; 7054 } 7055 if (warning) { 7056 said.set_usageWarning(*warning); 7057 } 7058 } 7059 } 7060 if (scope == &currScope() && extends) { 7061 // The parent component has not yet been added to the scope. 7062 scope = extends->scope(); 7063 } else { 7064 scope = scope->GetDerivedTypeParent(); 7065 } 7066 } 7067 return true; 7068 } 7069 7070 ParamValue DeclarationVisitor::GetParamValue( 7071 const parser::TypeParamValue &x, common::TypeParamAttr attr) { 7072 return common::visit( 7073 common::visitors{ 7074 [=](const parser::ScalarIntExpr &x) { // C704 7075 return ParamValue{EvaluateIntExpr(x), attr}; 7076 }, 7077 [=](const parser::Star &) { return ParamValue::Assumed(attr); }, 7078 [=](const parser::TypeParamValue::Deferred &) { 7079 return ParamValue::Deferred(attr); 7080 }, 7081 }, 7082 x.u); 7083 } 7084 7085 // ConstructVisitor implementation 7086 7087 void ConstructVisitor::ResolveIndexName( 7088 const parser::ConcurrentControl &control) { 7089 const parser::Name &name{std::get<parser::Name>(control.t)}; 7090 auto *prev{FindSymbol(name)}; 7091 if (prev) { 7092 if (prev->owner() == currScope()) { 7093 SayAlreadyDeclared(name, *prev); 7094 return; 7095 } else if (prev->owner().kind() == Scope::Kind::Forall && 7096 context().ShouldWarn( 7097 common::LanguageFeature::OddIndexVariableRestrictions)) { 7098 SayWithDecl(name, *prev, 7099 "Index variable '%s' should not also be an index in an enclosing FORALL or DO CONCURRENT"_port_en_US) 7100 .set_languageFeature( 7101 common::LanguageFeature::OddIndexVariableRestrictions); 7102 } 7103 name.symbol = nullptr; 7104 } 7105 auto &symbol{DeclareObjectEntity(name)}; 7106 if (symbol.GetType()) { 7107 // type came from explicit type-spec 7108 } else if (!prev) { 7109 ApplyImplicitRules(symbol); 7110 } else { 7111 // Odd rules in F'2023 19.4 paras 6 & 8. 7112 Symbol &prevRoot{prev->GetUltimate()}; 7113 if (const auto *type{prevRoot.GetType()}) { 7114 symbol.SetType(*type); 7115 } else { 7116 ApplyImplicitRules(symbol); 7117 } 7118 if (prevRoot.has<ObjectEntityDetails>() || 7119 ConvertToObjectEntity(prevRoot)) { 7120 if (prevRoot.IsObjectArray() && 7121 context().ShouldWarn( 7122 common::LanguageFeature::OddIndexVariableRestrictions)) { 7123 SayWithDecl(name, *prev, 7124 "Index variable '%s' should be scalar in the enclosing scope"_port_en_US) 7125 .set_languageFeature( 7126 common::LanguageFeature::OddIndexVariableRestrictions); 7127 } 7128 } else if (!prevRoot.has<CommonBlockDetails>() && 7129 context().ShouldWarn( 7130 common::LanguageFeature::OddIndexVariableRestrictions)) { 7131 SayWithDecl(name, *prev, 7132 "Index variable '%s' should be a scalar object or common block if it is present in the enclosing scope"_port_en_US) 7133 .set_languageFeature( 7134 common::LanguageFeature::OddIndexVariableRestrictions); 7135 } 7136 } 7137 EvaluateExpr(parser::Scalar{parser::Integer{common::Clone(name)}}); 7138 } 7139 7140 // We need to make sure that all of the index-names get declared before the 7141 // expressions in the loop control are evaluated so that references to the 7142 // index-names in the expressions are correctly detected. 7143 bool ConstructVisitor::Pre(const parser::ConcurrentHeader &header) { 7144 BeginDeclTypeSpec(); 7145 Walk(std::get<std::optional<parser::IntegerTypeSpec>>(header.t)); 7146 const auto &controls{ 7147 std::get<std::list<parser::ConcurrentControl>>(header.t)}; 7148 for (const auto &control : controls) { 7149 ResolveIndexName(control); 7150 } 7151 Walk(controls); 7152 Walk(std::get<std::optional<parser::ScalarLogicalExpr>>(header.t)); 7153 EndDeclTypeSpec(); 7154 return false; 7155 } 7156 7157 bool ConstructVisitor::Pre(const parser::LocalitySpec::Local &x) { 7158 for (auto &name : x.v) { 7159 DeclareLocalEntity(name, Symbol::Flag::LocalityLocal); 7160 } 7161 return false; 7162 } 7163 7164 bool ConstructVisitor::Pre(const parser::LocalitySpec::LocalInit &x) { 7165 for (auto &name : x.v) { 7166 DeclareLocalEntity(name, Symbol::Flag::LocalityLocalInit); 7167 } 7168 return false; 7169 } 7170 7171 bool ConstructVisitor::Pre(const parser::LocalitySpec::Reduce &x) { 7172 for (const auto &name : std::get<std::list<parser::Name>>(x.t)) { 7173 DeclareLocalEntity(name, Symbol::Flag::LocalityReduce); 7174 } 7175 return false; 7176 } 7177 7178 bool ConstructVisitor::Pre(const parser::LocalitySpec::Shared &x) { 7179 for (const auto &name : x.v) { 7180 if (!FindSymbol(name)) { 7181 context().Warn(common::UsageWarning::ImplicitShared, name.source, 7182 "Variable '%s' with SHARED locality implicitly declared"_warn_en_US, 7183 name.source); 7184 } 7185 Symbol &prev{FindOrDeclareEnclosingEntity(name)}; 7186 if (PassesSharedLocalityChecks(name, prev)) { 7187 MakeHostAssocSymbol(name, prev).set(Symbol::Flag::LocalityShared); 7188 } 7189 } 7190 return false; 7191 } 7192 7193 bool ConstructVisitor::Pre(const parser::AcSpec &x) { 7194 ProcessTypeSpec(x.type); 7195 Walk(x.values); 7196 return false; 7197 } 7198 7199 // Section 19.4, paragraph 5 says that each ac-do-variable has the scope of the 7200 // enclosing ac-implied-do 7201 bool ConstructVisitor::Pre(const parser::AcImpliedDo &x) { 7202 auto &values{std::get<std::list<parser::AcValue>>(x.t)}; 7203 auto &control{std::get<parser::AcImpliedDoControl>(x.t)}; 7204 auto &type{std::get<std::optional<parser::IntegerTypeSpec>>(control.t)}; 7205 auto &bounds{std::get<parser::AcImpliedDoControl::Bounds>(control.t)}; 7206 // F'2018 has the scope of the implied DO variable covering the entire 7207 // implied DO production (19.4(5)), which seems wrong in cases where the name 7208 // of the implied DO variable appears in one of the bound expressions. Thus 7209 // this extension, which shrinks the scope of the variable to exclude the 7210 // expressions in the bounds. 7211 auto restore{BeginCheckOnIndexUseInOwnBounds(bounds.name)}; 7212 Walk(bounds.lower); 7213 Walk(bounds.upper); 7214 Walk(bounds.step); 7215 EndCheckOnIndexUseInOwnBounds(restore); 7216 PushScope(Scope::Kind::ImpliedDos, nullptr); 7217 DeclareStatementEntity(bounds.name, type); 7218 Walk(values); 7219 PopScope(); 7220 return false; 7221 } 7222 7223 bool ConstructVisitor::Pre(const parser::DataImpliedDo &x) { 7224 auto &objects{std::get<std::list<parser::DataIDoObject>>(x.t)}; 7225 auto &type{std::get<std::optional<parser::IntegerTypeSpec>>(x.t)}; 7226 auto &bounds{std::get<parser::DataImpliedDo::Bounds>(x.t)}; 7227 // See comment in Pre(AcImpliedDo) above. 7228 auto restore{BeginCheckOnIndexUseInOwnBounds(bounds.name)}; 7229 Walk(bounds.lower); 7230 Walk(bounds.upper); 7231 Walk(bounds.step); 7232 EndCheckOnIndexUseInOwnBounds(restore); 7233 bool pushScope{currScope().kind() != Scope::Kind::ImpliedDos}; 7234 if (pushScope) { 7235 PushScope(Scope::Kind::ImpliedDos, nullptr); 7236 } 7237 DeclareStatementEntity(bounds.name, type); 7238 Walk(objects); 7239 if (pushScope) { 7240 PopScope(); 7241 } 7242 return false; 7243 } 7244 7245 // Sets InDataStmt flag on a variable (or misidentified function) in a DATA 7246 // statement so that the predicate IsInitialized() will be true 7247 // during semantic analysis before the symbol's initializer is constructed. 7248 bool ConstructVisitor::Pre(const parser::DataIDoObject &x) { 7249 common::visit( 7250 common::visitors{ 7251 [&](const parser::Scalar<Indirection<parser::Designator>> &y) { 7252 Walk(y.thing.value()); 7253 const parser::Name &first{parser::GetFirstName(y.thing.value())}; 7254 if (first.symbol) { 7255 first.symbol->set(Symbol::Flag::InDataStmt); 7256 } 7257 }, 7258 [&](const Indirection<parser::DataImpliedDo> &y) { Walk(y.value()); }, 7259 }, 7260 x.u); 7261 return false; 7262 } 7263 7264 bool ConstructVisitor::Pre(const parser::DataStmtObject &x) { 7265 // Subtle: DATA statements may appear in both the specification and 7266 // execution parts, but should be treated as if in the execution part 7267 // for purposes of implicit variable declaration vs. host association. 7268 // When a name first appears as an object in a DATA statement, it should 7269 // be implicitly declared locally as if it had been assigned. 7270 auto flagRestorer{common::ScopedSet(inSpecificationPart_, false)}; 7271 common::visit( 7272 common::visitors{ 7273 [&](const Indirection<parser::Variable> &y) { 7274 auto restorer{common::ScopedSet(deferImplicitTyping_, true)}; 7275 Walk(y.value()); 7276 const parser::Name &first{parser::GetFirstName(y.value())}; 7277 if (first.symbol) { 7278 first.symbol->set(Symbol::Flag::InDataStmt); 7279 } 7280 }, 7281 [&](const parser::DataImpliedDo &y) { 7282 PushScope(Scope::Kind::ImpliedDos, nullptr); 7283 Walk(y); 7284 PopScope(); 7285 }, 7286 }, 7287 x.u); 7288 return false; 7289 } 7290 7291 bool ConstructVisitor::Pre(const parser::DataStmtValue &x) { 7292 const auto &data{std::get<parser::DataStmtConstant>(x.t)}; 7293 auto &mutableData{const_cast<parser::DataStmtConstant &>(data)}; 7294 if (auto *elem{parser::Unwrap<parser::ArrayElement>(mutableData)}) { 7295 if (const auto *name{std::get_if<parser::Name>(&elem->base.u)}) { 7296 if (const Symbol * symbol{FindSymbol(*name)}; 7297 symbol && symbol->GetUltimate().has<DerivedTypeDetails>()) { 7298 mutableData.u = elem->ConvertToStructureConstructor( 7299 DerivedTypeSpec{name->source, *symbol}); 7300 } 7301 } 7302 } 7303 return true; 7304 } 7305 7306 bool ConstructVisitor::Pre(const parser::DoConstruct &x) { 7307 if (x.IsDoConcurrent()) { 7308 // The new scope has Kind::Forall for index variable name conflict 7309 // detection with nested FORALL/DO CONCURRENT constructs in 7310 // ResolveIndexName(). 7311 PushScope(Scope::Kind::Forall, nullptr); 7312 } 7313 return true; 7314 } 7315 void ConstructVisitor::Post(const parser::DoConstruct &x) { 7316 if (x.IsDoConcurrent()) { 7317 PopScope(); 7318 } 7319 } 7320 7321 bool ConstructVisitor::Pre(const parser::ForallConstruct &) { 7322 PushScope(Scope::Kind::Forall, nullptr); 7323 return true; 7324 } 7325 void ConstructVisitor::Post(const parser::ForallConstruct &) { PopScope(); } 7326 bool ConstructVisitor::Pre(const parser::ForallStmt &) { 7327 PushScope(Scope::Kind::Forall, nullptr); 7328 return true; 7329 } 7330 void ConstructVisitor::Post(const parser::ForallStmt &) { PopScope(); } 7331 7332 bool ConstructVisitor::Pre(const parser::BlockConstruct &x) { 7333 const auto &[blockStmt, specPart, execPart, endBlockStmt] = x.t; 7334 Walk(blockStmt); 7335 CheckDef(blockStmt.statement.v); 7336 PushScope(Scope::Kind::BlockConstruct, nullptr); 7337 Walk(specPart); 7338 HandleImpliedAsynchronousInScope(execPart); 7339 Walk(execPart); 7340 Walk(endBlockStmt); 7341 PopScope(); 7342 CheckRef(endBlockStmt.statement.v); 7343 return false; 7344 } 7345 7346 void ConstructVisitor::Post(const parser::Selector &x) { 7347 GetCurrentAssociation().selector = ResolveSelector(x); 7348 } 7349 7350 void ConstructVisitor::Post(const parser::AssociateStmt &x) { 7351 CheckDef(x.t); 7352 PushScope(Scope::Kind::OtherConstruct, nullptr); 7353 const auto assocCount{std::get<std::list<parser::Association>>(x.t).size()}; 7354 for (auto nthLastAssoc{assocCount}; nthLastAssoc > 0; --nthLastAssoc) { 7355 SetCurrentAssociation(nthLastAssoc); 7356 if (auto *symbol{MakeAssocEntity()}) { 7357 const MaybeExpr &expr{GetCurrentAssociation().selector.expr}; 7358 if (ExtractCoarrayRef(expr)) { // C1103 7359 Say("Selector must not be a coindexed object"_err_en_US); 7360 } 7361 if (evaluate::IsAssumedRank(expr)) { 7362 Say("Selector must not be assumed-rank"_err_en_US); 7363 } 7364 SetTypeFromAssociation(*symbol); 7365 SetAttrsFromAssociation(*symbol); 7366 } 7367 } 7368 PopAssociation(assocCount); 7369 } 7370 7371 void ConstructVisitor::Post(const parser::EndAssociateStmt &x) { 7372 PopScope(); 7373 CheckRef(x.v); 7374 } 7375 7376 bool ConstructVisitor::Pre(const parser::Association &x) { 7377 PushAssociation(); 7378 const auto &name{std::get<parser::Name>(x.t)}; 7379 GetCurrentAssociation().name = &name; 7380 return true; 7381 } 7382 7383 bool ConstructVisitor::Pre(const parser::ChangeTeamStmt &x) { 7384 CheckDef(x.t); 7385 PushScope(Scope::Kind::OtherConstruct, nullptr); 7386 PushAssociation(); 7387 return true; 7388 } 7389 7390 void ConstructVisitor::Post(const parser::CoarrayAssociation &x) { 7391 const auto &decl{std::get<parser::CodimensionDecl>(x.t)}; 7392 const auto &name{std::get<parser::Name>(decl.t)}; 7393 if (auto *symbol{FindInScope(name)}) { 7394 const auto &selector{std::get<parser::Selector>(x.t)}; 7395 if (auto sel{ResolveSelector(selector)}) { 7396 const Symbol *whole{UnwrapWholeSymbolDataRef(sel.expr)}; 7397 if (!whole || whole->Corank() == 0) { 7398 Say(sel.source, // C1116 7399 "Selector in coarray association must name a coarray"_err_en_US); 7400 } else if (auto dynType{sel.expr->GetType()}) { 7401 if (!symbol->GetType()) { 7402 symbol->SetType(ToDeclTypeSpec(std::move(*dynType))); 7403 } 7404 } 7405 } 7406 } 7407 } 7408 7409 void ConstructVisitor::Post(const parser::EndChangeTeamStmt &x) { 7410 PopAssociation(); 7411 PopScope(); 7412 CheckRef(x.t); 7413 } 7414 7415 bool ConstructVisitor::Pre(const parser::SelectTypeConstruct &) { 7416 PushAssociation(); 7417 return true; 7418 } 7419 7420 void ConstructVisitor::Post(const parser::SelectTypeConstruct &) { 7421 PopAssociation(); 7422 } 7423 7424 void ConstructVisitor::Post(const parser::SelectTypeStmt &x) { 7425 auto &association{GetCurrentAssociation()}; 7426 if (const std::optional<parser::Name> &name{std::get<1>(x.t)}) { 7427 // This isn't a name in the current scope, it is in each TypeGuardStmt 7428 MakePlaceholder(*name, MiscDetails::Kind::SelectTypeAssociateName); 7429 association.name = &*name; 7430 if (ExtractCoarrayRef(association.selector.expr)) { // C1103 7431 Say("Selector must not be a coindexed object"_err_en_US); 7432 } 7433 if (association.selector.expr) { 7434 auto exprType{association.selector.expr->GetType()}; 7435 if (exprType && !exprType->IsPolymorphic()) { // C1159 7436 Say(association.selector.source, 7437 "Selector '%s' in SELECT TYPE statement must be " 7438 "polymorphic"_err_en_US); 7439 } 7440 } 7441 } else { 7442 if (const Symbol * 7443 whole{UnwrapWholeSymbolDataRef(association.selector.expr)}) { 7444 ConvertToObjectEntity(const_cast<Symbol &>(*whole)); 7445 if (!IsVariableName(*whole)) { 7446 Say(association.selector.source, // C901 7447 "Selector is not a variable"_err_en_US); 7448 association = {}; 7449 } 7450 if (const DeclTypeSpec * type{whole->GetType()}) { 7451 if (!type->IsPolymorphic()) { // C1159 7452 Say(association.selector.source, 7453 "Selector '%s' in SELECT TYPE statement must be " 7454 "polymorphic"_err_en_US); 7455 } 7456 } 7457 } else { 7458 Say(association.selector.source, // C1157 7459 "Selector is not a named variable: 'associate-name =>' is required"_err_en_US); 7460 association = {}; 7461 } 7462 } 7463 } 7464 7465 void ConstructVisitor::Post(const parser::SelectRankStmt &x) { 7466 auto &association{GetCurrentAssociation()}; 7467 if (const std::optional<parser::Name> &name{std::get<1>(x.t)}) { 7468 // This isn't a name in the current scope, it is in each SelectRankCaseStmt 7469 MakePlaceholder(*name, MiscDetails::Kind::SelectRankAssociateName); 7470 association.name = &*name; 7471 } 7472 } 7473 7474 bool ConstructVisitor::Pre(const parser::SelectTypeConstruct::TypeCase &) { 7475 PushScope(Scope::Kind::OtherConstruct, nullptr); 7476 return true; 7477 } 7478 void ConstructVisitor::Post(const parser::SelectTypeConstruct::TypeCase &) { 7479 PopScope(); 7480 } 7481 7482 bool ConstructVisitor::Pre(const parser::SelectRankConstruct::RankCase &) { 7483 PushScope(Scope::Kind::OtherConstruct, nullptr); 7484 return true; 7485 } 7486 void ConstructVisitor::Post(const parser::SelectRankConstruct::RankCase &) { 7487 PopScope(); 7488 } 7489 7490 bool ConstructVisitor::Pre(const parser::TypeGuardStmt::Guard &x) { 7491 if (std::holds_alternative<parser::DerivedTypeSpec>(x.u)) { 7492 // CLASS IS (t) 7493 SetDeclTypeSpecCategory(DeclTypeSpec::Category::ClassDerived); 7494 } 7495 return true; 7496 } 7497 7498 void ConstructVisitor::Post(const parser::TypeGuardStmt::Guard &x) { 7499 if (auto *symbol{MakeAssocEntity()}) { 7500 if (std::holds_alternative<parser::Default>(x.u)) { 7501 SetTypeFromAssociation(*symbol); 7502 } else if (const auto *type{GetDeclTypeSpec()}) { 7503 symbol->SetType(*type); 7504 } 7505 SetAttrsFromAssociation(*symbol); 7506 } 7507 } 7508 7509 void ConstructVisitor::Post(const parser::SelectRankCaseStmt::Rank &x) { 7510 if (auto *symbol{MakeAssocEntity()}) { 7511 SetTypeFromAssociation(*symbol); 7512 auto &details{symbol->get<AssocEntityDetails>()}; 7513 // Don't call SetAttrsFromAssociation() for SELECT RANK. 7514 Attrs selectorAttrs{ 7515 evaluate::GetAttrs(GetCurrentAssociation().selector.expr)}; 7516 Attrs attrsToKeep{Attr::ASYNCHRONOUS, Attr::TARGET, Attr::VOLATILE}; 7517 if (const auto *rankValue{ 7518 std::get_if<parser::ScalarIntConstantExpr>(&x.u)}) { 7519 // RANK(n) 7520 if (auto expr{EvaluateIntExpr(*rankValue)}) { 7521 if (auto val{evaluate::ToInt64(*expr)}) { 7522 details.set_rank(*val); 7523 attrsToKeep |= Attrs{Attr::ALLOCATABLE, Attr::POINTER}; 7524 } else { 7525 Say("RANK() expression must be constant"_err_en_US); 7526 } 7527 } 7528 } else if (std::holds_alternative<parser::Star>(x.u)) { 7529 // RANK(*): assumed-size 7530 details.set_IsAssumedSize(); 7531 } else { 7532 CHECK(std::holds_alternative<parser::Default>(x.u)); 7533 // RANK DEFAULT: assumed-rank 7534 details.set_IsAssumedRank(); 7535 attrsToKeep |= Attrs{Attr::ALLOCATABLE, Attr::POINTER}; 7536 } 7537 symbol->attrs() |= selectorAttrs & attrsToKeep; 7538 } 7539 } 7540 7541 bool ConstructVisitor::Pre(const parser::SelectRankConstruct &) { 7542 PushAssociation(); 7543 return true; 7544 } 7545 7546 void ConstructVisitor::Post(const parser::SelectRankConstruct &) { 7547 PopAssociation(); 7548 } 7549 7550 bool ConstructVisitor::CheckDef(const std::optional<parser::Name> &x) { 7551 if (x && !x->symbol) { 7552 // Construct names are not scoped by BLOCK in the standard, but many, 7553 // but not all, compilers do treat them as if they were so scoped. 7554 if (Symbol * inner{FindInScope(currScope(), *x)}) { 7555 SayAlreadyDeclared(*x, *inner); 7556 } else { 7557 if (context().ShouldWarn(common::LanguageFeature::BenignNameClash)) { 7558 if (Symbol * 7559 other{FindInScopeOrBlockConstructs(InclusiveScope(), x->source)}) { 7560 SayWithDecl(*x, *other, 7561 "The construct name '%s' should be distinct at the subprogram level"_port_en_US) 7562 .set_languageFeature(common::LanguageFeature::BenignNameClash); 7563 } 7564 } 7565 MakeSymbol(*x, MiscDetails{MiscDetails::Kind::ConstructName}); 7566 } 7567 } 7568 return true; 7569 } 7570 7571 void ConstructVisitor::CheckRef(const std::optional<parser::Name> &x) { 7572 if (x) { 7573 // Just add an occurrence of this name; checking is done in ValidateLabels 7574 FindSymbol(*x); 7575 } 7576 } 7577 7578 // Make a symbol for the associating entity of the current association. 7579 Symbol *ConstructVisitor::MakeAssocEntity() { 7580 Symbol *symbol{nullptr}; 7581 auto &association{GetCurrentAssociation()}; 7582 if (association.name) { 7583 symbol = &MakeSymbol(*association.name, UnknownDetails{}); 7584 if (symbol->has<AssocEntityDetails>() && symbol->owner() == currScope()) { 7585 Say(*association.name, // C1102 7586 "The associate name '%s' is already used in this associate statement"_err_en_US); 7587 return nullptr; 7588 } 7589 } else if (const Symbol * 7590 whole{UnwrapWholeSymbolDataRef(association.selector.expr)}) { 7591 symbol = &MakeSymbol(whole->name()); 7592 } else { 7593 return nullptr; 7594 } 7595 if (auto &expr{association.selector.expr}) { 7596 symbol->set_details(AssocEntityDetails{common::Clone(*expr)}); 7597 } else { 7598 symbol->set_details(AssocEntityDetails{}); 7599 } 7600 return symbol; 7601 } 7602 7603 // Set the type of symbol based on the current association selector. 7604 void ConstructVisitor::SetTypeFromAssociation(Symbol &symbol) { 7605 auto &details{symbol.get<AssocEntityDetails>()}; 7606 const MaybeExpr *pexpr{&details.expr()}; 7607 if (!*pexpr) { 7608 pexpr = &GetCurrentAssociation().selector.expr; 7609 } 7610 if (*pexpr) { 7611 const SomeExpr &expr{**pexpr}; 7612 if (std::optional<evaluate::DynamicType> type{expr.GetType()}) { 7613 if (const auto *charExpr{ 7614 evaluate::UnwrapExpr<evaluate::Expr<evaluate::SomeCharacter>>( 7615 expr)}) { 7616 symbol.SetType(ToDeclTypeSpec(std::move(*type), 7617 FoldExpr(common::visit( 7618 [](const auto &kindChar) { return kindChar.LEN(); }, 7619 charExpr->u)))); 7620 } else { 7621 symbol.SetType(ToDeclTypeSpec(std::move(*type))); 7622 } 7623 } else { 7624 // BOZ literals, procedure designators, &c. are not acceptable 7625 Say(symbol.name(), "Associate name '%s' must have a type"_err_en_US); 7626 } 7627 } 7628 } 7629 7630 // If current selector is a variable, set some of its attributes on symbol. 7631 // For ASSOCIATE, CHANGE TEAM, and SELECT TYPE only; not SELECT RANK. 7632 void ConstructVisitor::SetAttrsFromAssociation(Symbol &symbol) { 7633 Attrs attrs{evaluate::GetAttrs(GetCurrentAssociation().selector.expr)}; 7634 symbol.attrs() |= 7635 attrs & Attrs{Attr::TARGET, Attr::ASYNCHRONOUS, Attr::VOLATILE}; 7636 if (attrs.test(Attr::POINTER)) { 7637 SetImplicitAttr(symbol, Attr::TARGET); 7638 } 7639 } 7640 7641 ConstructVisitor::Selector ConstructVisitor::ResolveSelector( 7642 const parser::Selector &x) { 7643 return common::visit(common::visitors{ 7644 [&](const parser::Expr &expr) { 7645 return Selector{expr.source, EvaluateExpr(x)}; 7646 }, 7647 [&](const parser::Variable &var) { 7648 return Selector{var.GetSource(), EvaluateExpr(x)}; 7649 }, 7650 }, 7651 x.u); 7652 } 7653 7654 // Set the current association to the nth to the last association on the 7655 // association stack. The top of the stack is at n = 1. This allows access 7656 // to the interior of a list of associations at the top of the stack. 7657 void ConstructVisitor::SetCurrentAssociation(std::size_t n) { 7658 CHECK(n > 0 && n <= associationStack_.size()); 7659 currentAssociation_ = &associationStack_[associationStack_.size() - n]; 7660 } 7661 7662 ConstructVisitor::Association &ConstructVisitor::GetCurrentAssociation() { 7663 CHECK(currentAssociation_); 7664 return *currentAssociation_; 7665 } 7666 7667 void ConstructVisitor::PushAssociation() { 7668 associationStack_.emplace_back(Association{}); 7669 currentAssociation_ = &associationStack_.back(); 7670 } 7671 7672 void ConstructVisitor::PopAssociation(std::size_t count) { 7673 CHECK(count > 0 && count <= associationStack_.size()); 7674 associationStack_.resize(associationStack_.size() - count); 7675 currentAssociation_ = 7676 associationStack_.empty() ? nullptr : &associationStack_.back(); 7677 } 7678 7679 const DeclTypeSpec &ConstructVisitor::ToDeclTypeSpec( 7680 evaluate::DynamicType &&type) { 7681 switch (type.category()) { 7682 SWITCH_COVERS_ALL_CASES 7683 case common::TypeCategory::Integer: 7684 case common::TypeCategory::Unsigned: 7685 case common::TypeCategory::Real: 7686 case common::TypeCategory::Complex: 7687 return context().MakeNumericType(type.category(), type.kind()); 7688 case common::TypeCategory::Logical: 7689 return context().MakeLogicalType(type.kind()); 7690 case common::TypeCategory::Derived: 7691 if (type.IsAssumedType()) { 7692 return currScope().MakeTypeStarType(); 7693 } else if (type.IsUnlimitedPolymorphic()) { 7694 return currScope().MakeClassStarType(); 7695 } else { 7696 return currScope().MakeDerivedType( 7697 type.IsPolymorphic() ? DeclTypeSpec::ClassDerived 7698 : DeclTypeSpec::TypeDerived, 7699 common::Clone(type.GetDerivedTypeSpec()) 7700 7701 ); 7702 } 7703 case common::TypeCategory::Character: 7704 CRASH_NO_CASE; 7705 } 7706 } 7707 7708 const DeclTypeSpec &ConstructVisitor::ToDeclTypeSpec( 7709 evaluate::DynamicType &&type, MaybeSubscriptIntExpr &&length) { 7710 CHECK(type.category() == common::TypeCategory::Character); 7711 if (length) { 7712 return currScope().MakeCharacterType( 7713 ParamValue{SomeIntExpr{*std::move(length)}, common::TypeParamAttr::Len}, 7714 KindExpr{type.kind()}); 7715 } else { 7716 return currScope().MakeCharacterType( 7717 ParamValue::Deferred(common::TypeParamAttr::Len), 7718 KindExpr{type.kind()}); 7719 } 7720 } 7721 7722 class ExecutionPartSkimmerBase { 7723 public: 7724 template <typename A> bool Pre(const A &) { return true; } 7725 template <typename A> void Post(const A &) {} 7726 7727 bool InNestedBlockConstruct() const { return blockDepth_ > 0; } 7728 7729 bool Pre(const parser::AssociateConstruct &) { 7730 PushScope(); 7731 return true; 7732 } 7733 void Post(const parser::AssociateConstruct &) { PopScope(); } 7734 bool Pre(const parser::Association &x) { 7735 Hide(std::get<parser::Name>(x.t)); 7736 return true; 7737 } 7738 bool Pre(const parser::BlockConstruct &) { 7739 PushScope(); 7740 ++blockDepth_; 7741 return true; 7742 } 7743 void Post(const parser::BlockConstruct &) { 7744 --blockDepth_; 7745 PopScope(); 7746 } 7747 // Note declarations of local names in BLOCK constructs. 7748 // Don't have to worry about INTENT(), VALUE, or OPTIONAL 7749 // (pertinent only to dummy arguments), ASYNCHRONOUS/VOLATILE, 7750 // or accessibility attributes, 7751 bool Pre(const parser::EntityDecl &x) { 7752 Hide(std::get<parser::ObjectName>(x.t)); 7753 return true; 7754 } 7755 bool Pre(const parser::ObjectDecl &x) { 7756 Hide(std::get<parser::ObjectName>(x.t)); 7757 return true; 7758 } 7759 bool Pre(const parser::PointerDecl &x) { 7760 Hide(std::get<parser::Name>(x.t)); 7761 return true; 7762 } 7763 bool Pre(const parser::BindEntity &x) { 7764 Hide(std::get<parser::Name>(x.t)); 7765 return true; 7766 } 7767 bool Pre(const parser::ContiguousStmt &x) { 7768 for (const parser::Name &name : x.v) { 7769 Hide(name); 7770 } 7771 return true; 7772 } 7773 bool Pre(const parser::DimensionStmt::Declaration &x) { 7774 Hide(std::get<parser::Name>(x.t)); 7775 return true; 7776 } 7777 bool Pre(const parser::ExternalStmt &x) { 7778 for (const parser::Name &name : x.v) { 7779 Hide(name); 7780 } 7781 return true; 7782 } 7783 bool Pre(const parser::IntrinsicStmt &x) { 7784 for (const parser::Name &name : x.v) { 7785 Hide(name); 7786 } 7787 return true; 7788 } 7789 bool Pre(const parser::CodimensionStmt &x) { 7790 for (const parser::CodimensionDecl &decl : x.v) { 7791 Hide(std::get<parser::Name>(decl.t)); 7792 } 7793 return true; 7794 } 7795 void Post(const parser::ImportStmt &x) { 7796 if (x.kind == common::ImportKind::None || 7797 x.kind == common::ImportKind::Only) { 7798 if (!nestedScopes_.front().importOnly.has_value()) { 7799 nestedScopes_.front().importOnly.emplace(); 7800 } 7801 for (const auto &name : x.names) { 7802 nestedScopes_.front().importOnly->emplace(name.source); 7803 } 7804 } else { 7805 // no special handling needed for explicit names or IMPORT, ALL 7806 } 7807 } 7808 void Post(const parser::UseStmt &x) { 7809 if (const auto *onlyList{std::get_if<std::list<parser::Only>>(&x.u)}) { 7810 for (const auto &only : *onlyList) { 7811 if (const auto *name{std::get_if<parser::Name>(&only.u)}) { 7812 Hide(*name); 7813 } else if (const auto *rename{std::get_if<parser::Rename>(&only.u)}) { 7814 if (const auto *names{ 7815 std::get_if<parser::Rename::Names>(&rename->u)}) { 7816 Hide(std::get<0>(names->t)); 7817 } 7818 } 7819 } 7820 } else { 7821 // USE may or may not shadow symbols in host scopes 7822 nestedScopes_.front().hasUseWithoutOnly = true; 7823 } 7824 } 7825 bool Pre(const parser::DerivedTypeStmt &x) { 7826 Hide(std::get<parser::Name>(x.t)); 7827 PushScope(); 7828 return true; 7829 } 7830 void Post(const parser::DerivedTypeDef &) { PopScope(); } 7831 bool Pre(const parser::SelectTypeConstruct &) { 7832 PushScope(); 7833 return true; 7834 } 7835 void Post(const parser::SelectTypeConstruct &) { PopScope(); } 7836 bool Pre(const parser::SelectTypeStmt &x) { 7837 if (const auto &maybeName{std::get<1>(x.t)}) { 7838 Hide(*maybeName); 7839 } 7840 return true; 7841 } 7842 bool Pre(const parser::SelectRankConstruct &) { 7843 PushScope(); 7844 return true; 7845 } 7846 void Post(const parser::SelectRankConstruct &) { PopScope(); } 7847 bool Pre(const parser::SelectRankStmt &x) { 7848 if (const auto &maybeName{std::get<1>(x.t)}) { 7849 Hide(*maybeName); 7850 } 7851 return true; 7852 } 7853 7854 // Iterator-modifiers contain variable declarations, and do introduce 7855 // a new scope. These variables can only have integer types, and their 7856 // scope only extends until the end of the clause. A potential alternative 7857 // to the code below may be to ignore OpenMP clauses, but it's not clear 7858 // if OMP-specific checks can be avoided altogether. 7859 bool Pre(const parser::OmpClause &x) { 7860 if (OmpVisitor::NeedsScope(x)) { 7861 PushScope(); 7862 } 7863 return true; 7864 } 7865 void Post(const parser::OmpClause &x) { 7866 if (OmpVisitor::NeedsScope(x)) { 7867 PopScope(); 7868 } 7869 } 7870 7871 protected: 7872 bool IsHidden(SourceName name) { 7873 for (const auto &scope : nestedScopes_) { 7874 if (scope.locals.find(name) != scope.locals.end()) { 7875 return true; // shadowed by nested declaration 7876 } 7877 if (scope.hasUseWithoutOnly) { 7878 break; 7879 } 7880 if (scope.importOnly && 7881 scope.importOnly->find(name) == scope.importOnly->end()) { 7882 return true; // not imported 7883 } 7884 } 7885 return false; 7886 } 7887 7888 void EndWalk() { CHECK(nestedScopes_.empty()); } 7889 7890 private: 7891 void PushScope() { nestedScopes_.emplace_front(); } 7892 void PopScope() { nestedScopes_.pop_front(); } 7893 void Hide(const parser::Name &name) { 7894 nestedScopes_.front().locals.emplace(name.source); 7895 } 7896 7897 int blockDepth_{0}; 7898 struct NestedScopeInfo { 7899 bool hasUseWithoutOnly{false}; 7900 std::set<SourceName> locals; 7901 std::optional<std::set<SourceName>> importOnly; 7902 }; 7903 std::list<NestedScopeInfo> nestedScopes_; 7904 }; 7905 7906 class ExecutionPartAsyncIOSkimmer : public ExecutionPartSkimmerBase { 7907 public: 7908 explicit ExecutionPartAsyncIOSkimmer(SemanticsContext &context) 7909 : context_{context} {} 7910 7911 void Walk(const parser::Block &block) { 7912 parser::Walk(block, *this); 7913 EndWalk(); 7914 } 7915 7916 const std::set<SourceName> asyncIONames() const { return asyncIONames_; } 7917 7918 using ExecutionPartSkimmerBase::Post; 7919 using ExecutionPartSkimmerBase::Pre; 7920 7921 bool Pre(const parser::IoControlSpec::Asynchronous &async) { 7922 if (auto folded{evaluate::Fold( 7923 context_.foldingContext(), AnalyzeExpr(context_, async.v))}) { 7924 if (auto str{ 7925 evaluate::GetScalarConstantValue<evaluate::Ascii>(*folded)}) { 7926 for (char ch : *str) { 7927 if (ch != ' ') { 7928 inAsyncIO_ = ch == 'y' || ch == 'Y'; 7929 break; 7930 } 7931 } 7932 } 7933 } 7934 return true; 7935 } 7936 void Post(const parser::ReadStmt &) { inAsyncIO_ = false; } 7937 void Post(const parser::WriteStmt &) { inAsyncIO_ = false; } 7938 void Post(const parser::IoControlSpec::Size &size) { 7939 if (const auto *designator{ 7940 std::get_if<common::Indirection<parser::Designator>>( 7941 &size.v.thing.thing.u)}) { 7942 NoteAsyncIODesignator(designator->value()); 7943 } 7944 } 7945 void Post(const parser::InputItem &x) { 7946 if (const auto *var{std::get_if<parser::Variable>(&x.u)}) { 7947 if (const auto *designator{ 7948 std::get_if<common::Indirection<parser::Designator>>(&var->u)}) { 7949 NoteAsyncIODesignator(designator->value()); 7950 } 7951 } 7952 } 7953 void Post(const parser::OutputItem &x) { 7954 if (const auto *expr{std::get_if<parser::Expr>(&x.u)}) { 7955 if (const auto *designator{ 7956 std::get_if<common::Indirection<parser::Designator>>(&expr->u)}) { 7957 NoteAsyncIODesignator(designator->value()); 7958 } 7959 } 7960 } 7961 7962 private: 7963 void NoteAsyncIODesignator(const parser::Designator &designator) { 7964 if (inAsyncIO_ && !InNestedBlockConstruct()) { 7965 const parser::Name &name{parser::GetFirstName(designator)}; 7966 if (!IsHidden(name.source)) { 7967 asyncIONames_.insert(name.source); 7968 } 7969 } 7970 } 7971 7972 SemanticsContext &context_; 7973 bool inAsyncIO_{false}; 7974 std::set<SourceName> asyncIONames_; 7975 }; 7976 7977 // Any data list item or SIZE= specifier of an I/O data transfer statement 7978 // with ASYNCHRONOUS="YES" implicitly has the ASYNCHRONOUS attribute in the 7979 // local scope. 7980 void ConstructVisitor::HandleImpliedAsynchronousInScope( 7981 const parser::Block &block) { 7982 ExecutionPartAsyncIOSkimmer skimmer{context()}; 7983 skimmer.Walk(block); 7984 for (auto name : skimmer.asyncIONames()) { 7985 if (Symbol * symbol{currScope().FindSymbol(name)}) { 7986 if (!symbol->attrs().test(Attr::ASYNCHRONOUS)) { 7987 if (&symbol->owner() != &currScope()) { 7988 symbol = &*currScope() 7989 .try_emplace(name, HostAssocDetails{*symbol}) 7990 .first->second; 7991 } 7992 if (symbol->has<AssocEntityDetails>()) { 7993 symbol = const_cast<Symbol *>(&GetAssociationRoot(*symbol)); 7994 } 7995 SetImplicitAttr(*symbol, Attr::ASYNCHRONOUS); 7996 } 7997 } 7998 } 7999 } 8000 8001 // ResolveNamesVisitor implementation 8002 8003 bool ResolveNamesVisitor::Pre(const parser::FunctionReference &x) { 8004 HandleCall(Symbol::Flag::Function, x.v); 8005 return false; 8006 } 8007 bool ResolveNamesVisitor::Pre(const parser::CallStmt &x) { 8008 HandleCall(Symbol::Flag::Subroutine, x.call); 8009 Walk(x.chevrons); 8010 return false; 8011 } 8012 8013 bool ResolveNamesVisitor::Pre(const parser::ImportStmt &x) { 8014 auto &scope{currScope()}; 8015 // Check C896 and C899: where IMPORT statements are allowed 8016 switch (scope.kind()) { 8017 case Scope::Kind::Module: 8018 if (scope.IsModule()) { 8019 Say("IMPORT is not allowed in a module scoping unit"_err_en_US); 8020 return false; 8021 } else if (x.kind == common::ImportKind::None) { 8022 Say("IMPORT,NONE is not allowed in a submodule scoping unit"_err_en_US); 8023 return false; 8024 } 8025 break; 8026 case Scope::Kind::MainProgram: 8027 Say("IMPORT is not allowed in a main program scoping unit"_err_en_US); 8028 return false; 8029 case Scope::Kind::Subprogram: 8030 if (scope.parent().IsGlobal()) { 8031 Say("IMPORT is not allowed in an external subprogram scoping unit"_err_en_US); 8032 return false; 8033 } 8034 break; 8035 case Scope::Kind::BlockData: // C1415 (in part) 8036 Say("IMPORT is not allowed in a BLOCK DATA subprogram"_err_en_US); 8037 return false; 8038 default:; 8039 } 8040 if (auto error{scope.SetImportKind(x.kind)}) { 8041 Say(std::move(*error)); 8042 } 8043 for (auto &name : x.names) { 8044 if (Symbol * outer{FindSymbol(scope.parent(), name)}) { 8045 scope.add_importName(name.source); 8046 if (Symbol * symbol{FindInScope(name)}) { 8047 if (outer->GetUltimate() == symbol->GetUltimate()) { 8048 context().Warn(common::LanguageFeature::BenignNameClash, name.source, 8049 "The same '%s' is already present in this scope"_port_en_US, 8050 name.source); 8051 } else { 8052 Say(name, 8053 "A distinct '%s' is already present in this scope"_err_en_US) 8054 .Attach(symbol->name(), "Previous declaration of '%s'"_en_US) 8055 .Attach(outer->name(), "Declaration of '%s' in host scope"_en_US); 8056 } 8057 } 8058 } else { 8059 Say(name, "'%s' not found in host scope"_err_en_US); 8060 } 8061 } 8062 prevImportStmt_ = currStmtSource(); 8063 return false; 8064 } 8065 8066 const parser::Name *DeclarationVisitor::ResolveStructureComponent( 8067 const parser::StructureComponent &x) { 8068 return FindComponent(ResolveDataRef(x.base), x.component); 8069 } 8070 8071 const parser::Name *DeclarationVisitor::ResolveDesignator( 8072 const parser::Designator &x) { 8073 return common::visit( 8074 common::visitors{ 8075 [&](const parser::DataRef &x) { return ResolveDataRef(x); }, 8076 [&](const parser::Substring &x) { 8077 Walk(std::get<parser::SubstringRange>(x.t).t); 8078 return ResolveDataRef(std::get<parser::DataRef>(x.t)); 8079 }, 8080 }, 8081 x.u); 8082 } 8083 8084 const parser::Name *DeclarationVisitor::ResolveDataRef( 8085 const parser::DataRef &x) { 8086 return common::visit( 8087 common::visitors{ 8088 [=](const parser::Name &y) { return ResolveName(y); }, 8089 [=](const Indirection<parser::StructureComponent> &y) { 8090 return ResolveStructureComponent(y.value()); 8091 }, 8092 [&](const Indirection<parser::ArrayElement> &y) { 8093 Walk(y.value().subscripts); 8094 const parser::Name *name{ResolveDataRef(y.value().base)}; 8095 if (name && name->symbol) { 8096 if (!IsProcedure(*name->symbol)) { 8097 ConvertToObjectEntity(*name->symbol); 8098 } else if (!context().HasError(*name->symbol)) { 8099 SayWithDecl(*name, *name->symbol, 8100 "Cannot reference function '%s' as data"_err_en_US); 8101 context().SetError(*name->symbol); 8102 } 8103 } 8104 return name; 8105 }, 8106 [&](const Indirection<parser::CoindexedNamedObject> &y) { 8107 Walk(y.value().imageSelector); 8108 return ResolveDataRef(y.value().base); 8109 }, 8110 }, 8111 x.u); 8112 } 8113 8114 // If implicit types are allowed, ensure name is in the symbol table. 8115 // Otherwise, report an error if it hasn't been declared. 8116 const parser::Name *DeclarationVisitor::ResolveName(const parser::Name &name) { 8117 FindSymbol(name); 8118 if (CheckForHostAssociatedImplicit(name)) { 8119 NotePossibleBadForwardRef(name); 8120 return &name; 8121 } 8122 if (Symbol * symbol{name.symbol}) { 8123 if (CheckUseError(name)) { 8124 return nullptr; // reported an error 8125 } 8126 NotePossibleBadForwardRef(name); 8127 symbol->set(Symbol::Flag::ImplicitOrError, false); 8128 if (IsUplevelReference(*symbol)) { 8129 MakeHostAssocSymbol(name, *symbol); 8130 } else if (IsDummy(*symbol) || 8131 (!symbol->GetType() && FindCommonBlockContaining(*symbol))) { 8132 CheckEntryDummyUse(name.source, symbol); 8133 ConvertToObjectEntity(*symbol); 8134 ApplyImplicitRules(*symbol); 8135 } else if (const auto *tpd{symbol->detailsIf<TypeParamDetails>()}; 8136 tpd && !tpd->attr()) { 8137 Say(name, 8138 "Type parameter '%s' was referenced before being declared"_err_en_US, 8139 name.source); 8140 context().SetError(*symbol); 8141 } 8142 if (checkIndexUseInOwnBounds_ && 8143 *checkIndexUseInOwnBounds_ == name.source && !InModuleFile()) { 8144 context().Warn(common::LanguageFeature::ImpliedDoIndexScope, name.source, 8145 "Implied DO index '%s' uses an object of the same name in its bounds expressions"_port_en_US, 8146 name.source); 8147 } 8148 return &name; 8149 } 8150 if (isImplicitNoneType() && !deferImplicitTyping_) { 8151 Say(name, "No explicit type declared for '%s'"_err_en_US); 8152 return nullptr; 8153 } 8154 // Create the symbol, then ensure that it is accessible 8155 if (checkIndexUseInOwnBounds_ && *checkIndexUseInOwnBounds_ == name.source) { 8156 Say(name, 8157 "Implied DO index '%s' uses itself in its own bounds expressions"_err_en_US, 8158 name.source); 8159 } 8160 MakeSymbol(InclusiveScope(), name.source, Attrs{}); 8161 auto *symbol{FindSymbol(name)}; 8162 if (!symbol) { 8163 Say(name, 8164 "'%s' from host scoping unit is not accessible due to IMPORT"_err_en_US); 8165 return nullptr; 8166 } 8167 ConvertToObjectEntity(*symbol); 8168 ApplyImplicitRules(*symbol); 8169 NotePossibleBadForwardRef(name); 8170 return &name; 8171 } 8172 8173 // A specification expression may refer to a symbol in the host procedure that 8174 // is implicitly typed. Because specification parts are processed before 8175 // execution parts, this may be the first time we see the symbol. It can't be a 8176 // local in the current scope (because it's in a specification expression) so 8177 // either it is implicitly declared in the host procedure or it is an error. 8178 // We create a symbol in the host assuming it is the former; if that proves to 8179 // be wrong we report an error later in CheckDeclarations(). 8180 bool DeclarationVisitor::CheckForHostAssociatedImplicit( 8181 const parser::Name &name) { 8182 if (!inSpecificationPart_ || inEquivalenceStmt_) { 8183 return false; 8184 } 8185 if (name.symbol) { 8186 ApplyImplicitRules(*name.symbol, true); 8187 } 8188 if (Scope * host{GetHostProcedure()}; host && !isImplicitNoneType(*host)) { 8189 Symbol *hostSymbol{nullptr}; 8190 if (!name.symbol) { 8191 if (currScope().CanImport(name.source)) { 8192 hostSymbol = &MakeSymbol(*host, name.source, Attrs{}); 8193 ConvertToObjectEntity(*hostSymbol); 8194 ApplyImplicitRules(*hostSymbol); 8195 hostSymbol->set(Symbol::Flag::ImplicitOrError); 8196 } 8197 } else if (name.symbol->test(Symbol::Flag::ImplicitOrError)) { 8198 hostSymbol = name.symbol; 8199 } 8200 if (hostSymbol) { 8201 Symbol &symbol{MakeHostAssocSymbol(name, *hostSymbol)}; 8202 if (auto *assoc{symbol.detailsIf<HostAssocDetails>()}) { 8203 if (isImplicitNoneType()) { 8204 assoc->implicitOrExplicitTypeError = true; 8205 } else { 8206 assoc->implicitOrSpecExprError = true; 8207 } 8208 return true; 8209 } 8210 } 8211 } 8212 return false; 8213 } 8214 8215 bool DeclarationVisitor::IsUplevelReference(const Symbol &symbol) { 8216 const Scope &symbolUnit{GetProgramUnitContaining(symbol)}; 8217 if (symbolUnit == GetProgramUnitContaining(currScope())) { 8218 return false; 8219 } else { 8220 Scope::Kind kind{symbolUnit.kind()}; 8221 return kind == Scope::Kind::Subprogram || kind == Scope::Kind::MainProgram; 8222 } 8223 } 8224 8225 // base is a part-ref of a derived type; find the named component in its type. 8226 // Also handles intrinsic type parameter inquiries (%kind, %len) and 8227 // COMPLEX component references (%re, %im). 8228 const parser::Name *DeclarationVisitor::FindComponent( 8229 const parser::Name *base, const parser::Name &component) { 8230 if (!base || !base->symbol) { 8231 return nullptr; 8232 } 8233 if (auto *misc{base->symbol->detailsIf<MiscDetails>()}) { 8234 if (component.source == "kind") { 8235 if (misc->kind() == MiscDetails::Kind::ComplexPartRe || 8236 misc->kind() == MiscDetails::Kind::ComplexPartIm || 8237 misc->kind() == MiscDetails::Kind::KindParamInquiry || 8238 misc->kind() == MiscDetails::Kind::LenParamInquiry) { 8239 // x%{re,im,kind,len}%kind 8240 MakePlaceholder(component, MiscDetails::Kind::KindParamInquiry); 8241 return &component; 8242 } 8243 } 8244 } 8245 CheckEntryDummyUse(base->source, base->symbol); 8246 auto &symbol{base->symbol->GetUltimate()}; 8247 if (!symbol.has<AssocEntityDetails>() && !ConvertToObjectEntity(symbol)) { 8248 SayWithDecl(*base, symbol, 8249 "'%s' is not an object and may not be used as the base of a component reference or type parameter inquiry"_err_en_US); 8250 return nullptr; 8251 } 8252 auto *type{symbol.GetType()}; 8253 if (!type) { 8254 return nullptr; // should have already reported error 8255 } 8256 if (const IntrinsicTypeSpec * intrinsic{type->AsIntrinsic()}) { 8257 auto category{intrinsic->category()}; 8258 MiscDetails::Kind miscKind{MiscDetails::Kind::None}; 8259 if (component.source == "kind") { 8260 miscKind = MiscDetails::Kind::KindParamInquiry; 8261 } else if (category == TypeCategory::Character) { 8262 if (component.source == "len") { 8263 miscKind = MiscDetails::Kind::LenParamInquiry; 8264 } 8265 } else if (category == TypeCategory::Complex) { 8266 if (component.source == "re") { 8267 miscKind = MiscDetails::Kind::ComplexPartRe; 8268 } else if (component.source == "im") { 8269 miscKind = MiscDetails::Kind::ComplexPartIm; 8270 } 8271 } 8272 if (miscKind != MiscDetails::Kind::None) { 8273 MakePlaceholder(component, miscKind); 8274 return &component; 8275 } 8276 } else if (DerivedTypeSpec * derived{type->AsDerived()}) { 8277 derived->Instantiate(currScope()); // in case of forward referenced type 8278 if (const Scope * scope{derived->scope()}) { 8279 if (Resolve(component, scope->FindComponent(component.source))) { 8280 if (auto msg{CheckAccessibleSymbol(currScope(), *component.symbol)}) { 8281 context().Say(component.source, *msg); 8282 } 8283 return &component; 8284 } else { 8285 SayDerivedType(component.source, 8286 "Component '%s' not found in derived type '%s'"_err_en_US, *scope); 8287 } 8288 } 8289 return nullptr; 8290 } 8291 if (symbol.test(Symbol::Flag::Implicit)) { 8292 Say(*base, 8293 "'%s' is not an object of derived type; it is implicitly typed"_err_en_US); 8294 } else { 8295 SayWithDecl( 8296 *base, symbol, "'%s' is not an object of derived type"_err_en_US); 8297 } 8298 return nullptr; 8299 } 8300 8301 void DeclarationVisitor::Initialization(const parser::Name &name, 8302 const parser::Initialization &init, bool inComponentDecl) { 8303 // Traversal of the initializer was deferred to here so that the 8304 // symbol being declared can be available for use in the expression, e.g.: 8305 // real, parameter :: x = tiny(x) 8306 if (!name.symbol) { 8307 return; 8308 } 8309 Symbol &ultimate{name.symbol->GetUltimate()}; 8310 // TODO: check C762 - all bounds and type parameters of component 8311 // are colons or constant expressions if component is initialized 8312 common::visit( 8313 common::visitors{ 8314 [&](const parser::ConstantExpr &expr) { 8315 Walk(expr); 8316 if (IsNamedConstant(ultimate) || inComponentDecl) { 8317 NonPointerInitialization(name, expr); 8318 } else { 8319 // Defer analysis so forward references to nested subprograms 8320 // can be properly resolved when they appear in structure 8321 // constructors. 8322 ultimate.set(Symbol::Flag::InDataStmt); 8323 } 8324 }, 8325 [&](const parser::NullInit &null) { // => NULL() 8326 Walk(null); 8327 if (auto nullInit{EvaluateExpr(null)}) { 8328 if (!evaluate::IsNullPointer(*nullInit)) { // C813 8329 Say(null.v.value().source, 8330 "Pointer initializer must be intrinsic NULL()"_err_en_US); 8331 } else if (IsPointer(ultimate)) { 8332 if (auto *object{ultimate.detailsIf<ObjectEntityDetails>()}) { 8333 CHECK(!object->init()); 8334 object->set_init(std::move(*nullInit)); 8335 } else if (auto *procPtr{ 8336 ultimate.detailsIf<ProcEntityDetails>()}) { 8337 CHECK(!procPtr->init()); 8338 procPtr->set_init(nullptr); 8339 } 8340 } else { 8341 Say(name, 8342 "Non-pointer component '%s' initialized with null pointer"_err_en_US); 8343 } 8344 } 8345 }, 8346 [&](const parser::InitialDataTarget &target) { 8347 // Defer analysis to the end of the specification part 8348 // so that forward references and attribute checks like SAVE 8349 // work better. 8350 auto restorer{common::ScopedSet(deferImplicitTyping_, true)}; 8351 Walk(target); 8352 ultimate.set(Symbol::Flag::InDataStmt); 8353 }, 8354 [&](const std::list<Indirection<parser::DataStmtValue>> &values) { 8355 // Handled later in data-to-inits conversion 8356 ultimate.set(Symbol::Flag::InDataStmt); 8357 Walk(values); 8358 }, 8359 }, 8360 init.u); 8361 } 8362 8363 void DeclarationVisitor::PointerInitialization( 8364 const parser::Name &name, const parser::InitialDataTarget &target) { 8365 if (name.symbol) { 8366 Symbol &ultimate{name.symbol->GetUltimate()}; 8367 if (!context().HasError(ultimate)) { 8368 if (IsPointer(ultimate)) { 8369 Walk(target); 8370 if (MaybeExpr expr{EvaluateExpr(target)}) { 8371 // Validation is done in declaration checking. 8372 if (auto *details{ultimate.detailsIf<ObjectEntityDetails>()}) { 8373 CHECK(!details->init()); 8374 details->set_init(std::move(*expr)); 8375 ultimate.set(Symbol::Flag::InDataStmt, false); 8376 } else if (auto *details{ultimate.detailsIf<ProcEntityDetails>()}) { 8377 // something like "REAL, EXTERNAL, POINTER :: p => t" 8378 if (evaluate::IsNullProcedurePointer(*expr)) { 8379 CHECK(!details->init()); 8380 details->set_init(nullptr); 8381 } else if (const Symbol * 8382 targetSymbol{evaluate::UnwrapWholeSymbolDataRef(*expr)}) { 8383 CHECK(!details->init()); 8384 details->set_init(*targetSymbol); 8385 } else { 8386 Say(name, 8387 "Procedure pointer '%s' must be initialized with a procedure name or NULL()"_err_en_US); 8388 context().SetError(ultimate); 8389 } 8390 } 8391 } 8392 } else { 8393 Say(name, 8394 "'%s' is not a pointer but is initialized like one"_err_en_US); 8395 context().SetError(ultimate); 8396 } 8397 } 8398 } 8399 } 8400 void DeclarationVisitor::PointerInitialization( 8401 const parser::Name &name, const parser::ProcPointerInit &target) { 8402 if (name.symbol) { 8403 Symbol &ultimate{name.symbol->GetUltimate()}; 8404 if (!context().HasError(ultimate)) { 8405 if (IsProcedurePointer(ultimate)) { 8406 auto &details{ultimate.get<ProcEntityDetails>()}; 8407 CHECK(!details.init()); 8408 if (const auto *targetName{std::get_if<parser::Name>(&target.u)}) { 8409 Walk(target); 8410 if (!CheckUseError(*targetName) && targetName->symbol) { 8411 // Validation is done in declaration checking. 8412 details.set_init(*targetName->symbol); 8413 } 8414 } else { // explicit NULL 8415 details.set_init(nullptr); 8416 } 8417 } else { 8418 Say(name, 8419 "'%s' is not a procedure pointer but is initialized " 8420 "like one"_err_en_US); 8421 context().SetError(ultimate); 8422 } 8423 } 8424 } 8425 } 8426 8427 void DeclarationVisitor::NonPointerInitialization( 8428 const parser::Name &name, const parser::ConstantExpr &expr) { 8429 if (!context().HasError(name.symbol)) { 8430 Symbol &ultimate{name.symbol->GetUltimate()}; 8431 if (!context().HasError(ultimate)) { 8432 if (IsPointer(ultimate)) { 8433 Say(name, 8434 "'%s' is a pointer but is not initialized like one"_err_en_US); 8435 } else if (auto *details{ultimate.detailsIf<ObjectEntityDetails>()}) { 8436 if (details->init()) { 8437 SayWithDecl(name, *name.symbol, 8438 "'%s' has already been initialized"_err_en_US); 8439 } else if (IsAllocatable(ultimate)) { 8440 Say(name, "Allocatable object '%s' cannot be initialized"_err_en_US); 8441 } else if (ultimate.owner().IsParameterizedDerivedType()) { 8442 // Save the expression for per-instantiation analysis. 8443 details->set_unanalyzedPDTComponentInit(&expr.thing.value()); 8444 } else if (MaybeExpr folded{EvaluateNonPointerInitializer( 8445 ultimate, expr, expr.thing.value().source)}) { 8446 details->set_init(std::move(*folded)); 8447 ultimate.set(Symbol::Flag::InDataStmt, false); 8448 } 8449 } else { 8450 Say(name, "'%s' is not an object that can be initialized"_err_en_US); 8451 } 8452 } 8453 } 8454 } 8455 8456 void ResolveNamesVisitor::HandleCall( 8457 Symbol::Flag procFlag, const parser::Call &call) { 8458 common::visit( 8459 common::visitors{ 8460 [&](const parser::Name &x) { HandleProcedureName(procFlag, x); }, 8461 [&](const parser::ProcComponentRef &x) { 8462 Walk(x); 8463 const parser::Name &name{x.v.thing.component}; 8464 if (Symbol * symbol{name.symbol}) { 8465 if (IsProcedure(*symbol)) { 8466 SetProcFlag(name, *symbol, procFlag); 8467 } 8468 } 8469 }, 8470 }, 8471 std::get<parser::ProcedureDesignator>(call.t).u); 8472 const auto &arguments{std::get<std::list<parser::ActualArgSpec>>(call.t)}; 8473 Walk(arguments); 8474 // Once an object has appeared in a specification function reference as 8475 // a whole scalar actual argument, it cannot be (re)dimensioned later. 8476 // The fact that it appeared to be a scalar may determine the resolution 8477 // or the result of an inquiry intrinsic function or generic procedure. 8478 if (inSpecificationPart_) { 8479 for (const auto &argSpec : arguments) { 8480 const auto &actual{std::get<parser::ActualArg>(argSpec.t)}; 8481 if (const auto *expr{ 8482 std::get_if<common::Indirection<parser::Expr>>(&actual.u)}) { 8483 if (const auto *designator{ 8484 std::get_if<common::Indirection<parser::Designator>>( 8485 &expr->value().u)}) { 8486 if (const auto *dataRef{ 8487 std::get_if<parser::DataRef>(&designator->value().u)}) { 8488 if (const auto *name{std::get_if<parser::Name>(&dataRef->u)}; 8489 name && name->symbol) { 8490 const Symbol &symbol{*name->symbol}; 8491 const auto *object{symbol.detailsIf<ObjectEntityDetails>()}; 8492 if (symbol.has<EntityDetails>() || 8493 (object && !object->IsArray())) { 8494 NoteScalarSpecificationArgument(symbol); 8495 } 8496 } 8497 } 8498 } 8499 } 8500 } 8501 } 8502 } 8503 8504 void ResolveNamesVisitor::HandleProcedureName( 8505 Symbol::Flag flag, const parser::Name &name) { 8506 CHECK(flag == Symbol::Flag::Function || flag == Symbol::Flag::Subroutine); 8507 auto *symbol{FindSymbol(NonDerivedTypeScope(), name)}; 8508 if (!symbol) { 8509 if (IsIntrinsic(name.source, flag)) { 8510 symbol = &MakeSymbol(InclusiveScope(), name.source, Attrs{}); 8511 SetImplicitAttr(*symbol, Attr::INTRINSIC); 8512 } else if (const auto ppcBuiltinScope = 8513 currScope().context().GetPPCBuiltinsScope()) { 8514 // Check if it is a builtin from the predefined module 8515 symbol = FindSymbol(*ppcBuiltinScope, name); 8516 if (!symbol) { 8517 symbol = &MakeSymbol(context().globalScope(), name.source, Attrs{}); 8518 } 8519 } else { 8520 symbol = &MakeSymbol(context().globalScope(), name.source, Attrs{}); 8521 } 8522 Resolve(name, *symbol); 8523 ConvertToProcEntity(*symbol, name.source); 8524 if (!symbol->attrs().test(Attr::INTRINSIC)) { 8525 if (CheckImplicitNoneExternal(name.source, *symbol)) { 8526 MakeExternal(*symbol); 8527 // Create a place-holder HostAssocDetails symbol to preclude later 8528 // use of this name as a local symbol; but don't actually use this new 8529 // HostAssocDetails symbol in expressions. 8530 MakeHostAssocSymbol(name, *symbol); 8531 name.symbol = symbol; 8532 } 8533 } 8534 CheckEntryDummyUse(name.source, symbol); 8535 SetProcFlag(name, *symbol, flag); 8536 } else if (CheckUseError(name)) { 8537 // error was reported 8538 } else { 8539 symbol = &symbol->GetUltimate(); 8540 if (!name.symbol || 8541 (name.symbol->has<HostAssocDetails>() && symbol->owner().IsGlobal() && 8542 (symbol->has<ProcEntityDetails>() || 8543 (symbol->has<SubprogramDetails>() && 8544 symbol->scope() /*not ENTRY*/)))) { 8545 name.symbol = symbol; 8546 } 8547 CheckEntryDummyUse(name.source, symbol); 8548 bool convertedToProcEntity{ConvertToProcEntity(*symbol, name.source)}; 8549 if (convertedToProcEntity && !symbol->attrs().test(Attr::EXTERNAL) && 8550 IsIntrinsic(symbol->name(), flag) && !IsDummy(*symbol)) { 8551 AcquireIntrinsicProcedureFlags(*symbol); 8552 } 8553 if (!SetProcFlag(name, *symbol, flag)) { 8554 return; // reported error 8555 } 8556 CheckImplicitNoneExternal(name.source, *symbol); 8557 if (IsProcedure(*symbol) || symbol->has<DerivedTypeDetails>() || 8558 symbol->has<AssocEntityDetails>()) { 8559 // Symbols with DerivedTypeDetails and AssocEntityDetails are accepted 8560 // here as procedure-designators because this means the related 8561 // FunctionReference are mis-parsed structure constructors or array 8562 // references that will be fixed later when analyzing expressions. 8563 } else if (symbol->has<ObjectEntityDetails>()) { 8564 // Symbols with ObjectEntityDetails are also accepted because this can be 8565 // a mis-parsed array reference that will be fixed later. Ensure that if 8566 // this is a symbol from a host procedure, a symbol with HostAssocDetails 8567 // is created for the current scope. 8568 // Operate on non ultimate symbol so that HostAssocDetails are also 8569 // created for symbols used associated in the host procedure. 8570 ResolveName(name); 8571 } else if (symbol->test(Symbol::Flag::Implicit)) { 8572 Say(name, 8573 "Use of '%s' as a procedure conflicts with its implicit definition"_err_en_US); 8574 } else { 8575 SayWithDecl(name, *symbol, 8576 "Use of '%s' as a procedure conflicts with its declaration"_err_en_US); 8577 } 8578 } 8579 } 8580 8581 bool ResolveNamesVisitor::CheckImplicitNoneExternal( 8582 const SourceName &name, const Symbol &symbol) { 8583 if (symbol.has<ProcEntityDetails>() && isImplicitNoneExternal() && 8584 !symbol.attrs().test(Attr::EXTERNAL) && 8585 !symbol.attrs().test(Attr::INTRINSIC) && !symbol.HasExplicitInterface()) { 8586 Say(name, 8587 "'%s' is an external procedure without the EXTERNAL attribute in a scope with IMPLICIT NONE(EXTERNAL)"_err_en_US); 8588 return false; 8589 } 8590 return true; 8591 } 8592 8593 // Variant of HandleProcedureName() for use while skimming the executable 8594 // part of a subprogram to catch calls to dummy procedures that are part 8595 // of the subprogram's interface, and to mark as procedures any symbols 8596 // that might otherwise have been miscategorized as objects. 8597 void ResolveNamesVisitor::NoteExecutablePartCall( 8598 Symbol::Flag flag, SourceName name, bool hasCUDAChevrons) { 8599 // Subtlety: The symbol pointers in the parse tree are not set, because 8600 // they might end up resolving elsewhere (e.g., construct entities in 8601 // SELECT TYPE). 8602 if (Symbol * symbol{currScope().FindSymbol(name)}) { 8603 Symbol::Flag other{flag == Symbol::Flag::Subroutine 8604 ? Symbol::Flag::Function 8605 : Symbol::Flag::Subroutine}; 8606 if (!symbol->test(other)) { 8607 ConvertToProcEntity(*symbol, name); 8608 if (auto *details{symbol->detailsIf<ProcEntityDetails>()}) { 8609 symbol->set(flag); 8610 if (IsDummy(*symbol)) { 8611 SetImplicitAttr(*symbol, Attr::EXTERNAL); 8612 } 8613 ApplyImplicitRules(*symbol); 8614 if (hasCUDAChevrons) { 8615 details->set_isCUDAKernel(); 8616 } 8617 } 8618 } 8619 } 8620 } 8621 8622 static bool IsLocallyImplicitGlobalSymbol( 8623 const Symbol &symbol, const parser::Name &localName) { 8624 if (symbol.owner().IsGlobal()) { 8625 const auto *subp{symbol.detailsIf<SubprogramDetails>()}; 8626 const Scope *scope{ 8627 subp && subp->entryScope() ? subp->entryScope() : symbol.scope()}; 8628 return !(scope && scope->sourceRange().Contains(localName.source)); 8629 } 8630 return false; 8631 } 8632 8633 static bool TypesMismatchIfNonNull( 8634 const DeclTypeSpec *type1, const DeclTypeSpec *type2) { 8635 return type1 && type2 && *type1 != *type2; 8636 } 8637 8638 // Check and set the Function or Subroutine flag on symbol; false on error. 8639 bool ResolveNamesVisitor::SetProcFlag( 8640 const parser::Name &name, Symbol &symbol, Symbol::Flag flag) { 8641 if (symbol.test(Symbol::Flag::Function) && flag == Symbol::Flag::Subroutine) { 8642 SayWithDecl( 8643 name, symbol, "Cannot call function '%s' like a subroutine"_err_en_US); 8644 context().SetError(symbol); 8645 return false; 8646 } else if (symbol.test(Symbol::Flag::Subroutine) && 8647 flag == Symbol::Flag::Function) { 8648 SayWithDecl( 8649 name, symbol, "Cannot call subroutine '%s' like a function"_err_en_US); 8650 context().SetError(symbol); 8651 return false; 8652 } else if (flag == Symbol::Flag::Function && 8653 IsLocallyImplicitGlobalSymbol(symbol, name) && 8654 TypesMismatchIfNonNull(symbol.GetType(), GetImplicitType(symbol))) { 8655 SayWithDecl(name, symbol, 8656 "Implicit declaration of function '%s' has a different result type than in previous declaration"_err_en_US); 8657 return false; 8658 } else if (symbol.has<ProcEntityDetails>()) { 8659 symbol.set(flag); // in case it hasn't been set yet 8660 if (flag == Symbol::Flag::Function) { 8661 ApplyImplicitRules(symbol); 8662 } 8663 if (symbol.attrs().test(Attr::INTRINSIC)) { 8664 AcquireIntrinsicProcedureFlags(symbol); 8665 } 8666 } else if (symbol.GetType() && flag == Symbol::Flag::Subroutine) { 8667 SayWithDecl( 8668 name, symbol, "Cannot call function '%s' like a subroutine"_err_en_US); 8669 context().SetError(symbol); 8670 } else if (symbol.attrs().test(Attr::INTRINSIC)) { 8671 AcquireIntrinsicProcedureFlags(symbol); 8672 } 8673 return true; 8674 } 8675 8676 bool ModuleVisitor::Pre(const parser::AccessStmt &x) { 8677 Attr accessAttr{AccessSpecToAttr(std::get<parser::AccessSpec>(x.t))}; 8678 if (!currScope().IsModule()) { // C869 8679 Say(currStmtSource().value(), 8680 "%s statement may only appear in the specification part of a module"_err_en_US, 8681 EnumToString(accessAttr)); 8682 return false; 8683 } 8684 const auto &accessIds{std::get<std::list<parser::AccessId>>(x.t)}; 8685 if (accessIds.empty()) { 8686 if (prevAccessStmt_) { // C869 8687 Say("The default accessibility of this module has already been declared"_err_en_US) 8688 .Attach(*prevAccessStmt_, "Previous declaration"_en_US); 8689 } 8690 prevAccessStmt_ = currStmtSource(); 8691 auto *moduleDetails{DEREF(currScope().symbol()).detailsIf<ModuleDetails>()}; 8692 DEREF(moduleDetails).set_isDefaultPrivate(accessAttr == Attr::PRIVATE); 8693 } else { 8694 for (const auto &accessId : accessIds) { 8695 GenericSpecInfo info{accessId.v.value()}; 8696 auto *symbol{FindInScope(info.symbolName())}; 8697 if (!symbol && !info.kind().IsName()) { 8698 symbol = &MakeSymbol(info.symbolName(), Attrs{}, GenericDetails{}); 8699 } 8700 info.Resolve(&SetAccess(info.symbolName(), accessAttr, symbol)); 8701 } 8702 } 8703 return false; 8704 } 8705 8706 // Set the access specification for this symbol. 8707 Symbol &ModuleVisitor::SetAccess( 8708 const SourceName &name, Attr attr, Symbol *symbol) { 8709 if (!symbol) { 8710 symbol = &MakeSymbol(name); 8711 } 8712 Attrs &attrs{symbol->attrs()}; 8713 if (attrs.HasAny({Attr::PUBLIC, Attr::PRIVATE})) { 8714 // PUBLIC/PRIVATE already set: make it a fatal error if it changed 8715 Attr prev{attrs.test(Attr::PUBLIC) ? Attr::PUBLIC : Attr::PRIVATE}; 8716 if (attr != prev) { 8717 Say(name, 8718 "The accessibility of '%s' has already been specified as %s"_err_en_US, 8719 MakeOpName(name), EnumToString(prev)); 8720 } else { 8721 context().Warn(common::LanguageFeature::RedundantAttribute, name, 8722 "The accessibility of '%s' has already been specified as %s"_warn_en_US, 8723 MakeOpName(name), EnumToString(prev)); 8724 } 8725 } else { 8726 attrs.set(attr); 8727 } 8728 return *symbol; 8729 } 8730 8731 static bool NeedsExplicitType(const Symbol &symbol) { 8732 if (symbol.has<UnknownDetails>()) { 8733 return true; 8734 } else if (const auto *details{symbol.detailsIf<EntityDetails>()}) { 8735 return !details->type(); 8736 } else if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) { 8737 return !details->type(); 8738 } else if (const auto *details{symbol.detailsIf<ProcEntityDetails>()}) { 8739 return !details->procInterface() && !details->type(); 8740 } else { 8741 return false; 8742 } 8743 } 8744 8745 void ResolveNamesVisitor::HandleDerivedTypesInImplicitStmts( 8746 const parser::ImplicitPart &implicitPart, 8747 const std::list<parser::DeclarationConstruct> &decls) { 8748 // Detect derived type definitions and create symbols for them now if 8749 // they appear in IMPLICIT statements so that these forward-looking 8750 // references will not be ambiguous with host associations. 8751 std::set<SourceName> implicitDerivedTypes; 8752 for (const auto &ipStmt : implicitPart.v) { 8753 if (const auto *impl{std::get_if< 8754 parser::Statement<common::Indirection<parser::ImplicitStmt>>>( 8755 &ipStmt.u)}) { 8756 if (const auto *specs{std::get_if<std::list<parser::ImplicitSpec>>( 8757 &impl->statement.value().u)}) { 8758 for (const auto &spec : *specs) { 8759 const auto &declTypeSpec{ 8760 std::get<parser::DeclarationTypeSpec>(spec.t)}; 8761 if (const auto *dtSpec{common::visit( 8762 common::visitors{ 8763 [](const parser::DeclarationTypeSpec::Type &x) { 8764 return &x.derived; 8765 }, 8766 [](const parser::DeclarationTypeSpec::Class &x) { 8767 return &x.derived; 8768 }, 8769 [](const auto &) -> const parser::DerivedTypeSpec * { 8770 return nullptr; 8771 }}, 8772 declTypeSpec.u)}) { 8773 implicitDerivedTypes.emplace( 8774 std::get<parser::Name>(dtSpec->t).source); 8775 } 8776 } 8777 } 8778 } 8779 } 8780 if (!implicitDerivedTypes.empty()) { 8781 for (const auto &decl : decls) { 8782 if (const auto *spec{ 8783 std::get_if<parser::SpecificationConstruct>(&decl.u)}) { 8784 if (const auto *dtDef{ 8785 std::get_if<common::Indirection<parser::DerivedTypeDef>>( 8786 &spec->u)}) { 8787 const parser::DerivedTypeStmt &dtStmt{ 8788 std::get<parser::Statement<parser::DerivedTypeStmt>>( 8789 dtDef->value().t) 8790 .statement}; 8791 const parser::Name &name{std::get<parser::Name>(dtStmt.t)}; 8792 if (implicitDerivedTypes.find(name.source) != 8793 implicitDerivedTypes.end() && 8794 !FindInScope(name)) { 8795 DerivedTypeDetails details; 8796 details.set_isForwardReferenced(true); 8797 Resolve(name, MakeSymbol(name, std::move(details))); 8798 implicitDerivedTypes.erase(name.source); 8799 } 8800 } 8801 } 8802 } 8803 } 8804 } 8805 8806 bool ResolveNamesVisitor::Pre(const parser::SpecificationPart &x) { 8807 const auto &[accDecls, ompDecls, compilerDirectives, useStmts, importStmts, 8808 implicitPart, decls] = x.t; 8809 auto flagRestorer{common::ScopedSet(inSpecificationPart_, true)}; 8810 auto stateRestorer{ 8811 common::ScopedSet(specPartState_, SpecificationPartState{})}; 8812 Walk(accDecls); 8813 Walk(ompDecls); 8814 Walk(compilerDirectives); 8815 for (const auto &useStmt : useStmts) { 8816 CollectUseRenames(useStmt.statement.value()); 8817 } 8818 Walk(useStmts); 8819 UseCUDABuiltinNames(); 8820 ClearUseRenames(); 8821 ClearUseOnly(); 8822 ClearModuleUses(); 8823 Walk(importStmts); 8824 HandleDerivedTypesInImplicitStmts(implicitPart, decls); 8825 Walk(implicitPart); 8826 for (const auto &decl : decls) { 8827 if (const auto *spec{ 8828 std::get_if<parser::SpecificationConstruct>(&decl.u)}) { 8829 PreSpecificationConstruct(*spec); 8830 } 8831 } 8832 Walk(decls); 8833 FinishSpecificationPart(decls); 8834 return false; 8835 } 8836 8837 void ResolveNamesVisitor::UseCUDABuiltinNames() { 8838 if (FindCUDADeviceContext(&currScope())) { 8839 for (const auto &[name, symbol] : context().GetCUDABuiltinsScope()) { 8840 if (!FindInScope(name)) { 8841 auto &localSymbol{MakeSymbol(name)}; 8842 localSymbol.set_details(UseDetails{name, *symbol}); 8843 localSymbol.flags() = symbol->flags(); 8844 } 8845 } 8846 } 8847 } 8848 8849 // Initial processing on specification constructs, before visiting them. 8850 void ResolveNamesVisitor::PreSpecificationConstruct( 8851 const parser::SpecificationConstruct &spec) { 8852 common::visit( 8853 common::visitors{ 8854 [&](const parser::Statement<Indirection<parser::GenericStmt>> &y) { 8855 CreateGeneric(std::get<parser::GenericSpec>(y.statement.value().t)); 8856 }, 8857 [&](const Indirection<parser::InterfaceBlock> &y) { 8858 const auto &stmt{std::get<parser::Statement<parser::InterfaceStmt>>( 8859 y.value().t)}; 8860 if (const auto *spec{parser::Unwrap<parser::GenericSpec>(stmt)}) { 8861 CreateGeneric(*spec); 8862 } 8863 }, 8864 [&](const parser::Statement<parser::OtherSpecificationStmt> &y) { 8865 common::visit( 8866 common::visitors{ 8867 [&](const common::Indirection<parser::CommonStmt> &z) { 8868 CreateCommonBlockSymbols(z.value()); 8869 }, 8870 [&](const common::Indirection<parser::TargetStmt> &z) { 8871 CreateObjectSymbols(z.value().v, Attr::TARGET); 8872 }, 8873 [](const auto &) {}, 8874 }, 8875 y.statement.u); 8876 }, 8877 [](const auto &) {}, 8878 }, 8879 spec.u); 8880 } 8881 8882 void ResolveNamesVisitor::CreateCommonBlockSymbols( 8883 const parser::CommonStmt &commonStmt) { 8884 for (const parser::CommonStmt::Block &block : commonStmt.blocks) { 8885 const auto &[name, objects] = block.t; 8886 Symbol &commonBlock{MakeCommonBlockSymbol(name)}; 8887 for (const auto &object : objects) { 8888 Symbol &obj{DeclareObjectEntity(std::get<parser::Name>(object.t))}; 8889 if (auto *details{obj.detailsIf<ObjectEntityDetails>()}) { 8890 details->set_commonBlock(commonBlock); 8891 commonBlock.get<CommonBlockDetails>().add_object(obj); 8892 } 8893 } 8894 } 8895 } 8896 8897 void ResolveNamesVisitor::CreateObjectSymbols( 8898 const std::list<parser::ObjectDecl> &decls, Attr attr) { 8899 for (const parser::ObjectDecl &decl : decls) { 8900 SetImplicitAttr(DeclareEntity<ObjectEntityDetails>( 8901 std::get<parser::ObjectName>(decl.t), Attrs{}), 8902 attr); 8903 } 8904 } 8905 8906 void ResolveNamesVisitor::CreateGeneric(const parser::GenericSpec &x) { 8907 auto info{GenericSpecInfo{x}}; 8908 SourceName symbolName{info.symbolName()}; 8909 if (IsLogicalConstant(context(), symbolName)) { 8910 Say(symbolName, 8911 "Logical constant '%s' may not be used as a defined operator"_err_en_US); 8912 return; 8913 } 8914 GenericDetails genericDetails; 8915 Symbol *existing{nullptr}; 8916 // Check all variants of names, e.g. "operator(.ne.)" for "operator(/=)" 8917 for (const std::string &n : GetAllNames(context(), symbolName)) { 8918 existing = currScope().FindSymbol(SourceName{n}); 8919 if (existing) { 8920 break; 8921 } 8922 } 8923 if (existing) { 8924 Symbol &ultimate{existing->GetUltimate()}; 8925 if (auto *existingGeneric{ultimate.detailsIf<GenericDetails>()}) { 8926 if (&existing->owner() == &currScope()) { 8927 if (const auto *existingUse{existing->detailsIf<UseDetails>()}) { 8928 // Create a local copy of a use associated generic so that 8929 // it can be locally extended without corrupting the original. 8930 genericDetails.CopyFrom(*existingGeneric); 8931 if (existingGeneric->specific()) { 8932 genericDetails.set_specific(*existingGeneric->specific()); 8933 } 8934 AddGenericUse( 8935 genericDetails, existing->name(), existingUse->symbol()); 8936 } else if (existing == &ultimate) { 8937 // Extending an extant generic in the same scope 8938 info.Resolve(existing); 8939 return; 8940 } else { 8941 // Host association of a generic is handled elsewhere 8942 CHECK(existing->has<HostAssocDetails>()); 8943 } 8944 } else { 8945 // Create a new generic for this scope. 8946 } 8947 } else if (ultimate.has<SubprogramDetails>() || 8948 ultimate.has<SubprogramNameDetails>()) { 8949 genericDetails.set_specific(*existing); 8950 } else if (ultimate.has<ProcEntityDetails>()) { 8951 if (existing->name() != symbolName || 8952 !ultimate.attrs().test(Attr::INTRINSIC)) { 8953 genericDetails.set_specific(*existing); 8954 } 8955 } else if (ultimate.has<DerivedTypeDetails>()) { 8956 genericDetails.set_derivedType(*existing); 8957 } else if (&existing->owner() == &currScope()) { 8958 SayAlreadyDeclared(symbolName, *existing); 8959 return; 8960 } 8961 if (&existing->owner() == &currScope()) { 8962 EraseSymbol(*existing); 8963 } 8964 } 8965 info.Resolve(&MakeSymbol(symbolName, Attrs{}, std::move(genericDetails))); 8966 } 8967 8968 void ResolveNamesVisitor::FinishSpecificationPart( 8969 const std::list<parser::DeclarationConstruct> &decls) { 8970 misparsedStmtFuncFound_ = false; 8971 funcResultStack().CompleteFunctionResultType(); 8972 CheckImports(); 8973 bool inDeviceSubprogram = false; 8974 if (auto *subp{currScope().symbol() 8975 ? currScope().symbol()->detailsIf<SubprogramDetails>() 8976 : nullptr}) { 8977 if (auto attrs{subp->cudaSubprogramAttrs()}) { 8978 if (*attrs == common::CUDASubprogramAttrs::Device || 8979 *attrs == common::CUDASubprogramAttrs::Global || 8980 *attrs == common::CUDASubprogramAttrs::Grid_Global) { 8981 inDeviceSubprogram = true; 8982 } 8983 } 8984 } 8985 for (auto &pair : currScope()) { 8986 auto &symbol{*pair.second}; 8987 if (inInterfaceBlock()) { 8988 ConvertToObjectEntity(symbol); 8989 } 8990 if (NeedsExplicitType(symbol)) { 8991 ApplyImplicitRules(symbol); 8992 } 8993 if (inDeviceSubprogram && symbol.has<ObjectEntityDetails>()) { 8994 auto *object{symbol.detailsIf<ObjectEntityDetails>()}; 8995 if (!object->cudaDataAttr() && !IsValue(symbol) && 8996 (IsDummy(symbol) || object->IsArray())) { 8997 // Implicitly set device attribute if none is set in device context. 8998 object->set_cudaDataAttr(common::CUDADataAttr::Device); 8999 } 9000 } 9001 if (IsDummy(symbol) && isImplicitNoneType() && 9002 symbol.test(Symbol::Flag::Implicit) && !context().HasError(symbol)) { 9003 Say(symbol.name(), 9004 "No explicit type declared for dummy argument '%s'"_err_en_US); 9005 context().SetError(symbol); 9006 } 9007 if (symbol.has<GenericDetails>()) { 9008 CheckGenericProcedures(symbol); 9009 } 9010 if (!symbol.has<HostAssocDetails>()) { 9011 CheckPossibleBadForwardRef(symbol); 9012 } 9013 // Propagate BIND(C) attribute to procedure entities from their interfaces, 9014 // but not the NAME=, even if it is empty (which would be a reasonable 9015 // and useful behavior, actually). This interpretation is not at all 9016 // clearly described in the standard, but matches the behavior of several 9017 // other compilers. 9018 if (auto *proc{symbol.detailsIf<ProcEntityDetails>()}; proc && 9019 !proc->isDummy() && !IsPointer(symbol) && 9020 !symbol.attrs().test(Attr::BIND_C)) { 9021 if (const Symbol * iface{proc->procInterface()}; 9022 iface && IsBindCProcedure(*iface)) { 9023 SetImplicitAttr(symbol, Attr::BIND_C); 9024 SetBindNameOn(symbol); 9025 } 9026 } 9027 } 9028 currScope().InstantiateDerivedTypes(); 9029 for (const auto &decl : decls) { 9030 if (const auto *statement{std::get_if< 9031 parser::Statement<common::Indirection<parser::StmtFunctionStmt>>>( 9032 &decl.u)}) { 9033 messageHandler().set_currStmtSource(statement->source); 9034 AnalyzeStmtFunctionStmt(statement->statement.value()); 9035 } 9036 } 9037 // TODO: what about instantiations in BLOCK? 9038 CheckSaveStmts(); 9039 CheckCommonBlocks(); 9040 if (!inInterfaceBlock()) { 9041 // TODO: warn for the case where the EQUIVALENCE statement is in a 9042 // procedure declaration in an interface block 9043 CheckEquivalenceSets(); 9044 } 9045 } 9046 9047 // Analyze the bodies of statement functions now that the symbols in this 9048 // specification part have been fully declared and implicitly typed. 9049 // (Statement function references are not allowed in specification 9050 // expressions, so it's safe to defer processing their definitions.) 9051 void ResolveNamesVisitor::AnalyzeStmtFunctionStmt( 9052 const parser::StmtFunctionStmt &stmtFunc) { 9053 const auto &name{std::get<parser::Name>(stmtFunc.t)}; 9054 Symbol *symbol{name.symbol}; 9055 auto *details{symbol ? symbol->detailsIf<SubprogramDetails>() : nullptr}; 9056 if (!details || !symbol->scope() || 9057 &symbol->scope()->parent() != &currScope() || details->isInterface() || 9058 details->isDummy() || details->entryScope() || 9059 details->moduleInterface() || symbol->test(Symbol::Flag::Subroutine)) { 9060 return; // error recovery 9061 } 9062 // Resolve the symbols on the RHS of the statement function. 9063 PushScope(*symbol->scope()); 9064 const auto &parsedExpr{std::get<parser::Scalar<parser::Expr>>(stmtFunc.t)}; 9065 Walk(parsedExpr); 9066 PopScope(); 9067 if (auto expr{AnalyzeExpr(context(), stmtFunc)}) { 9068 if (auto type{evaluate::DynamicType::From(*symbol)}) { 9069 if (auto converted{evaluate::ConvertToType(*type, std::move(*expr))}) { 9070 details->set_stmtFunction(std::move(*converted)); 9071 } else { 9072 Say(name.source, 9073 "Defining expression of statement function '%s' cannot be converted to its result type %s"_err_en_US, 9074 name.source, type->AsFortran()); 9075 } 9076 } else { 9077 details->set_stmtFunction(std::move(*expr)); 9078 } 9079 } 9080 if (!details->stmtFunction()) { 9081 context().SetError(*symbol); 9082 } 9083 } 9084 9085 void ResolveNamesVisitor::CheckImports() { 9086 auto &scope{currScope()}; 9087 switch (scope.GetImportKind()) { 9088 case common::ImportKind::None: 9089 break; 9090 case common::ImportKind::All: 9091 // C8102: all entities in host must not be hidden 9092 for (const auto &pair : scope.parent()) { 9093 auto &name{pair.first}; 9094 std::optional<SourceName> scopeName{scope.GetName()}; 9095 if (!scopeName || name != *scopeName) { 9096 CheckImport(prevImportStmt_.value(), name); 9097 } 9098 } 9099 break; 9100 case common::ImportKind::Default: 9101 case common::ImportKind::Only: 9102 // C8102: entities named in IMPORT must not be hidden 9103 for (auto &name : scope.importNames()) { 9104 CheckImport(name, name); 9105 } 9106 break; 9107 } 9108 } 9109 9110 void ResolveNamesVisitor::CheckImport( 9111 const SourceName &location, const SourceName &name) { 9112 if (auto *symbol{FindInScope(name)}) { 9113 const Symbol &ultimate{symbol->GetUltimate()}; 9114 if (&ultimate.owner() == &currScope()) { 9115 Say(location, "'%s' from host is not accessible"_err_en_US, name) 9116 .Attach(symbol->name(), "'%s' is hidden by this entity"_because_en_US, 9117 symbol->name()); 9118 } 9119 } 9120 } 9121 9122 bool ResolveNamesVisitor::Pre(const parser::ImplicitStmt &x) { 9123 return CheckNotInBlock("IMPLICIT") && // C1107 9124 ImplicitRulesVisitor::Pre(x); 9125 } 9126 9127 void ResolveNamesVisitor::Post(const parser::PointerObject &x) { 9128 common::visit(common::visitors{ 9129 [&](const parser::Name &x) { ResolveName(x); }, 9130 [&](const parser::StructureComponent &x) { 9131 ResolveStructureComponent(x); 9132 }, 9133 }, 9134 x.u); 9135 } 9136 void ResolveNamesVisitor::Post(const parser::AllocateObject &x) { 9137 common::visit(common::visitors{ 9138 [&](const parser::Name &x) { ResolveName(x); }, 9139 [&](const parser::StructureComponent &x) { 9140 ResolveStructureComponent(x); 9141 }, 9142 }, 9143 x.u); 9144 } 9145 9146 bool ResolveNamesVisitor::Pre(const parser::PointerAssignmentStmt &x) { 9147 const auto &dataRef{std::get<parser::DataRef>(x.t)}; 9148 const auto &bounds{std::get<parser::PointerAssignmentStmt::Bounds>(x.t)}; 9149 const auto &expr{std::get<parser::Expr>(x.t)}; 9150 ResolveDataRef(dataRef); 9151 Symbol *ptrSymbol{parser::GetLastName(dataRef).symbol}; 9152 Walk(bounds); 9153 // Resolve unrestricted specific intrinsic procedures as in "p => cos". 9154 if (const parser::Name * name{parser::Unwrap<parser::Name>(expr)}) { 9155 if (NameIsKnownOrIntrinsic(*name)) { 9156 if (Symbol * symbol{name->symbol}) { 9157 if (IsProcedurePointer(ptrSymbol) && 9158 !ptrSymbol->test(Symbol::Flag::Function) && 9159 !ptrSymbol->test(Symbol::Flag::Subroutine)) { 9160 if (symbol->test(Symbol::Flag::Function)) { 9161 ApplyImplicitRules(*ptrSymbol); 9162 } 9163 } 9164 // If the name is known because it is an object entity from a host 9165 // procedure, create a host associated symbol. 9166 if (symbol->GetUltimate().has<ObjectEntityDetails>() && 9167 IsUplevelReference(*symbol)) { 9168 MakeHostAssocSymbol(*name, *symbol); 9169 } 9170 } 9171 return false; 9172 } 9173 // Can also reference a global external procedure here 9174 if (auto it{context().globalScope().find(name->source)}; 9175 it != context().globalScope().end()) { 9176 Symbol &global{*it->second}; 9177 if (IsProcedure(global)) { 9178 Resolve(*name, global); 9179 return false; 9180 } 9181 } 9182 if (IsProcedurePointer(parser::GetLastName(dataRef).symbol) && 9183 !FindSymbol(*name)) { 9184 // Unknown target of procedure pointer must be an external procedure 9185 Symbol &symbol{MakeSymbol( 9186 context().globalScope(), name->source, Attrs{Attr::EXTERNAL})}; 9187 symbol.implicitAttrs().set(Attr::EXTERNAL); 9188 Resolve(*name, symbol); 9189 ConvertToProcEntity(symbol, name->source); 9190 return false; 9191 } 9192 } 9193 Walk(expr); 9194 return false; 9195 } 9196 void ResolveNamesVisitor::Post(const parser::Designator &x) { 9197 ResolveDesignator(x); 9198 } 9199 void ResolveNamesVisitor::Post(const parser::SubstringInquiry &x) { 9200 Walk(std::get<parser::SubstringRange>(x.v.t).t); 9201 ResolveDataRef(std::get<parser::DataRef>(x.v.t)); 9202 } 9203 9204 void ResolveNamesVisitor::Post(const parser::ProcComponentRef &x) { 9205 ResolveStructureComponent(x.v.thing); 9206 } 9207 void ResolveNamesVisitor::Post(const parser::TypeGuardStmt &x) { 9208 DeclTypeSpecVisitor::Post(x); 9209 ConstructVisitor::Post(x); 9210 } 9211 bool ResolveNamesVisitor::Pre(const parser::StmtFunctionStmt &x) { 9212 if (HandleStmtFunction(x)) { 9213 return false; 9214 } else { 9215 // This is an array element or pointer-valued function assignment: 9216 // resolve the names of indices/arguments 9217 const auto &names{std::get<std::list<parser::Name>>(x.t)}; 9218 for (auto &name : names) { 9219 ResolveName(name); 9220 } 9221 return true; 9222 } 9223 } 9224 9225 bool ResolveNamesVisitor::Pre(const parser::DefinedOpName &x) { 9226 const parser::Name &name{x.v}; 9227 if (FindSymbol(name)) { 9228 // OK 9229 } else if (IsLogicalConstant(context(), name.source)) { 9230 Say(name, 9231 "Logical constant '%s' may not be used as a defined operator"_err_en_US); 9232 } else { 9233 // Resolved later in expression semantics 9234 MakePlaceholder(name, MiscDetails::Kind::TypeBoundDefinedOp); 9235 } 9236 return false; 9237 } 9238 9239 void ResolveNamesVisitor::Post(const parser::AssignStmt &x) { 9240 if (auto *name{ResolveName(std::get<parser::Name>(x.t))}) { 9241 CheckEntryDummyUse(name->source, name->symbol); 9242 ConvertToObjectEntity(DEREF(name->symbol)); 9243 } 9244 } 9245 void ResolveNamesVisitor::Post(const parser::AssignedGotoStmt &x) { 9246 if (auto *name{ResolveName(std::get<parser::Name>(x.t))}) { 9247 CheckEntryDummyUse(name->source, name->symbol); 9248 ConvertToObjectEntity(DEREF(name->symbol)); 9249 } 9250 } 9251 9252 void ResolveNamesVisitor::Post(const parser::CompilerDirective &x) { 9253 if (std::holds_alternative<parser::CompilerDirective::VectorAlways>(x.u)) { 9254 return; 9255 } 9256 if (const auto *tkr{ 9257 std::get_if<std::list<parser::CompilerDirective::IgnoreTKR>>(&x.u)}) { 9258 if (currScope().IsTopLevel() || 9259 GetProgramUnitContaining(currScope()).kind() != 9260 Scope::Kind::Subprogram) { 9261 Say(x.source, 9262 "!DIR$ IGNORE_TKR directive must appear in a subroutine or function"_err_en_US); 9263 return; 9264 } 9265 if (!inSpecificationPart_) { 9266 Say(x.source, 9267 "!DIR$ IGNORE_TKR directive must appear in the specification part"_err_en_US); 9268 return; 9269 } 9270 if (tkr->empty()) { 9271 Symbol *symbol{currScope().symbol()}; 9272 if (SubprogramDetails * 9273 subp{symbol ? symbol->detailsIf<SubprogramDetails>() : nullptr}) { 9274 subp->set_defaultIgnoreTKR(true); 9275 } 9276 } else { 9277 for (const parser::CompilerDirective::IgnoreTKR &item : *tkr) { 9278 common::IgnoreTKRSet set; 9279 if (const auto &maybeList{ 9280 std::get<std::optional<std::list<const char *>>>(item.t)}) { 9281 for (const char *p : *maybeList) { 9282 if (p) { 9283 switch (*p) { 9284 case 't': 9285 set.set(common::IgnoreTKR::Type); 9286 break; 9287 case 'k': 9288 set.set(common::IgnoreTKR::Kind); 9289 break; 9290 case 'r': 9291 set.set(common::IgnoreTKR::Rank); 9292 break; 9293 case 'd': 9294 set.set(common::IgnoreTKR::Device); 9295 break; 9296 case 'm': 9297 set.set(common::IgnoreTKR::Managed); 9298 break; 9299 case 'c': 9300 set.set(common::IgnoreTKR::Contiguous); 9301 break; 9302 case 'a': 9303 set = common::ignoreTKRAll; 9304 break; 9305 default: 9306 Say(x.source, 9307 "'%c' is not a valid letter for !DIR$ IGNORE_TKR directive"_err_en_US, 9308 *p); 9309 set = common::ignoreTKRAll; 9310 break; 9311 } 9312 } 9313 } 9314 if (set.empty()) { 9315 Say(x.source, 9316 "!DIR$ IGNORE_TKR directive may not have an empty parenthesized list of letters"_err_en_US); 9317 } 9318 } else { // no (list) 9319 set = common::ignoreTKRAll; 9320 ; 9321 } 9322 const auto &name{std::get<parser::Name>(item.t)}; 9323 Symbol *symbol{FindSymbol(name)}; 9324 if (!symbol) { 9325 symbol = &MakeSymbol(name, Attrs{}, ObjectEntityDetails{}); 9326 } 9327 if (symbol->owner() != currScope()) { 9328 SayWithDecl( 9329 name, *symbol, "'%s' must be local to this subprogram"_err_en_US); 9330 } else { 9331 ConvertToObjectEntity(*symbol); 9332 if (auto *object{symbol->detailsIf<ObjectEntityDetails>()}) { 9333 object->set_ignoreTKR(set); 9334 } else { 9335 SayWithDecl(name, *symbol, "'%s' must be an object"_err_en_US); 9336 } 9337 } 9338 } 9339 } 9340 } else if (context().ShouldWarn(common::UsageWarning::IgnoredDirective)) { 9341 Say(x.source, "Unrecognized compiler directive was ignored"_warn_en_US) 9342 .set_usageWarning(common::UsageWarning::IgnoredDirective); 9343 } 9344 } 9345 9346 bool ResolveNamesVisitor::Pre(const parser::ProgramUnit &x) { 9347 if (std::holds_alternative<common::Indirection<parser::CompilerDirective>>( 9348 x.u)) { 9349 // TODO: global directives 9350 return true; 9351 } 9352 if (std::holds_alternative< 9353 common::Indirection<parser::OpenACCRoutineConstruct>>(x.u)) { 9354 ResolveAccParts(context(), x, &topScope_); 9355 return false; 9356 } 9357 ProgramTree &root{ProgramTree::Build(x, context())}; 9358 SetScope(topScope_); 9359 ResolveSpecificationParts(root); 9360 FinishSpecificationParts(root); 9361 ResolveExecutionParts(root); 9362 FinishExecutionParts(root); 9363 ResolveAccParts(context(), x, /*topScope=*/nullptr); 9364 ResolveOmpParts(context(), x); 9365 return false; 9366 } 9367 9368 template <typename A> std::set<SourceName> GetUses(const A &x) { 9369 std::set<SourceName> uses; 9370 if constexpr (!std::is_same_v<A, parser::CompilerDirective> && 9371 !std::is_same_v<A, parser::OpenACCRoutineConstruct>) { 9372 const auto &spec{std::get<parser::SpecificationPart>(x.t)}; 9373 const auto &unitUses{std::get< 9374 std::list<parser::Statement<common::Indirection<parser::UseStmt>>>>( 9375 spec.t)}; 9376 for (const auto &u : unitUses) { 9377 uses.insert(u.statement.value().moduleName.source); 9378 } 9379 } 9380 return uses; 9381 } 9382 9383 bool ResolveNamesVisitor::Pre(const parser::Program &x) { 9384 std::map<SourceName, const parser::ProgramUnit *> modules; 9385 std::set<SourceName> uses; 9386 bool disordered{false}; 9387 for (const auto &progUnit : x.v) { 9388 if (const auto *indMod{ 9389 std::get_if<common::Indirection<parser::Module>>(&progUnit.u)}) { 9390 const parser::Module &mod{indMod->value()}; 9391 const auto &moduleStmt{ 9392 std::get<parser::Statement<parser::ModuleStmt>>(mod.t)}; 9393 const SourceName &name{moduleStmt.statement.v.source}; 9394 if (auto iter{modules.find(name)}; iter != modules.end()) { 9395 Say(name, 9396 "Module '%s' appears multiple times in a compilation unit"_err_en_US) 9397 .Attach(iter->first, "First definition of module"_en_US); 9398 return true; 9399 } 9400 modules.emplace(name, &progUnit); 9401 if (auto iter{uses.find(name)}; iter != uses.end()) { 9402 if (context().ShouldWarn(common::LanguageFeature::MiscUseExtensions)) { 9403 Say(name, 9404 "A USE statement referencing module '%s' appears earlier in this compilation unit"_port_en_US, 9405 name) 9406 .Attach(*iter, "First USE of module"_en_US); 9407 } 9408 disordered = true; 9409 } 9410 } 9411 for (SourceName used : common::visit( 9412 [](const auto &indUnit) { return GetUses(indUnit.value()); }, 9413 progUnit.u)) { 9414 uses.insert(used); 9415 } 9416 } 9417 if (!disordered) { 9418 return true; 9419 } 9420 // Process modules in topological order 9421 std::vector<const parser::ProgramUnit *> moduleOrder; 9422 while (!modules.empty()) { 9423 bool ok; 9424 for (const auto &pair : modules) { 9425 const SourceName &name{pair.first}; 9426 const parser::ProgramUnit &progUnit{*pair.second}; 9427 const parser::Module &m{ 9428 std::get<common::Indirection<parser::Module>>(progUnit.u).value()}; 9429 ok = true; 9430 for (const SourceName &use : GetUses(m)) { 9431 if (modules.find(use) != modules.end()) { 9432 ok = false; 9433 break; 9434 } 9435 } 9436 if (ok) { 9437 moduleOrder.push_back(&progUnit); 9438 modules.erase(name); 9439 break; 9440 } 9441 } 9442 if (!ok) { 9443 Message *msg{nullptr}; 9444 for (const auto &pair : modules) { 9445 if (msg) { 9446 msg->Attach(pair.first, "Module in a cycle"_en_US); 9447 } else { 9448 msg = &Say(pair.first, 9449 "Some modules in this compilation unit form one or more cycles of dependence"_err_en_US); 9450 } 9451 } 9452 return false; 9453 } 9454 } 9455 // Modules can be ordered. Process them first, and then all of the other 9456 // program units. 9457 for (const parser::ProgramUnit *progUnit : moduleOrder) { 9458 Walk(*progUnit); 9459 } 9460 for (const auto &progUnit : x.v) { 9461 if (!std::get_if<common::Indirection<parser::Module>>(&progUnit.u)) { 9462 Walk(progUnit); 9463 } 9464 } 9465 return false; 9466 } 9467 9468 // References to procedures need to record that their symbols are known 9469 // to be procedures, so that they don't get converted to objects by default. 9470 class ExecutionPartCallSkimmer : public ExecutionPartSkimmerBase { 9471 public: 9472 explicit ExecutionPartCallSkimmer(ResolveNamesVisitor &resolver) 9473 : resolver_{resolver} {} 9474 9475 void Walk(const parser::ExecutionPart &exec) { 9476 parser::Walk(exec, *this); 9477 EndWalk(); 9478 } 9479 9480 using ExecutionPartSkimmerBase::Post; 9481 using ExecutionPartSkimmerBase::Pre; 9482 9483 void Post(const parser::FunctionReference &fr) { 9484 NoteCall(Symbol::Flag::Function, fr.v, false); 9485 } 9486 void Post(const parser::CallStmt &cs) { 9487 NoteCall(Symbol::Flag::Subroutine, cs.call, cs.chevrons.has_value()); 9488 } 9489 9490 private: 9491 void NoteCall( 9492 Symbol::Flag flag, const parser::Call &call, bool hasCUDAChevrons) { 9493 auto &designator{std::get<parser::ProcedureDesignator>(call.t)}; 9494 if (const auto *name{std::get_if<parser::Name>(&designator.u)}) { 9495 if (!IsHidden(name->source)) { 9496 resolver_.NoteExecutablePartCall(flag, name->source, hasCUDAChevrons); 9497 } 9498 } 9499 } 9500 9501 ResolveNamesVisitor &resolver_; 9502 }; 9503 9504 // Build the scope tree and resolve names in the specification parts of this 9505 // node and its children 9506 void ResolveNamesVisitor::ResolveSpecificationParts(ProgramTree &node) { 9507 if (node.isSpecificationPartResolved()) { 9508 return; // been here already 9509 } 9510 node.set_isSpecificationPartResolved(); 9511 if (!BeginScopeForNode(node)) { 9512 return; // an error prevented scope from being created 9513 } 9514 Scope &scope{currScope()}; 9515 node.set_scope(scope); 9516 AddSubpNames(node); 9517 common::visit( 9518 [&](const auto *x) { 9519 if (x) { 9520 Walk(*x); 9521 } 9522 }, 9523 node.stmt()); 9524 Walk(node.spec()); 9525 // If this is a function, convert result to an object. This is to prevent the 9526 // result from being converted later to a function symbol if it is called 9527 // inside the function. 9528 // If the result is function pointer, then ConvertToObjectEntity will not 9529 // convert the result to an object, and calling the symbol inside the function 9530 // will result in calls to the result pointer. 9531 // A function cannot be called recursively if RESULT was not used to define a 9532 // distinct result name (15.6.2.2 point 4.). 9533 if (Symbol * symbol{scope.symbol()}) { 9534 if (auto *details{symbol->detailsIf<SubprogramDetails>()}) { 9535 if (details->isFunction()) { 9536 ConvertToObjectEntity(const_cast<Symbol &>(details->result())); 9537 } 9538 } 9539 } 9540 if (node.IsModule()) { 9541 ApplyDefaultAccess(); 9542 } 9543 for (auto &child : node.children()) { 9544 ResolveSpecificationParts(child); 9545 } 9546 if (node.exec()) { 9547 ExecutionPartCallSkimmer{*this}.Walk(*node.exec()); 9548 HandleImpliedAsynchronousInScope(node.exec()->v); 9549 } 9550 EndScopeForNode(node); 9551 // Ensure that every object entity has a type. 9552 bool inModule{node.GetKind() == ProgramTree::Kind::Module || 9553 node.GetKind() == ProgramTree::Kind::Submodule}; 9554 for (auto &pair : *node.scope()) { 9555 Symbol &symbol{*pair.second}; 9556 if (inModule && symbol.attrs().test(Attr::EXTERNAL) && !IsPointer(symbol) && 9557 !symbol.test(Symbol::Flag::Function) && 9558 !symbol.test(Symbol::Flag::Subroutine)) { 9559 // in a module, external proc without return type is subroutine 9560 symbol.set( 9561 symbol.GetType() ? Symbol::Flag::Function : Symbol::Flag::Subroutine); 9562 } 9563 ApplyImplicitRules(symbol); 9564 } 9565 } 9566 9567 // Add SubprogramNameDetails symbols for module and internal subprograms and 9568 // their ENTRY statements. 9569 void ResolveNamesVisitor::AddSubpNames(ProgramTree &node) { 9570 auto kind{ 9571 node.IsModule() ? SubprogramKind::Module : SubprogramKind::Internal}; 9572 for (auto &child : node.children()) { 9573 auto &symbol{MakeSymbol(child.name(), SubprogramNameDetails{kind, child})}; 9574 if (child.HasModulePrefix()) { 9575 SetExplicitAttr(symbol, Attr::MODULE); 9576 } 9577 if (child.bindingSpec()) { 9578 SetExplicitAttr(symbol, Attr::BIND_C); 9579 } 9580 auto childKind{child.GetKind()}; 9581 if (childKind == ProgramTree::Kind::Function) { 9582 symbol.set(Symbol::Flag::Function); 9583 } else if (childKind == ProgramTree::Kind::Subroutine) { 9584 symbol.set(Symbol::Flag::Subroutine); 9585 } else { 9586 continue; // make ENTRY symbols only where valid 9587 } 9588 for (const auto &entryStmt : child.entryStmts()) { 9589 SubprogramNameDetails details{kind, child}; 9590 auto &symbol{ 9591 MakeSymbol(std::get<parser::Name>(entryStmt->t), std::move(details))}; 9592 symbol.set(child.GetSubpFlag()); 9593 if (child.HasModulePrefix()) { 9594 SetExplicitAttr(symbol, Attr::MODULE); 9595 } 9596 if (child.bindingSpec()) { 9597 SetExplicitAttr(symbol, Attr::BIND_C); 9598 } 9599 } 9600 } 9601 for (const auto &generic : node.genericSpecs()) { 9602 if (const auto *name{std::get_if<parser::Name>(&generic->u)}) { 9603 if (currScope().find(name->source) != currScope().end()) { 9604 // If this scope has both a generic interface and a contained 9605 // subprogram with the same name, create the generic's symbol 9606 // now so that any other generics of the same name that are pulled 9607 // into scope later via USE association will properly merge instead 9608 // of raising a bogus error due a conflict with the subprogram. 9609 CreateGeneric(*generic); 9610 } 9611 } 9612 } 9613 } 9614 9615 // Push a new scope for this node or return false on error. 9616 bool ResolveNamesVisitor::BeginScopeForNode(const ProgramTree &node) { 9617 switch (node.GetKind()) { 9618 SWITCH_COVERS_ALL_CASES 9619 case ProgramTree::Kind::Program: 9620 PushScope(Scope::Kind::MainProgram, 9621 &MakeSymbol(node.name(), MainProgramDetails{})); 9622 return true; 9623 case ProgramTree::Kind::Function: 9624 case ProgramTree::Kind::Subroutine: 9625 return BeginSubprogram(node.name(), node.GetSubpFlag(), 9626 node.HasModulePrefix(), node.bindingSpec(), &node.entryStmts()); 9627 case ProgramTree::Kind::MpSubprogram: 9628 return BeginMpSubprogram(node.name()); 9629 case ProgramTree::Kind::Module: 9630 BeginModule(node.name(), false); 9631 return true; 9632 case ProgramTree::Kind::Submodule: 9633 return BeginSubmodule(node.name(), node.GetParentId()); 9634 case ProgramTree::Kind::BlockData: 9635 PushBlockDataScope(node.name()); 9636 return true; 9637 } 9638 } 9639 9640 void ResolveNamesVisitor::EndScopeForNode(const ProgramTree &node) { 9641 std::optional<parser::CharBlock> stmtSource; 9642 const std::optional<parser::LanguageBindingSpec> *binding{nullptr}; 9643 common::visit( 9644 common::visitors{ 9645 [&](const parser::Statement<parser::FunctionStmt> *stmt) { 9646 if (stmt) { 9647 stmtSource = stmt->source; 9648 if (const auto &maybeSuffix{ 9649 std::get<std::optional<parser::Suffix>>( 9650 stmt->statement.t)}) { 9651 binding = &maybeSuffix->binding; 9652 } 9653 } 9654 }, 9655 [&](const parser::Statement<parser::SubroutineStmt> *stmt) { 9656 if (stmt) { 9657 stmtSource = stmt->source; 9658 binding = &std::get<std::optional<parser::LanguageBindingSpec>>( 9659 stmt->statement.t); 9660 } 9661 }, 9662 [](const auto *) {}, 9663 }, 9664 node.stmt()); 9665 EndSubprogram(stmtSource, binding, &node.entryStmts()); 9666 } 9667 9668 // Some analyses and checks, such as the processing of initializers of 9669 // pointers, are deferred until all of the pertinent specification parts 9670 // have been visited. This deferred processing enables the use of forward 9671 // references in these circumstances. 9672 // Data statement objects with implicit derived types are finally 9673 // resolved here. 9674 class DeferredCheckVisitor { 9675 public: 9676 explicit DeferredCheckVisitor(ResolveNamesVisitor &resolver) 9677 : resolver_{resolver} {} 9678 9679 template <typename A> void Walk(const A &x) { parser::Walk(x, *this); } 9680 9681 template <typename A> bool Pre(const A &) { return true; } 9682 template <typename A> void Post(const A &) {} 9683 9684 void Post(const parser::DerivedTypeStmt &x) { 9685 const auto &name{std::get<parser::Name>(x.t)}; 9686 if (Symbol * symbol{name.symbol}) { 9687 if (Scope * scope{symbol->scope()}) { 9688 if (scope->IsDerivedType()) { 9689 CHECK(outerScope_ == nullptr); 9690 outerScope_ = &resolver_.currScope(); 9691 resolver_.SetScope(*scope); 9692 } 9693 } 9694 } 9695 } 9696 void Post(const parser::EndTypeStmt &) { 9697 if (outerScope_) { 9698 resolver_.SetScope(*outerScope_); 9699 outerScope_ = nullptr; 9700 } 9701 } 9702 9703 void Post(const parser::ProcInterface &pi) { 9704 if (const auto *name{std::get_if<parser::Name>(&pi.u)}) { 9705 resolver_.CheckExplicitInterface(*name); 9706 } 9707 } 9708 bool Pre(const parser::EntityDecl &decl) { 9709 Init(std::get<parser::Name>(decl.t), 9710 std::get<std::optional<parser::Initialization>>(decl.t)); 9711 return false; 9712 } 9713 bool Pre(const parser::ComponentDecl &decl) { 9714 Init(std::get<parser::Name>(decl.t), 9715 std::get<std::optional<parser::Initialization>>(decl.t)); 9716 return false; 9717 } 9718 bool Pre(const parser::ProcDecl &decl) { 9719 if (const auto &init{ 9720 std::get<std::optional<parser::ProcPointerInit>>(decl.t)}) { 9721 resolver_.PointerInitialization(std::get<parser::Name>(decl.t), *init); 9722 } 9723 return false; 9724 } 9725 void Post(const parser::TypeBoundProcedureStmt::WithInterface &tbps) { 9726 resolver_.CheckExplicitInterface(tbps.interfaceName); 9727 } 9728 void Post(const parser::TypeBoundProcedureStmt::WithoutInterface &tbps) { 9729 if (outerScope_) { 9730 resolver_.CheckBindings(tbps); 9731 } 9732 } 9733 bool Pre(const parser::DataStmtObject &) { 9734 ++dataStmtObjectNesting_; 9735 return true; 9736 } 9737 void Post(const parser::DataStmtObject &) { --dataStmtObjectNesting_; } 9738 void Post(const parser::Designator &x) { 9739 if (dataStmtObjectNesting_ > 0) { 9740 resolver_.ResolveDesignator(x); 9741 } 9742 } 9743 9744 private: 9745 void Init(const parser::Name &name, 9746 const std::optional<parser::Initialization> &init) { 9747 if (init) { 9748 if (const auto *target{ 9749 std::get_if<parser::InitialDataTarget>(&init->u)}) { 9750 resolver_.PointerInitialization(name, *target); 9751 } else if (const auto *expr{ 9752 std::get_if<parser::ConstantExpr>(&init->u)}) { 9753 if (name.symbol) { 9754 if (const auto *object{name.symbol->detailsIf<ObjectEntityDetails>()}; 9755 !object || !object->init()) { 9756 resolver_.NonPointerInitialization(name, *expr); 9757 } 9758 } 9759 } 9760 } 9761 } 9762 9763 ResolveNamesVisitor &resolver_; 9764 Scope *outerScope_{nullptr}; 9765 int dataStmtObjectNesting_{0}; 9766 }; 9767 9768 // Perform checks and completions that need to happen after all of 9769 // the specification parts but before any of the execution parts. 9770 void ResolveNamesVisitor::FinishSpecificationParts(const ProgramTree &node) { 9771 if (!node.scope()) { 9772 return; // error occurred creating scope 9773 } 9774 auto flagRestorer{common::ScopedSet(inSpecificationPart_, true)}; 9775 SetScope(*node.scope()); 9776 // The initializers of pointers and non-PARAMETER objects, the default 9777 // initializers of components, and non-deferred type-bound procedure 9778 // bindings have not yet been traversed. 9779 // We do that now, when any forward references that appeared 9780 // in those initializers will resolve to the right symbols without 9781 // incurring spurious errors with IMPLICIT NONE or forward references 9782 // to nested subprograms. 9783 DeferredCheckVisitor{*this}.Walk(node.spec()); 9784 for (Scope &childScope : currScope().children()) { 9785 if (childScope.IsParameterizedDerivedTypeInstantiation()) { 9786 FinishDerivedTypeInstantiation(childScope); 9787 } 9788 } 9789 for (const auto &child : node.children()) { 9790 FinishSpecificationParts(child); 9791 } 9792 } 9793 9794 void ResolveNamesVisitor::FinishExecutionParts(const ProgramTree &node) { 9795 if (node.scope()) { 9796 SetScope(*node.scope()); 9797 if (node.exec()) { 9798 DeferredCheckVisitor{*this}.Walk(*node.exec()); 9799 } 9800 for (const auto &child : node.children()) { 9801 FinishExecutionParts(child); 9802 } 9803 } 9804 } 9805 9806 // Duplicate and fold component object pointer default initializer designators 9807 // using the actual type parameter values of each particular instantiation. 9808 // Validation is done later in declaration checking. 9809 void ResolveNamesVisitor::FinishDerivedTypeInstantiation(Scope &scope) { 9810 CHECK(scope.IsDerivedType() && !scope.symbol()); 9811 if (DerivedTypeSpec * spec{scope.derivedTypeSpec()}) { 9812 spec->Instantiate(currScope()); 9813 const Symbol &origTypeSymbol{spec->typeSymbol()}; 9814 if (const Scope * origTypeScope{origTypeSymbol.scope()}) { 9815 CHECK(origTypeScope->IsDerivedType() && 9816 origTypeScope->symbol() == &origTypeSymbol); 9817 auto &foldingContext{GetFoldingContext()}; 9818 auto restorer{foldingContext.WithPDTInstance(*spec)}; 9819 for (auto &pair : scope) { 9820 Symbol &comp{*pair.second}; 9821 const Symbol &origComp{DEREF(FindInScope(*origTypeScope, comp.name()))}; 9822 if (IsPointer(comp)) { 9823 if (auto *details{comp.detailsIf<ObjectEntityDetails>()}) { 9824 auto origDetails{origComp.get<ObjectEntityDetails>()}; 9825 if (const MaybeExpr & init{origDetails.init()}) { 9826 SomeExpr newInit{*init}; 9827 MaybeExpr folded{FoldExpr(std::move(newInit))}; 9828 details->set_init(std::move(folded)); 9829 } 9830 } 9831 } 9832 } 9833 } 9834 } 9835 } 9836 9837 // Resolve names in the execution part of this node and its children 9838 void ResolveNamesVisitor::ResolveExecutionParts(const ProgramTree &node) { 9839 if (!node.scope()) { 9840 return; // error occurred creating scope 9841 } 9842 SetScope(*node.scope()); 9843 if (const auto *exec{node.exec()}) { 9844 Walk(*exec); 9845 } 9846 FinishNamelists(); 9847 if (node.IsModule()) { 9848 // A second final pass to catch new symbols added from implicitly 9849 // typed names in NAMELIST groups or the specification parts of 9850 // module subprograms. 9851 ApplyDefaultAccess(); 9852 } 9853 PopScope(); // converts unclassified entities into objects 9854 for (const auto &child : node.children()) { 9855 ResolveExecutionParts(child); 9856 } 9857 } 9858 9859 void ResolveNamesVisitor::Post(const parser::Program &x) { 9860 // ensure that all temps were deallocated 9861 CHECK(!attrs_); 9862 CHECK(!cudaDataAttr_); 9863 CHECK(!GetDeclTypeSpec()); 9864 // Top-level resolution to propagate information across program units after 9865 // each of them has been resolved separately. 9866 ResolveOmpTopLevelParts(context(), x); 9867 } 9868 9869 // A singleton instance of the scope -> IMPLICIT rules mapping is 9870 // shared by all instances of ResolveNamesVisitor and accessed by this 9871 // pointer when the visitors (other than the top-level original) are 9872 // constructed. 9873 static ImplicitRulesMap *sharedImplicitRulesMap{nullptr}; 9874 9875 bool ResolveNames( 9876 SemanticsContext &context, const parser::Program &program, Scope &top) { 9877 ImplicitRulesMap implicitRulesMap; 9878 auto restorer{common::ScopedSet(sharedImplicitRulesMap, &implicitRulesMap)}; 9879 ResolveNamesVisitor{context, implicitRulesMap, top}.Walk(program); 9880 return !context.AnyFatalError(); 9881 } 9882 9883 // Processes a module (but not internal) function when it is referenced 9884 // in a specification expression in a sibling procedure. 9885 void ResolveSpecificationParts( 9886 SemanticsContext &context, const Symbol &subprogram) { 9887 auto originalLocation{context.location()}; 9888 ImplicitRulesMap implicitRulesMap; 9889 bool localImplicitRulesMap{false}; 9890 if (!sharedImplicitRulesMap) { 9891 sharedImplicitRulesMap = &implicitRulesMap; 9892 localImplicitRulesMap = true; 9893 } 9894 ResolveNamesVisitor visitor{ 9895 context, *sharedImplicitRulesMap, context.globalScope()}; 9896 const auto &details{subprogram.get<SubprogramNameDetails>()}; 9897 ProgramTree &node{details.node()}; 9898 const Scope &moduleScope{subprogram.owner()}; 9899 if (localImplicitRulesMap) { 9900 visitor.BeginScope(const_cast<Scope &>(moduleScope)); 9901 } else { 9902 visitor.SetScope(const_cast<Scope &>(moduleScope)); 9903 } 9904 visitor.ResolveSpecificationParts(node); 9905 context.set_location(std::move(originalLocation)); 9906 if (localImplicitRulesMap) { 9907 sharedImplicitRulesMap = nullptr; 9908 } 9909 } 9910 9911 } // namespace Fortran::semantics 9912