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 && 4019 (mod->GetName().value() == "cudadevice" || 4020 mod->GetName().value() == "__cuda_device")) { 4021 return false; 4022 } 4023 // Implicitly USE the cudadevice module by copying its symbols in the 4024 // current scope. 4025 const Scope &cudaDeviceScope{context().GetCUDADeviceScope()}; 4026 for (auto sym : cudaDeviceScope.GetSymbols()) { 4027 if (!currScope().FindSymbol(sym->name())) { 4028 auto &localSymbol{MakeSymbol( 4029 sym->name(), Attrs{}, UseDetails{sym->name(), *sym})}; 4030 localSymbol.flags() = sym->flags(); 4031 } 4032 } 4033 } 4034 } 4035 } 4036 return false; 4037 } 4038 4039 void SubprogramVisitor::Post(const parser::PrefixSpec::Launch_Bounds &x) { 4040 std::vector<std::int64_t> bounds; 4041 bool ok{true}; 4042 for (const auto &sicx : x.v) { 4043 if (auto value{evaluate::ToInt64(EvaluateExpr(sicx))}) { 4044 bounds.push_back(*value); 4045 } else { 4046 ok = false; 4047 } 4048 } 4049 if (!ok || bounds.size() < 2 || bounds.size() > 3) { 4050 Say(currStmtSource().value(), 4051 "Operands of LAUNCH_BOUNDS() must be 2 or 3 integer constants"_err_en_US); 4052 } else if (auto *subp{currScope().symbol() 4053 ? currScope().symbol()->detailsIf<SubprogramDetails>() 4054 : nullptr}) { 4055 if (subp->cudaLaunchBounds().empty()) { 4056 subp->set_cudaLaunchBounds(std::move(bounds)); 4057 } else { 4058 Say(currStmtSource().value(), 4059 "LAUNCH_BOUNDS() may only appear once"_err_en_US); 4060 } 4061 } 4062 } 4063 4064 void SubprogramVisitor::Post(const parser::PrefixSpec::Cluster_Dims &x) { 4065 std::vector<std::int64_t> dims; 4066 bool ok{true}; 4067 for (const auto &sicx : x.v) { 4068 if (auto value{evaluate::ToInt64(EvaluateExpr(sicx))}) { 4069 dims.push_back(*value); 4070 } else { 4071 ok = false; 4072 } 4073 } 4074 if (!ok || dims.size() != 3) { 4075 Say(currStmtSource().value(), 4076 "Operands of CLUSTER_DIMS() must be three integer constants"_err_en_US); 4077 } else if (auto *subp{currScope().symbol() 4078 ? currScope().symbol()->detailsIf<SubprogramDetails>() 4079 : nullptr}) { 4080 if (subp->cudaClusterDims().empty()) { 4081 subp->set_cudaClusterDims(std::move(dims)); 4082 } else { 4083 Say(currStmtSource().value(), 4084 "CLUSTER_DIMS() may only appear once"_err_en_US); 4085 } 4086 } 4087 } 4088 4089 static bool HasModulePrefix(const std::list<parser::PrefixSpec> &prefixes) { 4090 for (const auto &prefix : prefixes) { 4091 if (std::holds_alternative<parser::PrefixSpec::Module>(prefix.u)) { 4092 return true; 4093 } 4094 } 4095 return false; 4096 } 4097 4098 bool SubprogramVisitor::Pre(const parser::InterfaceBody::Subroutine &x) { 4099 const auto &stmtTuple{ 4100 std::get<parser::Statement<parser::SubroutineStmt>>(x.t).statement.t}; 4101 return BeginSubprogram(std::get<parser::Name>(stmtTuple), 4102 Symbol::Flag::Subroutine, 4103 HasModulePrefix(std::get<std::list<parser::PrefixSpec>>(stmtTuple))); 4104 } 4105 void SubprogramVisitor::Post(const parser::InterfaceBody::Subroutine &x) { 4106 const auto &stmt{std::get<parser::Statement<parser::SubroutineStmt>>(x.t)}; 4107 EndSubprogram(stmt.source, 4108 &std::get<std::optional<parser::LanguageBindingSpec>>(stmt.statement.t)); 4109 } 4110 bool SubprogramVisitor::Pre(const parser::InterfaceBody::Function &x) { 4111 const auto &stmtTuple{ 4112 std::get<parser::Statement<parser::FunctionStmt>>(x.t).statement.t}; 4113 return BeginSubprogram(std::get<parser::Name>(stmtTuple), 4114 Symbol::Flag::Function, 4115 HasModulePrefix(std::get<std::list<parser::PrefixSpec>>(stmtTuple))); 4116 } 4117 void SubprogramVisitor::Post(const parser::InterfaceBody::Function &x) { 4118 const auto &stmt{std::get<parser::Statement<parser::FunctionStmt>>(x.t)}; 4119 const auto &maybeSuffix{ 4120 std::get<std::optional<parser::Suffix>>(stmt.statement.t)}; 4121 EndSubprogram(stmt.source, maybeSuffix ? &maybeSuffix->binding : nullptr); 4122 } 4123 4124 bool SubprogramVisitor::Pre(const parser::SubroutineStmt &stmt) { 4125 BeginAttrs(); 4126 Walk(std::get<std::list<parser::PrefixSpec>>(stmt.t)); 4127 Walk(std::get<parser::Name>(stmt.t)); 4128 Walk(std::get<std::list<parser::DummyArg>>(stmt.t)); 4129 // Don't traverse the LanguageBindingSpec now; it's deferred to EndSubprogram. 4130 Symbol &symbol{PostSubprogramStmt()}; 4131 SubprogramDetails &details{symbol.get<SubprogramDetails>()}; 4132 for (const auto &dummyArg : std::get<std::list<parser::DummyArg>>(stmt.t)) { 4133 if (const auto *dummyName{std::get_if<parser::Name>(&dummyArg.u)}) { 4134 CreateDummyArgument(details, *dummyName); 4135 } else { 4136 details.add_alternateReturn(); 4137 } 4138 } 4139 return false; 4140 } 4141 bool SubprogramVisitor::Pre(const parser::FunctionStmt &) { 4142 FuncResultStack::FuncInfo &info{DEREF(funcResultStack().Top())}; 4143 CHECK(!info.inFunctionStmt); 4144 info.inFunctionStmt = true; 4145 if (auto at{currStmtSource()}) { 4146 info.source = *at; 4147 } 4148 return BeginAttrs(); 4149 } 4150 bool SubprogramVisitor::Pre(const parser::EntryStmt &) { return BeginAttrs(); } 4151 4152 void SubprogramVisitor::Post(const parser::FunctionStmt &stmt) { 4153 const auto &name{std::get<parser::Name>(stmt.t)}; 4154 Symbol &symbol{PostSubprogramStmt()}; 4155 SubprogramDetails &details{symbol.get<SubprogramDetails>()}; 4156 for (const auto &dummyName : std::get<std::list<parser::Name>>(stmt.t)) { 4157 CreateDummyArgument(details, dummyName); 4158 } 4159 const parser::Name *funcResultName; 4160 FuncResultStack::FuncInfo &info{DEREF(funcResultStack().Top())}; 4161 CHECK(info.inFunctionStmt); 4162 info.inFunctionStmt = false; 4163 bool distinctResultName{ 4164 info.resultName && info.resultName->source != name.source}; 4165 if (distinctResultName) { 4166 // Note that RESULT is ignored if it has the same name as the function. 4167 // The symbol created by PushScope() is retained as a place-holder 4168 // for error detection. 4169 funcResultName = info.resultName; 4170 } else { 4171 EraseSymbol(name); // was added by PushScope() 4172 funcResultName = &name; 4173 } 4174 if (details.isFunction()) { 4175 CHECK(context().HasError(currScope().symbol())); 4176 } else { 4177 // RESULT(x) can be the same explicitly-named RESULT(x) as an ENTRY 4178 // statement. 4179 Symbol *result{nullptr}; 4180 if (distinctResultName) { 4181 if (auto iter{currScope().find(funcResultName->source)}; 4182 iter != currScope().end()) { 4183 Symbol &entryResult{*iter->second}; 4184 if (IsFunctionResult(entryResult)) { 4185 result = &entryResult; 4186 } 4187 } 4188 } 4189 if (result) { 4190 Resolve(*funcResultName, *result); 4191 } else { 4192 // add function result to function scope 4193 EntityDetails funcResultDetails; 4194 funcResultDetails.set_funcResult(true); 4195 result = &MakeSymbol(*funcResultName, std::move(funcResultDetails)); 4196 } 4197 info.resultSymbol = result; 4198 details.set_result(*result); 4199 } 4200 // C1560. 4201 if (info.resultName && !distinctResultName) { 4202 context().Warn(common::UsageWarning::HomonymousResult, 4203 info.resultName->source, 4204 "The function name should not appear in RESULT; references to '%s' " 4205 "inside the function will be considered as references to the " 4206 "result only"_warn_en_US, 4207 name.source); 4208 // RESULT name was ignored above, the only side effect from doing so will be 4209 // the inability to make recursive calls. The related parser::Name is still 4210 // resolved to the created function result symbol because every parser::Name 4211 // should be resolved to avoid internal errors. 4212 Resolve(*info.resultName, info.resultSymbol); 4213 } 4214 name.symbol = &symbol; // must not be function result symbol 4215 // Clear the RESULT() name now in case an ENTRY statement in the implicit-part 4216 // has a RESULT() suffix. 4217 info.resultName = nullptr; 4218 } 4219 4220 Symbol &SubprogramVisitor::PostSubprogramStmt() { 4221 Symbol &symbol{*currScope().symbol()}; 4222 SetExplicitAttrs(symbol, EndAttrs()); 4223 if (symbol.attrs().test(Attr::MODULE)) { 4224 symbol.attrs().set(Attr::EXTERNAL, false); 4225 symbol.implicitAttrs().set(Attr::EXTERNAL, false); 4226 } 4227 return symbol; 4228 } 4229 4230 void SubprogramVisitor::Post(const parser::EntryStmt &stmt) { 4231 if (const auto &suffix{std::get<std::optional<parser::Suffix>>(stmt.t)}) { 4232 Walk(suffix->binding); 4233 } 4234 PostEntryStmt(stmt); 4235 EndAttrs(); 4236 } 4237 4238 void SubprogramVisitor::CreateDummyArgument( 4239 SubprogramDetails &details, const parser::Name &name) { 4240 Symbol *dummy{FindInScope(name)}; 4241 if (dummy) { 4242 if (IsDummy(*dummy)) { 4243 if (dummy->test(Symbol::Flag::EntryDummyArgument)) { 4244 dummy->set(Symbol::Flag::EntryDummyArgument, false); 4245 } else { 4246 Say(name, 4247 "'%s' appears more than once as a dummy argument name in this subprogram"_err_en_US, 4248 name.source); 4249 return; 4250 } 4251 } else { 4252 SayWithDecl(name, *dummy, 4253 "'%s' may not appear as a dummy argument name in this subprogram"_err_en_US); 4254 return; 4255 } 4256 } else { 4257 dummy = &MakeSymbol(name, EntityDetails{true}); 4258 } 4259 details.add_dummyArg(DEREF(dummy)); 4260 } 4261 4262 void SubprogramVisitor::CreateEntry( 4263 const parser::EntryStmt &stmt, Symbol &subprogram) { 4264 const auto &entryName{std::get<parser::Name>(stmt.t)}; 4265 Scope &outer{currScope().parent()}; 4266 Symbol::Flag subpFlag{subprogram.test(Symbol::Flag::Function) 4267 ? Symbol::Flag::Function 4268 : Symbol::Flag::Subroutine}; 4269 Attrs attrs; 4270 const auto &suffix{std::get<std::optional<parser::Suffix>>(stmt.t)}; 4271 bool hasGlobalBindingName{outer.IsGlobal() && suffix && suffix->binding && 4272 std::get<std::optional<parser::ScalarDefaultCharConstantExpr>>( 4273 suffix->binding->t) 4274 .has_value()}; 4275 if (!hasGlobalBindingName) { 4276 if (Symbol * extant{FindSymbol(outer, entryName)}) { 4277 if (!HandlePreviousCalls(entryName, *extant, subpFlag)) { 4278 if (outer.IsTopLevel()) { 4279 Say2(entryName, 4280 "'%s' is already defined as a global identifier"_err_en_US, 4281 *extant, "Previous definition of '%s'"_en_US); 4282 } else { 4283 SayAlreadyDeclared(entryName, *extant); 4284 } 4285 return; 4286 } 4287 attrs = extant->attrs(); 4288 } 4289 } 4290 std::optional<SourceName> distinctResultName; 4291 if (suffix && suffix->resultName && 4292 suffix->resultName->source != entryName.source) { 4293 distinctResultName = suffix->resultName->source; 4294 } 4295 if (outer.IsModule() && !attrs.test(Attr::PRIVATE)) { 4296 attrs.set(Attr::PUBLIC); 4297 } 4298 Symbol *entrySymbol{nullptr}; 4299 if (hasGlobalBindingName) { 4300 // Hide the entry's symbol in a new anonymous global scope so 4301 // that its name doesn't clash with anything. 4302 Symbol &symbol{MakeSymbol(outer, context().GetTempName(outer), Attrs{})}; 4303 symbol.set_details(MiscDetails{MiscDetails::Kind::ScopeName}); 4304 Scope &hidden{outer.MakeScope(Scope::Kind::Global, &symbol)}; 4305 entrySymbol = &MakeSymbol(hidden, entryName.source, attrs); 4306 } else { 4307 entrySymbol = FindInScope(outer, entryName.source); 4308 if (entrySymbol) { 4309 if (auto *generic{entrySymbol->detailsIf<GenericDetails>()}) { 4310 if (auto *specific{generic->specific()}) { 4311 // Forward reference to ENTRY from a generic interface 4312 entrySymbol = specific; 4313 CheckDuplicatedAttrs(entryName.source, *entrySymbol, attrs); 4314 SetExplicitAttrs(*entrySymbol, attrs); 4315 } 4316 } 4317 } else { 4318 entrySymbol = &MakeSymbol(outer, entryName.source, attrs); 4319 } 4320 } 4321 SubprogramDetails entryDetails; 4322 entryDetails.set_entryScope(currScope()); 4323 entrySymbol->set(subpFlag); 4324 if (subpFlag == Symbol::Flag::Function) { 4325 Symbol *result{nullptr}; 4326 EntityDetails resultDetails; 4327 resultDetails.set_funcResult(true); 4328 if (distinctResultName) { 4329 // An explicit RESULT() can also be an explicit RESULT() 4330 // of the function or another ENTRY. 4331 if (auto iter{currScope().find(suffix->resultName->source)}; 4332 iter != currScope().end()) { 4333 result = &*iter->second; 4334 } 4335 if (!result) { 4336 result = 4337 &MakeSymbol(*distinctResultName, Attrs{}, std::move(resultDetails)); 4338 } else if (!result->has<EntityDetails>()) { 4339 Say(*distinctResultName, 4340 "ENTRY cannot have RESULT(%s) that is not a variable"_err_en_US, 4341 *distinctResultName) 4342 .Attach(result->name(), "Existing declaration of '%s'"_en_US, 4343 result->name()); 4344 result = nullptr; 4345 } 4346 if (result) { 4347 Resolve(*suffix->resultName, *result); 4348 } 4349 } else { 4350 result = &MakeSymbol(entryName.source, Attrs{}, std::move(resultDetails)); 4351 } 4352 if (result) { 4353 entryDetails.set_result(*result); 4354 } 4355 } 4356 if (subpFlag == Symbol::Flag::Subroutine || distinctResultName) { 4357 Symbol &assoc{MakeSymbol(entryName.source)}; 4358 assoc.set_details(HostAssocDetails{*entrySymbol}); 4359 assoc.set(Symbol::Flag::Subroutine); 4360 } 4361 Resolve(entryName, *entrySymbol); 4362 std::set<SourceName> dummies; 4363 for (const auto &dummyArg : std::get<std::list<parser::DummyArg>>(stmt.t)) { 4364 if (const auto *dummyName{std::get_if<parser::Name>(&dummyArg.u)}) { 4365 auto pair{dummies.insert(dummyName->source)}; 4366 if (!pair.second) { 4367 Say(*dummyName, 4368 "'%s' appears more than once as a dummy argument name in this ENTRY statement"_err_en_US, 4369 dummyName->source); 4370 continue; 4371 } 4372 Symbol *dummy{FindInScope(*dummyName)}; 4373 if (dummy) { 4374 if (!IsDummy(*dummy)) { 4375 evaluate::AttachDeclaration( 4376 Say(*dummyName, 4377 "'%s' may not appear as a dummy argument name in this ENTRY statement"_err_en_US, 4378 dummyName->source), 4379 *dummy); 4380 continue; 4381 } 4382 } else { 4383 dummy = &MakeSymbol(*dummyName, EntityDetails{true}); 4384 dummy->set(Symbol::Flag::EntryDummyArgument); 4385 } 4386 entryDetails.add_dummyArg(DEREF(dummy)); 4387 } else if (subpFlag == Symbol::Flag::Function) { // C1573 4388 Say(entryName, 4389 "ENTRY in a function may not have an alternate return dummy argument"_err_en_US); 4390 break; 4391 } else { 4392 entryDetails.add_alternateReturn(); 4393 } 4394 } 4395 entrySymbol->set_details(std::move(entryDetails)); 4396 } 4397 4398 void SubprogramVisitor::PostEntryStmt(const parser::EntryStmt &stmt) { 4399 // The entry symbol should have already been created and resolved 4400 // in CreateEntry(), called by BeginSubprogram(), with one exception (below). 4401 const auto &name{std::get<parser::Name>(stmt.t)}; 4402 Scope &inclusiveScope{InclusiveScope()}; 4403 if (!name.symbol) { 4404 if (inclusiveScope.kind() != Scope::Kind::Subprogram) { 4405 Say(name.source, 4406 "ENTRY '%s' may appear only in a subroutine or function"_err_en_US, 4407 name.source); 4408 } else if (FindSeparateModuleSubprogramInterface(inclusiveScope.symbol())) { 4409 Say(name.source, 4410 "ENTRY '%s' may not appear in a separate module procedure"_err_en_US, 4411 name.source); 4412 } else { 4413 // C1571 - entry is nested, so was not put into the program tree; error 4414 // is emitted from MiscChecker in semantics.cpp. 4415 } 4416 return; 4417 } 4418 Symbol &entrySymbol{*name.symbol}; 4419 if (context().HasError(entrySymbol)) { 4420 return; 4421 } 4422 if (!entrySymbol.has<SubprogramDetails>()) { 4423 SayAlreadyDeclared(name, entrySymbol); 4424 return; 4425 } 4426 SubprogramDetails &entryDetails{entrySymbol.get<SubprogramDetails>()}; 4427 CHECK(entryDetails.entryScope() == &inclusiveScope); 4428 SetCUDADataAttr(name.source, entrySymbol, cudaDataAttr()); 4429 entrySymbol.attrs() |= GetAttrs(); 4430 SetBindNameOn(entrySymbol); 4431 for (const auto &dummyArg : std::get<std::list<parser::DummyArg>>(stmt.t)) { 4432 if (const auto *dummyName{std::get_if<parser::Name>(&dummyArg.u)}) { 4433 if (Symbol * dummy{FindInScope(*dummyName)}) { 4434 if (dummy->test(Symbol::Flag::EntryDummyArgument)) { 4435 const auto *subp{dummy->detailsIf<SubprogramDetails>()}; 4436 if (subp && subp->isInterface()) { // ok 4437 } else if (!dummy->has<EntityDetails>() && 4438 !dummy->has<ObjectEntityDetails>() && 4439 !dummy->has<ProcEntityDetails>()) { 4440 SayWithDecl(*dummyName, *dummy, 4441 "ENTRY dummy argument '%s' was previously declared as an item that may not be used as a dummy argument"_err_en_US); 4442 } 4443 dummy->set(Symbol::Flag::EntryDummyArgument, false); 4444 } 4445 } 4446 } 4447 } 4448 } 4449 4450 Symbol *ScopeHandler::FindSeparateModuleProcedureInterface( 4451 const parser::Name &name) { 4452 auto *symbol{FindSymbol(name)}; 4453 if (symbol && symbol->has<SubprogramNameDetails>()) { 4454 const Scope *parent{nullptr}; 4455 if (currScope().IsSubmodule()) { 4456 parent = currScope().symbol()->get<ModuleDetails>().parent(); 4457 } 4458 symbol = parent ? FindSymbol(*parent, name) : nullptr; 4459 } 4460 if (symbol) { 4461 if (auto *generic{symbol->detailsIf<GenericDetails>()}) { 4462 symbol = generic->specific(); 4463 } 4464 } 4465 if (const Symbol * defnIface{FindSeparateModuleSubprogramInterface(symbol)}) { 4466 // Error recovery in case of multiple definitions 4467 symbol = const_cast<Symbol *>(defnIface); 4468 } 4469 if (!IsSeparateModuleProcedureInterface(symbol)) { 4470 Say(name, "'%s' was not declared a separate module procedure"_err_en_US); 4471 symbol = nullptr; 4472 } 4473 return symbol; 4474 } 4475 4476 // A subprogram declared with MODULE PROCEDURE 4477 bool SubprogramVisitor::BeginMpSubprogram(const parser::Name &name) { 4478 Symbol *symbol{FindSeparateModuleProcedureInterface(name)}; 4479 if (!symbol) { 4480 return false; 4481 } 4482 if (symbol->owner() == currScope() && symbol->scope()) { 4483 // This is a MODULE PROCEDURE whose interface appears in its host. 4484 // Convert the module procedure's interface into a subprogram. 4485 SetScope(DEREF(symbol->scope())); 4486 symbol->get<SubprogramDetails>().set_isInterface(false); 4487 name.symbol = symbol; 4488 } else { 4489 // Copy the interface into a new subprogram scope. 4490 EraseSymbol(name); 4491 Symbol &newSymbol{MakeSymbol(name, SubprogramDetails{})}; 4492 PushScope(Scope::Kind::Subprogram, &newSymbol); 4493 auto &newSubprogram{newSymbol.get<SubprogramDetails>()}; 4494 newSubprogram.set_moduleInterface(*symbol); 4495 auto &subprogram{symbol->get<SubprogramDetails>()}; 4496 if (const auto *name{subprogram.bindName()}) { 4497 newSubprogram.set_bindName(std::string{*name}); 4498 } 4499 newSymbol.attrs() |= symbol->attrs(); 4500 newSymbol.set(symbol->test(Symbol::Flag::Subroutine) 4501 ? Symbol::Flag::Subroutine 4502 : Symbol::Flag::Function); 4503 MapSubprogramToNewSymbols(*symbol, newSymbol, currScope()); 4504 } 4505 return true; 4506 } 4507 4508 // A subprogram or interface declared with SUBROUTINE or FUNCTION 4509 bool SubprogramVisitor::BeginSubprogram(const parser::Name &name, 4510 Symbol::Flag subpFlag, bool hasModulePrefix, 4511 const parser::LanguageBindingSpec *bindingSpec, 4512 const ProgramTree::EntryStmtList *entryStmts) { 4513 bool isValid{true}; 4514 if (hasModulePrefix && !currScope().IsModule() && 4515 !currScope().IsSubmodule()) { // C1547 4516 Say(name, 4517 "'%s' is a MODULE procedure which must be declared within a " 4518 "MODULE or SUBMODULE"_err_en_US); 4519 // Don't return here because it can be useful to have the scope set for 4520 // other semantic checks run before we print the errors 4521 isValid = false; 4522 } 4523 Symbol *moduleInterface{nullptr}; 4524 if (isValid && hasModulePrefix && !inInterfaceBlock()) { 4525 moduleInterface = FindSeparateModuleProcedureInterface(name); 4526 if (moduleInterface && &moduleInterface->owner() == &currScope()) { 4527 // Subprogram is MODULE FUNCTION or MODULE SUBROUTINE with an interface 4528 // previously defined in the same scope. 4529 if (GenericDetails * 4530 generic{DEREF(FindSymbol(name)).detailsIf<GenericDetails>()}) { 4531 generic->clear_specific(); 4532 name.symbol = nullptr; 4533 } else { 4534 EraseSymbol(name); 4535 } 4536 } 4537 } 4538 Symbol &newSymbol{ 4539 PushSubprogramScope(name, subpFlag, bindingSpec, hasModulePrefix)}; 4540 if (moduleInterface) { 4541 newSymbol.get<SubprogramDetails>().set_moduleInterface(*moduleInterface); 4542 if (moduleInterface->attrs().test(Attr::PRIVATE)) { 4543 SetImplicitAttr(newSymbol, Attr::PRIVATE); 4544 } else if (moduleInterface->attrs().test(Attr::PUBLIC)) { 4545 SetImplicitAttr(newSymbol, Attr::PUBLIC); 4546 } 4547 } 4548 if (entryStmts) { 4549 for (const auto &ref : *entryStmts) { 4550 CreateEntry(*ref, newSymbol); 4551 } 4552 } 4553 return true; 4554 } 4555 4556 void SubprogramVisitor::HandleLanguageBinding(Symbol *symbol, 4557 std::optional<parser::CharBlock> stmtSource, 4558 const std::optional<parser::LanguageBindingSpec> *binding) { 4559 if (binding && *binding && symbol) { 4560 // Finally process the BIND(C,NAME=name) now that symbols in the name 4561 // expression will resolve to local names if needed. 4562 auto flagRestorer{common::ScopedSet(inSpecificationPart_, false)}; 4563 auto originalStmtSource{messageHandler().currStmtSource()}; 4564 messageHandler().set_currStmtSource(stmtSource); 4565 BeginAttrs(); 4566 Walk(**binding); 4567 SetBindNameOn(*symbol); 4568 symbol->attrs() |= EndAttrs(); 4569 messageHandler().set_currStmtSource(originalStmtSource); 4570 } 4571 } 4572 4573 void SubprogramVisitor::EndSubprogram( 4574 std::optional<parser::CharBlock> stmtSource, 4575 const std::optional<parser::LanguageBindingSpec> *binding, 4576 const ProgramTree::EntryStmtList *entryStmts) { 4577 HandleLanguageBinding(currScope().symbol(), stmtSource, binding); 4578 if (entryStmts) { 4579 for (const auto &ref : *entryStmts) { 4580 const parser::EntryStmt &entryStmt{*ref}; 4581 if (const auto &suffix{ 4582 std::get<std::optional<parser::Suffix>>(entryStmt.t)}) { 4583 const auto &name{std::get<parser::Name>(entryStmt.t)}; 4584 HandleLanguageBinding(name.symbol, name.source, &suffix->binding); 4585 } 4586 } 4587 } 4588 if (inInterfaceBlock() && currScope().symbol()) { 4589 DeclaredPossibleSpecificProc(*currScope().symbol()); 4590 } 4591 PopScope(); 4592 } 4593 4594 bool SubprogramVisitor::HandlePreviousCalls( 4595 const parser::Name &name, Symbol &symbol, Symbol::Flag subpFlag) { 4596 // If the extant symbol is a generic, check its homonymous specific 4597 // procedure instead if it has one. 4598 if (auto *generic{symbol.detailsIf<GenericDetails>()}) { 4599 return generic->specific() && 4600 HandlePreviousCalls(name, *generic->specific(), subpFlag); 4601 } else if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}; proc && 4602 !proc->isDummy() && 4603 !symbol.attrs().HasAny(Attrs{Attr::INTRINSIC, Attr::POINTER})) { 4604 // There's a symbol created for previous calls to this subprogram or 4605 // ENTRY's name. We have to replace that symbol in situ to avoid the 4606 // obligation to rewrite symbol pointers in the parse tree. 4607 if (!symbol.test(subpFlag)) { 4608 auto other{subpFlag == Symbol::Flag::Subroutine 4609 ? Symbol::Flag::Function 4610 : Symbol::Flag::Subroutine}; 4611 // External statements issue an explicit EXTERNAL attribute. 4612 if (symbol.attrs().test(Attr::EXTERNAL) && 4613 !symbol.implicitAttrs().test(Attr::EXTERNAL)) { 4614 // Warn if external statement previously declared. 4615 context().Warn(common::LanguageFeature::RedundantAttribute, name.source, 4616 "EXTERNAL attribute was already specified on '%s'"_warn_en_US, 4617 name.source); 4618 } else if (symbol.test(other)) { 4619 Say2(name, 4620 subpFlag == Symbol::Flag::Function 4621 ? "'%s' was previously called as a subroutine"_err_en_US 4622 : "'%s' was previously called as a function"_err_en_US, 4623 symbol, "Previous call of '%s'"_en_US); 4624 } else { 4625 symbol.set(subpFlag); 4626 } 4627 } 4628 EntityDetails entity; 4629 if (proc->type()) { 4630 entity.set_type(*proc->type()); 4631 } 4632 symbol.details() = std::move(entity); 4633 return true; 4634 } else { 4635 return symbol.has<UnknownDetails>() || symbol.has<SubprogramNameDetails>(); 4636 } 4637 } 4638 4639 void SubprogramVisitor::CheckExtantProc( 4640 const parser::Name &name, Symbol::Flag subpFlag) { 4641 if (auto *prev{FindSymbol(name)}) { 4642 if (IsDummy(*prev)) { 4643 } else if (auto *entity{prev->detailsIf<EntityDetails>()}; 4644 IsPointer(*prev) && entity && !entity->type()) { 4645 // POINTER attribute set before interface 4646 } else if (inInterfaceBlock() && currScope() != prev->owner()) { 4647 // Procedures in an INTERFACE block do not resolve to symbols 4648 // in scopes between the global scope and the current scope. 4649 } else if (!HandlePreviousCalls(name, *prev, subpFlag)) { 4650 SayAlreadyDeclared(name, *prev); 4651 } 4652 } 4653 } 4654 4655 Symbol &SubprogramVisitor::PushSubprogramScope(const parser::Name &name, 4656 Symbol::Flag subpFlag, const parser::LanguageBindingSpec *bindingSpec, 4657 bool hasModulePrefix) { 4658 Symbol *symbol{GetSpecificFromGeneric(name)}; 4659 if (!symbol) { 4660 if (bindingSpec && currScope().IsGlobal() && 4661 std::get<std::optional<parser::ScalarDefaultCharConstantExpr>>( 4662 bindingSpec->t) 4663 .has_value()) { 4664 // Create this new top-level subprogram with a binding label 4665 // in a new global scope, so that its symbol's name won't clash 4666 // with another symbol that has a distinct binding label. 4667 PushScope(Scope::Kind::Global, 4668 &MakeSymbol(context().GetTempName(currScope()), Attrs{}, 4669 MiscDetails{MiscDetails::Kind::ScopeName})); 4670 } 4671 CheckExtantProc(name, subpFlag); 4672 symbol = &MakeSymbol(name, SubprogramDetails{}); 4673 } 4674 symbol->ReplaceName(name.source); 4675 symbol->set(subpFlag); 4676 PushScope(Scope::Kind::Subprogram, symbol); 4677 if (subpFlag == Symbol::Flag::Function) { 4678 funcResultStack().Push(currScope(), name.source); 4679 } 4680 if (inInterfaceBlock()) { 4681 auto &details{symbol->get<SubprogramDetails>()}; 4682 details.set_isInterface(); 4683 if (isAbstract()) { 4684 SetExplicitAttr(*symbol, Attr::ABSTRACT); 4685 } else if (hasModulePrefix) { 4686 SetExplicitAttr(*symbol, Attr::MODULE); 4687 } else { 4688 MakeExternal(*symbol); 4689 } 4690 if (isGeneric()) { 4691 Symbol &genericSymbol{GetGenericSymbol()}; 4692 if (auto *details{genericSymbol.detailsIf<GenericDetails>()}) { 4693 details->AddSpecificProc(*symbol, name.source); 4694 } else { 4695 CHECK(context().HasError(genericSymbol)); 4696 } 4697 } 4698 set_inheritFromParent(false); // interfaces don't inherit, even if MODULE 4699 } 4700 if (Symbol * found{FindSymbol(name)}; 4701 found && found->has<HostAssocDetails>()) { 4702 found->set(subpFlag); // PushScope() created symbol 4703 } 4704 return *symbol; 4705 } 4706 4707 void SubprogramVisitor::PushBlockDataScope(const parser::Name &name) { 4708 if (auto *prev{FindSymbol(name)}) { 4709 if (prev->attrs().test(Attr::EXTERNAL) && prev->has<ProcEntityDetails>()) { 4710 if (prev->test(Symbol::Flag::Subroutine) || 4711 prev->test(Symbol::Flag::Function)) { 4712 Say2(name, "BLOCK DATA '%s' has been called"_err_en_US, *prev, 4713 "Previous call of '%s'"_en_US); 4714 } 4715 EraseSymbol(name); 4716 } 4717 } 4718 if (name.source.empty()) { 4719 // Don't let unnamed BLOCK DATA conflict with unnamed PROGRAM 4720 PushScope(Scope::Kind::BlockData, nullptr); 4721 } else { 4722 PushScope(Scope::Kind::BlockData, &MakeSymbol(name, SubprogramDetails{})); 4723 } 4724 } 4725 4726 // If name is a generic, return specific subprogram with the same name. 4727 Symbol *SubprogramVisitor::GetSpecificFromGeneric(const parser::Name &name) { 4728 // Search for the name but don't resolve it 4729 if (auto *symbol{currScope().FindSymbol(name.source)}) { 4730 if (symbol->has<SubprogramNameDetails>()) { 4731 if (inInterfaceBlock()) { 4732 // Subtle: clear any MODULE flag so that the new interface 4733 // symbol doesn't inherit it and ruin the ability to check it. 4734 symbol->attrs().reset(Attr::MODULE); 4735 } 4736 } else if (auto *details{symbol->detailsIf<GenericDetails>()}) { 4737 // found generic, want specific procedure 4738 auto *specific{details->specific()}; 4739 Attrs moduleAttr; 4740 if (inInterfaceBlock()) { 4741 if (specific) { 4742 // Defining an interface in a generic of the same name which is 4743 // already shadowing another procedure. In some cases, the shadowed 4744 // procedure is about to be replaced. 4745 if (specific->has<SubprogramNameDetails>() && 4746 specific->attrs().test(Attr::MODULE)) { 4747 // The shadowed procedure is a separate module procedure that is 4748 // actually defined later in this (sub)module. 4749 // Define its interface now as a new symbol. 4750 moduleAttr.set(Attr::MODULE); 4751 specific = nullptr; 4752 } else if (&specific->owner() != &symbol->owner()) { 4753 // The shadowed procedure was from an enclosing scope and will be 4754 // overridden by this interface definition. 4755 specific = nullptr; 4756 } 4757 if (!specific) { 4758 details->clear_specific(); 4759 } 4760 } else if (const auto *dType{details->derivedType()}) { 4761 if (&dType->owner() != &symbol->owner()) { 4762 // The shadowed derived type was from an enclosing scope and 4763 // will be overridden by this interface definition. 4764 details->clear_derivedType(); 4765 } 4766 } 4767 } 4768 if (!specific) { 4769 specific = &currScope().MakeSymbol( 4770 name.source, std::move(moduleAttr), SubprogramDetails{}); 4771 if (details->derivedType()) { 4772 // A specific procedure with the same name as a derived type 4773 SayAlreadyDeclared(name, *details->derivedType()); 4774 } else { 4775 details->set_specific(Resolve(name, *specific)); 4776 } 4777 } else if (isGeneric()) { 4778 SayAlreadyDeclared(name, *specific); 4779 } 4780 if (specific->has<SubprogramNameDetails>()) { 4781 specific->set_details(Details{SubprogramDetails{}}); 4782 } 4783 return specific; 4784 } 4785 } 4786 return nullptr; 4787 } 4788 4789 // DeclarationVisitor implementation 4790 4791 bool DeclarationVisitor::BeginDecl() { 4792 BeginDeclTypeSpec(); 4793 BeginArraySpec(); 4794 return BeginAttrs(); 4795 } 4796 void DeclarationVisitor::EndDecl() { 4797 EndDeclTypeSpec(); 4798 EndArraySpec(); 4799 EndAttrs(); 4800 } 4801 4802 bool DeclarationVisitor::CheckUseError(const parser::Name &name) { 4803 return HadUseError(context(), name.source, name.symbol); 4804 } 4805 4806 // Report error if accessibility of symbol doesn't match isPrivate. 4807 void DeclarationVisitor::CheckAccessibility( 4808 const SourceName &name, bool isPrivate, Symbol &symbol) { 4809 if (symbol.attrs().test(Attr::PRIVATE) != isPrivate) { 4810 Say2(name, 4811 "'%s' does not have the same accessibility as its previous declaration"_err_en_US, 4812 symbol, "Previous declaration of '%s'"_en_US); 4813 } 4814 } 4815 4816 bool DeclarationVisitor::Pre(const parser::TypeDeclarationStmt &x) { 4817 BeginDecl(); 4818 // If INTRINSIC appears as an attr-spec, handle it now as if the 4819 // names had appeared on an INTRINSIC attribute statement beforehand. 4820 for (const auto &attr : std::get<std::list<parser::AttrSpec>>(x.t)) { 4821 if (std::holds_alternative<parser::Intrinsic>(attr.u)) { 4822 for (const auto &decl : std::get<std::list<parser::EntityDecl>>(x.t)) { 4823 DeclareIntrinsic(parser::GetFirstName(decl)); 4824 } 4825 break; 4826 } 4827 } 4828 return true; 4829 } 4830 void DeclarationVisitor::Post(const parser::TypeDeclarationStmt &) { 4831 EndDecl(); 4832 } 4833 4834 void DeclarationVisitor::Post(const parser::DimensionStmt::Declaration &x) { 4835 DeclareObjectEntity(std::get<parser::Name>(x.t)); 4836 } 4837 void DeclarationVisitor::Post(const parser::CodimensionDecl &x) { 4838 DeclareObjectEntity(std::get<parser::Name>(x.t)); 4839 } 4840 4841 bool DeclarationVisitor::Pre(const parser::Initialization &) { 4842 // Defer inspection of initializers to Initialization() so that the 4843 // symbol being initialized will be available within the initialization 4844 // expression. 4845 return false; 4846 } 4847 4848 void DeclarationVisitor::Post(const parser::EntityDecl &x) { 4849 const auto &name{std::get<parser::ObjectName>(x.t)}; 4850 Attrs attrs{attrs_ ? HandleSaveName(name.source, *attrs_) : Attrs{}}; 4851 attrs.set(Attr::INTRINSIC, false); // dealt with in Pre(TypeDeclarationStmt) 4852 Symbol &symbol{DeclareUnknownEntity(name, attrs)}; 4853 symbol.ReplaceName(name.source); 4854 SetCUDADataAttr(name.source, symbol, cudaDataAttr()); 4855 if (const auto &init{std::get<std::optional<parser::Initialization>>(x.t)}) { 4856 ConvertToObjectEntity(symbol) || ConvertToProcEntity(symbol); 4857 symbol.set( 4858 Symbol::Flag::EntryDummyArgument, false); // forestall excessive errors 4859 Initialization(name, *init, false); 4860 } else if (attrs.test(Attr::PARAMETER)) { // C882, C883 4861 Say(name, "Missing initialization for parameter '%s'"_err_en_US); 4862 } 4863 if (auto *scopeSymbol{currScope().symbol()}) { 4864 if (auto *details{scopeSymbol->detailsIf<DerivedTypeDetails>()}) { 4865 if (details->isDECStructure()) { 4866 details->add_component(symbol); 4867 } 4868 } 4869 } 4870 } 4871 4872 void DeclarationVisitor::Post(const parser::PointerDecl &x) { 4873 const auto &name{std::get<parser::Name>(x.t)}; 4874 if (const auto &deferredShapeSpecs{ 4875 std::get<std::optional<parser::DeferredShapeSpecList>>(x.t)}) { 4876 CHECK(arraySpec().empty()); 4877 BeginArraySpec(); 4878 set_arraySpec(AnalyzeDeferredShapeSpecList(context(), *deferredShapeSpecs)); 4879 Symbol &symbol{DeclareObjectEntity(name, Attrs{Attr::POINTER})}; 4880 symbol.ReplaceName(name.source); 4881 EndArraySpec(); 4882 } else { 4883 if (const auto *symbol{FindInScope(name)}) { 4884 const auto *subp{symbol->detailsIf<SubprogramDetails>()}; 4885 if (!symbol->has<UseDetails>() && // error caught elsewhere 4886 !symbol->has<ObjectEntityDetails>() && 4887 !symbol->has<ProcEntityDetails>() && 4888 !symbol->CanReplaceDetails(ObjectEntityDetails{}) && 4889 !symbol->CanReplaceDetails(ProcEntityDetails{}) && 4890 !(subp && subp->isInterface())) { 4891 Say(name, "'%s' cannot have the POINTER attribute"_err_en_US); 4892 } 4893 } 4894 HandleAttributeStmt(Attr::POINTER, std::get<parser::Name>(x.t)); 4895 } 4896 } 4897 4898 bool DeclarationVisitor::Pre(const parser::BindEntity &x) { 4899 auto kind{std::get<parser::BindEntity::Kind>(x.t)}; 4900 auto &name{std::get<parser::Name>(x.t)}; 4901 Symbol *symbol; 4902 if (kind == parser::BindEntity::Kind::Object) { 4903 symbol = &HandleAttributeStmt(Attr::BIND_C, name); 4904 } else { 4905 symbol = &MakeCommonBlockSymbol(name); 4906 SetExplicitAttr(*symbol, Attr::BIND_C); 4907 } 4908 // 8.6.4(1) 4909 // Some entities such as named constant or module name need to checked 4910 // elsewhere. This is to skip the ICE caused by setting Bind name for non-name 4911 // things such as data type and also checks for procedures. 4912 if (symbol->has<CommonBlockDetails>() || symbol->has<ObjectEntityDetails>() || 4913 symbol->has<EntityDetails>()) { 4914 SetBindNameOn(*symbol); 4915 } else { 4916 Say(name, 4917 "Only variable and named common block can be in BIND statement"_err_en_US); 4918 } 4919 return false; 4920 } 4921 bool DeclarationVisitor::Pre(const parser::OldParameterStmt &x) { 4922 inOldStyleParameterStmt_ = true; 4923 Walk(x.v); 4924 inOldStyleParameterStmt_ = false; 4925 return false; 4926 } 4927 bool DeclarationVisitor::Pre(const parser::NamedConstantDef &x) { 4928 auto &name{std::get<parser::NamedConstant>(x.t).v}; 4929 auto &symbol{HandleAttributeStmt(Attr::PARAMETER, name)}; 4930 ConvertToObjectEntity(symbol); 4931 auto *details{symbol.detailsIf<ObjectEntityDetails>()}; 4932 if (!details || symbol.test(Symbol::Flag::CrayPointer) || 4933 symbol.test(Symbol::Flag::CrayPointee)) { 4934 SayWithDecl( 4935 name, symbol, "PARAMETER attribute not allowed on '%s'"_err_en_US); 4936 return false; 4937 } 4938 const auto &expr{std::get<parser::ConstantExpr>(x.t)}; 4939 if (details->init() || symbol.test(Symbol::Flag::InDataStmt)) { 4940 Say(name, "Named constant '%s' already has a value"_err_en_US); 4941 } 4942 if (inOldStyleParameterStmt_) { 4943 // non-standard extension PARAMETER statement (no parentheses) 4944 Walk(expr); 4945 auto folded{EvaluateExpr(expr)}; 4946 if (details->type()) { 4947 SayWithDecl(name, symbol, 4948 "Alternative style PARAMETER '%s' must not already have an explicit type"_err_en_US); 4949 } else if (folded) { 4950 auto at{expr.thing.value().source}; 4951 if (evaluate::IsActuallyConstant(*folded)) { 4952 if (const auto *type{currScope().GetType(*folded)}) { 4953 if (type->IsPolymorphic()) { 4954 Say(at, "The expression must not be polymorphic"_err_en_US); 4955 } else if (auto shape{ToArraySpec( 4956 GetFoldingContext(), evaluate::GetShape(*folded))}) { 4957 // The type of the named constant is assumed from the expression. 4958 details->set_type(*type); 4959 details->set_init(std::move(*folded)); 4960 details->set_shape(std::move(*shape)); 4961 } else { 4962 Say(at, "The expression must have constant shape"_err_en_US); 4963 } 4964 } else { 4965 Say(at, "The expression must have a known type"_err_en_US); 4966 } 4967 } else { 4968 Say(at, "The expression must be a constant of known type"_err_en_US); 4969 } 4970 } 4971 } else { 4972 // standard-conforming PARAMETER statement (with parentheses) 4973 ApplyImplicitRules(symbol); 4974 Walk(expr); 4975 if (auto converted{EvaluateNonPointerInitializer( 4976 symbol, expr, expr.thing.value().source)}) { 4977 details->set_init(std::move(*converted)); 4978 } 4979 } 4980 return false; 4981 } 4982 bool DeclarationVisitor::Pre(const parser::NamedConstant &x) { 4983 const parser::Name &name{x.v}; 4984 if (!FindSymbol(name)) { 4985 Say(name, "Named constant '%s' not found"_err_en_US); 4986 } else { 4987 CheckUseError(name); 4988 } 4989 return false; 4990 } 4991 4992 bool DeclarationVisitor::Pre(const parser::Enumerator &enumerator) { 4993 const parser::Name &name{std::get<parser::NamedConstant>(enumerator.t).v}; 4994 Symbol *symbol{FindInScope(name)}; 4995 if (symbol && !symbol->has<UnknownDetails>()) { 4996 // Contrary to named constants appearing in a PARAMETER statement, 4997 // enumerator names should not have their type, dimension or any other 4998 // attributes defined before they are declared in the enumerator statement, 4999 // with the exception of accessibility. 5000 // This is not explicitly forbidden by the standard, but they are scalars 5001 // which type is left for the compiler to chose, so do not let users try to 5002 // tamper with that. 5003 SayAlreadyDeclared(name, *symbol); 5004 symbol = nullptr; 5005 } else { 5006 // Enumerators are treated as PARAMETER (section 7.6 paragraph (4)) 5007 symbol = &MakeSymbol(name, Attrs{Attr::PARAMETER}, ObjectEntityDetails{}); 5008 symbol->SetType(context().MakeNumericType( 5009 TypeCategory::Integer, evaluate::CInteger::kind)); 5010 } 5011 5012 if (auto &init{std::get<std::optional<parser::ScalarIntConstantExpr>>( 5013 enumerator.t)}) { 5014 Walk(*init); // Resolve names in expression before evaluation. 5015 if (auto value{EvaluateInt64(context(), *init)}) { 5016 // Cast all init expressions to C_INT so that they can then be 5017 // safely incremented (see 7.6 Note 2). 5018 enumerationState_.value = static_cast<int>(*value); 5019 } else { 5020 Say(name, 5021 "Enumerator value could not be computed " 5022 "from the given expression"_err_en_US); 5023 // Prevent resolution of next enumerators value 5024 enumerationState_.value = std::nullopt; 5025 } 5026 } 5027 5028 if (symbol) { 5029 if (enumerationState_.value) { 5030 symbol->get<ObjectEntityDetails>().set_init(SomeExpr{ 5031 evaluate::Expr<evaluate::CInteger>{*enumerationState_.value}}); 5032 } else { 5033 context().SetError(*symbol); 5034 } 5035 } 5036 5037 if (enumerationState_.value) { 5038 (*enumerationState_.value)++; 5039 } 5040 return false; 5041 } 5042 5043 void DeclarationVisitor::Post(const parser::EnumDef &) { 5044 enumerationState_ = EnumeratorState{}; 5045 } 5046 5047 bool DeclarationVisitor::Pre(const parser::AccessSpec &x) { 5048 Attr attr{AccessSpecToAttr(x)}; 5049 if (!NonDerivedTypeScope().IsModule()) { // C817 5050 Say(currStmtSource().value(), 5051 "%s attribute may only appear in the specification part of a module"_err_en_US, 5052 EnumToString(attr)); 5053 } 5054 CheckAndSet(attr); 5055 return false; 5056 } 5057 5058 bool DeclarationVisitor::Pre(const parser::AsynchronousStmt &x) { 5059 return HandleAttributeStmt(Attr::ASYNCHRONOUS, x.v); 5060 } 5061 bool DeclarationVisitor::Pre(const parser::ContiguousStmt &x) { 5062 return HandleAttributeStmt(Attr::CONTIGUOUS, x.v); 5063 } 5064 bool DeclarationVisitor::Pre(const parser::ExternalStmt &x) { 5065 HandleAttributeStmt(Attr::EXTERNAL, x.v); 5066 for (const auto &name : x.v) { 5067 auto *symbol{FindSymbol(name)}; 5068 if (!ConvertToProcEntity(DEREF(symbol), name.source)) { 5069 // Check if previous symbol is an interface. 5070 if (auto *details{symbol->detailsIf<SubprogramDetails>()}) { 5071 if (details->isInterface()) { 5072 // Warn if interface previously declared. 5073 context().Warn(common::LanguageFeature::RedundantAttribute, 5074 name.source, 5075 "EXTERNAL attribute was already specified on '%s'"_warn_en_US, 5076 name.source); 5077 } 5078 } else { 5079 SayWithDecl( 5080 name, *symbol, "EXTERNAL attribute not allowed on '%s'"_err_en_US); 5081 } 5082 } else if (symbol->attrs().test(Attr::INTRINSIC)) { // C840 5083 Say(symbol->name(), 5084 "Symbol '%s' cannot have both INTRINSIC and EXTERNAL attributes"_err_en_US, 5085 symbol->name()); 5086 } 5087 } 5088 return false; 5089 } 5090 bool DeclarationVisitor::Pre(const parser::IntentStmt &x) { 5091 auto &intentSpec{std::get<parser::IntentSpec>(x.t)}; 5092 auto &names{std::get<std::list<parser::Name>>(x.t)}; 5093 return CheckNotInBlock("INTENT") && // C1107 5094 HandleAttributeStmt(IntentSpecToAttr(intentSpec), names); 5095 } 5096 bool DeclarationVisitor::Pre(const parser::IntrinsicStmt &x) { 5097 for (const auto &name : x.v) { 5098 DeclareIntrinsic(name); 5099 } 5100 return false; 5101 } 5102 void DeclarationVisitor::DeclareIntrinsic(const parser::Name &name) { 5103 HandleAttributeStmt(Attr::INTRINSIC, name); 5104 if (!IsIntrinsic(name.source, std::nullopt)) { 5105 Say(name.source, "'%s' is not a known intrinsic procedure"_err_en_US); 5106 } 5107 auto &symbol{DEREF(FindSymbol(name))}; 5108 if (symbol.has<GenericDetails>()) { 5109 // Generic interface is extending intrinsic; ok 5110 } else if (!ConvertToProcEntity(symbol, name.source)) { 5111 SayWithDecl( 5112 name, symbol, "INTRINSIC attribute not allowed on '%s'"_err_en_US); 5113 } else if (symbol.attrs().test(Attr::EXTERNAL)) { // C840 5114 Say(symbol.name(), 5115 "Symbol '%s' cannot have both EXTERNAL and INTRINSIC attributes"_err_en_US, 5116 symbol.name()); 5117 } else { 5118 if (symbol.GetType()) { 5119 // These warnings are worded so that they should make sense in either 5120 // order. 5121 if (auto *msg{context().Warn( 5122 common::UsageWarning::IgnoredIntrinsicFunctionType, symbol.name(), 5123 "Explicit type declaration ignored for intrinsic function '%s'"_warn_en_US, 5124 symbol.name())}) { 5125 msg->Attach(name.source, 5126 "INTRINSIC statement for explicitly-typed '%s'"_en_US, name.source); 5127 } 5128 } 5129 if (!symbol.test(Symbol::Flag::Function) && 5130 !symbol.test(Symbol::Flag::Subroutine)) { 5131 if (context().intrinsics().IsIntrinsicFunction(name.source.ToString())) { 5132 symbol.set(Symbol::Flag::Function); 5133 } else if (context().intrinsics().IsIntrinsicSubroutine( 5134 name.source.ToString())) { 5135 symbol.set(Symbol::Flag::Subroutine); 5136 } 5137 } 5138 } 5139 } 5140 bool DeclarationVisitor::Pre(const parser::OptionalStmt &x) { 5141 return CheckNotInBlock("OPTIONAL") && // C1107 5142 HandleAttributeStmt(Attr::OPTIONAL, x.v); 5143 } 5144 bool DeclarationVisitor::Pre(const parser::ProtectedStmt &x) { 5145 return HandleAttributeStmt(Attr::PROTECTED, x.v); 5146 } 5147 bool DeclarationVisitor::Pre(const parser::ValueStmt &x) { 5148 return CheckNotInBlock("VALUE") && // C1107 5149 HandleAttributeStmt(Attr::VALUE, x.v); 5150 } 5151 bool DeclarationVisitor::Pre(const parser::VolatileStmt &x) { 5152 return HandleAttributeStmt(Attr::VOLATILE, x.v); 5153 } 5154 bool DeclarationVisitor::Pre(const parser::CUDAAttributesStmt &x) { 5155 auto attr{std::get<common::CUDADataAttr>(x.t)}; 5156 for (const auto &name : std::get<std::list<parser::Name>>(x.t)) { 5157 auto *symbol{FindInScope(name)}; 5158 if (symbol && symbol->has<UseDetails>()) { 5159 Say(currStmtSource().value(), 5160 "Cannot apply CUDA data attribute to use-associated '%s'"_err_en_US, 5161 name.source); 5162 } else { 5163 if (!symbol) { 5164 symbol = &MakeSymbol(name, ObjectEntityDetails{}); 5165 } 5166 SetCUDADataAttr(name.source, *symbol, attr); 5167 } 5168 } 5169 return false; 5170 } 5171 // Handle a statement that sets an attribute on a list of names. 5172 bool DeclarationVisitor::HandleAttributeStmt( 5173 Attr attr, const std::list<parser::Name> &names) { 5174 for (const auto &name : names) { 5175 HandleAttributeStmt(attr, name); 5176 } 5177 return false; 5178 } 5179 Symbol &DeclarationVisitor::HandleAttributeStmt( 5180 Attr attr, const parser::Name &name) { 5181 auto *symbol{FindInScope(name)}; 5182 if (attr == Attr::ASYNCHRONOUS || attr == Attr::VOLATILE) { 5183 // these can be set on a symbol that is host-assoc or use-assoc 5184 if (!symbol && 5185 (currScope().kind() == Scope::Kind::Subprogram || 5186 currScope().kind() == Scope::Kind::BlockConstruct)) { 5187 if (auto *hostSymbol{FindSymbol(name)}) { 5188 symbol = &MakeHostAssocSymbol(name, *hostSymbol); 5189 } 5190 } 5191 } else if (symbol && symbol->has<UseDetails>()) { 5192 if (symbol->GetUltimate().attrs().test(attr)) { 5193 context().Warn(common::LanguageFeature::RedundantAttribute, 5194 currStmtSource().value(), 5195 "Use-associated '%s' already has '%s' attribute"_warn_en_US, 5196 name.source, EnumToString(attr)); 5197 } else { 5198 Say(currStmtSource().value(), 5199 "Cannot change %s attribute on use-associated '%s'"_err_en_US, 5200 EnumToString(attr), name.source); 5201 } 5202 return *symbol; 5203 } 5204 if (!symbol) { 5205 symbol = &MakeSymbol(name, EntityDetails{}); 5206 } 5207 if (CheckDuplicatedAttr(name.source, *symbol, attr)) { 5208 HandleSaveName(name.source, Attrs{attr}); 5209 SetExplicitAttr(*symbol, attr); 5210 } 5211 return *symbol; 5212 } 5213 // C1107 5214 bool DeclarationVisitor::CheckNotInBlock(const char *stmt) { 5215 if (currScope().kind() == Scope::Kind::BlockConstruct) { 5216 Say(MessageFormattedText{ 5217 "%s statement is not allowed in a BLOCK construct"_err_en_US, stmt}); 5218 return false; 5219 } else { 5220 return true; 5221 } 5222 } 5223 5224 void DeclarationVisitor::Post(const parser::ObjectDecl &x) { 5225 CHECK(objectDeclAttr_); 5226 const auto &name{std::get<parser::ObjectName>(x.t)}; 5227 DeclareObjectEntity(name, Attrs{*objectDeclAttr_}); 5228 } 5229 5230 // Declare an entity not yet known to be an object or proc. 5231 Symbol &DeclarationVisitor::DeclareUnknownEntity( 5232 const parser::Name &name, Attrs attrs) { 5233 if (!arraySpec().empty() || !coarraySpec().empty()) { 5234 return DeclareObjectEntity(name, attrs); 5235 } else { 5236 Symbol &symbol{DeclareEntity<EntityDetails>(name, attrs)}; 5237 if (auto *type{GetDeclTypeSpec()}) { 5238 SetType(name, *type); 5239 } 5240 charInfo_.length.reset(); 5241 if (symbol.attrs().test(Attr::EXTERNAL)) { 5242 ConvertToProcEntity(symbol); 5243 } else if (symbol.attrs().HasAny(Attrs{Attr::ALLOCATABLE, 5244 Attr::ASYNCHRONOUS, Attr::CONTIGUOUS, Attr::PARAMETER, 5245 Attr::SAVE, Attr::TARGET, Attr::VALUE, Attr::VOLATILE})) { 5246 ConvertToObjectEntity(symbol); 5247 } 5248 if (attrs.test(Attr::BIND_C)) { 5249 SetBindNameOn(symbol); 5250 } 5251 return symbol; 5252 } 5253 } 5254 5255 bool DeclarationVisitor::HasCycle( 5256 const Symbol &procSymbol, const Symbol *interface) { 5257 SourceOrderedSymbolSet procsInCycle; 5258 procsInCycle.insert(procSymbol); 5259 while (interface) { 5260 if (procsInCycle.count(*interface) > 0) { 5261 for (const auto &procInCycle : procsInCycle) { 5262 Say(procInCycle->name(), 5263 "The interface for procedure '%s' is recursively defined"_err_en_US, 5264 procInCycle->name()); 5265 context().SetError(*procInCycle); 5266 } 5267 return true; 5268 } else if (const auto *procDetails{ 5269 interface->detailsIf<ProcEntityDetails>()}) { 5270 procsInCycle.insert(*interface); 5271 interface = procDetails->procInterface(); 5272 } else { 5273 break; 5274 } 5275 } 5276 return false; 5277 } 5278 5279 Symbol &DeclarationVisitor::DeclareProcEntity( 5280 const parser::Name &name, Attrs attrs, const Symbol *interface) { 5281 Symbol *proc{nullptr}; 5282 if (auto *extant{FindInScope(name)}) { 5283 if (auto *d{extant->detailsIf<GenericDetails>()}; d && !d->derivedType()) { 5284 // procedure pointer with same name as a generic 5285 if (auto *specific{d->specific()}) { 5286 SayAlreadyDeclared(name, *specific); 5287 } else { 5288 // Create the ProcEntityDetails symbol in the scope as the "specific()" 5289 // symbol behind an existing GenericDetails symbol of the same name. 5290 proc = &Resolve(name, 5291 currScope().MakeSymbol(name.source, attrs, ProcEntityDetails{})); 5292 d->set_specific(*proc); 5293 } 5294 } 5295 } 5296 Symbol &symbol{proc ? *proc : DeclareEntity<ProcEntityDetails>(name, attrs)}; 5297 if (auto *details{symbol.detailsIf<ProcEntityDetails>()}) { 5298 if (context().HasError(symbol)) { 5299 } else if (HasCycle(symbol, interface)) { 5300 return symbol; 5301 } else if (interface && (details->procInterface() || details->type())) { 5302 SayWithDecl(name, symbol, 5303 "The interface for procedure '%s' has already been declared"_err_en_US); 5304 context().SetError(symbol); 5305 } else if (interface) { 5306 details->set_procInterfaces( 5307 *interface, BypassGeneric(interface->GetUltimate())); 5308 if (interface->test(Symbol::Flag::Function)) { 5309 symbol.set(Symbol::Flag::Function); 5310 } else if (interface->test(Symbol::Flag::Subroutine)) { 5311 symbol.set(Symbol::Flag::Subroutine); 5312 } 5313 } else if (auto *type{GetDeclTypeSpec()}) { 5314 SetType(name, *type); 5315 symbol.set(Symbol::Flag::Function); 5316 } 5317 SetBindNameOn(symbol); 5318 SetPassNameOn(symbol); 5319 } 5320 return symbol; 5321 } 5322 5323 Symbol &DeclarationVisitor::DeclareObjectEntity( 5324 const parser::Name &name, Attrs attrs) { 5325 Symbol &symbol{DeclareEntity<ObjectEntityDetails>(name, attrs)}; 5326 if (auto *details{symbol.detailsIf<ObjectEntityDetails>()}) { 5327 if (auto *type{GetDeclTypeSpec()}) { 5328 SetType(name, *type); 5329 } 5330 if (!arraySpec().empty()) { 5331 if (details->IsArray()) { 5332 if (!context().HasError(symbol)) { 5333 Say(name, 5334 "The dimensions of '%s' have already been declared"_err_en_US); 5335 context().SetError(symbol); 5336 } 5337 } else if (MustBeScalar(symbol)) { 5338 context().Warn(common::UsageWarning::PreviousScalarUse, name.source, 5339 "'%s' appeared earlier as a scalar actual argument to a specification function"_warn_en_US, 5340 name.source); 5341 } else if (details->init() || symbol.test(Symbol::Flag::InDataStmt)) { 5342 Say(name, "'%s' was initialized earlier as a scalar"_err_en_US); 5343 } else { 5344 details->set_shape(arraySpec()); 5345 } 5346 } 5347 if (!coarraySpec().empty()) { 5348 if (details->IsCoarray()) { 5349 if (!context().HasError(symbol)) { 5350 Say(name, 5351 "The codimensions of '%s' have already been declared"_err_en_US); 5352 context().SetError(symbol); 5353 } 5354 } else { 5355 details->set_coshape(coarraySpec()); 5356 } 5357 } 5358 SetBindNameOn(symbol); 5359 } 5360 ClearArraySpec(); 5361 ClearCoarraySpec(); 5362 charInfo_.length.reset(); 5363 return symbol; 5364 } 5365 5366 void DeclarationVisitor::Post(const parser::IntegerTypeSpec &x) { 5367 if (!isVectorType_) { 5368 SetDeclTypeSpec(MakeNumericType(TypeCategory::Integer, x.v)); 5369 } 5370 } 5371 void DeclarationVisitor::Post(const parser::UnsignedTypeSpec &x) { 5372 if (!isVectorType_) { 5373 if (!context().IsEnabled(common::LanguageFeature::Unsigned) && 5374 !context().AnyFatalError()) { 5375 context().Say("-funsigned is required to enable UNSIGNED type"_err_en_US); 5376 } 5377 SetDeclTypeSpec(MakeNumericType(TypeCategory::Unsigned, x.v)); 5378 } 5379 } 5380 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Real &x) { 5381 if (!isVectorType_) { 5382 SetDeclTypeSpec(MakeNumericType(TypeCategory::Real, x.kind)); 5383 } 5384 } 5385 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Complex &x) { 5386 SetDeclTypeSpec(MakeNumericType(TypeCategory::Complex, x.kind)); 5387 } 5388 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Logical &x) { 5389 SetDeclTypeSpec(MakeLogicalType(x.kind)); 5390 } 5391 void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Character &) { 5392 if (!charInfo_.length) { 5393 charInfo_.length = ParamValue{1, common::TypeParamAttr::Len}; 5394 } 5395 if (!charInfo_.kind) { 5396 charInfo_.kind = 5397 KindExpr{context().GetDefaultKind(TypeCategory::Character)}; 5398 } 5399 SetDeclTypeSpec(currScope().MakeCharacterType( 5400 std::move(*charInfo_.length), std::move(*charInfo_.kind))); 5401 charInfo_ = {}; 5402 } 5403 void DeclarationVisitor::Post(const parser::CharSelector::LengthAndKind &x) { 5404 charInfo_.kind = EvaluateSubscriptIntExpr(x.kind); 5405 std::optional<std::int64_t> intKind{ToInt64(charInfo_.kind)}; 5406 if (intKind && 5407 !context().targetCharacteristics().IsTypeEnabled( 5408 TypeCategory::Character, *intKind)) { // C715, C719 5409 Say(currStmtSource().value(), 5410 "KIND value (%jd) not valid for CHARACTER"_err_en_US, *intKind); 5411 charInfo_.kind = std::nullopt; // prevent further errors 5412 } 5413 if (x.length) { 5414 charInfo_.length = GetParamValue(*x.length, common::TypeParamAttr::Len); 5415 } 5416 } 5417 void DeclarationVisitor::Post(const parser::CharLength &x) { 5418 if (const auto *length{std::get_if<std::uint64_t>(&x.u)}) { 5419 charInfo_.length = ParamValue{ 5420 static_cast<ConstantSubscript>(*length), common::TypeParamAttr::Len}; 5421 } else { 5422 charInfo_.length = GetParamValue( 5423 std::get<parser::TypeParamValue>(x.u), common::TypeParamAttr::Len); 5424 } 5425 } 5426 void DeclarationVisitor::Post(const parser::LengthSelector &x) { 5427 if (const auto *param{std::get_if<parser::TypeParamValue>(&x.u)}) { 5428 charInfo_.length = GetParamValue(*param, common::TypeParamAttr::Len); 5429 } 5430 } 5431 5432 bool DeclarationVisitor::Pre(const parser::KindParam &x) { 5433 if (const auto *kind{std::get_if< 5434 parser::Scalar<parser::Integer<parser::Constant<parser::Name>>>>( 5435 &x.u)}) { 5436 const parser::Name &name{kind->thing.thing.thing}; 5437 if (!FindSymbol(name)) { 5438 Say(name, "Parameter '%s' not found"_err_en_US); 5439 } 5440 } 5441 return false; 5442 } 5443 5444 int DeclarationVisitor::GetVectorElementKind( 5445 TypeCategory category, const std::optional<parser::KindSelector> &kind) { 5446 KindExpr value{GetKindParamExpr(category, kind)}; 5447 if (auto known{evaluate::ToInt64(value)}) { 5448 return static_cast<int>(*known); 5449 } 5450 common::die("Vector element kind must be known at compile-time"); 5451 } 5452 5453 bool DeclarationVisitor::Pre(const parser::VectorTypeSpec &) { 5454 // PowerPC vector types are allowed only on Power architectures. 5455 if (!currScope().context().targetCharacteristics().isPPC()) { 5456 Say(currStmtSource().value(), 5457 "Vector type is only supported for PowerPC"_err_en_US); 5458 isVectorType_ = false; 5459 return false; 5460 } 5461 isVectorType_ = true; 5462 return true; 5463 } 5464 // Create semantic::DerivedTypeSpec for Vector types here. 5465 void DeclarationVisitor::Post(const parser::VectorTypeSpec &x) { 5466 llvm::StringRef typeName; 5467 llvm::SmallVector<ParamValue> typeParams; 5468 DerivedTypeSpec::Category vectorCategory; 5469 5470 isVectorType_ = false; 5471 common::visit( 5472 common::visitors{ 5473 [&](const parser::IntrinsicVectorTypeSpec &y) { 5474 vectorCategory = DerivedTypeSpec::Category::IntrinsicVector; 5475 int vecElemKind = 0; 5476 typeName = "__builtin_ppc_intrinsic_vector"; 5477 common::visit( 5478 common::visitors{ 5479 [&](const parser::IntegerTypeSpec &z) { 5480 vecElemKind = GetVectorElementKind( 5481 TypeCategory::Integer, std::move(z.v)); 5482 typeParams.push_back(ParamValue( 5483 static_cast<common::ConstantSubscript>( 5484 common::VectorElementCategory::Integer), 5485 common::TypeParamAttr::Kind)); 5486 }, 5487 [&](const parser::IntrinsicTypeSpec::Real &z) { 5488 vecElemKind = GetVectorElementKind( 5489 TypeCategory::Real, std::move(z.kind)); 5490 typeParams.push_back( 5491 ParamValue(static_cast<common::ConstantSubscript>( 5492 common::VectorElementCategory::Real), 5493 common::TypeParamAttr::Kind)); 5494 }, 5495 [&](const parser::UnsignedTypeSpec &z) { 5496 vecElemKind = GetVectorElementKind( 5497 TypeCategory::Integer, std::move(z.v)); 5498 typeParams.push_back(ParamValue( 5499 static_cast<common::ConstantSubscript>( 5500 common::VectorElementCategory::Unsigned), 5501 common::TypeParamAttr::Kind)); 5502 }, 5503 }, 5504 y.v.u); 5505 typeParams.push_back( 5506 ParamValue(static_cast<common::ConstantSubscript>(vecElemKind), 5507 common::TypeParamAttr::Kind)); 5508 }, 5509 [&](const parser::VectorTypeSpec::PairVectorTypeSpec &y) { 5510 vectorCategory = DerivedTypeSpec::Category::PairVector; 5511 typeName = "__builtin_ppc_pair_vector"; 5512 }, 5513 [&](const parser::VectorTypeSpec::QuadVectorTypeSpec &y) { 5514 vectorCategory = DerivedTypeSpec::Category::QuadVector; 5515 typeName = "__builtin_ppc_quad_vector"; 5516 }, 5517 }, 5518 x.u); 5519 5520 auto ppcBuiltinTypesScope = currScope().context().GetPPCBuiltinTypesScope(); 5521 if (!ppcBuiltinTypesScope) { 5522 common::die("INTERNAL: The __ppc_types module was not found "); 5523 } 5524 5525 auto iter{ppcBuiltinTypesScope->find( 5526 semantics::SourceName{typeName.data(), typeName.size()})}; 5527 if (iter == ppcBuiltinTypesScope->cend()) { 5528 common::die("INTERNAL: The __ppc_types module does not define " 5529 "the type '%s'", 5530 typeName.data()); 5531 } 5532 5533 const semantics::Symbol &typeSymbol{*iter->second}; 5534 DerivedTypeSpec vectorDerivedType{typeName.data(), typeSymbol}; 5535 vectorDerivedType.set_category(vectorCategory); 5536 if (typeParams.size()) { 5537 vectorDerivedType.AddRawParamValue(nullptr, std::move(typeParams[0])); 5538 vectorDerivedType.AddRawParamValue(nullptr, std::move(typeParams[1])); 5539 vectorDerivedType.CookParameters(GetFoldingContext()); 5540 } 5541 5542 if (const DeclTypeSpec * 5543 extant{ppcBuiltinTypesScope->FindInstantiatedDerivedType( 5544 vectorDerivedType, DeclTypeSpec::Category::TypeDerived)}) { 5545 // This derived type and parameter expressions (if any) are already present 5546 // in the __ppc_intrinsics scope. 5547 SetDeclTypeSpec(*extant); 5548 } else { 5549 DeclTypeSpec &type{ppcBuiltinTypesScope->MakeDerivedType( 5550 DeclTypeSpec::Category::TypeDerived, std::move(vectorDerivedType))}; 5551 DerivedTypeSpec &derived{type.derivedTypeSpec()}; 5552 auto restorer{ 5553 GetFoldingContext().messages().SetLocation(currStmtSource().value())}; 5554 derived.Instantiate(*ppcBuiltinTypesScope); 5555 SetDeclTypeSpec(type); 5556 } 5557 } 5558 5559 bool DeclarationVisitor::Pre(const parser::DeclarationTypeSpec::Type &) { 5560 CHECK(GetDeclTypeSpecCategory() == DeclTypeSpec::Category::TypeDerived); 5561 return true; 5562 } 5563 5564 void DeclarationVisitor::Post(const parser::DeclarationTypeSpec::Type &type) { 5565 const parser::Name &derivedName{std::get<parser::Name>(type.derived.t)}; 5566 if (const Symbol * derivedSymbol{derivedName.symbol}) { 5567 CheckForAbstractType(*derivedSymbol); // C706 5568 } 5569 } 5570 5571 bool DeclarationVisitor::Pre(const parser::DeclarationTypeSpec::Class &) { 5572 SetDeclTypeSpecCategory(DeclTypeSpec::Category::ClassDerived); 5573 return true; 5574 } 5575 5576 void DeclarationVisitor::Post( 5577 const parser::DeclarationTypeSpec::Class &parsedClass) { 5578 const auto &typeName{std::get<parser::Name>(parsedClass.derived.t)}; 5579 if (auto spec{ResolveDerivedType(typeName)}; 5580 spec && !IsExtensibleType(&*spec)) { // C705 5581 SayWithDecl(typeName, *typeName.symbol, 5582 "Non-extensible derived type '%s' may not be used with CLASS" 5583 " keyword"_err_en_US); 5584 } 5585 } 5586 5587 void DeclarationVisitor::Post(const parser::DerivedTypeSpec &x) { 5588 const auto &typeName{std::get<parser::Name>(x.t)}; 5589 auto spec{ResolveDerivedType(typeName)}; 5590 if (!spec) { 5591 return; 5592 } 5593 bool seenAnyName{false}; 5594 for (const auto &typeParamSpec : 5595 std::get<std::list<parser::TypeParamSpec>>(x.t)) { 5596 const auto &optKeyword{ 5597 std::get<std::optional<parser::Keyword>>(typeParamSpec.t)}; 5598 std::optional<SourceName> name; 5599 if (optKeyword) { 5600 seenAnyName = true; 5601 name = optKeyword->v.source; 5602 } else if (seenAnyName) { 5603 Say(typeName.source, "Type parameter value must have a name"_err_en_US); 5604 continue; 5605 } 5606 const auto &value{std::get<parser::TypeParamValue>(typeParamSpec.t)}; 5607 // The expressions in a derived type specifier whose values define 5608 // non-defaulted type parameters are evaluated (folded) in the enclosing 5609 // scope. The KIND/LEN distinction is resolved later in 5610 // DerivedTypeSpec::CookParameters(). 5611 ParamValue param{GetParamValue(value, common::TypeParamAttr::Kind)}; 5612 if (!param.isExplicit() || param.GetExplicit()) { 5613 spec->AddRawParamValue( 5614 common::GetPtrFromOptional(optKeyword), std::move(param)); 5615 } 5616 } 5617 // The DerivedTypeSpec *spec is used initially as a search key. 5618 // If it turns out to have the same name and actual parameter 5619 // value expressions as another DerivedTypeSpec in the current 5620 // scope does, then we'll use that extant spec; otherwise, when this 5621 // spec is distinct from all derived types previously instantiated 5622 // in the current scope, this spec will be moved into that collection. 5623 const auto &dtDetails{spec->typeSymbol().get<DerivedTypeDetails>()}; 5624 auto category{GetDeclTypeSpecCategory()}; 5625 if (dtDetails.isForwardReferenced()) { 5626 DeclTypeSpec &type{currScope().MakeDerivedType(category, std::move(*spec))}; 5627 SetDeclTypeSpec(type); 5628 return; 5629 } 5630 // Normalize parameters to produce a better search key. 5631 spec->CookParameters(GetFoldingContext()); 5632 if (!spec->MightBeParameterized()) { 5633 spec->EvaluateParameters(context()); 5634 } 5635 if (const DeclTypeSpec * 5636 extant{currScope().FindInstantiatedDerivedType(*spec, category)}) { 5637 // This derived type and parameter expressions (if any) are already present 5638 // in this scope. 5639 SetDeclTypeSpec(*extant); 5640 } else { 5641 DeclTypeSpec &type{currScope().MakeDerivedType(category, std::move(*spec))}; 5642 DerivedTypeSpec &derived{type.derivedTypeSpec()}; 5643 if (derived.MightBeParameterized() && 5644 currScope().IsParameterizedDerivedType()) { 5645 // Defer instantiation; use the derived type's definition's scope. 5646 derived.set_scope(DEREF(spec->typeSymbol().scope())); 5647 } else if (&currScope() == spec->typeSymbol().scope()) { 5648 // Direct recursive use of a type in the definition of one of its 5649 // components: defer instantiation 5650 } else { 5651 auto restorer{ 5652 GetFoldingContext().messages().SetLocation(currStmtSource().value())}; 5653 derived.Instantiate(currScope()); 5654 } 5655 SetDeclTypeSpec(type); 5656 } 5657 // Capture the DerivedTypeSpec in the parse tree for use in building 5658 // structure constructor expressions. 5659 x.derivedTypeSpec = &GetDeclTypeSpec()->derivedTypeSpec(); 5660 } 5661 5662 void DeclarationVisitor::Post(const parser::DeclarationTypeSpec::Record &rec) { 5663 const auto &typeName{rec.v}; 5664 if (auto spec{ResolveDerivedType(typeName)}) { 5665 spec->CookParameters(GetFoldingContext()); 5666 spec->EvaluateParameters(context()); 5667 if (const DeclTypeSpec * 5668 extant{currScope().FindInstantiatedDerivedType( 5669 *spec, DeclTypeSpec::TypeDerived)}) { 5670 SetDeclTypeSpec(*extant); 5671 } else { 5672 Say(typeName.source, "%s is not a known STRUCTURE"_err_en_US, 5673 typeName.source); 5674 } 5675 } 5676 } 5677 5678 // The descendents of DerivedTypeDef in the parse tree are visited directly 5679 // in this Pre() routine so that recursive use of the derived type can be 5680 // supported in the components. 5681 bool DeclarationVisitor::Pre(const parser::DerivedTypeDef &x) { 5682 auto &stmt{std::get<parser::Statement<parser::DerivedTypeStmt>>(x.t)}; 5683 Walk(stmt); 5684 Walk(std::get<std::list<parser::Statement<parser::TypeParamDefStmt>>>(x.t)); 5685 auto &scope{currScope()}; 5686 CHECK(scope.symbol()); 5687 CHECK(scope.symbol()->scope() == &scope); 5688 auto &details{scope.symbol()->get<DerivedTypeDetails>()}; 5689 for (auto ¶mName : std::get<std::list<parser::Name>>(stmt.statement.t)) { 5690 if (auto *symbol{FindInScope(scope, paramName)}) { 5691 if (auto *details{symbol->detailsIf<TypeParamDetails>()}) { 5692 if (!details->attr()) { 5693 Say(paramName, 5694 "No definition found for type parameter '%s'"_err_en_US); // C742 5695 } 5696 } 5697 } 5698 } 5699 Walk(std::get<std::list<parser::Statement<parser::PrivateOrSequence>>>(x.t)); 5700 const auto &componentDefs{ 5701 std::get<std::list<parser::Statement<parser::ComponentDefStmt>>>(x.t)}; 5702 Walk(componentDefs); 5703 if (derivedTypeInfo_.sequence) { 5704 details.set_sequence(true); 5705 if (componentDefs.empty()) { 5706 // F'2023 C745 - not enforced by any compiler 5707 context().Warn(common::LanguageFeature::EmptySequenceType, stmt.source, 5708 "A sequence type should have at least one component"_warn_en_US); 5709 } 5710 if (!details.paramDeclOrder().empty()) { // C740 5711 Say(stmt.source, 5712 "A sequence type may not have type parameters"_err_en_US); 5713 } 5714 if (derivedTypeInfo_.extends) { // C735 5715 Say(stmt.source, 5716 "A sequence type may not have the EXTENDS attribute"_err_en_US); 5717 } 5718 } 5719 Walk(std::get<std::optional<parser::TypeBoundProcedurePart>>(x.t)); 5720 Walk(std::get<parser::Statement<parser::EndTypeStmt>>(x.t)); 5721 details.set_isForwardReferenced(false); 5722 derivedTypeInfo_ = {}; 5723 PopScope(); 5724 return false; 5725 } 5726 5727 bool DeclarationVisitor::Pre(const parser::DerivedTypeStmt &) { 5728 return BeginAttrs(); 5729 } 5730 void DeclarationVisitor::Post(const parser::DerivedTypeStmt &x) { 5731 auto &name{std::get<parser::Name>(x.t)}; 5732 // Resolve the EXTENDS() clause before creating the derived 5733 // type's symbol to foil attempts to recursively extend a type. 5734 auto *extendsName{derivedTypeInfo_.extends}; 5735 std::optional<DerivedTypeSpec> extendsType{ 5736 ResolveExtendsType(name, extendsName)}; 5737 DerivedTypeDetails derivedTypeDetails; 5738 // Catch any premature structure constructors within the definition 5739 derivedTypeDetails.set_isForwardReferenced(true); 5740 auto &symbol{MakeSymbol(name, GetAttrs(), std::move(derivedTypeDetails))}; 5741 symbol.ReplaceName(name.source); 5742 derivedTypeInfo_.type = &symbol; 5743 PushScope(Scope::Kind::DerivedType, &symbol); 5744 if (extendsType) { 5745 // Declare the "parent component"; private if the type is. 5746 // Any symbol stored in the EXTENDS() clause is temporarily 5747 // hidden so that a new symbol can be created for the parent 5748 // component without producing spurious errors about already 5749 // existing. 5750 const Symbol &extendsSymbol{extendsType->typeSymbol()}; 5751 auto restorer{common::ScopedSet(extendsName->symbol, nullptr)}; 5752 if (OkToAddComponent(*extendsName, &extendsSymbol)) { 5753 auto &comp{DeclareEntity<ObjectEntityDetails>(*extendsName, Attrs{})}; 5754 comp.attrs().set( 5755 Attr::PRIVATE, extendsSymbol.attrs().test(Attr::PRIVATE)); 5756 comp.implicitAttrs().set( 5757 Attr::PRIVATE, extendsSymbol.implicitAttrs().test(Attr::PRIVATE)); 5758 comp.set(Symbol::Flag::ParentComp); 5759 DeclTypeSpec &type{currScope().MakeDerivedType( 5760 DeclTypeSpec::TypeDerived, std::move(*extendsType))}; 5761 type.derivedTypeSpec().set_scope(DEREF(extendsSymbol.scope())); 5762 comp.SetType(type); 5763 DerivedTypeDetails &details{symbol.get<DerivedTypeDetails>()}; 5764 details.add_component(comp); 5765 } 5766 } 5767 // Create symbols now for type parameters so that they shadow names 5768 // from the enclosing specification part. 5769 if (auto *details{symbol.detailsIf<DerivedTypeDetails>()}) { 5770 for (const auto &name : std::get<std::list<parser::Name>>(x.t)) { 5771 if (Symbol * symbol{MakeTypeSymbol(name, TypeParamDetails{})}) { 5772 details->add_paramNameOrder(*symbol); 5773 } 5774 } 5775 } 5776 EndAttrs(); 5777 } 5778 5779 void DeclarationVisitor::Post(const parser::TypeParamDefStmt &x) { 5780 auto *type{GetDeclTypeSpec()}; 5781 DerivedTypeDetails *derivedDetails{nullptr}; 5782 if (Symbol * dtSym{currScope().symbol()}) { 5783 derivedDetails = dtSym->detailsIf<DerivedTypeDetails>(); 5784 } 5785 auto attr{std::get<common::TypeParamAttr>(x.t)}; 5786 for (auto &decl : std::get<std::list<parser::TypeParamDecl>>(x.t)) { 5787 auto &name{std::get<parser::Name>(decl.t)}; 5788 if (Symbol * symbol{FindInScope(currScope(), name)}) { 5789 if (auto *paramDetails{symbol->detailsIf<TypeParamDetails>()}) { 5790 if (!paramDetails->attr()) { 5791 paramDetails->set_attr(attr); 5792 SetType(name, *type); 5793 if (auto &init{std::get<std::optional<parser::ScalarIntConstantExpr>>( 5794 decl.t)}) { 5795 if (auto maybeExpr{AnalyzeExpr(context(), *init)}) { 5796 if (auto *intExpr{std::get_if<SomeIntExpr>(&maybeExpr->u)}) { 5797 paramDetails->set_init(std::move(*intExpr)); 5798 } 5799 } 5800 } 5801 if (derivedDetails) { 5802 derivedDetails->add_paramDeclOrder(*symbol); 5803 } 5804 } else { 5805 Say(name, 5806 "Type parameter '%s' was already declared in this derived type"_err_en_US); 5807 } 5808 } 5809 } else { 5810 Say(name, "'%s' is not a parameter of this derived type"_err_en_US); 5811 } 5812 } 5813 EndDecl(); 5814 } 5815 bool DeclarationVisitor::Pre(const parser::TypeAttrSpec::Extends &x) { 5816 if (derivedTypeInfo_.extends) { 5817 Say(currStmtSource().value(), 5818 "Attribute 'EXTENDS' cannot be used more than once"_err_en_US); 5819 } else { 5820 derivedTypeInfo_.extends = &x.v; 5821 } 5822 return false; 5823 } 5824 5825 bool DeclarationVisitor::Pre(const parser::PrivateStmt &) { 5826 if (!currScope().parent().IsModule()) { 5827 Say("PRIVATE is only allowed in a derived type that is" 5828 " in a module"_err_en_US); // C766 5829 } else if (derivedTypeInfo_.sawContains) { 5830 derivedTypeInfo_.privateBindings = true; 5831 } else if (!derivedTypeInfo_.privateComps) { 5832 derivedTypeInfo_.privateComps = true; 5833 } else { // C738 5834 context().Warn(common::LanguageFeature::RedundantAttribute, 5835 "PRIVATE should not appear more than once in derived type components"_warn_en_US); 5836 } 5837 return false; 5838 } 5839 bool DeclarationVisitor::Pre(const parser::SequenceStmt &) { 5840 if (derivedTypeInfo_.sequence) { // C738 5841 context().Warn(common::LanguageFeature::RedundantAttribute, 5842 "SEQUENCE should not appear more than once in derived type components"_warn_en_US); 5843 } 5844 derivedTypeInfo_.sequence = true; 5845 return false; 5846 } 5847 void DeclarationVisitor::Post(const parser::ComponentDecl &x) { 5848 const auto &name{std::get<parser::Name>(x.t)}; 5849 auto attrs{GetAttrs()}; 5850 if (derivedTypeInfo_.privateComps && 5851 !attrs.HasAny({Attr::PUBLIC, Attr::PRIVATE})) { 5852 attrs.set(Attr::PRIVATE); 5853 } 5854 if (const auto *declType{GetDeclTypeSpec()}) { 5855 if (const auto *derived{declType->AsDerived()}) { 5856 if (!attrs.HasAny({Attr::POINTER, Attr::ALLOCATABLE})) { 5857 if (derivedTypeInfo_.type == &derived->typeSymbol()) { // C744 5858 Say("Recursive use of the derived type requires " 5859 "POINTER or ALLOCATABLE"_err_en_US); 5860 } 5861 } 5862 // TODO: This would be more appropriate in CheckDerivedType() 5863 if (auto it{FindCoarrayUltimateComponent(*derived)}) { // C748 5864 std::string ultimateName{it.BuildResultDesignatorName()}; 5865 // Strip off the leading "%" 5866 if (ultimateName.length() > 1) { 5867 ultimateName.erase(0, 1); 5868 if (attrs.HasAny({Attr::POINTER, Attr::ALLOCATABLE})) { 5869 evaluate::AttachDeclaration( 5870 Say(name.source, 5871 "A component with a POINTER or ALLOCATABLE attribute may " 5872 "not " 5873 "be of a type with a coarray ultimate component (named " 5874 "'%s')"_err_en_US, 5875 ultimateName), 5876 derived->typeSymbol()); 5877 } 5878 if (!arraySpec().empty() || !coarraySpec().empty()) { 5879 evaluate::AttachDeclaration( 5880 Say(name.source, 5881 "An array or coarray component may not be of a type with a " 5882 "coarray ultimate component (named '%s')"_err_en_US, 5883 ultimateName), 5884 derived->typeSymbol()); 5885 } 5886 } 5887 } 5888 } 5889 } 5890 if (OkToAddComponent(name)) { 5891 auto &symbol{DeclareObjectEntity(name, attrs)}; 5892 SetCUDADataAttr(name.source, symbol, cudaDataAttr()); 5893 if (symbol.has<ObjectEntityDetails>()) { 5894 if (auto &init{std::get<std::optional<parser::Initialization>>(x.t)}) { 5895 Initialization(name, *init, true); 5896 } 5897 } 5898 currScope().symbol()->get<DerivedTypeDetails>().add_component(symbol); 5899 } 5900 ClearArraySpec(); 5901 ClearCoarraySpec(); 5902 } 5903 void DeclarationVisitor::Post(const parser::FillDecl &x) { 5904 // Replace "%FILL" with a distinct generated name 5905 const auto &name{std::get<parser::Name>(x.t)}; 5906 const_cast<SourceName &>(name.source) = context().GetTempName(currScope()); 5907 if (OkToAddComponent(name)) { 5908 auto &symbol{DeclareObjectEntity(name, GetAttrs())}; 5909 currScope().symbol()->get<DerivedTypeDetails>().add_component(symbol); 5910 } 5911 ClearArraySpec(); 5912 } 5913 bool DeclarationVisitor::Pre(const parser::ProcedureDeclarationStmt &x) { 5914 CHECK(!interfaceName_); 5915 const auto &procAttrSpec{std::get<std::list<parser::ProcAttrSpec>>(x.t)}; 5916 for (const parser::ProcAttrSpec &procAttr : procAttrSpec) { 5917 if (auto *bindC{std::get_if<parser::LanguageBindingSpec>(&procAttr.u)}) { 5918 if (std::get<std::optional<parser::ScalarDefaultCharConstantExpr>>( 5919 bindC->t) 5920 .has_value()) { 5921 if (std::get<std::list<parser::ProcDecl>>(x.t).size() > 1) { 5922 Say(context().location().value(), 5923 "A procedure declaration statement with a binding name may not declare multiple procedures"_err_en_US); 5924 } 5925 break; 5926 } 5927 } 5928 } 5929 return BeginDecl(); 5930 } 5931 void DeclarationVisitor::Post(const parser::ProcedureDeclarationStmt &) { 5932 interfaceName_ = nullptr; 5933 EndDecl(); 5934 } 5935 bool DeclarationVisitor::Pre(const parser::DataComponentDefStmt &x) { 5936 // Overrides parse tree traversal so as to handle attributes first, 5937 // so POINTER & ALLOCATABLE enable forward references to derived types. 5938 Walk(std::get<std::list<parser::ComponentAttrSpec>>(x.t)); 5939 set_allowForwardReferenceToDerivedType( 5940 GetAttrs().HasAny({Attr::POINTER, Attr::ALLOCATABLE})); 5941 Walk(std::get<parser::DeclarationTypeSpec>(x.t)); 5942 set_allowForwardReferenceToDerivedType(false); 5943 if (derivedTypeInfo_.sequence) { // C740 5944 if (const auto *declType{GetDeclTypeSpec()}) { 5945 if (!declType->AsIntrinsic() && !declType->IsSequenceType() && 5946 !InModuleFile()) { 5947 if (GetAttrs().test(Attr::POINTER) && 5948 context().IsEnabled(common::LanguageFeature::PointerInSeqType)) { 5949 context().Warn(common::LanguageFeature::PointerInSeqType, 5950 "A sequence type data component that is a pointer to a non-sequence type is not standard"_port_en_US); 5951 } else { 5952 Say("A sequence type data component must either be of an intrinsic type or a derived sequence type"_err_en_US); 5953 } 5954 } 5955 } 5956 } 5957 Walk(std::get<std::list<parser::ComponentOrFill>>(x.t)); 5958 return false; 5959 } 5960 bool DeclarationVisitor::Pre(const parser::ProcComponentDefStmt &) { 5961 CHECK(!interfaceName_); 5962 return true; 5963 } 5964 void DeclarationVisitor::Post(const parser::ProcComponentDefStmt &) { 5965 interfaceName_ = nullptr; 5966 } 5967 bool DeclarationVisitor::Pre(const parser::ProcPointerInit &x) { 5968 if (auto *name{std::get_if<parser::Name>(&x.u)}) { 5969 return !NameIsKnownOrIntrinsic(*name) && !CheckUseError(*name); 5970 } else { 5971 const auto &null{DEREF(std::get_if<parser::NullInit>(&x.u))}; 5972 Walk(null); 5973 if (auto nullInit{EvaluateExpr(null)}) { 5974 if (!evaluate::IsNullPointer(*nullInit)) { 5975 Say(null.v.value().source, 5976 "Procedure pointer initializer must be a name or intrinsic NULL()"_err_en_US); 5977 } 5978 } 5979 return false; 5980 } 5981 } 5982 void DeclarationVisitor::Post(const parser::ProcInterface &x) { 5983 if (auto *name{std::get_if<parser::Name>(&x.u)}) { 5984 interfaceName_ = name; 5985 NoteInterfaceName(*name); 5986 } 5987 } 5988 void DeclarationVisitor::Post(const parser::ProcDecl &x) { 5989 const auto &name{std::get<parser::Name>(x.t)}; 5990 // Don't use BypassGeneric or GetUltimate on this symbol, they can 5991 // lead to unusable names in module files. 5992 const Symbol *procInterface{ 5993 interfaceName_ ? interfaceName_->symbol : nullptr}; 5994 auto attrs{HandleSaveName(name.source, GetAttrs())}; 5995 DerivedTypeDetails *dtDetails{nullptr}; 5996 if (Symbol * symbol{currScope().symbol()}) { 5997 dtDetails = symbol->detailsIf<DerivedTypeDetails>(); 5998 } 5999 if (!dtDetails) { 6000 attrs.set(Attr::EXTERNAL); 6001 } 6002 Symbol &symbol{DeclareProcEntity(name, attrs, procInterface)}; 6003 SetCUDADataAttr(name.source, symbol, cudaDataAttr()); // for error 6004 symbol.ReplaceName(name.source); 6005 if (dtDetails) { 6006 dtDetails->add_component(symbol); 6007 } 6008 DeclaredPossibleSpecificProc(symbol); 6009 } 6010 6011 bool DeclarationVisitor::Pre(const parser::TypeBoundProcedurePart &) { 6012 derivedTypeInfo_.sawContains = true; 6013 return true; 6014 } 6015 6016 // Resolve binding names from type-bound generics, saved in genericBindings_. 6017 void DeclarationVisitor::Post(const parser::TypeBoundProcedurePart &) { 6018 // track specifics seen for the current generic to detect duplicates: 6019 const Symbol *currGeneric{nullptr}; 6020 std::set<SourceName> specifics; 6021 for (const auto &[generic, bindingName] : genericBindings_) { 6022 if (generic != currGeneric) { 6023 currGeneric = generic; 6024 specifics.clear(); 6025 } 6026 auto [it, inserted]{specifics.insert(bindingName->source)}; 6027 if (!inserted) { 6028 Say(*bindingName, // C773 6029 "Binding name '%s' was already specified for generic '%s'"_err_en_US, 6030 bindingName->source, generic->name()) 6031 .Attach(*it, "Previous specification of '%s'"_en_US, *it); 6032 continue; 6033 } 6034 auto *symbol{FindInTypeOrParents(*bindingName)}; 6035 if (!symbol) { 6036 Say(*bindingName, // C772 6037 "Binding name '%s' not found in this derived type"_err_en_US); 6038 } else if (!symbol->has<ProcBindingDetails>()) { 6039 SayWithDecl(*bindingName, *symbol, // C772 6040 "'%s' is not the name of a specific binding of this type"_err_en_US); 6041 } else { 6042 generic->get<GenericDetails>().AddSpecificProc( 6043 *symbol, bindingName->source); 6044 } 6045 } 6046 genericBindings_.clear(); 6047 } 6048 6049 void DeclarationVisitor::Post(const parser::ContainsStmt &) { 6050 if (derivedTypeInfo_.sequence) { 6051 Say("A sequence type may not have a CONTAINS statement"_err_en_US); // C740 6052 } 6053 } 6054 6055 void DeclarationVisitor::Post( 6056 const parser::TypeBoundProcedureStmt::WithoutInterface &x) { 6057 if (GetAttrs().test(Attr::DEFERRED)) { // C783 6058 Say("DEFERRED is only allowed when an interface-name is provided"_err_en_US); 6059 } 6060 for (auto &declaration : x.declarations) { 6061 auto &bindingName{std::get<parser::Name>(declaration.t)}; 6062 auto &optName{std::get<std::optional<parser::Name>>(declaration.t)}; 6063 const parser::Name &procedureName{optName ? *optName : bindingName}; 6064 Symbol *procedure{FindSymbol(procedureName)}; 6065 if (!procedure) { 6066 procedure = NoteInterfaceName(procedureName); 6067 } 6068 if (procedure) { 6069 const Symbol &bindTo{BypassGeneric(*procedure)}; 6070 if (auto *s{MakeTypeSymbol(bindingName, ProcBindingDetails{bindTo})}) { 6071 SetPassNameOn(*s); 6072 if (GetAttrs().test(Attr::DEFERRED)) { 6073 context().SetError(*s); 6074 } 6075 } 6076 } 6077 } 6078 } 6079 6080 void DeclarationVisitor::CheckBindings( 6081 const parser::TypeBoundProcedureStmt::WithoutInterface &tbps) { 6082 CHECK(currScope().IsDerivedType()); 6083 for (auto &declaration : tbps.declarations) { 6084 auto &bindingName{std::get<parser::Name>(declaration.t)}; 6085 if (Symbol * binding{FindInScope(bindingName)}) { 6086 if (auto *details{binding->detailsIf<ProcBindingDetails>()}) { 6087 const Symbol &ultimate{details->symbol().GetUltimate()}; 6088 const Symbol &procedure{BypassGeneric(ultimate)}; 6089 if (&procedure != &ultimate) { 6090 details->ReplaceSymbol(procedure); 6091 } 6092 if (!CanBeTypeBoundProc(procedure)) { 6093 if (details->symbol().name() != binding->name()) { 6094 Say(binding->name(), 6095 "The binding of '%s' ('%s') must be either an accessible " 6096 "module procedure or an external procedure with " 6097 "an explicit interface"_err_en_US, 6098 binding->name(), details->symbol().name()); 6099 } else { 6100 Say(binding->name(), 6101 "'%s' must be either an accessible module procedure " 6102 "or an external procedure with an explicit interface"_err_en_US, 6103 binding->name()); 6104 } 6105 context().SetError(*binding); 6106 } 6107 } 6108 } 6109 } 6110 } 6111 6112 void DeclarationVisitor::Post( 6113 const parser::TypeBoundProcedureStmt::WithInterface &x) { 6114 if (!GetAttrs().test(Attr::DEFERRED)) { // C783 6115 Say("DEFERRED is required when an interface-name is provided"_err_en_US); 6116 } 6117 if (Symbol * interface{NoteInterfaceName(x.interfaceName)}) { 6118 for (auto &bindingName : x.bindingNames) { 6119 if (auto *s{ 6120 MakeTypeSymbol(bindingName, ProcBindingDetails{*interface})}) { 6121 SetPassNameOn(*s); 6122 if (!GetAttrs().test(Attr::DEFERRED)) { 6123 context().SetError(*s); 6124 } 6125 } 6126 } 6127 } 6128 } 6129 6130 bool DeclarationVisitor::Pre(const parser::FinalProcedureStmt &x) { 6131 if (currScope().IsDerivedType() && currScope().symbol()) { 6132 if (auto *details{currScope().symbol()->detailsIf<DerivedTypeDetails>()}) { 6133 for (const auto &subrName : x.v) { 6134 Symbol *symbol{FindSymbol(subrName)}; 6135 if (!symbol) { 6136 // FINAL procedures must be module subroutines 6137 symbol = &MakeSymbol( 6138 currScope().parent(), subrName.source, Attrs{Attr::MODULE}); 6139 Resolve(subrName, symbol); 6140 symbol->set_details(ProcEntityDetails{}); 6141 symbol->set(Symbol::Flag::Subroutine); 6142 } 6143 if (auto pair{details->finals().emplace(subrName.source, *symbol)}; 6144 !pair.second) { // C787 6145 Say(subrName.source, 6146 "FINAL subroutine '%s' already appeared in this derived type"_err_en_US, 6147 subrName.source) 6148 .Attach(pair.first->first, 6149 "earlier appearance of this FINAL subroutine"_en_US); 6150 } 6151 } 6152 } 6153 } 6154 return false; 6155 } 6156 6157 bool DeclarationVisitor::Pre(const parser::TypeBoundGenericStmt &x) { 6158 const auto &accessSpec{std::get<std::optional<parser::AccessSpec>>(x.t)}; 6159 const auto &genericSpec{std::get<Indirection<parser::GenericSpec>>(x.t)}; 6160 const auto &bindingNames{std::get<std::list<parser::Name>>(x.t)}; 6161 GenericSpecInfo info{genericSpec.value()}; 6162 SourceName symbolName{info.symbolName()}; 6163 bool isPrivate{accessSpec ? accessSpec->v == parser::AccessSpec::Kind::Private 6164 : derivedTypeInfo_.privateBindings}; 6165 auto *genericSymbol{FindInScope(symbolName)}; 6166 if (genericSymbol) { 6167 if (!genericSymbol->has<GenericDetails>()) { 6168 genericSymbol = nullptr; // MakeTypeSymbol will report the error below 6169 } 6170 } else { 6171 // look in ancestor types for a generic of the same name 6172 for (const auto &name : GetAllNames(context(), symbolName)) { 6173 if (Symbol * inherited{currScope().FindComponent(SourceName{name})}) { 6174 if (inherited->has<GenericDetails>()) { 6175 CheckAccessibility(symbolName, isPrivate, *inherited); // C771 6176 } else { 6177 Say(symbolName, 6178 "Type bound generic procedure '%s' may not have the same name as a non-generic symbol inherited from an ancestor type"_err_en_US) 6179 .Attach(inherited->name(), "Inherited symbol"_en_US); 6180 } 6181 break; 6182 } 6183 } 6184 } 6185 if (genericSymbol) { 6186 CheckAccessibility(symbolName, isPrivate, *genericSymbol); // C771 6187 } else { 6188 genericSymbol = MakeTypeSymbol(symbolName, GenericDetails{}); 6189 if (!genericSymbol) { 6190 return false; 6191 } 6192 if (isPrivate) { 6193 SetExplicitAttr(*genericSymbol, Attr::PRIVATE); 6194 } 6195 } 6196 for (const parser::Name &bindingName : bindingNames) { 6197 genericBindings_.emplace(genericSymbol, &bindingName); 6198 } 6199 info.Resolve(genericSymbol); 6200 return false; 6201 } 6202 6203 // DEC STRUCTUREs are handled thus to allow for nested definitions. 6204 bool DeclarationVisitor::Pre(const parser::StructureDef &def) { 6205 const auto &structureStatement{ 6206 std::get<parser::Statement<parser::StructureStmt>>(def.t)}; 6207 auto saveDerivedTypeInfo{derivedTypeInfo_}; 6208 derivedTypeInfo_ = {}; 6209 derivedTypeInfo_.isStructure = true; 6210 derivedTypeInfo_.sequence = true; 6211 Scope *previousStructure{nullptr}; 6212 if (saveDerivedTypeInfo.isStructure) { 6213 previousStructure = &currScope(); 6214 PopScope(); 6215 } 6216 const parser::StructureStmt &structStmt{structureStatement.statement}; 6217 const auto &name{std::get<std::optional<parser::Name>>(structStmt.t)}; 6218 if (!name) { 6219 // Construct a distinct generated name for an anonymous structure 6220 auto &mutableName{const_cast<std::optional<parser::Name> &>(name)}; 6221 mutableName.emplace( 6222 parser::Name{context().GetTempName(currScope()), nullptr}); 6223 } 6224 auto &symbol{MakeSymbol(*name, DerivedTypeDetails{})}; 6225 symbol.ReplaceName(name->source); 6226 symbol.get<DerivedTypeDetails>().set_sequence(true); 6227 symbol.get<DerivedTypeDetails>().set_isDECStructure(true); 6228 derivedTypeInfo_.type = &symbol; 6229 PushScope(Scope::Kind::DerivedType, &symbol); 6230 const auto &fields{std::get<std::list<parser::StructureField>>(def.t)}; 6231 Walk(fields); 6232 PopScope(); 6233 // Complete the definition 6234 DerivedTypeSpec derivedTypeSpec{symbol.name(), symbol}; 6235 derivedTypeSpec.set_scope(DEREF(symbol.scope())); 6236 derivedTypeSpec.CookParameters(GetFoldingContext()); 6237 derivedTypeSpec.EvaluateParameters(context()); 6238 DeclTypeSpec &type{currScope().MakeDerivedType( 6239 DeclTypeSpec::TypeDerived, std::move(derivedTypeSpec))}; 6240 type.derivedTypeSpec().Instantiate(currScope()); 6241 // Restore previous structure definition context, if any 6242 derivedTypeInfo_ = saveDerivedTypeInfo; 6243 if (previousStructure) { 6244 PushScope(*previousStructure); 6245 } 6246 // Handle any entity declarations on the STRUCTURE statement 6247 const auto &decls{std::get<std::list<parser::EntityDecl>>(structStmt.t)}; 6248 if (!decls.empty()) { 6249 BeginDecl(); 6250 SetDeclTypeSpec(type); 6251 Walk(decls); 6252 EndDecl(); 6253 } 6254 return false; 6255 } 6256 6257 bool DeclarationVisitor::Pre(const parser::Union::UnionStmt &) { 6258 Say("support for UNION"_todo_en_US); // TODO 6259 return true; 6260 } 6261 6262 bool DeclarationVisitor::Pre(const parser::StructureField &x) { 6263 if (std::holds_alternative<parser::Statement<parser::DataComponentDefStmt>>( 6264 x.u)) { 6265 BeginDecl(); 6266 } 6267 return true; 6268 } 6269 6270 void DeclarationVisitor::Post(const parser::StructureField &x) { 6271 if (std::holds_alternative<parser::Statement<parser::DataComponentDefStmt>>( 6272 x.u)) { 6273 EndDecl(); 6274 } 6275 } 6276 6277 bool DeclarationVisitor::Pre(const parser::AllocateStmt &) { 6278 BeginDeclTypeSpec(); 6279 return true; 6280 } 6281 void DeclarationVisitor::Post(const parser::AllocateStmt &) { 6282 EndDeclTypeSpec(); 6283 } 6284 6285 bool DeclarationVisitor::Pre(const parser::StructureConstructor &x) { 6286 auto &parsedType{std::get<parser::DerivedTypeSpec>(x.t)}; 6287 const DeclTypeSpec *type{ProcessTypeSpec(parsedType)}; 6288 if (!type) { 6289 return false; 6290 } 6291 const DerivedTypeSpec *spec{type->AsDerived()}; 6292 const Scope *typeScope{spec ? spec->scope() : nullptr}; 6293 if (!typeScope) { 6294 return false; 6295 } 6296 6297 // N.B C7102 is implicitly enforced by having inaccessible types not 6298 // being found in resolution. 6299 // More constraints are enforced in expression.cpp so that they 6300 // can apply to structure constructors that have been converted 6301 // from misparsed function references. 6302 for (const auto &component : 6303 std::get<std::list<parser::ComponentSpec>>(x.t)) { 6304 // Visit the component spec expression, but not the keyword, since 6305 // we need to resolve its symbol in the scope of the derived type. 6306 Walk(std::get<parser::ComponentDataSource>(component.t)); 6307 if (const auto &kw{std::get<std::optional<parser::Keyword>>(component.t)}) { 6308 FindInTypeOrParents(*typeScope, kw->v); 6309 } 6310 } 6311 return false; 6312 } 6313 6314 bool DeclarationVisitor::Pre(const parser::BasedPointer &) { 6315 BeginArraySpec(); 6316 return true; 6317 } 6318 6319 void DeclarationVisitor::Post(const parser::BasedPointer &bp) { 6320 const parser::ObjectName &pointerName{std::get<0>(bp.t)}; 6321 auto *pointer{FindSymbol(pointerName)}; 6322 if (!pointer) { 6323 pointer = &MakeSymbol(pointerName, ObjectEntityDetails{}); 6324 } else if (!ConvertToObjectEntity(*pointer)) { 6325 SayWithDecl(pointerName, *pointer, "'%s' is not a variable"_err_en_US); 6326 } else if (IsNamedConstant(*pointer)) { 6327 SayWithDecl(pointerName, *pointer, 6328 "'%s' is a named constant and may not be a Cray pointer"_err_en_US); 6329 } else if (pointer->Rank() > 0) { 6330 SayWithDecl( 6331 pointerName, *pointer, "Cray pointer '%s' must be a scalar"_err_en_US); 6332 } else if (pointer->test(Symbol::Flag::CrayPointee)) { 6333 Say(pointerName, 6334 "'%s' cannot be a Cray pointer as it is already a Cray pointee"_err_en_US); 6335 } 6336 pointer->set(Symbol::Flag::CrayPointer); 6337 const DeclTypeSpec &pointerType{MakeNumericType( 6338 TypeCategory::Integer, context().defaultKinds().subscriptIntegerKind())}; 6339 const auto *type{pointer->GetType()}; 6340 if (!type) { 6341 pointer->SetType(pointerType); 6342 } else if (*type != pointerType) { 6343 Say(pointerName.source, "Cray pointer '%s' must have type %s"_err_en_US, 6344 pointerName.source, pointerType.AsFortran()); 6345 } 6346 const parser::ObjectName &pointeeName{std::get<1>(bp.t)}; 6347 DeclareObjectEntity(pointeeName); 6348 if (Symbol * pointee{pointeeName.symbol}) { 6349 if (!ConvertToObjectEntity(*pointee)) { 6350 return; 6351 } 6352 if (IsNamedConstant(*pointee)) { 6353 Say(pointeeName, 6354 "'%s' is a named constant and may not be a Cray pointee"_err_en_US); 6355 return; 6356 } 6357 if (pointee->test(Symbol::Flag::CrayPointer)) { 6358 Say(pointeeName, 6359 "'%s' cannot be a Cray pointee as it is already a Cray pointer"_err_en_US); 6360 } else if (pointee->test(Symbol::Flag::CrayPointee)) { 6361 Say(pointeeName, "'%s' was already declared as a Cray pointee"_err_en_US); 6362 } else { 6363 pointee->set(Symbol::Flag::CrayPointee); 6364 } 6365 if (const auto *pointeeType{pointee->GetType()}) { 6366 if (const auto *derived{pointeeType->AsDerived()}) { 6367 if (!IsSequenceOrBindCType(derived)) { 6368 context().Warn(common::LanguageFeature::NonSequenceCrayPointee, 6369 pointeeName.source, 6370 "Type of Cray pointee '%s' is a derived type that is neither SEQUENCE nor BIND(C)"_warn_en_US, 6371 pointeeName.source); 6372 } 6373 } 6374 } 6375 currScope().add_crayPointer(pointeeName.source, *pointer); 6376 } 6377 } 6378 6379 bool DeclarationVisitor::Pre(const parser::NamelistStmt::Group &x) { 6380 if (!CheckNotInBlock("NAMELIST")) { // C1107 6381 return false; 6382 } 6383 const auto &groupName{std::get<parser::Name>(x.t)}; 6384 auto *groupSymbol{FindInScope(groupName)}; 6385 if (!groupSymbol || !groupSymbol->has<NamelistDetails>()) { 6386 groupSymbol = &MakeSymbol(groupName, NamelistDetails{}); 6387 groupSymbol->ReplaceName(groupName.source); 6388 } 6389 // Name resolution of group items is deferred to FinishNamelists() 6390 // so that host association is handled correctly. 6391 GetDeferredDeclarationState(true)->namelistGroups.emplace_back(&x); 6392 return false; 6393 } 6394 6395 void DeclarationVisitor::FinishNamelists() { 6396 if (auto *deferred{GetDeferredDeclarationState()}) { 6397 for (const parser::NamelistStmt::Group *group : deferred->namelistGroups) { 6398 if (auto *groupSymbol{FindInScope(std::get<parser::Name>(group->t))}) { 6399 if (auto *details{groupSymbol->detailsIf<NamelistDetails>()}) { 6400 for (const auto &name : std::get<std::list<parser::Name>>(group->t)) { 6401 auto *symbol{FindSymbol(name)}; 6402 if (!symbol) { 6403 symbol = &MakeSymbol(name, ObjectEntityDetails{}); 6404 ApplyImplicitRules(*symbol); 6405 } else if (!ConvertToObjectEntity(symbol->GetUltimate())) { 6406 SayWithDecl(name, *symbol, "'%s' is not a variable"_err_en_US); 6407 context().SetError(*groupSymbol); 6408 } 6409 symbol->GetUltimate().set(Symbol::Flag::InNamelist); 6410 details->add_object(*symbol); 6411 } 6412 } 6413 } 6414 } 6415 deferred->namelistGroups.clear(); 6416 } 6417 } 6418 6419 bool DeclarationVisitor::Pre(const parser::IoControlSpec &x) { 6420 if (const auto *name{std::get_if<parser::Name>(&x.u)}) { 6421 auto *symbol{FindSymbol(*name)}; 6422 if (!symbol) { 6423 Say(*name, "Namelist group '%s' not found"_err_en_US); 6424 } else if (!symbol->GetUltimate().has<NamelistDetails>()) { 6425 SayWithDecl( 6426 *name, *symbol, "'%s' is not the name of a namelist group"_err_en_US); 6427 } 6428 } 6429 return true; 6430 } 6431 6432 bool DeclarationVisitor::Pre(const parser::CommonStmt::Block &x) { 6433 CheckNotInBlock("COMMON"); // C1107 6434 return true; 6435 } 6436 6437 bool DeclarationVisitor::Pre(const parser::CommonBlockObject &) { 6438 BeginArraySpec(); 6439 return true; 6440 } 6441 6442 void DeclarationVisitor::Post(const parser::CommonBlockObject &x) { 6443 const auto &name{std::get<parser::Name>(x.t)}; 6444 DeclareObjectEntity(name); 6445 auto pair{specPartState_.commonBlockObjects.insert(name.source)}; 6446 if (!pair.second) { 6447 const SourceName &prev{*pair.first}; 6448 Say2(name.source, "'%s' is already in a COMMON block"_err_en_US, prev, 6449 "Previous occurrence of '%s' in a COMMON block"_en_US); 6450 } 6451 } 6452 6453 bool DeclarationVisitor::Pre(const parser::EquivalenceStmt &x) { 6454 // save equivalence sets to be processed after specification part 6455 if (CheckNotInBlock("EQUIVALENCE")) { // C1107 6456 for (const std::list<parser::EquivalenceObject> &set : x.v) { 6457 specPartState_.equivalenceSets.push_back(&set); 6458 } 6459 } 6460 return false; // don't implicitly declare names yet 6461 } 6462 6463 void DeclarationVisitor::CheckEquivalenceSets() { 6464 EquivalenceSets equivSets{context()}; 6465 inEquivalenceStmt_ = true; 6466 for (const auto *set : specPartState_.equivalenceSets) { 6467 const auto &source{set->front().v.value().source}; 6468 if (set->size() <= 1) { // R871 6469 Say(source, "Equivalence set must have more than one object"_err_en_US); 6470 } 6471 for (const parser::EquivalenceObject &object : *set) { 6472 const auto &designator{object.v.value()}; 6473 // The designator was not resolved when it was encountered, so do it now. 6474 // AnalyzeExpr causes array sections to be changed to substrings as needed 6475 Walk(designator); 6476 if (AnalyzeExpr(context(), designator)) { 6477 equivSets.AddToSet(designator); 6478 } 6479 } 6480 equivSets.FinishSet(source); 6481 } 6482 inEquivalenceStmt_ = false; 6483 for (auto &set : equivSets.sets()) { 6484 if (!set.empty()) { 6485 currScope().add_equivalenceSet(std::move(set)); 6486 } 6487 } 6488 specPartState_.equivalenceSets.clear(); 6489 } 6490 6491 bool DeclarationVisitor::Pre(const parser::SaveStmt &x) { 6492 if (x.v.empty()) { 6493 specPartState_.saveInfo.saveAll = currStmtSource(); 6494 currScope().set_hasSAVE(); 6495 } else { 6496 for (const parser::SavedEntity &y : x.v) { 6497 auto kind{std::get<parser::SavedEntity::Kind>(y.t)}; 6498 const auto &name{std::get<parser::Name>(y.t)}; 6499 if (kind == parser::SavedEntity::Kind::Common) { 6500 MakeCommonBlockSymbol(name); 6501 AddSaveName(specPartState_.saveInfo.commons, name.source); 6502 } else { 6503 HandleAttributeStmt(Attr::SAVE, name); 6504 } 6505 } 6506 } 6507 return false; 6508 } 6509 6510 void DeclarationVisitor::CheckSaveStmts() { 6511 for (const SourceName &name : specPartState_.saveInfo.entities) { 6512 auto *symbol{FindInScope(name)}; 6513 if (!symbol) { 6514 // error was reported 6515 } else if (specPartState_.saveInfo.saveAll) { 6516 // C889 - note that pgi, ifort, xlf do not enforce this constraint 6517 if (context().ShouldWarn(common::LanguageFeature::RedundantAttribute)) { 6518 Say2(name, 6519 "Explicit SAVE of '%s' is redundant due to global SAVE statement"_warn_en_US, 6520 *specPartState_.saveInfo.saveAll, "Global SAVE statement"_en_US) 6521 .set_languageFeature(common::LanguageFeature::RedundantAttribute); 6522 } 6523 } else if (!IsSaved(*symbol)) { 6524 SetExplicitAttr(*symbol, Attr::SAVE); 6525 } 6526 } 6527 for (const SourceName &name : specPartState_.saveInfo.commons) { 6528 if (auto *symbol{currScope().FindCommonBlock(name)}) { 6529 auto &objects{symbol->get<CommonBlockDetails>().objects()}; 6530 if (objects.empty()) { 6531 if (currScope().kind() != Scope::Kind::BlockConstruct) { 6532 Say(name, 6533 "'%s' appears as a COMMON block in a SAVE statement but not in" 6534 " a COMMON statement"_err_en_US); 6535 } else { // C1108 6536 Say(name, 6537 "SAVE statement in BLOCK construct may not contain a" 6538 " common block name '%s'"_err_en_US); 6539 } 6540 } else { 6541 for (auto &object : symbol->get<CommonBlockDetails>().objects()) { 6542 if (!IsSaved(*object)) { 6543 SetImplicitAttr(*object, Attr::SAVE); 6544 } 6545 } 6546 } 6547 } 6548 } 6549 specPartState_.saveInfo = {}; 6550 } 6551 6552 // Record SAVEd names in specPartState_.saveInfo.entities. 6553 Attrs DeclarationVisitor::HandleSaveName(const SourceName &name, Attrs attrs) { 6554 if (attrs.test(Attr::SAVE)) { 6555 AddSaveName(specPartState_.saveInfo.entities, name); 6556 } 6557 return attrs; 6558 } 6559 6560 // Record a name in a set of those to be saved. 6561 void DeclarationVisitor::AddSaveName( 6562 std::set<SourceName> &set, const SourceName &name) { 6563 auto pair{set.insert(name)}; 6564 if (!pair.second && 6565 context().ShouldWarn(common::LanguageFeature::RedundantAttribute)) { 6566 Say2(name, "SAVE attribute was already specified on '%s'"_warn_en_US, 6567 *pair.first, "Previous specification of SAVE attribute"_en_US) 6568 .set_languageFeature(common::LanguageFeature::RedundantAttribute); 6569 } 6570 } 6571 6572 // Check types of common block objects, now that they are known. 6573 void DeclarationVisitor::CheckCommonBlocks() { 6574 // check for empty common blocks 6575 for (const auto &pair : currScope().commonBlocks()) { 6576 const auto &symbol{*pair.second}; 6577 if (symbol.get<CommonBlockDetails>().objects().empty() && 6578 symbol.attrs().test(Attr::BIND_C)) { 6579 Say(symbol.name(), 6580 "'%s' appears as a COMMON block in a BIND statement but not in" 6581 " a COMMON statement"_err_en_US); 6582 } 6583 } 6584 // check objects in common blocks 6585 for (const auto &name : specPartState_.commonBlockObjects) { 6586 const auto *symbol{currScope().FindSymbol(name)}; 6587 if (!symbol) { 6588 continue; 6589 } 6590 const auto &attrs{symbol->attrs()}; 6591 if (attrs.test(Attr::ALLOCATABLE)) { 6592 Say(name, 6593 "ALLOCATABLE object '%s' may not appear in a COMMON block"_err_en_US); 6594 } else if (attrs.test(Attr::BIND_C)) { 6595 Say(name, 6596 "Variable '%s' with BIND attribute may not appear in a COMMON block"_err_en_US); 6597 } else if (IsNamedConstant(*symbol)) { 6598 Say(name, 6599 "A named constant '%s' may not appear in a COMMON block"_err_en_US); 6600 } else if (IsDummy(*symbol)) { 6601 Say(name, 6602 "Dummy argument '%s' may not appear in a COMMON block"_err_en_US); 6603 } else if (symbol->IsFuncResult()) { 6604 Say(name, 6605 "Function result '%s' may not appear in a COMMON block"_err_en_US); 6606 } else if (const DeclTypeSpec * type{symbol->GetType()}) { 6607 if (type->category() == DeclTypeSpec::ClassStar) { 6608 Say(name, 6609 "Unlimited polymorphic pointer '%s' may not appear in a COMMON block"_err_en_US); 6610 } else if (const auto *derived{type->AsDerived()}) { 6611 if (!IsSequenceOrBindCType(derived)) { 6612 Say(name, 6613 "Derived type '%s' in COMMON block must have the BIND or" 6614 " SEQUENCE attribute"_err_en_US); 6615 } 6616 UnorderedSymbolSet typeSet; 6617 CheckCommonBlockDerivedType(name, derived->typeSymbol(), typeSet); 6618 } 6619 } 6620 } 6621 specPartState_.commonBlockObjects = {}; 6622 } 6623 6624 Symbol &DeclarationVisitor::MakeCommonBlockSymbol(const parser::Name &name) { 6625 return Resolve(name, currScope().MakeCommonBlock(name.source)); 6626 } 6627 Symbol &DeclarationVisitor::MakeCommonBlockSymbol( 6628 const std::optional<parser::Name> &name) { 6629 if (name) { 6630 return MakeCommonBlockSymbol(*name); 6631 } else { 6632 return MakeCommonBlockSymbol(parser::Name{}); 6633 } 6634 } 6635 6636 bool DeclarationVisitor::NameIsKnownOrIntrinsic(const parser::Name &name) { 6637 return FindSymbol(name) || HandleUnrestrictedSpecificIntrinsicFunction(name); 6638 } 6639 6640 // Check if this derived type can be in a COMMON block. 6641 void DeclarationVisitor::CheckCommonBlockDerivedType(const SourceName &name, 6642 const Symbol &typeSymbol, UnorderedSymbolSet &typeSet) { 6643 if (auto iter{typeSet.find(SymbolRef{typeSymbol})}; iter != typeSet.end()) { 6644 return; 6645 } 6646 typeSet.emplace(typeSymbol); 6647 if (const auto *scope{typeSymbol.scope()}) { 6648 for (const auto &pair : *scope) { 6649 const Symbol &component{*pair.second}; 6650 if (component.attrs().test(Attr::ALLOCATABLE)) { 6651 Say2(name, 6652 "Derived type variable '%s' may not appear in a COMMON block" 6653 " due to ALLOCATABLE component"_err_en_US, 6654 component.name(), "Component with ALLOCATABLE attribute"_en_US); 6655 return; 6656 } 6657 const auto *details{component.detailsIf<ObjectEntityDetails>()}; 6658 if (component.test(Symbol::Flag::InDataStmt) || 6659 (details && details->init())) { 6660 Say2(name, 6661 "Derived type variable '%s' may not appear in a COMMON block due to component with default initialization"_err_en_US, 6662 component.name(), "Component with default initialization"_en_US); 6663 return; 6664 } 6665 if (details) { 6666 if (const auto *type{details->type()}) { 6667 if (const auto *derived{type->AsDerived()}) { 6668 const Symbol &derivedTypeSymbol{derived->typeSymbol()}; 6669 CheckCommonBlockDerivedType(name, derivedTypeSymbol, typeSet); 6670 } 6671 } 6672 } 6673 } 6674 } 6675 } 6676 6677 bool DeclarationVisitor::HandleUnrestrictedSpecificIntrinsicFunction( 6678 const parser::Name &name) { 6679 if (auto interface{context().intrinsics().IsSpecificIntrinsicFunction( 6680 name.source.ToString())}) { 6681 // Unrestricted specific intrinsic function names (e.g., "cos") 6682 // are acceptable as procedure interfaces. The presence of the 6683 // INTRINSIC flag will cause this symbol to have a complete interface 6684 // recreated for it later on demand, but capturing its result type here 6685 // will make GetType() return a correct result without having to 6686 // probe the intrinsics table again. 6687 Symbol &symbol{MakeSymbol(InclusiveScope(), name.source, Attrs{})}; 6688 SetImplicitAttr(symbol, Attr::INTRINSIC); 6689 CHECK(interface->functionResult.has_value()); 6690 evaluate::DynamicType dyType{ 6691 DEREF(interface->functionResult->GetTypeAndShape()).type()}; 6692 CHECK(common::IsNumericTypeCategory(dyType.category())); 6693 const DeclTypeSpec &typeSpec{ 6694 MakeNumericType(dyType.category(), dyType.kind())}; 6695 ProcEntityDetails details; 6696 details.set_type(typeSpec); 6697 symbol.set_details(std::move(details)); 6698 symbol.set(Symbol::Flag::Function); 6699 if (interface->IsElemental()) { 6700 SetExplicitAttr(symbol, Attr::ELEMENTAL); 6701 } 6702 if (interface->IsPure()) { 6703 SetExplicitAttr(symbol, Attr::PURE); 6704 } 6705 Resolve(name, symbol); 6706 return true; 6707 } else { 6708 return false; 6709 } 6710 } 6711 6712 // Checks for all locality-specs: LOCAL, LOCAL_INIT, and SHARED 6713 bool DeclarationVisitor::PassesSharedLocalityChecks( 6714 const parser::Name &name, Symbol &symbol) { 6715 if (!IsVariableName(symbol)) { 6716 SayLocalMustBeVariable(name, symbol); // C1124 6717 return false; 6718 } 6719 if (symbol.owner() == currScope()) { // C1125 and C1126 6720 SayAlreadyDeclared(name, symbol); 6721 return false; 6722 } 6723 return true; 6724 } 6725 6726 // Checks for locality-specs LOCAL, LOCAL_INIT, and REDUCE 6727 bool DeclarationVisitor::PassesLocalityChecks( 6728 const parser::Name &name, Symbol &symbol, Symbol::Flag flag) { 6729 bool isReduce{flag == Symbol::Flag::LocalityReduce}; 6730 const char *specName{ 6731 flag == Symbol::Flag::LocalityLocalInit ? "LOCAL_INIT" : "LOCAL"}; 6732 if (IsAllocatable(symbol) && !isReduce) { // F'2023 C1130 6733 SayWithDecl(name, symbol, 6734 "ALLOCATABLE variable '%s' not allowed in a %s locality-spec"_err_en_US, 6735 specName); 6736 return false; 6737 } 6738 if (IsOptional(symbol)) { // F'2023 C1130-C1131 6739 SayWithDecl(name, symbol, 6740 "OPTIONAL argument '%s' not allowed in a locality-spec"_err_en_US); 6741 return false; 6742 } 6743 if (IsIntentIn(symbol)) { // F'2023 C1130-C1131 6744 SayWithDecl(name, symbol, 6745 "INTENT IN argument '%s' not allowed in a locality-spec"_err_en_US); 6746 return false; 6747 } 6748 if (IsFinalizable(symbol) && !isReduce) { // F'2023 C1130 6749 SayWithDecl(name, symbol, 6750 "Finalizable variable '%s' not allowed in a %s locality-spec"_err_en_US, 6751 specName); 6752 return false; 6753 } 6754 if (evaluate::IsCoarray(symbol) && !isReduce) { // F'2023 C1130 6755 SayWithDecl(name, symbol, 6756 "Coarray '%s' not allowed in a %s locality-spec"_err_en_US, specName); 6757 return false; 6758 } 6759 if (const DeclTypeSpec * type{symbol.GetType()}) { 6760 if (type->IsPolymorphic() && IsDummy(symbol) && !IsPointer(symbol) && 6761 !isReduce) { // F'2023 C1130 6762 SayWithDecl(name, symbol, 6763 "Nonpointer polymorphic argument '%s' not allowed in a %s locality-spec"_err_en_US, 6764 specName); 6765 return false; 6766 } 6767 } 6768 if (symbol.attrs().test(Attr::ASYNCHRONOUS) && isReduce) { // F'2023 C1131 6769 SayWithDecl(name, symbol, 6770 "ASYNCHRONOUS variable '%s' not allowed in a REDUCE locality-spec"_err_en_US); 6771 return false; 6772 } 6773 if (symbol.attrs().test(Attr::VOLATILE) && isReduce) { // F'2023 C1131 6774 SayWithDecl(name, symbol, 6775 "VOLATILE variable '%s' not allowed in a REDUCE locality-spec"_err_en_US); 6776 return false; 6777 } 6778 if (IsAssumedSizeArray(symbol)) { // F'2023 C1130-C1131 6779 SayWithDecl(name, symbol, 6780 "Assumed size array '%s' not allowed in a locality-spec"_err_en_US); 6781 return false; 6782 } 6783 if (std::optional<Message> whyNot{WhyNotDefinable( 6784 name.source, currScope(), DefinabilityFlags{}, symbol)}) { 6785 SayWithReason(name, symbol, 6786 "'%s' may not appear in a locality-spec because it is not definable"_err_en_US, 6787 std::move(whyNot->set_severity(parser::Severity::Because))); 6788 return false; 6789 } 6790 return PassesSharedLocalityChecks(name, symbol); 6791 } 6792 6793 Symbol &DeclarationVisitor::FindOrDeclareEnclosingEntity( 6794 const parser::Name &name) { 6795 Symbol *prev{FindSymbol(name)}; 6796 if (!prev) { 6797 // Declare the name as an object in the enclosing scope so that 6798 // the name can't be repurposed there later as something else. 6799 prev = &MakeSymbol(InclusiveScope(), name.source, Attrs{}); 6800 ConvertToObjectEntity(*prev); 6801 ApplyImplicitRules(*prev); 6802 } 6803 return *prev; 6804 } 6805 6806 void DeclarationVisitor::DeclareLocalEntity( 6807 const parser::Name &name, Symbol::Flag flag) { 6808 Symbol &prev{FindOrDeclareEnclosingEntity(name)}; 6809 if (PassesLocalityChecks(name, prev, flag)) { 6810 if (auto *symbol{&MakeHostAssocSymbol(name, prev)}) { 6811 symbol->set(flag); 6812 } 6813 } 6814 } 6815 6816 Symbol *DeclarationVisitor::DeclareStatementEntity( 6817 const parser::DoVariable &doVar, 6818 const std::optional<parser::IntegerTypeSpec> &type) { 6819 const parser::Name &name{doVar.thing.thing}; 6820 const DeclTypeSpec *declTypeSpec{nullptr}; 6821 if (auto *prev{FindSymbol(name)}) { 6822 if (prev->owner() == currScope()) { 6823 SayAlreadyDeclared(name, *prev); 6824 return nullptr; 6825 } 6826 name.symbol = nullptr; 6827 // F'2023 19.4 p5 ambiguous rule about outer declarations 6828 declTypeSpec = prev->GetType(); 6829 } 6830 Symbol &symbol{DeclareEntity<ObjectEntityDetails>(name, {})}; 6831 if (!symbol.has<ObjectEntityDetails>()) { 6832 return nullptr; // error was reported in DeclareEntity 6833 } 6834 if (type) { 6835 declTypeSpec = ProcessTypeSpec(*type); 6836 } 6837 if (declTypeSpec) { 6838 // Subtlety: Don't let a "*length" specifier (if any is pending) affect the 6839 // declaration of this implied DO loop control variable. 6840 auto restorer{ 6841 common::ScopedSet(charInfo_.length, std::optional<ParamValue>{})}; 6842 SetType(name, *declTypeSpec); 6843 } else { 6844 ApplyImplicitRules(symbol); 6845 } 6846 return Resolve(name, &symbol); 6847 } 6848 6849 // Set the type of an entity or report an error. 6850 void DeclarationVisitor::SetType( 6851 const parser::Name &name, const DeclTypeSpec &type) { 6852 CHECK(name.symbol); 6853 auto &symbol{*name.symbol}; 6854 if (charInfo_.length) { // Declaration has "*length" (R723) 6855 auto length{std::move(*charInfo_.length)}; 6856 charInfo_.length.reset(); 6857 if (type.category() == DeclTypeSpec::Character) { 6858 auto kind{type.characterTypeSpec().kind()}; 6859 // Recurse with correct type. 6860 SetType(name, 6861 currScope().MakeCharacterType(std::move(length), std::move(kind))); 6862 return; 6863 } else { // C753 6864 Say(name, 6865 "A length specifier cannot be used to declare the non-character entity '%s'"_err_en_US); 6866 } 6867 } 6868 if (auto *proc{symbol.detailsIf<ProcEntityDetails>()}) { 6869 if (proc->procInterface()) { 6870 Say(name, 6871 "'%s' has an explicit interface and may not also have a type"_err_en_US); 6872 context().SetError(symbol); 6873 return; 6874 } 6875 } 6876 auto *prevType{symbol.GetType()}; 6877 if (!prevType) { 6878 if (symbol.test(Symbol::Flag::InDataStmt) && isImplicitNoneType()) { 6879 context().Warn(common::LanguageFeature::ForwardRefImplicitNoneData, 6880 name.source, 6881 "'%s' appeared in a DATA statement before its type was declared under IMPLICIT NONE(TYPE)"_port_en_US, 6882 name.source); 6883 } 6884 symbol.SetType(type); 6885 } else if (symbol.has<UseDetails>()) { 6886 // error recovery case, redeclaration of use-associated name 6887 } else if (HadForwardRef(symbol)) { 6888 // error recovery after use of host-associated name 6889 } else if (!symbol.test(Symbol::Flag::Implicit)) { 6890 SayWithDecl( 6891 name, symbol, "The type of '%s' has already been declared"_err_en_US); 6892 context().SetError(symbol); 6893 } else if (type != *prevType) { 6894 SayWithDecl(name, symbol, 6895 "The type of '%s' has already been implicitly declared"_err_en_US); 6896 context().SetError(symbol); 6897 } else { 6898 symbol.set(Symbol::Flag::Implicit, false); 6899 } 6900 } 6901 6902 std::optional<DerivedTypeSpec> DeclarationVisitor::ResolveDerivedType( 6903 const parser::Name &name) { 6904 Scope &outer{NonDerivedTypeScope()}; 6905 Symbol *symbol{FindSymbol(outer, name)}; 6906 Symbol *ultimate{symbol ? &symbol->GetUltimate() : nullptr}; 6907 auto *generic{ultimate ? ultimate->detailsIf<GenericDetails>() : nullptr}; 6908 if (generic) { 6909 if (Symbol * genDT{generic->derivedType()}) { 6910 symbol = genDT; 6911 generic = nullptr; 6912 } 6913 } 6914 if (!symbol || symbol->has<UnknownDetails>() || 6915 (generic && &ultimate->owner() == &outer)) { 6916 if (allowForwardReferenceToDerivedType()) { 6917 if (!symbol) { 6918 symbol = &MakeSymbol(outer, name.source, Attrs{}); 6919 Resolve(name, *symbol); 6920 } else if (generic) { 6921 // forward ref to type with later homonymous generic 6922 symbol = &outer.MakeSymbol(name.source, Attrs{}, UnknownDetails{}); 6923 generic->set_derivedType(*symbol); 6924 name.symbol = symbol; 6925 } 6926 DerivedTypeDetails details; 6927 details.set_isForwardReferenced(true); 6928 symbol->set_details(std::move(details)); 6929 } else { // C732 6930 Say(name, "Derived type '%s' not found"_err_en_US); 6931 return std::nullopt; 6932 } 6933 } else if (&DEREF(symbol).owner() != &outer && 6934 !ultimate->has<GenericDetails>()) { 6935 // Prevent a later declaration in this scope of a host-associated 6936 // type name. 6937 outer.add_importName(name.source); 6938 } 6939 if (CheckUseError(name)) { 6940 return std::nullopt; 6941 } else if (symbol->GetUltimate().has<DerivedTypeDetails>()) { 6942 return DerivedTypeSpec{name.source, *symbol}; 6943 } else { 6944 Say(name, "'%s' is not a derived type"_err_en_US); 6945 return std::nullopt; 6946 } 6947 } 6948 6949 std::optional<DerivedTypeSpec> DeclarationVisitor::ResolveExtendsType( 6950 const parser::Name &typeName, const parser::Name *extendsName) { 6951 if (extendsName) { 6952 if (typeName.source == extendsName->source) { 6953 Say(extendsName->source, 6954 "Derived type '%s' cannot extend itself"_err_en_US); 6955 } else if (auto dtSpec{ResolveDerivedType(*extendsName)}) { 6956 if (!dtSpec->IsForwardReferenced()) { 6957 return dtSpec; 6958 } 6959 Say(typeName.source, 6960 "Derived type '%s' cannot extend type '%s' that has not yet been defined"_err_en_US, 6961 typeName.source, extendsName->source); 6962 } 6963 } 6964 return std::nullopt; 6965 } 6966 6967 Symbol *DeclarationVisitor::NoteInterfaceName(const parser::Name &name) { 6968 // The symbol is checked later by CheckExplicitInterface() and 6969 // CheckBindings(). It can be a forward reference. 6970 if (!NameIsKnownOrIntrinsic(name)) { 6971 Symbol &symbol{MakeSymbol(InclusiveScope(), name.source, Attrs{})}; 6972 Resolve(name, symbol); 6973 } 6974 return name.symbol; 6975 } 6976 6977 void DeclarationVisitor::CheckExplicitInterface(const parser::Name &name) { 6978 if (const Symbol * symbol{name.symbol}) { 6979 const Symbol &ultimate{symbol->GetUltimate()}; 6980 if (!context().HasError(*symbol) && !context().HasError(ultimate) && 6981 !BypassGeneric(ultimate).HasExplicitInterface()) { 6982 Say(name, 6983 "'%s' must be an abstract interface or a procedure with an explicit interface"_err_en_US, 6984 symbol->name()); 6985 } 6986 } 6987 } 6988 6989 // Create a symbol for a type parameter, component, or procedure binding in 6990 // the current derived type scope. Return false on error. 6991 Symbol *DeclarationVisitor::MakeTypeSymbol( 6992 const parser::Name &name, Details &&details) { 6993 return Resolve(name, MakeTypeSymbol(name.source, std::move(details))); 6994 } 6995 Symbol *DeclarationVisitor::MakeTypeSymbol( 6996 const SourceName &name, Details &&details) { 6997 Scope &derivedType{currScope()}; 6998 CHECK(derivedType.IsDerivedType()); 6999 if (auto *symbol{FindInScope(derivedType, name)}) { // C742 7000 Say2(name, 7001 "Type parameter, component, or procedure binding '%s'" 7002 " already defined in this type"_err_en_US, 7003 *symbol, "Previous definition of '%s'"_en_US); 7004 return nullptr; 7005 } else { 7006 auto attrs{GetAttrs()}; 7007 // Apply binding-private-stmt if present and this is a procedure binding 7008 if (derivedTypeInfo_.privateBindings && 7009 !attrs.HasAny({Attr::PUBLIC, Attr::PRIVATE}) && 7010 std::holds_alternative<ProcBindingDetails>(details)) { 7011 attrs.set(Attr::PRIVATE); 7012 } 7013 Symbol &result{MakeSymbol(name, attrs, std::move(details))}; 7014 SetCUDADataAttr(name, result, cudaDataAttr()); 7015 return &result; 7016 } 7017 } 7018 7019 // Return true if it is ok to declare this component in the current scope. 7020 // Otherwise, emit an error and return false. 7021 bool DeclarationVisitor::OkToAddComponent( 7022 const parser::Name &name, const Symbol *extends) { 7023 for (const Scope *scope{&currScope()}; scope;) { 7024 CHECK(scope->IsDerivedType()); 7025 if (auto *prev{FindInScope(*scope, name.source)}) { 7026 std::optional<parser::MessageFixedText> msg; 7027 std::optional<common::UsageWarning> warning; 7028 if (context().HasError(*prev)) { // don't pile on 7029 } else if (extends) { 7030 msg = "Type cannot be extended as it has a component named" 7031 " '%s'"_err_en_US; 7032 } else if (CheckAccessibleSymbol(currScope(), *prev)) { 7033 // inaccessible component -- redeclaration is ok 7034 if (context().ShouldWarn( 7035 common::UsageWarning::RedeclaredInaccessibleComponent)) { 7036 msg = 7037 "Component '%s' is inaccessibly declared in or as a parent of this derived type"_warn_en_US; 7038 warning = common::UsageWarning::RedeclaredInaccessibleComponent; 7039 } 7040 } else if (prev->test(Symbol::Flag::ParentComp)) { 7041 msg = 7042 "'%s' is a parent type of this type and so cannot be a component"_err_en_US; 7043 } else if (scope == &currScope()) { 7044 msg = 7045 "Component '%s' is already declared in this derived type"_err_en_US; 7046 } else { 7047 msg = 7048 "Component '%s' is already declared in a parent of this derived type"_err_en_US; 7049 } 7050 if (msg) { 7051 auto &said{Say2(name, std::move(*msg), *prev, 7052 "Previous declaration of '%s'"_en_US)}; 7053 if (msg->severity() == parser::Severity::Error) { 7054 Resolve(name, *prev); 7055 return false; 7056 } 7057 if (warning) { 7058 said.set_usageWarning(*warning); 7059 } 7060 } 7061 } 7062 if (scope == &currScope() && extends) { 7063 // The parent component has not yet been added to the scope. 7064 scope = extends->scope(); 7065 } else { 7066 scope = scope->GetDerivedTypeParent(); 7067 } 7068 } 7069 return true; 7070 } 7071 7072 ParamValue DeclarationVisitor::GetParamValue( 7073 const parser::TypeParamValue &x, common::TypeParamAttr attr) { 7074 return common::visit( 7075 common::visitors{ 7076 [=](const parser::ScalarIntExpr &x) { // C704 7077 return ParamValue{EvaluateIntExpr(x), attr}; 7078 }, 7079 [=](const parser::Star &) { return ParamValue::Assumed(attr); }, 7080 [=](const parser::TypeParamValue::Deferred &) { 7081 return ParamValue::Deferred(attr); 7082 }, 7083 }, 7084 x.u); 7085 } 7086 7087 // ConstructVisitor implementation 7088 7089 void ConstructVisitor::ResolveIndexName( 7090 const parser::ConcurrentControl &control) { 7091 const parser::Name &name{std::get<parser::Name>(control.t)}; 7092 auto *prev{FindSymbol(name)}; 7093 if (prev) { 7094 if (prev->owner() == currScope()) { 7095 SayAlreadyDeclared(name, *prev); 7096 return; 7097 } else if (prev->owner().kind() == Scope::Kind::Forall && 7098 context().ShouldWarn( 7099 common::LanguageFeature::OddIndexVariableRestrictions)) { 7100 SayWithDecl(name, *prev, 7101 "Index variable '%s' should not also be an index in an enclosing FORALL or DO CONCURRENT"_port_en_US) 7102 .set_languageFeature( 7103 common::LanguageFeature::OddIndexVariableRestrictions); 7104 } 7105 name.symbol = nullptr; 7106 } 7107 auto &symbol{DeclareObjectEntity(name)}; 7108 if (symbol.GetType()) { 7109 // type came from explicit type-spec 7110 } else if (!prev) { 7111 ApplyImplicitRules(symbol); 7112 } else { 7113 // Odd rules in F'2023 19.4 paras 6 & 8. 7114 Symbol &prevRoot{prev->GetUltimate()}; 7115 if (const auto *type{prevRoot.GetType()}) { 7116 symbol.SetType(*type); 7117 } else { 7118 ApplyImplicitRules(symbol); 7119 } 7120 if (prevRoot.has<ObjectEntityDetails>() || 7121 ConvertToObjectEntity(prevRoot)) { 7122 if (prevRoot.IsObjectArray() && 7123 context().ShouldWarn( 7124 common::LanguageFeature::OddIndexVariableRestrictions)) { 7125 SayWithDecl(name, *prev, 7126 "Index variable '%s' should be scalar in the enclosing scope"_port_en_US) 7127 .set_languageFeature( 7128 common::LanguageFeature::OddIndexVariableRestrictions); 7129 } 7130 } else if (!prevRoot.has<CommonBlockDetails>() && 7131 context().ShouldWarn( 7132 common::LanguageFeature::OddIndexVariableRestrictions)) { 7133 SayWithDecl(name, *prev, 7134 "Index variable '%s' should be a scalar object or common block if it is present in the enclosing scope"_port_en_US) 7135 .set_languageFeature( 7136 common::LanguageFeature::OddIndexVariableRestrictions); 7137 } 7138 } 7139 EvaluateExpr(parser::Scalar{parser::Integer{common::Clone(name)}}); 7140 } 7141 7142 // We need to make sure that all of the index-names get declared before the 7143 // expressions in the loop control are evaluated so that references to the 7144 // index-names in the expressions are correctly detected. 7145 bool ConstructVisitor::Pre(const parser::ConcurrentHeader &header) { 7146 BeginDeclTypeSpec(); 7147 Walk(std::get<std::optional<parser::IntegerTypeSpec>>(header.t)); 7148 const auto &controls{ 7149 std::get<std::list<parser::ConcurrentControl>>(header.t)}; 7150 for (const auto &control : controls) { 7151 ResolveIndexName(control); 7152 } 7153 Walk(controls); 7154 Walk(std::get<std::optional<parser::ScalarLogicalExpr>>(header.t)); 7155 EndDeclTypeSpec(); 7156 return false; 7157 } 7158 7159 bool ConstructVisitor::Pre(const parser::LocalitySpec::Local &x) { 7160 for (auto &name : x.v) { 7161 DeclareLocalEntity(name, Symbol::Flag::LocalityLocal); 7162 } 7163 return false; 7164 } 7165 7166 bool ConstructVisitor::Pre(const parser::LocalitySpec::LocalInit &x) { 7167 for (auto &name : x.v) { 7168 DeclareLocalEntity(name, Symbol::Flag::LocalityLocalInit); 7169 } 7170 return false; 7171 } 7172 7173 bool ConstructVisitor::Pre(const parser::LocalitySpec::Reduce &x) { 7174 for (const auto &name : std::get<std::list<parser::Name>>(x.t)) { 7175 DeclareLocalEntity(name, Symbol::Flag::LocalityReduce); 7176 } 7177 return false; 7178 } 7179 7180 bool ConstructVisitor::Pre(const parser::LocalitySpec::Shared &x) { 7181 for (const auto &name : x.v) { 7182 if (!FindSymbol(name)) { 7183 context().Warn(common::UsageWarning::ImplicitShared, name.source, 7184 "Variable '%s' with SHARED locality implicitly declared"_warn_en_US, 7185 name.source); 7186 } 7187 Symbol &prev{FindOrDeclareEnclosingEntity(name)}; 7188 if (PassesSharedLocalityChecks(name, prev)) { 7189 MakeHostAssocSymbol(name, prev).set(Symbol::Flag::LocalityShared); 7190 } 7191 } 7192 return false; 7193 } 7194 7195 bool ConstructVisitor::Pre(const parser::AcSpec &x) { 7196 ProcessTypeSpec(x.type); 7197 Walk(x.values); 7198 return false; 7199 } 7200 7201 // Section 19.4, paragraph 5 says that each ac-do-variable has the scope of the 7202 // enclosing ac-implied-do 7203 bool ConstructVisitor::Pre(const parser::AcImpliedDo &x) { 7204 auto &values{std::get<std::list<parser::AcValue>>(x.t)}; 7205 auto &control{std::get<parser::AcImpliedDoControl>(x.t)}; 7206 auto &type{std::get<std::optional<parser::IntegerTypeSpec>>(control.t)}; 7207 auto &bounds{std::get<parser::AcImpliedDoControl::Bounds>(control.t)}; 7208 // F'2018 has the scope of the implied DO variable covering the entire 7209 // implied DO production (19.4(5)), which seems wrong in cases where the name 7210 // of the implied DO variable appears in one of the bound expressions. Thus 7211 // this extension, which shrinks the scope of the variable to exclude the 7212 // expressions in the bounds. 7213 auto restore{BeginCheckOnIndexUseInOwnBounds(bounds.name)}; 7214 Walk(bounds.lower); 7215 Walk(bounds.upper); 7216 Walk(bounds.step); 7217 EndCheckOnIndexUseInOwnBounds(restore); 7218 PushScope(Scope::Kind::ImpliedDos, nullptr); 7219 DeclareStatementEntity(bounds.name, type); 7220 Walk(values); 7221 PopScope(); 7222 return false; 7223 } 7224 7225 bool ConstructVisitor::Pre(const parser::DataImpliedDo &x) { 7226 auto &objects{std::get<std::list<parser::DataIDoObject>>(x.t)}; 7227 auto &type{std::get<std::optional<parser::IntegerTypeSpec>>(x.t)}; 7228 auto &bounds{std::get<parser::DataImpliedDo::Bounds>(x.t)}; 7229 // See comment in Pre(AcImpliedDo) above. 7230 auto restore{BeginCheckOnIndexUseInOwnBounds(bounds.name)}; 7231 Walk(bounds.lower); 7232 Walk(bounds.upper); 7233 Walk(bounds.step); 7234 EndCheckOnIndexUseInOwnBounds(restore); 7235 bool pushScope{currScope().kind() != Scope::Kind::ImpliedDos}; 7236 if (pushScope) { 7237 PushScope(Scope::Kind::ImpliedDos, nullptr); 7238 } 7239 DeclareStatementEntity(bounds.name, type); 7240 Walk(objects); 7241 if (pushScope) { 7242 PopScope(); 7243 } 7244 return false; 7245 } 7246 7247 // Sets InDataStmt flag on a variable (or misidentified function) in a DATA 7248 // statement so that the predicate IsInitialized() will be true 7249 // during semantic analysis before the symbol's initializer is constructed. 7250 bool ConstructVisitor::Pre(const parser::DataIDoObject &x) { 7251 common::visit( 7252 common::visitors{ 7253 [&](const parser::Scalar<Indirection<parser::Designator>> &y) { 7254 Walk(y.thing.value()); 7255 const parser::Name &first{parser::GetFirstName(y.thing.value())}; 7256 if (first.symbol) { 7257 first.symbol->set(Symbol::Flag::InDataStmt); 7258 } 7259 }, 7260 [&](const Indirection<parser::DataImpliedDo> &y) { Walk(y.value()); }, 7261 }, 7262 x.u); 7263 return false; 7264 } 7265 7266 bool ConstructVisitor::Pre(const parser::DataStmtObject &x) { 7267 // Subtle: DATA statements may appear in both the specification and 7268 // execution parts, but should be treated as if in the execution part 7269 // for purposes of implicit variable declaration vs. host association. 7270 // When a name first appears as an object in a DATA statement, it should 7271 // be implicitly declared locally as if it had been assigned. 7272 auto flagRestorer{common::ScopedSet(inSpecificationPart_, false)}; 7273 common::visit( 7274 common::visitors{ 7275 [&](const Indirection<parser::Variable> &y) { 7276 auto restorer{common::ScopedSet(deferImplicitTyping_, true)}; 7277 Walk(y.value()); 7278 const parser::Name &first{parser::GetFirstName(y.value())}; 7279 if (first.symbol) { 7280 first.symbol->set(Symbol::Flag::InDataStmt); 7281 } 7282 }, 7283 [&](const parser::DataImpliedDo &y) { 7284 PushScope(Scope::Kind::ImpliedDos, nullptr); 7285 Walk(y); 7286 PopScope(); 7287 }, 7288 }, 7289 x.u); 7290 return false; 7291 } 7292 7293 bool ConstructVisitor::Pre(const parser::DataStmtValue &x) { 7294 const auto &data{std::get<parser::DataStmtConstant>(x.t)}; 7295 auto &mutableData{const_cast<parser::DataStmtConstant &>(data)}; 7296 if (auto *elem{parser::Unwrap<parser::ArrayElement>(mutableData)}) { 7297 if (const auto *name{std::get_if<parser::Name>(&elem->base.u)}) { 7298 if (const Symbol * symbol{FindSymbol(*name)}; 7299 symbol && symbol->GetUltimate().has<DerivedTypeDetails>()) { 7300 mutableData.u = elem->ConvertToStructureConstructor( 7301 DerivedTypeSpec{name->source, *symbol}); 7302 } 7303 } 7304 } 7305 return true; 7306 } 7307 7308 bool ConstructVisitor::Pre(const parser::DoConstruct &x) { 7309 if (x.IsDoConcurrent()) { 7310 // The new scope has Kind::Forall for index variable name conflict 7311 // detection with nested FORALL/DO CONCURRENT constructs in 7312 // ResolveIndexName(). 7313 PushScope(Scope::Kind::Forall, nullptr); 7314 } 7315 return true; 7316 } 7317 void ConstructVisitor::Post(const parser::DoConstruct &x) { 7318 if (x.IsDoConcurrent()) { 7319 PopScope(); 7320 } 7321 } 7322 7323 bool ConstructVisitor::Pre(const parser::ForallConstruct &) { 7324 PushScope(Scope::Kind::Forall, nullptr); 7325 return true; 7326 } 7327 void ConstructVisitor::Post(const parser::ForallConstruct &) { PopScope(); } 7328 bool ConstructVisitor::Pre(const parser::ForallStmt &) { 7329 PushScope(Scope::Kind::Forall, nullptr); 7330 return true; 7331 } 7332 void ConstructVisitor::Post(const parser::ForallStmt &) { PopScope(); } 7333 7334 bool ConstructVisitor::Pre(const parser::BlockConstruct &x) { 7335 const auto &[blockStmt, specPart, execPart, endBlockStmt] = x.t; 7336 Walk(blockStmt); 7337 CheckDef(blockStmt.statement.v); 7338 PushScope(Scope::Kind::BlockConstruct, nullptr); 7339 Walk(specPart); 7340 HandleImpliedAsynchronousInScope(execPart); 7341 Walk(execPart); 7342 Walk(endBlockStmt); 7343 PopScope(); 7344 CheckRef(endBlockStmt.statement.v); 7345 return false; 7346 } 7347 7348 void ConstructVisitor::Post(const parser::Selector &x) { 7349 GetCurrentAssociation().selector = ResolveSelector(x); 7350 } 7351 7352 void ConstructVisitor::Post(const parser::AssociateStmt &x) { 7353 CheckDef(x.t); 7354 PushScope(Scope::Kind::OtherConstruct, nullptr); 7355 const auto assocCount{std::get<std::list<parser::Association>>(x.t).size()}; 7356 for (auto nthLastAssoc{assocCount}; nthLastAssoc > 0; --nthLastAssoc) { 7357 SetCurrentAssociation(nthLastAssoc); 7358 if (auto *symbol{MakeAssocEntity()}) { 7359 const MaybeExpr &expr{GetCurrentAssociation().selector.expr}; 7360 if (ExtractCoarrayRef(expr)) { // C1103 7361 Say("Selector must not be a coindexed object"_err_en_US); 7362 } 7363 if (evaluate::IsAssumedRank(expr)) { 7364 Say("Selector must not be assumed-rank"_err_en_US); 7365 } 7366 SetTypeFromAssociation(*symbol); 7367 SetAttrsFromAssociation(*symbol); 7368 } 7369 } 7370 PopAssociation(assocCount); 7371 } 7372 7373 void ConstructVisitor::Post(const parser::EndAssociateStmt &x) { 7374 PopScope(); 7375 CheckRef(x.v); 7376 } 7377 7378 bool ConstructVisitor::Pre(const parser::Association &x) { 7379 PushAssociation(); 7380 const auto &name{std::get<parser::Name>(x.t)}; 7381 GetCurrentAssociation().name = &name; 7382 return true; 7383 } 7384 7385 bool ConstructVisitor::Pre(const parser::ChangeTeamStmt &x) { 7386 CheckDef(x.t); 7387 PushScope(Scope::Kind::OtherConstruct, nullptr); 7388 PushAssociation(); 7389 return true; 7390 } 7391 7392 void ConstructVisitor::Post(const parser::CoarrayAssociation &x) { 7393 const auto &decl{std::get<parser::CodimensionDecl>(x.t)}; 7394 const auto &name{std::get<parser::Name>(decl.t)}; 7395 if (auto *symbol{FindInScope(name)}) { 7396 const auto &selector{std::get<parser::Selector>(x.t)}; 7397 if (auto sel{ResolveSelector(selector)}) { 7398 const Symbol *whole{UnwrapWholeSymbolDataRef(sel.expr)}; 7399 if (!whole || whole->Corank() == 0) { 7400 Say(sel.source, // C1116 7401 "Selector in coarray association must name a coarray"_err_en_US); 7402 } else if (auto dynType{sel.expr->GetType()}) { 7403 if (!symbol->GetType()) { 7404 symbol->SetType(ToDeclTypeSpec(std::move(*dynType))); 7405 } 7406 } 7407 } 7408 } 7409 } 7410 7411 void ConstructVisitor::Post(const parser::EndChangeTeamStmt &x) { 7412 PopAssociation(); 7413 PopScope(); 7414 CheckRef(x.t); 7415 } 7416 7417 bool ConstructVisitor::Pre(const parser::SelectTypeConstruct &) { 7418 PushAssociation(); 7419 return true; 7420 } 7421 7422 void ConstructVisitor::Post(const parser::SelectTypeConstruct &) { 7423 PopAssociation(); 7424 } 7425 7426 void ConstructVisitor::Post(const parser::SelectTypeStmt &x) { 7427 auto &association{GetCurrentAssociation()}; 7428 if (const std::optional<parser::Name> &name{std::get<1>(x.t)}) { 7429 // This isn't a name in the current scope, it is in each TypeGuardStmt 7430 MakePlaceholder(*name, MiscDetails::Kind::SelectTypeAssociateName); 7431 association.name = &*name; 7432 if (ExtractCoarrayRef(association.selector.expr)) { // C1103 7433 Say("Selector must not be a coindexed object"_err_en_US); 7434 } 7435 if (association.selector.expr) { 7436 auto exprType{association.selector.expr->GetType()}; 7437 if (exprType && !exprType->IsPolymorphic()) { // C1159 7438 Say(association.selector.source, 7439 "Selector '%s' in SELECT TYPE statement must be " 7440 "polymorphic"_err_en_US); 7441 } 7442 } 7443 } else { 7444 if (const Symbol * 7445 whole{UnwrapWholeSymbolDataRef(association.selector.expr)}) { 7446 ConvertToObjectEntity(const_cast<Symbol &>(*whole)); 7447 if (!IsVariableName(*whole)) { 7448 Say(association.selector.source, // C901 7449 "Selector is not a variable"_err_en_US); 7450 association = {}; 7451 } 7452 if (const DeclTypeSpec * type{whole->GetType()}) { 7453 if (!type->IsPolymorphic()) { // C1159 7454 Say(association.selector.source, 7455 "Selector '%s' in SELECT TYPE statement must be " 7456 "polymorphic"_err_en_US); 7457 } 7458 } 7459 } else { 7460 Say(association.selector.source, // C1157 7461 "Selector is not a named variable: 'associate-name =>' is required"_err_en_US); 7462 association = {}; 7463 } 7464 } 7465 } 7466 7467 void ConstructVisitor::Post(const parser::SelectRankStmt &x) { 7468 auto &association{GetCurrentAssociation()}; 7469 if (const std::optional<parser::Name> &name{std::get<1>(x.t)}) { 7470 // This isn't a name in the current scope, it is in each SelectRankCaseStmt 7471 MakePlaceholder(*name, MiscDetails::Kind::SelectRankAssociateName); 7472 association.name = &*name; 7473 } 7474 } 7475 7476 bool ConstructVisitor::Pre(const parser::SelectTypeConstruct::TypeCase &) { 7477 PushScope(Scope::Kind::OtherConstruct, nullptr); 7478 return true; 7479 } 7480 void ConstructVisitor::Post(const parser::SelectTypeConstruct::TypeCase &) { 7481 PopScope(); 7482 } 7483 7484 bool ConstructVisitor::Pre(const parser::SelectRankConstruct::RankCase &) { 7485 PushScope(Scope::Kind::OtherConstruct, nullptr); 7486 return true; 7487 } 7488 void ConstructVisitor::Post(const parser::SelectRankConstruct::RankCase &) { 7489 PopScope(); 7490 } 7491 7492 bool ConstructVisitor::Pre(const parser::TypeGuardStmt::Guard &x) { 7493 if (std::holds_alternative<parser::DerivedTypeSpec>(x.u)) { 7494 // CLASS IS (t) 7495 SetDeclTypeSpecCategory(DeclTypeSpec::Category::ClassDerived); 7496 } 7497 return true; 7498 } 7499 7500 void ConstructVisitor::Post(const parser::TypeGuardStmt::Guard &x) { 7501 if (auto *symbol{MakeAssocEntity()}) { 7502 if (std::holds_alternative<parser::Default>(x.u)) { 7503 SetTypeFromAssociation(*symbol); 7504 } else if (const auto *type{GetDeclTypeSpec()}) { 7505 symbol->SetType(*type); 7506 } 7507 SetAttrsFromAssociation(*symbol); 7508 } 7509 } 7510 7511 void ConstructVisitor::Post(const parser::SelectRankCaseStmt::Rank &x) { 7512 if (auto *symbol{MakeAssocEntity()}) { 7513 SetTypeFromAssociation(*symbol); 7514 auto &details{symbol->get<AssocEntityDetails>()}; 7515 // Don't call SetAttrsFromAssociation() for SELECT RANK. 7516 Attrs selectorAttrs{ 7517 evaluate::GetAttrs(GetCurrentAssociation().selector.expr)}; 7518 Attrs attrsToKeep{Attr::ASYNCHRONOUS, Attr::TARGET, Attr::VOLATILE}; 7519 if (const auto *rankValue{ 7520 std::get_if<parser::ScalarIntConstantExpr>(&x.u)}) { 7521 // RANK(n) 7522 if (auto expr{EvaluateIntExpr(*rankValue)}) { 7523 if (auto val{evaluate::ToInt64(*expr)}) { 7524 details.set_rank(*val); 7525 attrsToKeep |= Attrs{Attr::ALLOCATABLE, Attr::POINTER}; 7526 } else { 7527 Say("RANK() expression must be constant"_err_en_US); 7528 } 7529 } 7530 } else if (std::holds_alternative<parser::Star>(x.u)) { 7531 // RANK(*): assumed-size 7532 details.set_IsAssumedSize(); 7533 } else { 7534 CHECK(std::holds_alternative<parser::Default>(x.u)); 7535 // RANK DEFAULT: assumed-rank 7536 details.set_IsAssumedRank(); 7537 attrsToKeep |= Attrs{Attr::ALLOCATABLE, Attr::POINTER}; 7538 } 7539 symbol->attrs() |= selectorAttrs & attrsToKeep; 7540 } 7541 } 7542 7543 bool ConstructVisitor::Pre(const parser::SelectRankConstruct &) { 7544 PushAssociation(); 7545 return true; 7546 } 7547 7548 void ConstructVisitor::Post(const parser::SelectRankConstruct &) { 7549 PopAssociation(); 7550 } 7551 7552 bool ConstructVisitor::CheckDef(const std::optional<parser::Name> &x) { 7553 if (x && !x->symbol) { 7554 // Construct names are not scoped by BLOCK in the standard, but many, 7555 // but not all, compilers do treat them as if they were so scoped. 7556 if (Symbol * inner{FindInScope(currScope(), *x)}) { 7557 SayAlreadyDeclared(*x, *inner); 7558 } else { 7559 if (context().ShouldWarn(common::LanguageFeature::BenignNameClash)) { 7560 if (Symbol * 7561 other{FindInScopeOrBlockConstructs(InclusiveScope(), x->source)}) { 7562 SayWithDecl(*x, *other, 7563 "The construct name '%s' should be distinct at the subprogram level"_port_en_US) 7564 .set_languageFeature(common::LanguageFeature::BenignNameClash); 7565 } 7566 } 7567 MakeSymbol(*x, MiscDetails{MiscDetails::Kind::ConstructName}); 7568 } 7569 } 7570 return true; 7571 } 7572 7573 void ConstructVisitor::CheckRef(const std::optional<parser::Name> &x) { 7574 if (x) { 7575 // Just add an occurrence of this name; checking is done in ValidateLabels 7576 FindSymbol(*x); 7577 } 7578 } 7579 7580 // Make a symbol for the associating entity of the current association. 7581 Symbol *ConstructVisitor::MakeAssocEntity() { 7582 Symbol *symbol{nullptr}; 7583 auto &association{GetCurrentAssociation()}; 7584 if (association.name) { 7585 symbol = &MakeSymbol(*association.name, UnknownDetails{}); 7586 if (symbol->has<AssocEntityDetails>() && symbol->owner() == currScope()) { 7587 Say(*association.name, // C1102 7588 "The associate name '%s' is already used in this associate statement"_err_en_US); 7589 return nullptr; 7590 } 7591 } else if (const Symbol * 7592 whole{UnwrapWholeSymbolDataRef(association.selector.expr)}) { 7593 symbol = &MakeSymbol(whole->name()); 7594 } else { 7595 return nullptr; 7596 } 7597 if (auto &expr{association.selector.expr}) { 7598 symbol->set_details(AssocEntityDetails{common::Clone(*expr)}); 7599 } else { 7600 symbol->set_details(AssocEntityDetails{}); 7601 } 7602 return symbol; 7603 } 7604 7605 // Set the type of symbol based on the current association selector. 7606 void ConstructVisitor::SetTypeFromAssociation(Symbol &symbol) { 7607 auto &details{symbol.get<AssocEntityDetails>()}; 7608 const MaybeExpr *pexpr{&details.expr()}; 7609 if (!*pexpr) { 7610 pexpr = &GetCurrentAssociation().selector.expr; 7611 } 7612 if (*pexpr) { 7613 const SomeExpr &expr{**pexpr}; 7614 if (std::optional<evaluate::DynamicType> type{expr.GetType()}) { 7615 if (const auto *charExpr{ 7616 evaluate::UnwrapExpr<evaluate::Expr<evaluate::SomeCharacter>>( 7617 expr)}) { 7618 symbol.SetType(ToDeclTypeSpec(std::move(*type), 7619 FoldExpr(common::visit( 7620 [](const auto &kindChar) { return kindChar.LEN(); }, 7621 charExpr->u)))); 7622 } else { 7623 symbol.SetType(ToDeclTypeSpec(std::move(*type))); 7624 } 7625 } else { 7626 // BOZ literals, procedure designators, &c. are not acceptable 7627 Say(symbol.name(), "Associate name '%s' must have a type"_err_en_US); 7628 } 7629 } 7630 } 7631 7632 // If current selector is a variable, set some of its attributes on symbol. 7633 // For ASSOCIATE, CHANGE TEAM, and SELECT TYPE only; not SELECT RANK. 7634 void ConstructVisitor::SetAttrsFromAssociation(Symbol &symbol) { 7635 Attrs attrs{evaluate::GetAttrs(GetCurrentAssociation().selector.expr)}; 7636 symbol.attrs() |= 7637 attrs & Attrs{Attr::TARGET, Attr::ASYNCHRONOUS, Attr::VOLATILE}; 7638 if (attrs.test(Attr::POINTER)) { 7639 SetImplicitAttr(symbol, Attr::TARGET); 7640 } 7641 } 7642 7643 ConstructVisitor::Selector ConstructVisitor::ResolveSelector( 7644 const parser::Selector &x) { 7645 return common::visit(common::visitors{ 7646 [&](const parser::Expr &expr) { 7647 return Selector{expr.source, EvaluateExpr(x)}; 7648 }, 7649 [&](const parser::Variable &var) { 7650 return Selector{var.GetSource(), EvaluateExpr(x)}; 7651 }, 7652 }, 7653 x.u); 7654 } 7655 7656 // Set the current association to the nth to the last association on the 7657 // association stack. The top of the stack is at n = 1. This allows access 7658 // to the interior of a list of associations at the top of the stack. 7659 void ConstructVisitor::SetCurrentAssociation(std::size_t n) { 7660 CHECK(n > 0 && n <= associationStack_.size()); 7661 currentAssociation_ = &associationStack_[associationStack_.size() - n]; 7662 } 7663 7664 ConstructVisitor::Association &ConstructVisitor::GetCurrentAssociation() { 7665 CHECK(currentAssociation_); 7666 return *currentAssociation_; 7667 } 7668 7669 void ConstructVisitor::PushAssociation() { 7670 associationStack_.emplace_back(Association{}); 7671 currentAssociation_ = &associationStack_.back(); 7672 } 7673 7674 void ConstructVisitor::PopAssociation(std::size_t count) { 7675 CHECK(count > 0 && count <= associationStack_.size()); 7676 associationStack_.resize(associationStack_.size() - count); 7677 currentAssociation_ = 7678 associationStack_.empty() ? nullptr : &associationStack_.back(); 7679 } 7680 7681 const DeclTypeSpec &ConstructVisitor::ToDeclTypeSpec( 7682 evaluate::DynamicType &&type) { 7683 switch (type.category()) { 7684 SWITCH_COVERS_ALL_CASES 7685 case common::TypeCategory::Integer: 7686 case common::TypeCategory::Unsigned: 7687 case common::TypeCategory::Real: 7688 case common::TypeCategory::Complex: 7689 return context().MakeNumericType(type.category(), type.kind()); 7690 case common::TypeCategory::Logical: 7691 return context().MakeLogicalType(type.kind()); 7692 case common::TypeCategory::Derived: 7693 if (type.IsAssumedType()) { 7694 return currScope().MakeTypeStarType(); 7695 } else if (type.IsUnlimitedPolymorphic()) { 7696 return currScope().MakeClassStarType(); 7697 } else { 7698 return currScope().MakeDerivedType( 7699 type.IsPolymorphic() ? DeclTypeSpec::ClassDerived 7700 : DeclTypeSpec::TypeDerived, 7701 common::Clone(type.GetDerivedTypeSpec()) 7702 7703 ); 7704 } 7705 case common::TypeCategory::Character: 7706 CRASH_NO_CASE; 7707 } 7708 } 7709 7710 const DeclTypeSpec &ConstructVisitor::ToDeclTypeSpec( 7711 evaluate::DynamicType &&type, MaybeSubscriptIntExpr &&length) { 7712 CHECK(type.category() == common::TypeCategory::Character); 7713 if (length) { 7714 return currScope().MakeCharacterType( 7715 ParamValue{SomeIntExpr{*std::move(length)}, common::TypeParamAttr::Len}, 7716 KindExpr{type.kind()}); 7717 } else { 7718 return currScope().MakeCharacterType( 7719 ParamValue::Deferred(common::TypeParamAttr::Len), 7720 KindExpr{type.kind()}); 7721 } 7722 } 7723 7724 class ExecutionPartSkimmerBase { 7725 public: 7726 template <typename A> bool Pre(const A &) { return true; } 7727 template <typename A> void Post(const A &) {} 7728 7729 bool InNestedBlockConstruct() const { return blockDepth_ > 0; } 7730 7731 bool Pre(const parser::AssociateConstruct &) { 7732 PushScope(); 7733 return true; 7734 } 7735 void Post(const parser::AssociateConstruct &) { PopScope(); } 7736 bool Pre(const parser::Association &x) { 7737 Hide(std::get<parser::Name>(x.t)); 7738 return true; 7739 } 7740 bool Pre(const parser::BlockConstruct &) { 7741 PushScope(); 7742 ++blockDepth_; 7743 return true; 7744 } 7745 void Post(const parser::BlockConstruct &) { 7746 --blockDepth_; 7747 PopScope(); 7748 } 7749 // Note declarations of local names in BLOCK constructs. 7750 // Don't have to worry about INTENT(), VALUE, or OPTIONAL 7751 // (pertinent only to dummy arguments), ASYNCHRONOUS/VOLATILE, 7752 // or accessibility attributes, 7753 bool Pre(const parser::EntityDecl &x) { 7754 Hide(std::get<parser::ObjectName>(x.t)); 7755 return true; 7756 } 7757 bool Pre(const parser::ObjectDecl &x) { 7758 Hide(std::get<parser::ObjectName>(x.t)); 7759 return true; 7760 } 7761 bool Pre(const parser::PointerDecl &x) { 7762 Hide(std::get<parser::Name>(x.t)); 7763 return true; 7764 } 7765 bool Pre(const parser::BindEntity &x) { 7766 Hide(std::get<parser::Name>(x.t)); 7767 return true; 7768 } 7769 bool Pre(const parser::ContiguousStmt &x) { 7770 for (const parser::Name &name : x.v) { 7771 Hide(name); 7772 } 7773 return true; 7774 } 7775 bool Pre(const parser::DimensionStmt::Declaration &x) { 7776 Hide(std::get<parser::Name>(x.t)); 7777 return true; 7778 } 7779 bool Pre(const parser::ExternalStmt &x) { 7780 for (const parser::Name &name : x.v) { 7781 Hide(name); 7782 } 7783 return true; 7784 } 7785 bool Pre(const parser::IntrinsicStmt &x) { 7786 for (const parser::Name &name : x.v) { 7787 Hide(name); 7788 } 7789 return true; 7790 } 7791 bool Pre(const parser::CodimensionStmt &x) { 7792 for (const parser::CodimensionDecl &decl : x.v) { 7793 Hide(std::get<parser::Name>(decl.t)); 7794 } 7795 return true; 7796 } 7797 void Post(const parser::ImportStmt &x) { 7798 if (x.kind == common::ImportKind::None || 7799 x.kind == common::ImportKind::Only) { 7800 if (!nestedScopes_.front().importOnly.has_value()) { 7801 nestedScopes_.front().importOnly.emplace(); 7802 } 7803 for (const auto &name : x.names) { 7804 nestedScopes_.front().importOnly->emplace(name.source); 7805 } 7806 } else { 7807 // no special handling needed for explicit names or IMPORT, ALL 7808 } 7809 } 7810 void Post(const parser::UseStmt &x) { 7811 if (const auto *onlyList{std::get_if<std::list<parser::Only>>(&x.u)}) { 7812 for (const auto &only : *onlyList) { 7813 if (const auto *name{std::get_if<parser::Name>(&only.u)}) { 7814 Hide(*name); 7815 } else if (const auto *rename{std::get_if<parser::Rename>(&only.u)}) { 7816 if (const auto *names{ 7817 std::get_if<parser::Rename::Names>(&rename->u)}) { 7818 Hide(std::get<0>(names->t)); 7819 } 7820 } 7821 } 7822 } else { 7823 // USE may or may not shadow symbols in host scopes 7824 nestedScopes_.front().hasUseWithoutOnly = true; 7825 } 7826 } 7827 bool Pre(const parser::DerivedTypeStmt &x) { 7828 Hide(std::get<parser::Name>(x.t)); 7829 PushScope(); 7830 return true; 7831 } 7832 void Post(const parser::DerivedTypeDef &) { PopScope(); } 7833 bool Pre(const parser::SelectTypeConstruct &) { 7834 PushScope(); 7835 return true; 7836 } 7837 void Post(const parser::SelectTypeConstruct &) { PopScope(); } 7838 bool Pre(const parser::SelectTypeStmt &x) { 7839 if (const auto &maybeName{std::get<1>(x.t)}) { 7840 Hide(*maybeName); 7841 } 7842 return true; 7843 } 7844 bool Pre(const parser::SelectRankConstruct &) { 7845 PushScope(); 7846 return true; 7847 } 7848 void Post(const parser::SelectRankConstruct &) { PopScope(); } 7849 bool Pre(const parser::SelectRankStmt &x) { 7850 if (const auto &maybeName{std::get<1>(x.t)}) { 7851 Hide(*maybeName); 7852 } 7853 return true; 7854 } 7855 7856 // Iterator-modifiers contain variable declarations, and do introduce 7857 // a new scope. These variables can only have integer types, and their 7858 // scope only extends until the end of the clause. A potential alternative 7859 // to the code below may be to ignore OpenMP clauses, but it's not clear 7860 // if OMP-specific checks can be avoided altogether. 7861 bool Pre(const parser::OmpClause &x) { 7862 if (OmpVisitor::NeedsScope(x)) { 7863 PushScope(); 7864 } 7865 return true; 7866 } 7867 void Post(const parser::OmpClause &x) { 7868 if (OmpVisitor::NeedsScope(x)) { 7869 PopScope(); 7870 } 7871 } 7872 7873 protected: 7874 bool IsHidden(SourceName name) { 7875 for (const auto &scope : nestedScopes_) { 7876 if (scope.locals.find(name) != scope.locals.end()) { 7877 return true; // shadowed by nested declaration 7878 } 7879 if (scope.hasUseWithoutOnly) { 7880 break; 7881 } 7882 if (scope.importOnly && 7883 scope.importOnly->find(name) == scope.importOnly->end()) { 7884 return true; // not imported 7885 } 7886 } 7887 return false; 7888 } 7889 7890 void EndWalk() { CHECK(nestedScopes_.empty()); } 7891 7892 private: 7893 void PushScope() { nestedScopes_.emplace_front(); } 7894 void PopScope() { nestedScopes_.pop_front(); } 7895 void Hide(const parser::Name &name) { 7896 nestedScopes_.front().locals.emplace(name.source); 7897 } 7898 7899 int blockDepth_{0}; 7900 struct NestedScopeInfo { 7901 bool hasUseWithoutOnly{false}; 7902 std::set<SourceName> locals; 7903 std::optional<std::set<SourceName>> importOnly; 7904 }; 7905 std::list<NestedScopeInfo> nestedScopes_; 7906 }; 7907 7908 class ExecutionPartAsyncIOSkimmer : public ExecutionPartSkimmerBase { 7909 public: 7910 explicit ExecutionPartAsyncIOSkimmer(SemanticsContext &context) 7911 : context_{context} {} 7912 7913 void Walk(const parser::Block &block) { 7914 parser::Walk(block, *this); 7915 EndWalk(); 7916 } 7917 7918 const std::set<SourceName> asyncIONames() const { return asyncIONames_; } 7919 7920 using ExecutionPartSkimmerBase::Post; 7921 using ExecutionPartSkimmerBase::Pre; 7922 7923 bool Pre(const parser::IoControlSpec::Asynchronous &async) { 7924 if (auto folded{evaluate::Fold( 7925 context_.foldingContext(), AnalyzeExpr(context_, async.v))}) { 7926 if (auto str{ 7927 evaluate::GetScalarConstantValue<evaluate::Ascii>(*folded)}) { 7928 for (char ch : *str) { 7929 if (ch != ' ') { 7930 inAsyncIO_ = ch == 'y' || ch == 'Y'; 7931 break; 7932 } 7933 } 7934 } 7935 } 7936 return true; 7937 } 7938 void Post(const parser::ReadStmt &) { inAsyncIO_ = false; } 7939 void Post(const parser::WriteStmt &) { inAsyncIO_ = false; } 7940 void Post(const parser::IoControlSpec::Size &size) { 7941 if (const auto *designator{ 7942 std::get_if<common::Indirection<parser::Designator>>( 7943 &size.v.thing.thing.u)}) { 7944 NoteAsyncIODesignator(designator->value()); 7945 } 7946 } 7947 void Post(const parser::InputItem &x) { 7948 if (const auto *var{std::get_if<parser::Variable>(&x.u)}) { 7949 if (const auto *designator{ 7950 std::get_if<common::Indirection<parser::Designator>>(&var->u)}) { 7951 NoteAsyncIODesignator(designator->value()); 7952 } 7953 } 7954 } 7955 void Post(const parser::OutputItem &x) { 7956 if (const auto *expr{std::get_if<parser::Expr>(&x.u)}) { 7957 if (const auto *designator{ 7958 std::get_if<common::Indirection<parser::Designator>>(&expr->u)}) { 7959 NoteAsyncIODesignator(designator->value()); 7960 } 7961 } 7962 } 7963 7964 private: 7965 void NoteAsyncIODesignator(const parser::Designator &designator) { 7966 if (inAsyncIO_ && !InNestedBlockConstruct()) { 7967 const parser::Name &name{parser::GetFirstName(designator)}; 7968 if (!IsHidden(name.source)) { 7969 asyncIONames_.insert(name.source); 7970 } 7971 } 7972 } 7973 7974 SemanticsContext &context_; 7975 bool inAsyncIO_{false}; 7976 std::set<SourceName> asyncIONames_; 7977 }; 7978 7979 // Any data list item or SIZE= specifier of an I/O data transfer statement 7980 // with ASYNCHRONOUS="YES" implicitly has the ASYNCHRONOUS attribute in the 7981 // local scope. 7982 void ConstructVisitor::HandleImpliedAsynchronousInScope( 7983 const parser::Block &block) { 7984 ExecutionPartAsyncIOSkimmer skimmer{context()}; 7985 skimmer.Walk(block); 7986 for (auto name : skimmer.asyncIONames()) { 7987 if (Symbol * symbol{currScope().FindSymbol(name)}) { 7988 if (!symbol->attrs().test(Attr::ASYNCHRONOUS)) { 7989 if (&symbol->owner() != &currScope()) { 7990 symbol = &*currScope() 7991 .try_emplace(name, HostAssocDetails{*symbol}) 7992 .first->second; 7993 } 7994 if (symbol->has<AssocEntityDetails>()) { 7995 symbol = const_cast<Symbol *>(&GetAssociationRoot(*symbol)); 7996 } 7997 SetImplicitAttr(*symbol, Attr::ASYNCHRONOUS); 7998 } 7999 } 8000 } 8001 } 8002 8003 // ResolveNamesVisitor implementation 8004 8005 bool ResolveNamesVisitor::Pre(const parser::FunctionReference &x) { 8006 HandleCall(Symbol::Flag::Function, x.v); 8007 return false; 8008 } 8009 bool ResolveNamesVisitor::Pre(const parser::CallStmt &x) { 8010 HandleCall(Symbol::Flag::Subroutine, x.call); 8011 Walk(x.chevrons); 8012 return false; 8013 } 8014 8015 bool ResolveNamesVisitor::Pre(const parser::ImportStmt &x) { 8016 auto &scope{currScope()}; 8017 // Check C896 and C899: where IMPORT statements are allowed 8018 switch (scope.kind()) { 8019 case Scope::Kind::Module: 8020 if (scope.IsModule()) { 8021 Say("IMPORT is not allowed in a module scoping unit"_err_en_US); 8022 return false; 8023 } else if (x.kind == common::ImportKind::None) { 8024 Say("IMPORT,NONE is not allowed in a submodule scoping unit"_err_en_US); 8025 return false; 8026 } 8027 break; 8028 case Scope::Kind::MainProgram: 8029 Say("IMPORT is not allowed in a main program scoping unit"_err_en_US); 8030 return false; 8031 case Scope::Kind::Subprogram: 8032 if (scope.parent().IsGlobal()) { 8033 Say("IMPORT is not allowed in an external subprogram scoping unit"_err_en_US); 8034 return false; 8035 } 8036 break; 8037 case Scope::Kind::BlockData: // C1415 (in part) 8038 Say("IMPORT is not allowed in a BLOCK DATA subprogram"_err_en_US); 8039 return false; 8040 default:; 8041 } 8042 if (auto error{scope.SetImportKind(x.kind)}) { 8043 Say(std::move(*error)); 8044 } 8045 for (auto &name : x.names) { 8046 if (Symbol * outer{FindSymbol(scope.parent(), name)}) { 8047 scope.add_importName(name.source); 8048 if (Symbol * symbol{FindInScope(name)}) { 8049 if (outer->GetUltimate() == symbol->GetUltimate()) { 8050 context().Warn(common::LanguageFeature::BenignNameClash, name.source, 8051 "The same '%s' is already present in this scope"_port_en_US, 8052 name.source); 8053 } else { 8054 Say(name, 8055 "A distinct '%s' is already present in this scope"_err_en_US) 8056 .Attach(symbol->name(), "Previous declaration of '%s'"_en_US) 8057 .Attach(outer->name(), "Declaration of '%s' in host scope"_en_US); 8058 } 8059 } 8060 } else { 8061 Say(name, "'%s' not found in host scope"_err_en_US); 8062 } 8063 } 8064 prevImportStmt_ = currStmtSource(); 8065 return false; 8066 } 8067 8068 const parser::Name *DeclarationVisitor::ResolveStructureComponent( 8069 const parser::StructureComponent &x) { 8070 return FindComponent(ResolveDataRef(x.base), x.component); 8071 } 8072 8073 const parser::Name *DeclarationVisitor::ResolveDesignator( 8074 const parser::Designator &x) { 8075 return common::visit( 8076 common::visitors{ 8077 [&](const parser::DataRef &x) { return ResolveDataRef(x); }, 8078 [&](const parser::Substring &x) { 8079 Walk(std::get<parser::SubstringRange>(x.t).t); 8080 return ResolveDataRef(std::get<parser::DataRef>(x.t)); 8081 }, 8082 }, 8083 x.u); 8084 } 8085 8086 const parser::Name *DeclarationVisitor::ResolveDataRef( 8087 const parser::DataRef &x) { 8088 return common::visit( 8089 common::visitors{ 8090 [=](const parser::Name &y) { return ResolveName(y); }, 8091 [=](const Indirection<parser::StructureComponent> &y) { 8092 return ResolveStructureComponent(y.value()); 8093 }, 8094 [&](const Indirection<parser::ArrayElement> &y) { 8095 Walk(y.value().subscripts); 8096 const parser::Name *name{ResolveDataRef(y.value().base)}; 8097 if (name && name->symbol) { 8098 if (!IsProcedure(*name->symbol)) { 8099 ConvertToObjectEntity(*name->symbol); 8100 } else if (!context().HasError(*name->symbol)) { 8101 SayWithDecl(*name, *name->symbol, 8102 "Cannot reference function '%s' as data"_err_en_US); 8103 context().SetError(*name->symbol); 8104 } 8105 } 8106 return name; 8107 }, 8108 [&](const Indirection<parser::CoindexedNamedObject> &y) { 8109 Walk(y.value().imageSelector); 8110 return ResolveDataRef(y.value().base); 8111 }, 8112 }, 8113 x.u); 8114 } 8115 8116 // If implicit types are allowed, ensure name is in the symbol table. 8117 // Otherwise, report an error if it hasn't been declared. 8118 const parser::Name *DeclarationVisitor::ResolveName(const parser::Name &name) { 8119 FindSymbol(name); 8120 if (CheckForHostAssociatedImplicit(name)) { 8121 NotePossibleBadForwardRef(name); 8122 return &name; 8123 } 8124 if (Symbol * symbol{name.symbol}) { 8125 if (CheckUseError(name)) { 8126 return nullptr; // reported an error 8127 } 8128 NotePossibleBadForwardRef(name); 8129 symbol->set(Symbol::Flag::ImplicitOrError, false); 8130 if (IsUplevelReference(*symbol)) { 8131 MakeHostAssocSymbol(name, *symbol); 8132 } else if (IsDummy(*symbol) || 8133 (!symbol->GetType() && FindCommonBlockContaining(*symbol))) { 8134 CheckEntryDummyUse(name.source, symbol); 8135 ConvertToObjectEntity(*symbol); 8136 ApplyImplicitRules(*symbol); 8137 } else if (const auto *tpd{symbol->detailsIf<TypeParamDetails>()}; 8138 tpd && !tpd->attr()) { 8139 Say(name, 8140 "Type parameter '%s' was referenced before being declared"_err_en_US, 8141 name.source); 8142 context().SetError(*symbol); 8143 } 8144 if (checkIndexUseInOwnBounds_ && 8145 *checkIndexUseInOwnBounds_ == name.source && !InModuleFile()) { 8146 context().Warn(common::LanguageFeature::ImpliedDoIndexScope, name.source, 8147 "Implied DO index '%s' uses an object of the same name in its bounds expressions"_port_en_US, 8148 name.source); 8149 } 8150 return &name; 8151 } 8152 if (isImplicitNoneType() && !deferImplicitTyping_) { 8153 Say(name, "No explicit type declared for '%s'"_err_en_US); 8154 return nullptr; 8155 } 8156 // Create the symbol, then ensure that it is accessible 8157 if (checkIndexUseInOwnBounds_ && *checkIndexUseInOwnBounds_ == name.source) { 8158 Say(name, 8159 "Implied DO index '%s' uses itself in its own bounds expressions"_err_en_US, 8160 name.source); 8161 } 8162 MakeSymbol(InclusiveScope(), name.source, Attrs{}); 8163 auto *symbol{FindSymbol(name)}; 8164 if (!symbol) { 8165 Say(name, 8166 "'%s' from host scoping unit is not accessible due to IMPORT"_err_en_US); 8167 return nullptr; 8168 } 8169 ConvertToObjectEntity(*symbol); 8170 ApplyImplicitRules(*symbol); 8171 NotePossibleBadForwardRef(name); 8172 return &name; 8173 } 8174 8175 // A specification expression may refer to a symbol in the host procedure that 8176 // is implicitly typed. Because specification parts are processed before 8177 // execution parts, this may be the first time we see the symbol. It can't be a 8178 // local in the current scope (because it's in a specification expression) so 8179 // either it is implicitly declared in the host procedure or it is an error. 8180 // We create a symbol in the host assuming it is the former; if that proves to 8181 // be wrong we report an error later in CheckDeclarations(). 8182 bool DeclarationVisitor::CheckForHostAssociatedImplicit( 8183 const parser::Name &name) { 8184 if (!inSpecificationPart_ || inEquivalenceStmt_) { 8185 return false; 8186 } 8187 if (name.symbol) { 8188 ApplyImplicitRules(*name.symbol, true); 8189 } 8190 if (Scope * host{GetHostProcedure()}; host && !isImplicitNoneType(*host)) { 8191 Symbol *hostSymbol{nullptr}; 8192 if (!name.symbol) { 8193 if (currScope().CanImport(name.source)) { 8194 hostSymbol = &MakeSymbol(*host, name.source, Attrs{}); 8195 ConvertToObjectEntity(*hostSymbol); 8196 ApplyImplicitRules(*hostSymbol); 8197 hostSymbol->set(Symbol::Flag::ImplicitOrError); 8198 } 8199 } else if (name.symbol->test(Symbol::Flag::ImplicitOrError)) { 8200 hostSymbol = name.symbol; 8201 } 8202 if (hostSymbol) { 8203 Symbol &symbol{MakeHostAssocSymbol(name, *hostSymbol)}; 8204 if (auto *assoc{symbol.detailsIf<HostAssocDetails>()}) { 8205 if (isImplicitNoneType()) { 8206 assoc->implicitOrExplicitTypeError = true; 8207 } else { 8208 assoc->implicitOrSpecExprError = true; 8209 } 8210 return true; 8211 } 8212 } 8213 } 8214 return false; 8215 } 8216 8217 bool DeclarationVisitor::IsUplevelReference(const Symbol &symbol) { 8218 const Scope &symbolUnit{GetProgramUnitContaining(symbol)}; 8219 if (symbolUnit == GetProgramUnitContaining(currScope())) { 8220 return false; 8221 } else { 8222 Scope::Kind kind{symbolUnit.kind()}; 8223 return kind == Scope::Kind::Subprogram || kind == Scope::Kind::MainProgram; 8224 } 8225 } 8226 8227 // base is a part-ref of a derived type; find the named component in its type. 8228 // Also handles intrinsic type parameter inquiries (%kind, %len) and 8229 // COMPLEX component references (%re, %im). 8230 const parser::Name *DeclarationVisitor::FindComponent( 8231 const parser::Name *base, const parser::Name &component) { 8232 if (!base || !base->symbol) { 8233 return nullptr; 8234 } 8235 if (auto *misc{base->symbol->detailsIf<MiscDetails>()}) { 8236 if (component.source == "kind") { 8237 if (misc->kind() == MiscDetails::Kind::ComplexPartRe || 8238 misc->kind() == MiscDetails::Kind::ComplexPartIm || 8239 misc->kind() == MiscDetails::Kind::KindParamInquiry || 8240 misc->kind() == MiscDetails::Kind::LenParamInquiry) { 8241 // x%{re,im,kind,len}%kind 8242 MakePlaceholder(component, MiscDetails::Kind::KindParamInquiry); 8243 return &component; 8244 } 8245 } 8246 } 8247 CheckEntryDummyUse(base->source, base->symbol); 8248 auto &symbol{base->symbol->GetUltimate()}; 8249 if (!symbol.has<AssocEntityDetails>() && !ConvertToObjectEntity(symbol)) { 8250 SayWithDecl(*base, symbol, 8251 "'%s' is not an object and may not be used as the base of a component reference or type parameter inquiry"_err_en_US); 8252 return nullptr; 8253 } 8254 auto *type{symbol.GetType()}; 8255 if (!type) { 8256 return nullptr; // should have already reported error 8257 } 8258 if (const IntrinsicTypeSpec * intrinsic{type->AsIntrinsic()}) { 8259 auto category{intrinsic->category()}; 8260 MiscDetails::Kind miscKind{MiscDetails::Kind::None}; 8261 if (component.source == "kind") { 8262 miscKind = MiscDetails::Kind::KindParamInquiry; 8263 } else if (category == TypeCategory::Character) { 8264 if (component.source == "len") { 8265 miscKind = MiscDetails::Kind::LenParamInquiry; 8266 } 8267 } else if (category == TypeCategory::Complex) { 8268 if (component.source == "re") { 8269 miscKind = MiscDetails::Kind::ComplexPartRe; 8270 } else if (component.source == "im") { 8271 miscKind = MiscDetails::Kind::ComplexPartIm; 8272 } 8273 } 8274 if (miscKind != MiscDetails::Kind::None) { 8275 MakePlaceholder(component, miscKind); 8276 return &component; 8277 } 8278 } else if (DerivedTypeSpec * derived{type->AsDerived()}) { 8279 derived->Instantiate(currScope()); // in case of forward referenced type 8280 if (const Scope * scope{derived->scope()}) { 8281 if (Resolve(component, scope->FindComponent(component.source))) { 8282 if (auto msg{CheckAccessibleSymbol(currScope(), *component.symbol)}) { 8283 context().Say(component.source, *msg); 8284 } 8285 return &component; 8286 } else { 8287 SayDerivedType(component.source, 8288 "Component '%s' not found in derived type '%s'"_err_en_US, *scope); 8289 } 8290 } 8291 return nullptr; 8292 } 8293 if (symbol.test(Symbol::Flag::Implicit)) { 8294 Say(*base, 8295 "'%s' is not an object of derived type; it is implicitly typed"_err_en_US); 8296 } else { 8297 SayWithDecl( 8298 *base, symbol, "'%s' is not an object of derived type"_err_en_US); 8299 } 8300 return nullptr; 8301 } 8302 8303 void DeclarationVisitor::Initialization(const parser::Name &name, 8304 const parser::Initialization &init, bool inComponentDecl) { 8305 // Traversal of the initializer was deferred to here so that the 8306 // symbol being declared can be available for use in the expression, e.g.: 8307 // real, parameter :: x = tiny(x) 8308 if (!name.symbol) { 8309 return; 8310 } 8311 Symbol &ultimate{name.symbol->GetUltimate()}; 8312 // TODO: check C762 - all bounds and type parameters of component 8313 // are colons or constant expressions if component is initialized 8314 common::visit( 8315 common::visitors{ 8316 [&](const parser::ConstantExpr &expr) { 8317 Walk(expr); 8318 if (IsNamedConstant(ultimate) || inComponentDecl) { 8319 NonPointerInitialization(name, expr); 8320 } else { 8321 // Defer analysis so forward references to nested subprograms 8322 // can be properly resolved when they appear in structure 8323 // constructors. 8324 ultimate.set(Symbol::Flag::InDataStmt); 8325 } 8326 }, 8327 [&](const parser::NullInit &null) { // => NULL() 8328 Walk(null); 8329 if (auto nullInit{EvaluateExpr(null)}) { 8330 if (!evaluate::IsNullPointer(*nullInit)) { // C813 8331 Say(null.v.value().source, 8332 "Pointer initializer must be intrinsic NULL()"_err_en_US); 8333 } else if (IsPointer(ultimate)) { 8334 if (auto *object{ultimate.detailsIf<ObjectEntityDetails>()}) { 8335 CHECK(!object->init()); 8336 object->set_init(std::move(*nullInit)); 8337 } else if (auto *procPtr{ 8338 ultimate.detailsIf<ProcEntityDetails>()}) { 8339 CHECK(!procPtr->init()); 8340 procPtr->set_init(nullptr); 8341 } 8342 } else { 8343 Say(name, 8344 "Non-pointer component '%s' initialized with null pointer"_err_en_US); 8345 } 8346 } 8347 }, 8348 [&](const parser::InitialDataTarget &target) { 8349 // Defer analysis to the end of the specification part 8350 // so that forward references and attribute checks like SAVE 8351 // work better. 8352 auto restorer{common::ScopedSet(deferImplicitTyping_, true)}; 8353 Walk(target); 8354 ultimate.set(Symbol::Flag::InDataStmt); 8355 }, 8356 [&](const std::list<Indirection<parser::DataStmtValue>> &values) { 8357 // Handled later in data-to-inits conversion 8358 ultimate.set(Symbol::Flag::InDataStmt); 8359 Walk(values); 8360 }, 8361 }, 8362 init.u); 8363 } 8364 8365 void DeclarationVisitor::PointerInitialization( 8366 const parser::Name &name, const parser::InitialDataTarget &target) { 8367 if (name.symbol) { 8368 Symbol &ultimate{name.symbol->GetUltimate()}; 8369 if (!context().HasError(ultimate)) { 8370 if (IsPointer(ultimate)) { 8371 Walk(target); 8372 if (MaybeExpr expr{EvaluateExpr(target)}) { 8373 // Validation is done in declaration checking. 8374 if (auto *details{ultimate.detailsIf<ObjectEntityDetails>()}) { 8375 CHECK(!details->init()); 8376 details->set_init(std::move(*expr)); 8377 ultimate.set(Symbol::Flag::InDataStmt, false); 8378 } else if (auto *details{ultimate.detailsIf<ProcEntityDetails>()}) { 8379 // something like "REAL, EXTERNAL, POINTER :: p => t" 8380 if (evaluate::IsNullProcedurePointer(*expr)) { 8381 CHECK(!details->init()); 8382 details->set_init(nullptr); 8383 } else if (const Symbol * 8384 targetSymbol{evaluate::UnwrapWholeSymbolDataRef(*expr)}) { 8385 CHECK(!details->init()); 8386 details->set_init(*targetSymbol); 8387 } else { 8388 Say(name, 8389 "Procedure pointer '%s' must be initialized with a procedure name or NULL()"_err_en_US); 8390 context().SetError(ultimate); 8391 } 8392 } 8393 } 8394 } else { 8395 Say(name, 8396 "'%s' is not a pointer but is initialized like one"_err_en_US); 8397 context().SetError(ultimate); 8398 } 8399 } 8400 } 8401 } 8402 void DeclarationVisitor::PointerInitialization( 8403 const parser::Name &name, const parser::ProcPointerInit &target) { 8404 if (name.symbol) { 8405 Symbol &ultimate{name.symbol->GetUltimate()}; 8406 if (!context().HasError(ultimate)) { 8407 if (IsProcedurePointer(ultimate)) { 8408 auto &details{ultimate.get<ProcEntityDetails>()}; 8409 CHECK(!details.init()); 8410 if (const auto *targetName{std::get_if<parser::Name>(&target.u)}) { 8411 Walk(target); 8412 if (!CheckUseError(*targetName) && targetName->symbol) { 8413 // Validation is done in declaration checking. 8414 details.set_init(*targetName->symbol); 8415 } 8416 } else { // explicit NULL 8417 details.set_init(nullptr); 8418 } 8419 } else { 8420 Say(name, 8421 "'%s' is not a procedure pointer but is initialized " 8422 "like one"_err_en_US); 8423 context().SetError(ultimate); 8424 } 8425 } 8426 } 8427 } 8428 8429 void DeclarationVisitor::NonPointerInitialization( 8430 const parser::Name &name, const parser::ConstantExpr &expr) { 8431 if (!context().HasError(name.symbol)) { 8432 Symbol &ultimate{name.symbol->GetUltimate()}; 8433 if (!context().HasError(ultimate)) { 8434 if (IsPointer(ultimate)) { 8435 Say(name, 8436 "'%s' is a pointer but is not initialized like one"_err_en_US); 8437 } else if (auto *details{ultimate.detailsIf<ObjectEntityDetails>()}) { 8438 if (details->init()) { 8439 SayWithDecl(name, *name.symbol, 8440 "'%s' has already been initialized"_err_en_US); 8441 } else if (IsAllocatable(ultimate)) { 8442 Say(name, "Allocatable object '%s' cannot be initialized"_err_en_US); 8443 } else if (ultimate.owner().IsParameterizedDerivedType()) { 8444 // Save the expression for per-instantiation analysis. 8445 details->set_unanalyzedPDTComponentInit(&expr.thing.value()); 8446 } else if (MaybeExpr folded{EvaluateNonPointerInitializer( 8447 ultimate, expr, expr.thing.value().source)}) { 8448 details->set_init(std::move(*folded)); 8449 ultimate.set(Symbol::Flag::InDataStmt, false); 8450 } 8451 } else { 8452 Say(name, "'%s' is not an object that can be initialized"_err_en_US); 8453 } 8454 } 8455 } 8456 } 8457 8458 void ResolveNamesVisitor::HandleCall( 8459 Symbol::Flag procFlag, const parser::Call &call) { 8460 common::visit( 8461 common::visitors{ 8462 [&](const parser::Name &x) { HandleProcedureName(procFlag, x); }, 8463 [&](const parser::ProcComponentRef &x) { 8464 Walk(x); 8465 const parser::Name &name{x.v.thing.component}; 8466 if (Symbol * symbol{name.symbol}) { 8467 if (IsProcedure(*symbol)) { 8468 SetProcFlag(name, *symbol, procFlag); 8469 } 8470 } 8471 }, 8472 }, 8473 std::get<parser::ProcedureDesignator>(call.t).u); 8474 const auto &arguments{std::get<std::list<parser::ActualArgSpec>>(call.t)}; 8475 Walk(arguments); 8476 // Once an object has appeared in a specification function reference as 8477 // a whole scalar actual argument, it cannot be (re)dimensioned later. 8478 // The fact that it appeared to be a scalar may determine the resolution 8479 // or the result of an inquiry intrinsic function or generic procedure. 8480 if (inSpecificationPart_) { 8481 for (const auto &argSpec : arguments) { 8482 const auto &actual{std::get<parser::ActualArg>(argSpec.t)}; 8483 if (const auto *expr{ 8484 std::get_if<common::Indirection<parser::Expr>>(&actual.u)}) { 8485 if (const auto *designator{ 8486 std::get_if<common::Indirection<parser::Designator>>( 8487 &expr->value().u)}) { 8488 if (const auto *dataRef{ 8489 std::get_if<parser::DataRef>(&designator->value().u)}) { 8490 if (const auto *name{std::get_if<parser::Name>(&dataRef->u)}; 8491 name && name->symbol) { 8492 const Symbol &symbol{*name->symbol}; 8493 const auto *object{symbol.detailsIf<ObjectEntityDetails>()}; 8494 if (symbol.has<EntityDetails>() || 8495 (object && !object->IsArray())) { 8496 NoteScalarSpecificationArgument(symbol); 8497 } 8498 } 8499 } 8500 } 8501 } 8502 } 8503 } 8504 } 8505 8506 void ResolveNamesVisitor::HandleProcedureName( 8507 Symbol::Flag flag, const parser::Name &name) { 8508 CHECK(flag == Symbol::Flag::Function || flag == Symbol::Flag::Subroutine); 8509 auto *symbol{FindSymbol(NonDerivedTypeScope(), name)}; 8510 if (!symbol) { 8511 if (IsIntrinsic(name.source, flag)) { 8512 symbol = &MakeSymbol(InclusiveScope(), name.source, Attrs{}); 8513 SetImplicitAttr(*symbol, Attr::INTRINSIC); 8514 } else if (const auto ppcBuiltinScope = 8515 currScope().context().GetPPCBuiltinsScope()) { 8516 // Check if it is a builtin from the predefined module 8517 symbol = FindSymbol(*ppcBuiltinScope, name); 8518 if (!symbol) { 8519 symbol = &MakeSymbol(context().globalScope(), name.source, Attrs{}); 8520 } 8521 } else { 8522 symbol = &MakeSymbol(context().globalScope(), name.source, Attrs{}); 8523 } 8524 Resolve(name, *symbol); 8525 ConvertToProcEntity(*symbol, name.source); 8526 if (!symbol->attrs().test(Attr::INTRINSIC)) { 8527 if (CheckImplicitNoneExternal(name.source, *symbol)) { 8528 MakeExternal(*symbol); 8529 // Create a place-holder HostAssocDetails symbol to preclude later 8530 // use of this name as a local symbol; but don't actually use this new 8531 // HostAssocDetails symbol in expressions. 8532 MakeHostAssocSymbol(name, *symbol); 8533 name.symbol = symbol; 8534 } 8535 } 8536 CheckEntryDummyUse(name.source, symbol); 8537 SetProcFlag(name, *symbol, flag); 8538 } else if (CheckUseError(name)) { 8539 // error was reported 8540 } else { 8541 symbol = &symbol->GetUltimate(); 8542 if (!name.symbol || 8543 (name.symbol->has<HostAssocDetails>() && symbol->owner().IsGlobal() && 8544 (symbol->has<ProcEntityDetails>() || 8545 (symbol->has<SubprogramDetails>() && 8546 symbol->scope() /*not ENTRY*/)))) { 8547 name.symbol = symbol; 8548 } 8549 CheckEntryDummyUse(name.source, symbol); 8550 bool convertedToProcEntity{ConvertToProcEntity(*symbol, name.source)}; 8551 if (convertedToProcEntity && !symbol->attrs().test(Attr::EXTERNAL) && 8552 IsIntrinsic(symbol->name(), flag) && !IsDummy(*symbol)) { 8553 AcquireIntrinsicProcedureFlags(*symbol); 8554 } 8555 if (!SetProcFlag(name, *symbol, flag)) { 8556 return; // reported error 8557 } 8558 CheckImplicitNoneExternal(name.source, *symbol); 8559 if (IsProcedure(*symbol) || symbol->has<DerivedTypeDetails>() || 8560 symbol->has<AssocEntityDetails>()) { 8561 // Symbols with DerivedTypeDetails and AssocEntityDetails are accepted 8562 // here as procedure-designators because this means the related 8563 // FunctionReference are mis-parsed structure constructors or array 8564 // references that will be fixed later when analyzing expressions. 8565 } else if (symbol->has<ObjectEntityDetails>()) { 8566 // Symbols with ObjectEntityDetails are also accepted because this can be 8567 // a mis-parsed array reference that will be fixed later. Ensure that if 8568 // this is a symbol from a host procedure, a symbol with HostAssocDetails 8569 // is created for the current scope. 8570 // Operate on non ultimate symbol so that HostAssocDetails are also 8571 // created for symbols used associated in the host procedure. 8572 ResolveName(name); 8573 } else if (symbol->test(Symbol::Flag::Implicit)) { 8574 Say(name, 8575 "Use of '%s' as a procedure conflicts with its implicit definition"_err_en_US); 8576 } else { 8577 SayWithDecl(name, *symbol, 8578 "Use of '%s' as a procedure conflicts with its declaration"_err_en_US); 8579 } 8580 } 8581 } 8582 8583 bool ResolveNamesVisitor::CheckImplicitNoneExternal( 8584 const SourceName &name, const Symbol &symbol) { 8585 if (symbol.has<ProcEntityDetails>() && isImplicitNoneExternal() && 8586 !symbol.attrs().test(Attr::EXTERNAL) && 8587 !symbol.attrs().test(Attr::INTRINSIC) && !symbol.HasExplicitInterface()) { 8588 Say(name, 8589 "'%s' is an external procedure without the EXTERNAL attribute in a scope with IMPLICIT NONE(EXTERNAL)"_err_en_US); 8590 return false; 8591 } 8592 return true; 8593 } 8594 8595 // Variant of HandleProcedureName() for use while skimming the executable 8596 // part of a subprogram to catch calls to dummy procedures that are part 8597 // of the subprogram's interface, and to mark as procedures any symbols 8598 // that might otherwise have been miscategorized as objects. 8599 void ResolveNamesVisitor::NoteExecutablePartCall( 8600 Symbol::Flag flag, SourceName name, bool hasCUDAChevrons) { 8601 // Subtlety: The symbol pointers in the parse tree are not set, because 8602 // they might end up resolving elsewhere (e.g., construct entities in 8603 // SELECT TYPE). 8604 if (Symbol * symbol{currScope().FindSymbol(name)}) { 8605 Symbol::Flag other{flag == Symbol::Flag::Subroutine 8606 ? Symbol::Flag::Function 8607 : Symbol::Flag::Subroutine}; 8608 if (!symbol->test(other)) { 8609 ConvertToProcEntity(*symbol, name); 8610 if (auto *details{symbol->detailsIf<ProcEntityDetails>()}) { 8611 symbol->set(flag); 8612 if (IsDummy(*symbol)) { 8613 SetImplicitAttr(*symbol, Attr::EXTERNAL); 8614 } 8615 ApplyImplicitRules(*symbol); 8616 if (hasCUDAChevrons) { 8617 details->set_isCUDAKernel(); 8618 } 8619 } 8620 } 8621 } 8622 } 8623 8624 static bool IsLocallyImplicitGlobalSymbol( 8625 const Symbol &symbol, const parser::Name &localName) { 8626 if (symbol.owner().IsGlobal()) { 8627 const auto *subp{symbol.detailsIf<SubprogramDetails>()}; 8628 const Scope *scope{ 8629 subp && subp->entryScope() ? subp->entryScope() : symbol.scope()}; 8630 return !(scope && scope->sourceRange().Contains(localName.source)); 8631 } 8632 return false; 8633 } 8634 8635 static bool TypesMismatchIfNonNull( 8636 const DeclTypeSpec *type1, const DeclTypeSpec *type2) { 8637 return type1 && type2 && *type1 != *type2; 8638 } 8639 8640 // Check and set the Function or Subroutine flag on symbol; false on error. 8641 bool ResolveNamesVisitor::SetProcFlag( 8642 const parser::Name &name, Symbol &symbol, Symbol::Flag flag) { 8643 if (symbol.test(Symbol::Flag::Function) && flag == Symbol::Flag::Subroutine) { 8644 SayWithDecl( 8645 name, symbol, "Cannot call function '%s' like a subroutine"_err_en_US); 8646 context().SetError(symbol); 8647 return false; 8648 } else if (symbol.test(Symbol::Flag::Subroutine) && 8649 flag == Symbol::Flag::Function) { 8650 SayWithDecl( 8651 name, symbol, "Cannot call subroutine '%s' like a function"_err_en_US); 8652 context().SetError(symbol); 8653 return false; 8654 } else if (flag == Symbol::Flag::Function && 8655 IsLocallyImplicitGlobalSymbol(symbol, name) && 8656 TypesMismatchIfNonNull(symbol.GetType(), GetImplicitType(symbol))) { 8657 SayWithDecl(name, symbol, 8658 "Implicit declaration of function '%s' has a different result type than in previous declaration"_err_en_US); 8659 return false; 8660 } else if (symbol.has<ProcEntityDetails>()) { 8661 symbol.set(flag); // in case it hasn't been set yet 8662 if (flag == Symbol::Flag::Function) { 8663 ApplyImplicitRules(symbol); 8664 } 8665 if (symbol.attrs().test(Attr::INTRINSIC)) { 8666 AcquireIntrinsicProcedureFlags(symbol); 8667 } 8668 } else if (symbol.GetType() && flag == Symbol::Flag::Subroutine) { 8669 SayWithDecl( 8670 name, symbol, "Cannot call function '%s' like a subroutine"_err_en_US); 8671 context().SetError(symbol); 8672 } else if (symbol.attrs().test(Attr::INTRINSIC)) { 8673 AcquireIntrinsicProcedureFlags(symbol); 8674 } 8675 return true; 8676 } 8677 8678 bool ModuleVisitor::Pre(const parser::AccessStmt &x) { 8679 Attr accessAttr{AccessSpecToAttr(std::get<parser::AccessSpec>(x.t))}; 8680 if (!currScope().IsModule()) { // C869 8681 Say(currStmtSource().value(), 8682 "%s statement may only appear in the specification part of a module"_err_en_US, 8683 EnumToString(accessAttr)); 8684 return false; 8685 } 8686 const auto &accessIds{std::get<std::list<parser::AccessId>>(x.t)}; 8687 if (accessIds.empty()) { 8688 if (prevAccessStmt_) { // C869 8689 Say("The default accessibility of this module has already been declared"_err_en_US) 8690 .Attach(*prevAccessStmt_, "Previous declaration"_en_US); 8691 } 8692 prevAccessStmt_ = currStmtSource(); 8693 auto *moduleDetails{DEREF(currScope().symbol()).detailsIf<ModuleDetails>()}; 8694 DEREF(moduleDetails).set_isDefaultPrivate(accessAttr == Attr::PRIVATE); 8695 } else { 8696 for (const auto &accessId : accessIds) { 8697 GenericSpecInfo info{accessId.v.value()}; 8698 auto *symbol{FindInScope(info.symbolName())}; 8699 if (!symbol && !info.kind().IsName()) { 8700 symbol = &MakeSymbol(info.symbolName(), Attrs{}, GenericDetails{}); 8701 } 8702 info.Resolve(&SetAccess(info.symbolName(), accessAttr, symbol)); 8703 } 8704 } 8705 return false; 8706 } 8707 8708 // Set the access specification for this symbol. 8709 Symbol &ModuleVisitor::SetAccess( 8710 const SourceName &name, Attr attr, Symbol *symbol) { 8711 if (!symbol) { 8712 symbol = &MakeSymbol(name); 8713 } 8714 Attrs &attrs{symbol->attrs()}; 8715 if (attrs.HasAny({Attr::PUBLIC, Attr::PRIVATE})) { 8716 // PUBLIC/PRIVATE already set: make it a fatal error if it changed 8717 Attr prev{attrs.test(Attr::PUBLIC) ? Attr::PUBLIC : Attr::PRIVATE}; 8718 if (attr != prev) { 8719 Say(name, 8720 "The accessibility of '%s' has already been specified as %s"_err_en_US, 8721 MakeOpName(name), EnumToString(prev)); 8722 } else { 8723 context().Warn(common::LanguageFeature::RedundantAttribute, name, 8724 "The accessibility of '%s' has already been specified as %s"_warn_en_US, 8725 MakeOpName(name), EnumToString(prev)); 8726 } 8727 } else { 8728 attrs.set(attr); 8729 } 8730 return *symbol; 8731 } 8732 8733 static bool NeedsExplicitType(const Symbol &symbol) { 8734 if (symbol.has<UnknownDetails>()) { 8735 return true; 8736 } else if (const auto *details{symbol.detailsIf<EntityDetails>()}) { 8737 return !details->type(); 8738 } else if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) { 8739 return !details->type(); 8740 } else if (const auto *details{symbol.detailsIf<ProcEntityDetails>()}) { 8741 return !details->procInterface() && !details->type(); 8742 } else { 8743 return false; 8744 } 8745 } 8746 8747 void ResolveNamesVisitor::HandleDerivedTypesInImplicitStmts( 8748 const parser::ImplicitPart &implicitPart, 8749 const std::list<parser::DeclarationConstruct> &decls) { 8750 // Detect derived type definitions and create symbols for them now if 8751 // they appear in IMPLICIT statements so that these forward-looking 8752 // references will not be ambiguous with host associations. 8753 std::set<SourceName> implicitDerivedTypes; 8754 for (const auto &ipStmt : implicitPart.v) { 8755 if (const auto *impl{std::get_if< 8756 parser::Statement<common::Indirection<parser::ImplicitStmt>>>( 8757 &ipStmt.u)}) { 8758 if (const auto *specs{std::get_if<std::list<parser::ImplicitSpec>>( 8759 &impl->statement.value().u)}) { 8760 for (const auto &spec : *specs) { 8761 const auto &declTypeSpec{ 8762 std::get<parser::DeclarationTypeSpec>(spec.t)}; 8763 if (const auto *dtSpec{common::visit( 8764 common::visitors{ 8765 [](const parser::DeclarationTypeSpec::Type &x) { 8766 return &x.derived; 8767 }, 8768 [](const parser::DeclarationTypeSpec::Class &x) { 8769 return &x.derived; 8770 }, 8771 [](const auto &) -> const parser::DerivedTypeSpec * { 8772 return nullptr; 8773 }}, 8774 declTypeSpec.u)}) { 8775 implicitDerivedTypes.emplace( 8776 std::get<parser::Name>(dtSpec->t).source); 8777 } 8778 } 8779 } 8780 } 8781 } 8782 if (!implicitDerivedTypes.empty()) { 8783 for (const auto &decl : decls) { 8784 if (const auto *spec{ 8785 std::get_if<parser::SpecificationConstruct>(&decl.u)}) { 8786 if (const auto *dtDef{ 8787 std::get_if<common::Indirection<parser::DerivedTypeDef>>( 8788 &spec->u)}) { 8789 const parser::DerivedTypeStmt &dtStmt{ 8790 std::get<parser::Statement<parser::DerivedTypeStmt>>( 8791 dtDef->value().t) 8792 .statement}; 8793 const parser::Name &name{std::get<parser::Name>(dtStmt.t)}; 8794 if (implicitDerivedTypes.find(name.source) != 8795 implicitDerivedTypes.end() && 8796 !FindInScope(name)) { 8797 DerivedTypeDetails details; 8798 details.set_isForwardReferenced(true); 8799 Resolve(name, MakeSymbol(name, std::move(details))); 8800 implicitDerivedTypes.erase(name.source); 8801 } 8802 } 8803 } 8804 } 8805 } 8806 } 8807 8808 bool ResolveNamesVisitor::Pre(const parser::SpecificationPart &x) { 8809 const auto &[accDecls, ompDecls, compilerDirectives, useStmts, importStmts, 8810 implicitPart, decls] = x.t; 8811 auto flagRestorer{common::ScopedSet(inSpecificationPart_, true)}; 8812 auto stateRestorer{ 8813 common::ScopedSet(specPartState_, SpecificationPartState{})}; 8814 Walk(accDecls); 8815 Walk(ompDecls); 8816 Walk(compilerDirectives); 8817 for (const auto &useStmt : useStmts) { 8818 CollectUseRenames(useStmt.statement.value()); 8819 } 8820 Walk(useStmts); 8821 UseCUDABuiltinNames(); 8822 ClearUseRenames(); 8823 ClearUseOnly(); 8824 ClearModuleUses(); 8825 Walk(importStmts); 8826 HandleDerivedTypesInImplicitStmts(implicitPart, decls); 8827 Walk(implicitPart); 8828 for (const auto &decl : decls) { 8829 if (const auto *spec{ 8830 std::get_if<parser::SpecificationConstruct>(&decl.u)}) { 8831 PreSpecificationConstruct(*spec); 8832 } 8833 } 8834 Walk(decls); 8835 FinishSpecificationPart(decls); 8836 return false; 8837 } 8838 8839 void ResolveNamesVisitor::UseCUDABuiltinNames() { 8840 if (FindCUDADeviceContext(&currScope())) { 8841 for (const auto &[name, symbol] : context().GetCUDABuiltinsScope()) { 8842 if (!FindInScope(name)) { 8843 auto &localSymbol{MakeSymbol(name)}; 8844 localSymbol.set_details(UseDetails{name, *symbol}); 8845 localSymbol.flags() = symbol->flags(); 8846 } 8847 } 8848 } 8849 } 8850 8851 // Initial processing on specification constructs, before visiting them. 8852 void ResolveNamesVisitor::PreSpecificationConstruct( 8853 const parser::SpecificationConstruct &spec) { 8854 common::visit( 8855 common::visitors{ 8856 [&](const parser::Statement<Indirection<parser::GenericStmt>> &y) { 8857 CreateGeneric(std::get<parser::GenericSpec>(y.statement.value().t)); 8858 }, 8859 [&](const Indirection<parser::InterfaceBlock> &y) { 8860 const auto &stmt{std::get<parser::Statement<parser::InterfaceStmt>>( 8861 y.value().t)}; 8862 if (const auto *spec{parser::Unwrap<parser::GenericSpec>(stmt)}) { 8863 CreateGeneric(*spec); 8864 } 8865 }, 8866 [&](const parser::Statement<parser::OtherSpecificationStmt> &y) { 8867 common::visit( 8868 common::visitors{ 8869 [&](const common::Indirection<parser::CommonStmt> &z) { 8870 CreateCommonBlockSymbols(z.value()); 8871 }, 8872 [&](const common::Indirection<parser::TargetStmt> &z) { 8873 CreateObjectSymbols(z.value().v, Attr::TARGET); 8874 }, 8875 [](const auto &) {}, 8876 }, 8877 y.statement.u); 8878 }, 8879 [](const auto &) {}, 8880 }, 8881 spec.u); 8882 } 8883 8884 void ResolveNamesVisitor::CreateCommonBlockSymbols( 8885 const parser::CommonStmt &commonStmt) { 8886 for (const parser::CommonStmt::Block &block : commonStmt.blocks) { 8887 const auto &[name, objects] = block.t; 8888 Symbol &commonBlock{MakeCommonBlockSymbol(name)}; 8889 for (const auto &object : objects) { 8890 Symbol &obj{DeclareObjectEntity(std::get<parser::Name>(object.t))}; 8891 if (auto *details{obj.detailsIf<ObjectEntityDetails>()}) { 8892 details->set_commonBlock(commonBlock); 8893 commonBlock.get<CommonBlockDetails>().add_object(obj); 8894 } 8895 } 8896 } 8897 } 8898 8899 void ResolveNamesVisitor::CreateObjectSymbols( 8900 const std::list<parser::ObjectDecl> &decls, Attr attr) { 8901 for (const parser::ObjectDecl &decl : decls) { 8902 SetImplicitAttr(DeclareEntity<ObjectEntityDetails>( 8903 std::get<parser::ObjectName>(decl.t), Attrs{}), 8904 attr); 8905 } 8906 } 8907 8908 void ResolveNamesVisitor::CreateGeneric(const parser::GenericSpec &x) { 8909 auto info{GenericSpecInfo{x}}; 8910 SourceName symbolName{info.symbolName()}; 8911 if (IsLogicalConstant(context(), symbolName)) { 8912 Say(symbolName, 8913 "Logical constant '%s' may not be used as a defined operator"_err_en_US); 8914 return; 8915 } 8916 GenericDetails genericDetails; 8917 Symbol *existing{nullptr}; 8918 // Check all variants of names, e.g. "operator(.ne.)" for "operator(/=)" 8919 for (const std::string &n : GetAllNames(context(), symbolName)) { 8920 existing = currScope().FindSymbol(SourceName{n}); 8921 if (existing) { 8922 break; 8923 } 8924 } 8925 if (existing) { 8926 Symbol &ultimate{existing->GetUltimate()}; 8927 if (auto *existingGeneric{ultimate.detailsIf<GenericDetails>()}) { 8928 if (&existing->owner() == &currScope()) { 8929 if (const auto *existingUse{existing->detailsIf<UseDetails>()}) { 8930 // Create a local copy of a use associated generic so that 8931 // it can be locally extended without corrupting the original. 8932 genericDetails.CopyFrom(*existingGeneric); 8933 if (existingGeneric->specific()) { 8934 genericDetails.set_specific(*existingGeneric->specific()); 8935 } 8936 AddGenericUse( 8937 genericDetails, existing->name(), existingUse->symbol()); 8938 } else if (existing == &ultimate) { 8939 // Extending an extant generic in the same scope 8940 info.Resolve(existing); 8941 return; 8942 } else { 8943 // Host association of a generic is handled elsewhere 8944 CHECK(existing->has<HostAssocDetails>()); 8945 } 8946 } else { 8947 // Create a new generic for this scope. 8948 } 8949 } else if (ultimate.has<SubprogramDetails>() || 8950 ultimate.has<SubprogramNameDetails>()) { 8951 genericDetails.set_specific(*existing); 8952 } else if (ultimate.has<ProcEntityDetails>()) { 8953 if (existing->name() != symbolName || 8954 !ultimate.attrs().test(Attr::INTRINSIC)) { 8955 genericDetails.set_specific(*existing); 8956 } 8957 } else if (ultimate.has<DerivedTypeDetails>()) { 8958 genericDetails.set_derivedType(*existing); 8959 } else if (&existing->owner() == &currScope()) { 8960 SayAlreadyDeclared(symbolName, *existing); 8961 return; 8962 } 8963 if (&existing->owner() == &currScope()) { 8964 EraseSymbol(*existing); 8965 } 8966 } 8967 info.Resolve(&MakeSymbol(symbolName, Attrs{}, std::move(genericDetails))); 8968 } 8969 8970 void ResolveNamesVisitor::FinishSpecificationPart( 8971 const std::list<parser::DeclarationConstruct> &decls) { 8972 misparsedStmtFuncFound_ = false; 8973 funcResultStack().CompleteFunctionResultType(); 8974 CheckImports(); 8975 for (auto &pair : currScope()) { 8976 auto &symbol{*pair.second}; 8977 if (inInterfaceBlock()) { 8978 ConvertToObjectEntity(symbol); 8979 } 8980 if (NeedsExplicitType(symbol)) { 8981 ApplyImplicitRules(symbol); 8982 } 8983 if (IsDummy(symbol) && isImplicitNoneType() && 8984 symbol.test(Symbol::Flag::Implicit) && !context().HasError(symbol)) { 8985 Say(symbol.name(), 8986 "No explicit type declared for dummy argument '%s'"_err_en_US); 8987 context().SetError(symbol); 8988 } 8989 if (symbol.has<GenericDetails>()) { 8990 CheckGenericProcedures(symbol); 8991 } 8992 if (!symbol.has<HostAssocDetails>()) { 8993 CheckPossibleBadForwardRef(symbol); 8994 } 8995 // Propagate BIND(C) attribute to procedure entities from their interfaces, 8996 // but not the NAME=, even if it is empty (which would be a reasonable 8997 // and useful behavior, actually). This interpretation is not at all 8998 // clearly described in the standard, but matches the behavior of several 8999 // other compilers. 9000 if (auto *proc{symbol.detailsIf<ProcEntityDetails>()}; proc && 9001 !proc->isDummy() && !IsPointer(symbol) && 9002 !symbol.attrs().test(Attr::BIND_C)) { 9003 if (const Symbol * iface{proc->procInterface()}; 9004 iface && IsBindCProcedure(*iface)) { 9005 SetImplicitAttr(symbol, Attr::BIND_C); 9006 SetBindNameOn(symbol); 9007 } 9008 } 9009 } 9010 currScope().InstantiateDerivedTypes(); 9011 for (const auto &decl : decls) { 9012 if (const auto *statement{std::get_if< 9013 parser::Statement<common::Indirection<parser::StmtFunctionStmt>>>( 9014 &decl.u)}) { 9015 messageHandler().set_currStmtSource(statement->source); 9016 AnalyzeStmtFunctionStmt(statement->statement.value()); 9017 } 9018 } 9019 // TODO: what about instantiations in BLOCK? 9020 CheckSaveStmts(); 9021 CheckCommonBlocks(); 9022 if (!inInterfaceBlock()) { 9023 // TODO: warn for the case where the EQUIVALENCE statement is in a 9024 // procedure declaration in an interface block 9025 CheckEquivalenceSets(); 9026 } 9027 } 9028 9029 // Analyze the bodies of statement functions now that the symbols in this 9030 // specification part have been fully declared and implicitly typed. 9031 // (Statement function references are not allowed in specification 9032 // expressions, so it's safe to defer processing their definitions.) 9033 void ResolveNamesVisitor::AnalyzeStmtFunctionStmt( 9034 const parser::StmtFunctionStmt &stmtFunc) { 9035 const auto &name{std::get<parser::Name>(stmtFunc.t)}; 9036 Symbol *symbol{name.symbol}; 9037 auto *details{symbol ? symbol->detailsIf<SubprogramDetails>() : nullptr}; 9038 if (!details || !symbol->scope() || 9039 &symbol->scope()->parent() != &currScope() || details->isInterface() || 9040 details->isDummy() || details->entryScope() || 9041 details->moduleInterface() || symbol->test(Symbol::Flag::Subroutine)) { 9042 return; // error recovery 9043 } 9044 // Resolve the symbols on the RHS of the statement function. 9045 PushScope(*symbol->scope()); 9046 const auto &parsedExpr{std::get<parser::Scalar<parser::Expr>>(stmtFunc.t)}; 9047 Walk(parsedExpr); 9048 PopScope(); 9049 if (auto expr{AnalyzeExpr(context(), stmtFunc)}) { 9050 if (auto type{evaluate::DynamicType::From(*symbol)}) { 9051 if (auto converted{evaluate::ConvertToType(*type, std::move(*expr))}) { 9052 details->set_stmtFunction(std::move(*converted)); 9053 } else { 9054 Say(name.source, 9055 "Defining expression of statement function '%s' cannot be converted to its result type %s"_err_en_US, 9056 name.source, type->AsFortran()); 9057 } 9058 } else { 9059 details->set_stmtFunction(std::move(*expr)); 9060 } 9061 } 9062 if (!details->stmtFunction()) { 9063 context().SetError(*symbol); 9064 } 9065 } 9066 9067 void ResolveNamesVisitor::CheckImports() { 9068 auto &scope{currScope()}; 9069 switch (scope.GetImportKind()) { 9070 case common::ImportKind::None: 9071 break; 9072 case common::ImportKind::All: 9073 // C8102: all entities in host must not be hidden 9074 for (const auto &pair : scope.parent()) { 9075 auto &name{pair.first}; 9076 std::optional<SourceName> scopeName{scope.GetName()}; 9077 if (!scopeName || name != *scopeName) { 9078 CheckImport(prevImportStmt_.value(), name); 9079 } 9080 } 9081 break; 9082 case common::ImportKind::Default: 9083 case common::ImportKind::Only: 9084 // C8102: entities named in IMPORT must not be hidden 9085 for (auto &name : scope.importNames()) { 9086 CheckImport(name, name); 9087 } 9088 break; 9089 } 9090 } 9091 9092 void ResolveNamesVisitor::CheckImport( 9093 const SourceName &location, const SourceName &name) { 9094 if (auto *symbol{FindInScope(name)}) { 9095 const Symbol &ultimate{symbol->GetUltimate()}; 9096 if (&ultimate.owner() == &currScope()) { 9097 Say(location, "'%s' from host is not accessible"_err_en_US, name) 9098 .Attach(symbol->name(), "'%s' is hidden by this entity"_because_en_US, 9099 symbol->name()); 9100 } 9101 } 9102 } 9103 9104 bool ResolveNamesVisitor::Pre(const parser::ImplicitStmt &x) { 9105 return CheckNotInBlock("IMPLICIT") && // C1107 9106 ImplicitRulesVisitor::Pre(x); 9107 } 9108 9109 void ResolveNamesVisitor::Post(const parser::PointerObject &x) { 9110 common::visit(common::visitors{ 9111 [&](const parser::Name &x) { ResolveName(x); }, 9112 [&](const parser::StructureComponent &x) { 9113 ResolveStructureComponent(x); 9114 }, 9115 }, 9116 x.u); 9117 } 9118 void ResolveNamesVisitor::Post(const parser::AllocateObject &x) { 9119 common::visit(common::visitors{ 9120 [&](const parser::Name &x) { ResolveName(x); }, 9121 [&](const parser::StructureComponent &x) { 9122 ResolveStructureComponent(x); 9123 }, 9124 }, 9125 x.u); 9126 } 9127 9128 bool ResolveNamesVisitor::Pre(const parser::PointerAssignmentStmt &x) { 9129 const auto &dataRef{std::get<parser::DataRef>(x.t)}; 9130 const auto &bounds{std::get<parser::PointerAssignmentStmt::Bounds>(x.t)}; 9131 const auto &expr{std::get<parser::Expr>(x.t)}; 9132 ResolveDataRef(dataRef); 9133 Symbol *ptrSymbol{parser::GetLastName(dataRef).symbol}; 9134 Walk(bounds); 9135 // Resolve unrestricted specific intrinsic procedures as in "p => cos". 9136 if (const parser::Name * name{parser::Unwrap<parser::Name>(expr)}) { 9137 if (NameIsKnownOrIntrinsic(*name)) { 9138 if (Symbol * symbol{name->symbol}) { 9139 if (IsProcedurePointer(ptrSymbol) && 9140 !ptrSymbol->test(Symbol::Flag::Function) && 9141 !ptrSymbol->test(Symbol::Flag::Subroutine)) { 9142 if (symbol->test(Symbol::Flag::Function)) { 9143 ApplyImplicitRules(*ptrSymbol); 9144 } 9145 } 9146 // If the name is known because it is an object entity from a host 9147 // procedure, create a host associated symbol. 9148 if (symbol->GetUltimate().has<ObjectEntityDetails>() && 9149 IsUplevelReference(*symbol)) { 9150 MakeHostAssocSymbol(*name, *symbol); 9151 } 9152 } 9153 return false; 9154 } 9155 // Can also reference a global external procedure here 9156 if (auto it{context().globalScope().find(name->source)}; 9157 it != context().globalScope().end()) { 9158 Symbol &global{*it->second}; 9159 if (IsProcedure(global)) { 9160 Resolve(*name, global); 9161 return false; 9162 } 9163 } 9164 if (IsProcedurePointer(parser::GetLastName(dataRef).symbol) && 9165 !FindSymbol(*name)) { 9166 // Unknown target of procedure pointer must be an external procedure 9167 Symbol &symbol{MakeSymbol( 9168 context().globalScope(), name->source, Attrs{Attr::EXTERNAL})}; 9169 symbol.implicitAttrs().set(Attr::EXTERNAL); 9170 Resolve(*name, symbol); 9171 ConvertToProcEntity(symbol, name->source); 9172 return false; 9173 } 9174 } 9175 Walk(expr); 9176 return false; 9177 } 9178 void ResolveNamesVisitor::Post(const parser::Designator &x) { 9179 ResolveDesignator(x); 9180 } 9181 void ResolveNamesVisitor::Post(const parser::SubstringInquiry &x) { 9182 Walk(std::get<parser::SubstringRange>(x.v.t).t); 9183 ResolveDataRef(std::get<parser::DataRef>(x.v.t)); 9184 } 9185 9186 void ResolveNamesVisitor::Post(const parser::ProcComponentRef &x) { 9187 ResolveStructureComponent(x.v.thing); 9188 } 9189 void ResolveNamesVisitor::Post(const parser::TypeGuardStmt &x) { 9190 DeclTypeSpecVisitor::Post(x); 9191 ConstructVisitor::Post(x); 9192 } 9193 bool ResolveNamesVisitor::Pre(const parser::StmtFunctionStmt &x) { 9194 if (HandleStmtFunction(x)) { 9195 return false; 9196 } else { 9197 // This is an array element or pointer-valued function assignment: 9198 // resolve the names of indices/arguments 9199 const auto &names{std::get<std::list<parser::Name>>(x.t)}; 9200 for (auto &name : names) { 9201 ResolveName(name); 9202 } 9203 return true; 9204 } 9205 } 9206 9207 bool ResolveNamesVisitor::Pre(const parser::DefinedOpName &x) { 9208 const parser::Name &name{x.v}; 9209 if (FindSymbol(name)) { 9210 // OK 9211 } else if (IsLogicalConstant(context(), name.source)) { 9212 Say(name, 9213 "Logical constant '%s' may not be used as a defined operator"_err_en_US); 9214 } else { 9215 // Resolved later in expression semantics 9216 MakePlaceholder(name, MiscDetails::Kind::TypeBoundDefinedOp); 9217 } 9218 return false; 9219 } 9220 9221 void ResolveNamesVisitor::Post(const parser::AssignStmt &x) { 9222 if (auto *name{ResolveName(std::get<parser::Name>(x.t))}) { 9223 CheckEntryDummyUse(name->source, name->symbol); 9224 ConvertToObjectEntity(DEREF(name->symbol)); 9225 } 9226 } 9227 void ResolveNamesVisitor::Post(const parser::AssignedGotoStmt &x) { 9228 if (auto *name{ResolveName(std::get<parser::Name>(x.t))}) { 9229 CheckEntryDummyUse(name->source, name->symbol); 9230 ConvertToObjectEntity(DEREF(name->symbol)); 9231 } 9232 } 9233 9234 void ResolveNamesVisitor::Post(const parser::CompilerDirective &x) { 9235 if (std::holds_alternative<parser::CompilerDirective::VectorAlways>(x.u)) { 9236 return; 9237 } 9238 if (const auto *tkr{ 9239 std::get_if<std::list<parser::CompilerDirective::IgnoreTKR>>(&x.u)}) { 9240 if (currScope().IsTopLevel() || 9241 GetProgramUnitContaining(currScope()).kind() != 9242 Scope::Kind::Subprogram) { 9243 Say(x.source, 9244 "!DIR$ IGNORE_TKR directive must appear in a subroutine or function"_err_en_US); 9245 return; 9246 } 9247 if (!inSpecificationPart_) { 9248 Say(x.source, 9249 "!DIR$ IGNORE_TKR directive must appear in the specification part"_err_en_US); 9250 return; 9251 } 9252 if (tkr->empty()) { 9253 Symbol *symbol{currScope().symbol()}; 9254 if (SubprogramDetails * 9255 subp{symbol ? symbol->detailsIf<SubprogramDetails>() : nullptr}) { 9256 subp->set_defaultIgnoreTKR(true); 9257 } 9258 } else { 9259 for (const parser::CompilerDirective::IgnoreTKR &item : *tkr) { 9260 common::IgnoreTKRSet set; 9261 if (const auto &maybeList{ 9262 std::get<std::optional<std::list<const char *>>>(item.t)}) { 9263 for (const char *p : *maybeList) { 9264 if (p) { 9265 switch (*p) { 9266 case 't': 9267 set.set(common::IgnoreTKR::Type); 9268 break; 9269 case 'k': 9270 set.set(common::IgnoreTKR::Kind); 9271 break; 9272 case 'r': 9273 set.set(common::IgnoreTKR::Rank); 9274 break; 9275 case 'd': 9276 set.set(common::IgnoreTKR::Device); 9277 break; 9278 case 'm': 9279 set.set(common::IgnoreTKR::Managed); 9280 break; 9281 case 'c': 9282 set.set(common::IgnoreTKR::Contiguous); 9283 break; 9284 case 'a': 9285 set = common::ignoreTKRAll; 9286 break; 9287 default: 9288 Say(x.source, 9289 "'%c' is not a valid letter for !DIR$ IGNORE_TKR directive"_err_en_US, 9290 *p); 9291 set = common::ignoreTKRAll; 9292 break; 9293 } 9294 } 9295 } 9296 if (set.empty()) { 9297 Say(x.source, 9298 "!DIR$ IGNORE_TKR directive may not have an empty parenthesized list of letters"_err_en_US); 9299 } 9300 } else { // no (list) 9301 set = common::ignoreTKRAll; 9302 ; 9303 } 9304 const auto &name{std::get<parser::Name>(item.t)}; 9305 Symbol *symbol{FindSymbol(name)}; 9306 if (!symbol) { 9307 symbol = &MakeSymbol(name, Attrs{}, ObjectEntityDetails{}); 9308 } 9309 if (symbol->owner() != currScope()) { 9310 SayWithDecl( 9311 name, *symbol, "'%s' must be local to this subprogram"_err_en_US); 9312 } else { 9313 ConvertToObjectEntity(*symbol); 9314 if (auto *object{symbol->detailsIf<ObjectEntityDetails>()}) { 9315 object->set_ignoreTKR(set); 9316 } else { 9317 SayWithDecl(name, *symbol, "'%s' must be an object"_err_en_US); 9318 } 9319 } 9320 } 9321 } 9322 } else if (context().ShouldWarn(common::UsageWarning::IgnoredDirective)) { 9323 Say(x.source, "Unrecognized compiler directive was ignored"_warn_en_US) 9324 .set_usageWarning(common::UsageWarning::IgnoredDirective); 9325 } 9326 } 9327 9328 bool ResolveNamesVisitor::Pre(const parser::ProgramUnit &x) { 9329 if (std::holds_alternative<common::Indirection<parser::CompilerDirective>>( 9330 x.u)) { 9331 // TODO: global directives 9332 return true; 9333 } 9334 if (std::holds_alternative< 9335 common::Indirection<parser::OpenACCRoutineConstruct>>(x.u)) { 9336 ResolveAccParts(context(), x, &topScope_); 9337 return false; 9338 } 9339 ProgramTree &root{ProgramTree::Build(x, context())}; 9340 SetScope(topScope_); 9341 ResolveSpecificationParts(root); 9342 FinishSpecificationParts(root); 9343 ResolveExecutionParts(root); 9344 FinishExecutionParts(root); 9345 ResolveAccParts(context(), x, /*topScope=*/nullptr); 9346 ResolveOmpParts(context(), x); 9347 return false; 9348 } 9349 9350 template <typename A> std::set<SourceName> GetUses(const A &x) { 9351 std::set<SourceName> uses; 9352 if constexpr (!std::is_same_v<A, parser::CompilerDirective> && 9353 !std::is_same_v<A, parser::OpenACCRoutineConstruct>) { 9354 const auto &spec{std::get<parser::SpecificationPart>(x.t)}; 9355 const auto &unitUses{std::get< 9356 std::list<parser::Statement<common::Indirection<parser::UseStmt>>>>( 9357 spec.t)}; 9358 for (const auto &u : unitUses) { 9359 uses.insert(u.statement.value().moduleName.source); 9360 } 9361 } 9362 return uses; 9363 } 9364 9365 bool ResolveNamesVisitor::Pre(const parser::Program &x) { 9366 std::map<SourceName, const parser::ProgramUnit *> modules; 9367 std::set<SourceName> uses; 9368 bool disordered{false}; 9369 for (const auto &progUnit : x.v) { 9370 if (const auto *indMod{ 9371 std::get_if<common::Indirection<parser::Module>>(&progUnit.u)}) { 9372 const parser::Module &mod{indMod->value()}; 9373 const auto &moduleStmt{ 9374 std::get<parser::Statement<parser::ModuleStmt>>(mod.t)}; 9375 const SourceName &name{moduleStmt.statement.v.source}; 9376 if (auto iter{modules.find(name)}; iter != modules.end()) { 9377 Say(name, 9378 "Module '%s' appears multiple times in a compilation unit"_err_en_US) 9379 .Attach(iter->first, "First definition of module"_en_US); 9380 return true; 9381 } 9382 modules.emplace(name, &progUnit); 9383 if (auto iter{uses.find(name)}; iter != uses.end()) { 9384 if (context().ShouldWarn(common::LanguageFeature::MiscUseExtensions)) { 9385 Say(name, 9386 "A USE statement referencing module '%s' appears earlier in this compilation unit"_port_en_US, 9387 name) 9388 .Attach(*iter, "First USE of module"_en_US); 9389 } 9390 disordered = true; 9391 } 9392 } 9393 for (SourceName used : common::visit( 9394 [](const auto &indUnit) { return GetUses(indUnit.value()); }, 9395 progUnit.u)) { 9396 uses.insert(used); 9397 } 9398 } 9399 if (!disordered) { 9400 return true; 9401 } 9402 // Process modules in topological order 9403 std::vector<const parser::ProgramUnit *> moduleOrder; 9404 while (!modules.empty()) { 9405 bool ok; 9406 for (const auto &pair : modules) { 9407 const SourceName &name{pair.first}; 9408 const parser::ProgramUnit &progUnit{*pair.second}; 9409 const parser::Module &m{ 9410 std::get<common::Indirection<parser::Module>>(progUnit.u).value()}; 9411 ok = true; 9412 for (const SourceName &use : GetUses(m)) { 9413 if (modules.find(use) != modules.end()) { 9414 ok = false; 9415 break; 9416 } 9417 } 9418 if (ok) { 9419 moduleOrder.push_back(&progUnit); 9420 modules.erase(name); 9421 break; 9422 } 9423 } 9424 if (!ok) { 9425 Message *msg{nullptr}; 9426 for (const auto &pair : modules) { 9427 if (msg) { 9428 msg->Attach(pair.first, "Module in a cycle"_en_US); 9429 } else { 9430 msg = &Say(pair.first, 9431 "Some modules in this compilation unit form one or more cycles of dependence"_err_en_US); 9432 } 9433 } 9434 return false; 9435 } 9436 } 9437 // Modules can be ordered. Process them first, and then all of the other 9438 // program units. 9439 for (const parser::ProgramUnit *progUnit : moduleOrder) { 9440 Walk(*progUnit); 9441 } 9442 for (const auto &progUnit : x.v) { 9443 if (!std::get_if<common::Indirection<parser::Module>>(&progUnit.u)) { 9444 Walk(progUnit); 9445 } 9446 } 9447 return false; 9448 } 9449 9450 // References to procedures need to record that their symbols are known 9451 // to be procedures, so that they don't get converted to objects by default. 9452 class ExecutionPartCallSkimmer : public ExecutionPartSkimmerBase { 9453 public: 9454 explicit ExecutionPartCallSkimmer(ResolveNamesVisitor &resolver) 9455 : resolver_{resolver} {} 9456 9457 void Walk(const parser::ExecutionPart &exec) { 9458 parser::Walk(exec, *this); 9459 EndWalk(); 9460 } 9461 9462 using ExecutionPartSkimmerBase::Post; 9463 using ExecutionPartSkimmerBase::Pre; 9464 9465 void Post(const parser::FunctionReference &fr) { 9466 NoteCall(Symbol::Flag::Function, fr.v, false); 9467 } 9468 void Post(const parser::CallStmt &cs) { 9469 NoteCall(Symbol::Flag::Subroutine, cs.call, cs.chevrons.has_value()); 9470 } 9471 9472 private: 9473 void NoteCall( 9474 Symbol::Flag flag, const parser::Call &call, bool hasCUDAChevrons) { 9475 auto &designator{std::get<parser::ProcedureDesignator>(call.t)}; 9476 if (const auto *name{std::get_if<parser::Name>(&designator.u)}) { 9477 if (!IsHidden(name->source)) { 9478 resolver_.NoteExecutablePartCall(flag, name->source, hasCUDAChevrons); 9479 } 9480 } 9481 } 9482 9483 ResolveNamesVisitor &resolver_; 9484 }; 9485 9486 // Build the scope tree and resolve names in the specification parts of this 9487 // node and its children 9488 void ResolveNamesVisitor::ResolveSpecificationParts(ProgramTree &node) { 9489 if (node.isSpecificationPartResolved()) { 9490 return; // been here already 9491 } 9492 node.set_isSpecificationPartResolved(); 9493 if (!BeginScopeForNode(node)) { 9494 return; // an error prevented scope from being created 9495 } 9496 Scope &scope{currScope()}; 9497 node.set_scope(scope); 9498 AddSubpNames(node); 9499 common::visit( 9500 [&](const auto *x) { 9501 if (x) { 9502 Walk(*x); 9503 } 9504 }, 9505 node.stmt()); 9506 Walk(node.spec()); 9507 bool inDeviceSubprogram = false; 9508 // If this is a function, convert result to an object. This is to prevent the 9509 // result from being converted later to a function symbol if it is called 9510 // inside the function. 9511 // If the result is function pointer, then ConvertToObjectEntity will not 9512 // convert the result to an object, and calling the symbol inside the function 9513 // will result in calls to the result pointer. 9514 // A function cannot be called recursively if RESULT was not used to define a 9515 // distinct result name (15.6.2.2 point 4.). 9516 if (Symbol * symbol{scope.symbol()}) { 9517 if (auto *details{symbol->detailsIf<SubprogramDetails>()}) { 9518 if (details->isFunction()) { 9519 ConvertToObjectEntity(const_cast<Symbol &>(details->result())); 9520 } 9521 // Check the current procedure is a device procedure to apply implicit 9522 // attribute at the end. 9523 if (auto attrs{details->cudaSubprogramAttrs()}) { 9524 if (*attrs == common::CUDASubprogramAttrs::Device || 9525 *attrs == common::CUDASubprogramAttrs::Global || 9526 *attrs == common::CUDASubprogramAttrs::Grid_Global) { 9527 inDeviceSubprogram = true; 9528 } 9529 } 9530 } 9531 } 9532 if (node.IsModule()) { 9533 ApplyDefaultAccess(); 9534 } 9535 for (auto &child : node.children()) { 9536 ResolveSpecificationParts(child); 9537 } 9538 if (node.exec()) { 9539 ExecutionPartCallSkimmer{*this}.Walk(*node.exec()); 9540 HandleImpliedAsynchronousInScope(node.exec()->v); 9541 } 9542 EndScopeForNode(node); 9543 // Ensure that every object entity has a type. 9544 bool inModule{node.GetKind() == ProgramTree::Kind::Module || 9545 node.GetKind() == ProgramTree::Kind::Submodule}; 9546 for (auto &pair : *node.scope()) { 9547 Symbol &symbol{*pair.second}; 9548 if (inModule && symbol.attrs().test(Attr::EXTERNAL) && !IsPointer(symbol) && 9549 !symbol.test(Symbol::Flag::Function) && 9550 !symbol.test(Symbol::Flag::Subroutine)) { 9551 // in a module, external proc without return type is subroutine 9552 symbol.set( 9553 symbol.GetType() ? Symbol::Flag::Function : Symbol::Flag::Subroutine); 9554 } 9555 ApplyImplicitRules(symbol); 9556 // Apply CUDA implicit attributes if needed. 9557 if (inDeviceSubprogram && symbol.has<ObjectEntityDetails>()) { 9558 auto *object{symbol.detailsIf<ObjectEntityDetails>()}; 9559 if (!object->cudaDataAttr() && !IsValue(symbol) && 9560 (IsDummy(symbol) || object->IsArray())) { 9561 // Implicitly set device attribute if none is set in device context. 9562 object->set_cudaDataAttr(common::CUDADataAttr::Device); 9563 } 9564 } 9565 } 9566 } 9567 9568 // Add SubprogramNameDetails symbols for module and internal subprograms and 9569 // their ENTRY statements. 9570 void ResolveNamesVisitor::AddSubpNames(ProgramTree &node) { 9571 auto kind{ 9572 node.IsModule() ? SubprogramKind::Module : SubprogramKind::Internal}; 9573 for (auto &child : node.children()) { 9574 auto &symbol{MakeSymbol(child.name(), SubprogramNameDetails{kind, child})}; 9575 if (child.HasModulePrefix()) { 9576 SetExplicitAttr(symbol, Attr::MODULE); 9577 } 9578 if (child.bindingSpec()) { 9579 SetExplicitAttr(symbol, Attr::BIND_C); 9580 } 9581 auto childKind{child.GetKind()}; 9582 if (childKind == ProgramTree::Kind::Function) { 9583 symbol.set(Symbol::Flag::Function); 9584 } else if (childKind == ProgramTree::Kind::Subroutine) { 9585 symbol.set(Symbol::Flag::Subroutine); 9586 } else { 9587 continue; // make ENTRY symbols only where valid 9588 } 9589 for (const auto &entryStmt : child.entryStmts()) { 9590 SubprogramNameDetails details{kind, child}; 9591 auto &symbol{ 9592 MakeSymbol(std::get<parser::Name>(entryStmt->t), std::move(details))}; 9593 symbol.set(child.GetSubpFlag()); 9594 if (child.HasModulePrefix()) { 9595 SetExplicitAttr(symbol, Attr::MODULE); 9596 } 9597 if (child.bindingSpec()) { 9598 SetExplicitAttr(symbol, Attr::BIND_C); 9599 } 9600 } 9601 } 9602 for (const auto &generic : node.genericSpecs()) { 9603 if (const auto *name{std::get_if<parser::Name>(&generic->u)}) { 9604 if (currScope().find(name->source) != currScope().end()) { 9605 // If this scope has both a generic interface and a contained 9606 // subprogram with the same name, create the generic's symbol 9607 // now so that any other generics of the same name that are pulled 9608 // into scope later via USE association will properly merge instead 9609 // of raising a bogus error due a conflict with the subprogram. 9610 CreateGeneric(*generic); 9611 } 9612 } 9613 } 9614 } 9615 9616 // Push a new scope for this node or return false on error. 9617 bool ResolveNamesVisitor::BeginScopeForNode(const ProgramTree &node) { 9618 switch (node.GetKind()) { 9619 SWITCH_COVERS_ALL_CASES 9620 case ProgramTree::Kind::Program: 9621 PushScope(Scope::Kind::MainProgram, 9622 &MakeSymbol(node.name(), MainProgramDetails{})); 9623 return true; 9624 case ProgramTree::Kind::Function: 9625 case ProgramTree::Kind::Subroutine: 9626 return BeginSubprogram(node.name(), node.GetSubpFlag(), 9627 node.HasModulePrefix(), node.bindingSpec(), &node.entryStmts()); 9628 case ProgramTree::Kind::MpSubprogram: 9629 return BeginMpSubprogram(node.name()); 9630 case ProgramTree::Kind::Module: 9631 BeginModule(node.name(), false); 9632 return true; 9633 case ProgramTree::Kind::Submodule: 9634 return BeginSubmodule(node.name(), node.GetParentId()); 9635 case ProgramTree::Kind::BlockData: 9636 PushBlockDataScope(node.name()); 9637 return true; 9638 } 9639 } 9640 9641 void ResolveNamesVisitor::EndScopeForNode(const ProgramTree &node) { 9642 std::optional<parser::CharBlock> stmtSource; 9643 const std::optional<parser::LanguageBindingSpec> *binding{nullptr}; 9644 common::visit( 9645 common::visitors{ 9646 [&](const parser::Statement<parser::FunctionStmt> *stmt) { 9647 if (stmt) { 9648 stmtSource = stmt->source; 9649 if (const auto &maybeSuffix{ 9650 std::get<std::optional<parser::Suffix>>( 9651 stmt->statement.t)}) { 9652 binding = &maybeSuffix->binding; 9653 } 9654 } 9655 }, 9656 [&](const parser::Statement<parser::SubroutineStmt> *stmt) { 9657 if (stmt) { 9658 stmtSource = stmt->source; 9659 binding = &std::get<std::optional<parser::LanguageBindingSpec>>( 9660 stmt->statement.t); 9661 } 9662 }, 9663 [](const auto *) {}, 9664 }, 9665 node.stmt()); 9666 EndSubprogram(stmtSource, binding, &node.entryStmts()); 9667 } 9668 9669 // Some analyses and checks, such as the processing of initializers of 9670 // pointers, are deferred until all of the pertinent specification parts 9671 // have been visited. This deferred processing enables the use of forward 9672 // references in these circumstances. 9673 // Data statement objects with implicit derived types are finally 9674 // resolved here. 9675 class DeferredCheckVisitor { 9676 public: 9677 explicit DeferredCheckVisitor(ResolveNamesVisitor &resolver) 9678 : resolver_{resolver} {} 9679 9680 template <typename A> void Walk(const A &x) { parser::Walk(x, *this); } 9681 9682 template <typename A> bool Pre(const A &) { return true; } 9683 template <typename A> void Post(const A &) {} 9684 9685 void Post(const parser::DerivedTypeStmt &x) { 9686 const auto &name{std::get<parser::Name>(x.t)}; 9687 if (Symbol * symbol{name.symbol}) { 9688 if (Scope * scope{symbol->scope()}) { 9689 if (scope->IsDerivedType()) { 9690 CHECK(outerScope_ == nullptr); 9691 outerScope_ = &resolver_.currScope(); 9692 resolver_.SetScope(*scope); 9693 } 9694 } 9695 } 9696 } 9697 void Post(const parser::EndTypeStmt &) { 9698 if (outerScope_) { 9699 resolver_.SetScope(*outerScope_); 9700 outerScope_ = nullptr; 9701 } 9702 } 9703 9704 void Post(const parser::ProcInterface &pi) { 9705 if (const auto *name{std::get_if<parser::Name>(&pi.u)}) { 9706 resolver_.CheckExplicitInterface(*name); 9707 } 9708 } 9709 bool Pre(const parser::EntityDecl &decl) { 9710 Init(std::get<parser::Name>(decl.t), 9711 std::get<std::optional<parser::Initialization>>(decl.t)); 9712 return false; 9713 } 9714 bool Pre(const parser::ComponentDecl &decl) { 9715 Init(std::get<parser::Name>(decl.t), 9716 std::get<std::optional<parser::Initialization>>(decl.t)); 9717 return false; 9718 } 9719 bool Pre(const parser::ProcDecl &decl) { 9720 if (const auto &init{ 9721 std::get<std::optional<parser::ProcPointerInit>>(decl.t)}) { 9722 resolver_.PointerInitialization(std::get<parser::Name>(decl.t), *init); 9723 } 9724 return false; 9725 } 9726 void Post(const parser::TypeBoundProcedureStmt::WithInterface &tbps) { 9727 resolver_.CheckExplicitInterface(tbps.interfaceName); 9728 } 9729 void Post(const parser::TypeBoundProcedureStmt::WithoutInterface &tbps) { 9730 if (outerScope_) { 9731 resolver_.CheckBindings(tbps); 9732 } 9733 } 9734 bool Pre(const parser::DataStmtObject &) { 9735 ++dataStmtObjectNesting_; 9736 return true; 9737 } 9738 void Post(const parser::DataStmtObject &) { --dataStmtObjectNesting_; } 9739 void Post(const parser::Designator &x) { 9740 if (dataStmtObjectNesting_ > 0) { 9741 resolver_.ResolveDesignator(x); 9742 } 9743 } 9744 9745 private: 9746 void Init(const parser::Name &name, 9747 const std::optional<parser::Initialization> &init) { 9748 if (init) { 9749 if (const auto *target{ 9750 std::get_if<parser::InitialDataTarget>(&init->u)}) { 9751 resolver_.PointerInitialization(name, *target); 9752 } else if (const auto *expr{ 9753 std::get_if<parser::ConstantExpr>(&init->u)}) { 9754 if (name.symbol) { 9755 if (const auto *object{name.symbol->detailsIf<ObjectEntityDetails>()}; 9756 !object || !object->init()) { 9757 resolver_.NonPointerInitialization(name, *expr); 9758 } 9759 } 9760 } 9761 } 9762 } 9763 9764 ResolveNamesVisitor &resolver_; 9765 Scope *outerScope_{nullptr}; 9766 int dataStmtObjectNesting_{0}; 9767 }; 9768 9769 // Perform checks and completions that need to happen after all of 9770 // the specification parts but before any of the execution parts. 9771 void ResolveNamesVisitor::FinishSpecificationParts(const ProgramTree &node) { 9772 if (!node.scope()) { 9773 return; // error occurred creating scope 9774 } 9775 auto flagRestorer{common::ScopedSet(inSpecificationPart_, true)}; 9776 SetScope(*node.scope()); 9777 // The initializers of pointers and non-PARAMETER objects, the default 9778 // initializers of components, and non-deferred type-bound procedure 9779 // bindings have not yet been traversed. 9780 // We do that now, when any forward references that appeared 9781 // in those initializers will resolve to the right symbols without 9782 // incurring spurious errors with IMPLICIT NONE or forward references 9783 // to nested subprograms. 9784 DeferredCheckVisitor{*this}.Walk(node.spec()); 9785 for (Scope &childScope : currScope().children()) { 9786 if (childScope.IsParameterizedDerivedTypeInstantiation()) { 9787 FinishDerivedTypeInstantiation(childScope); 9788 } 9789 } 9790 for (const auto &child : node.children()) { 9791 FinishSpecificationParts(child); 9792 } 9793 } 9794 9795 void ResolveNamesVisitor::FinishExecutionParts(const ProgramTree &node) { 9796 if (node.scope()) { 9797 SetScope(*node.scope()); 9798 if (node.exec()) { 9799 DeferredCheckVisitor{*this}.Walk(*node.exec()); 9800 } 9801 for (const auto &child : node.children()) { 9802 FinishExecutionParts(child); 9803 } 9804 } 9805 } 9806 9807 // Duplicate and fold component object pointer default initializer designators 9808 // using the actual type parameter values of each particular instantiation. 9809 // Validation is done later in declaration checking. 9810 void ResolveNamesVisitor::FinishDerivedTypeInstantiation(Scope &scope) { 9811 CHECK(scope.IsDerivedType() && !scope.symbol()); 9812 if (DerivedTypeSpec * spec{scope.derivedTypeSpec()}) { 9813 spec->Instantiate(currScope()); 9814 const Symbol &origTypeSymbol{spec->typeSymbol()}; 9815 if (const Scope * origTypeScope{origTypeSymbol.scope()}) { 9816 CHECK(origTypeScope->IsDerivedType() && 9817 origTypeScope->symbol() == &origTypeSymbol); 9818 auto &foldingContext{GetFoldingContext()}; 9819 auto restorer{foldingContext.WithPDTInstance(*spec)}; 9820 for (auto &pair : scope) { 9821 Symbol &comp{*pair.second}; 9822 const Symbol &origComp{DEREF(FindInScope(*origTypeScope, comp.name()))}; 9823 if (IsPointer(comp)) { 9824 if (auto *details{comp.detailsIf<ObjectEntityDetails>()}) { 9825 auto origDetails{origComp.get<ObjectEntityDetails>()}; 9826 if (const MaybeExpr & init{origDetails.init()}) { 9827 SomeExpr newInit{*init}; 9828 MaybeExpr folded{FoldExpr(std::move(newInit))}; 9829 details->set_init(std::move(folded)); 9830 } 9831 } 9832 } 9833 } 9834 } 9835 } 9836 } 9837 9838 // Resolve names in the execution part of this node and its children 9839 void ResolveNamesVisitor::ResolveExecutionParts(const ProgramTree &node) { 9840 if (!node.scope()) { 9841 return; // error occurred creating scope 9842 } 9843 SetScope(*node.scope()); 9844 if (const auto *exec{node.exec()}) { 9845 Walk(*exec); 9846 } 9847 FinishNamelists(); 9848 if (node.IsModule()) { 9849 // A second final pass to catch new symbols added from implicitly 9850 // typed names in NAMELIST groups or the specification parts of 9851 // module subprograms. 9852 ApplyDefaultAccess(); 9853 } 9854 PopScope(); // converts unclassified entities into objects 9855 for (const auto &child : node.children()) { 9856 ResolveExecutionParts(child); 9857 } 9858 } 9859 9860 void ResolveNamesVisitor::Post(const parser::Program &x) { 9861 // ensure that all temps were deallocated 9862 CHECK(!attrs_); 9863 CHECK(!cudaDataAttr_); 9864 CHECK(!GetDeclTypeSpec()); 9865 // Top-level resolution to propagate information across program units after 9866 // each of them has been resolved separately. 9867 ResolveOmpTopLevelParts(context(), x); 9868 } 9869 9870 // A singleton instance of the scope -> IMPLICIT rules mapping is 9871 // shared by all instances of ResolveNamesVisitor and accessed by this 9872 // pointer when the visitors (other than the top-level original) are 9873 // constructed. 9874 static ImplicitRulesMap *sharedImplicitRulesMap{nullptr}; 9875 9876 bool ResolveNames( 9877 SemanticsContext &context, const parser::Program &program, Scope &top) { 9878 ImplicitRulesMap implicitRulesMap; 9879 auto restorer{common::ScopedSet(sharedImplicitRulesMap, &implicitRulesMap)}; 9880 ResolveNamesVisitor{context, implicitRulesMap, top}.Walk(program); 9881 return !context.AnyFatalError(); 9882 } 9883 9884 // Processes a module (but not internal) function when it is referenced 9885 // in a specification expression in a sibling procedure. 9886 void ResolveSpecificationParts( 9887 SemanticsContext &context, const Symbol &subprogram) { 9888 auto originalLocation{context.location()}; 9889 ImplicitRulesMap implicitRulesMap; 9890 bool localImplicitRulesMap{false}; 9891 if (!sharedImplicitRulesMap) { 9892 sharedImplicitRulesMap = &implicitRulesMap; 9893 localImplicitRulesMap = true; 9894 } 9895 ResolveNamesVisitor visitor{ 9896 context, *sharedImplicitRulesMap, context.globalScope()}; 9897 const auto &details{subprogram.get<SubprogramNameDetails>()}; 9898 ProgramTree &node{details.node()}; 9899 const Scope &moduleScope{subprogram.owner()}; 9900 if (localImplicitRulesMap) { 9901 visitor.BeginScope(const_cast<Scope &>(moduleScope)); 9902 } else { 9903 visitor.SetScope(const_cast<Scope &>(moduleScope)); 9904 } 9905 visitor.ResolveSpecificationParts(node); 9906 context.set_location(std::move(originalLocation)); 9907 if (localImplicitRulesMap) { 9908 sharedImplicitRulesMap = nullptr; 9909 } 9910 } 9911 9912 } // namespace Fortran::semantics 9913