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