Debian Codegraph @

flang/lib/Semantics/resolve-names.cpp

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