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