1 //===-- lib/Semantics/expression.cpp --------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "flang/Semantics/expression.h"
10 #include "check-call.h"
11 #include "pointer-assignment.h"
12 #include "resolve-names-utils.h"
13 #include "resolve-names.h"
14 #include "flang/Common/Fortran.h"
15 #include "flang/Common/idioms.h"
16 #include "flang/Evaluate/common.h"
17 #include "flang/Evaluate/fold.h"
18 #include "flang/Evaluate/tools.h"
19 #include "flang/Parser/characters.h"
20 #include "flang/Parser/dump-parse-tree.h"
21 #include "flang/Parser/parse-tree-visitor.h"
22 #include "flang/Parser/parse-tree.h"
23 #include "flang/Semantics/scope.h"
24 #include "flang/Semantics/semantics.h"
25 #include "flang/Semantics/symbol.h"
26 #include "flang/Semantics/tools.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <algorithm>
29 #include <functional>
30 #include <optional>
31 #include <set>
32 
33 // Typedef for optional generic expressions (ubiquitous in this file)
34 using MaybeExpr =
35     std::optional<Fortran::evaluate::Expr<Fortran::evaluate::SomeType>>;
36 
37 // Much of the code that implements semantic analysis of expressions is
38 // tightly coupled with their typed representations in lib/Evaluate,
39 // and appears here in namespace Fortran::evaluate for convenience.
40 namespace Fortran::evaluate {
41 
42 using common::LanguageFeature;
43 using common::NumericOperator;
44 using common::TypeCategory;
45 
46 static inline std::string ToUpperCase(const std::string &str) {
47   return parser::ToUpperCaseLetters(str);
48 }
49 
50 struct DynamicTypeWithLength : public DynamicType {
51   explicit DynamicTypeWithLength(const DynamicType &t) : DynamicType{t} {}
52   std::optional<Expr<SubscriptInteger>> LEN() const;
53   std::optional<Expr<SubscriptInteger>> length;
54 };
55 
56 std::optional<Expr<SubscriptInteger>> DynamicTypeWithLength::LEN() const {
57   if (length) {
58     return length;
59   } else {
60     return GetCharLength();
61   }
62 }
63 
64 static std::optional<DynamicTypeWithLength> AnalyzeTypeSpec(
65     const std::optional<parser::TypeSpec> &spec) {
66   if (spec) {
67     if (const semantics::DeclTypeSpec * typeSpec{spec->declTypeSpec}) {
68       // Name resolution sets TypeSpec::declTypeSpec only when it's valid
69       // (viz., an intrinsic type with valid known kind or a non-polymorphic
70       // & non-ABSTRACT derived type).
71       if (const semantics::IntrinsicTypeSpec *
72           intrinsic{typeSpec->AsIntrinsic()}) {
73         TypeCategory category{intrinsic->category()};
74         if (auto optKind{ToInt64(intrinsic->kind())}) {
75           int kind{static_cast<int>(*optKind)};
76           if (category == TypeCategory::Character) {
77             const semantics::CharacterTypeSpec &cts{
78                 typeSpec->characterTypeSpec()};
79             const semantics::ParamValue &len{cts.length()};
80             // N.B. CHARACTER(LEN=*) is allowed in type-specs in ALLOCATE() &
81             // type guards, but not in array constructors.
82             return DynamicTypeWithLength{DynamicType{kind, len}};
83           } else {
84             return DynamicTypeWithLength{DynamicType{category, kind}};
85           }
86         }
87       } else if (const semantics::DerivedTypeSpec *
88           derived{typeSpec->AsDerived()}) {
89         return DynamicTypeWithLength{DynamicType{*derived}};
90       }
91     }
92   }
93   return std::nullopt;
94 }
95 
96 // Utilities to set a source location, if we have one, on an actual argument,
97 // when it is statically present.
98 static void SetArgSourceLocation(ActualArgument &x, parser::CharBlock at) {
99   x.set_sourceLocation(at);
100 }
101 static void SetArgSourceLocation(
102     std::optional<ActualArgument> &x, parser::CharBlock at) {
103   if (x) {
104     x->set_sourceLocation(at);
105   }
106 }
107 static void SetArgSourceLocation(
108     std::optional<ActualArgument> &x, std::optional<parser::CharBlock> at) {
109   if (x && at) {
110     x->set_sourceLocation(*at);
111   }
112 }
113 
114 class ArgumentAnalyzer {
115 public:
116   explicit ArgumentAnalyzer(ExpressionAnalyzer &context)
117       : context_{context}, source_{context.GetContextualMessages().at()},
118         isProcedureCall_{false} {}
119   ArgumentAnalyzer(ExpressionAnalyzer &context, parser::CharBlock source,
120       bool isProcedureCall = false)
121       : context_{context}, source_{source}, isProcedureCall_{isProcedureCall} {}
122   bool fatalErrors() const { return fatalErrors_; }
123   ActualArguments &&GetActuals() {
124     CHECK(!fatalErrors_);
125     return std::move(actuals_);
126   }
127   const Expr<SomeType> &GetExpr(std::size_t i) const {
128     return DEREF(actuals_.at(i).value().UnwrapExpr());
129   }
130   Expr<SomeType> &&MoveExpr(std::size_t i) {
131     return std::move(DEREF(actuals_.at(i).value().UnwrapExpr()));
132   }
133   void Analyze(const common::Indirection<parser::Expr> &x) {
134     Analyze(x.value());
135   }
136   void Analyze(const parser::Expr &x) {
137     actuals_.emplace_back(AnalyzeExpr(x));
138     SetArgSourceLocation(actuals_.back(), x.source);
139     fatalErrors_ |= !actuals_.back();
140   }
141   void Analyze(const parser::Variable &);
142   void Analyze(const parser::ActualArgSpec &, bool isSubroutine);
143   void ConvertBOZ(std::optional<DynamicType> &thisType, std::size_t i,
144       std::optional<DynamicType> otherType);
145 
146   bool IsIntrinsicRelational(
147       RelationalOperator, const DynamicType &, const DynamicType &) const;
148   bool IsIntrinsicLogical() const;
149   bool IsIntrinsicNumeric(NumericOperator) const;
150   bool IsIntrinsicConcat() const;
151 
152   bool CheckConformance();
153   bool CheckForNullPointer(const char *where = "as an operand here");
154 
155   // Find and return a user-defined operator or report an error.
156   // The provided message is used if there is no such operator.
157   MaybeExpr TryDefinedOp(const char *, parser::MessageFixedText,
158       const Symbol **definedOpSymbolPtr = nullptr, bool isUserOp = false);
159   template <typename E>
160   MaybeExpr TryDefinedOp(E opr, parser::MessageFixedText msg) {
161     return TryDefinedOp(
162         context_.context().languageFeatures().GetNames(opr), msg);
163   }
164   // Find and return a user-defined assignment
165   std::optional<ProcedureRef> TryDefinedAssignment();
166   std::optional<ProcedureRef> GetDefinedAssignmentProc();
167   std::optional<DynamicType> GetType(std::size_t) const;
168   void Dump(llvm::raw_ostream &);
169 
170 private:
171   MaybeExpr TryDefinedOp(std::vector<const char *>, parser::MessageFixedText);
172   MaybeExpr TryBoundOp(const Symbol &, int passIndex);
173   std::optional<ActualArgument> AnalyzeExpr(const parser::Expr &);
174   MaybeExpr AnalyzeExprOrWholeAssumedSizeArray(const parser::Expr &);
175   bool AreConformable() const;
176   const Symbol *FindBoundOp(
177       parser::CharBlock, int passIndex, const Symbol *&definedOp);
178   void AddAssignmentConversion(
179       const DynamicType &lhsType, const DynamicType &rhsType);
180   bool OkLogicalIntegerAssignment(TypeCategory lhs, TypeCategory rhs);
181   int GetRank(std::size_t) const;
182   bool IsBOZLiteral(std::size_t i) const {
183     return evaluate::IsBOZLiteral(GetExpr(i));
184   }
185   void SayNoMatch(const std::string &, bool isAssignment = false);
186   std::string TypeAsFortran(std::size_t);
187   bool AnyUntypedOrMissingOperand();
188 
189   ExpressionAnalyzer &context_;
190   ActualArguments actuals_;
191   parser::CharBlock source_;
192   bool fatalErrors_{false};
193   const bool isProcedureCall_; // false for user-defined op or assignment
194 };
195 
196 // Wraps a data reference in a typed Designator<>, and a procedure
197 // or procedure pointer reference in a ProcedureDesignator.
198 MaybeExpr ExpressionAnalyzer::Designate(DataRef &&ref) {
199   const Symbol &last{ref.GetLastSymbol()};
200   const Symbol &symbol{BypassGeneric(last).GetUltimate()};
201   if (semantics::IsProcedure(symbol)) {
202     if (auto *component{std::get_if<Component>(&ref.u)}) {
203       return Expr<SomeType>{ProcedureDesignator{std::move(*component)}};
204     } else if (!std::holds_alternative<SymbolRef>(ref.u)) {
205       DIE("unexpected alternative in DataRef");
206     } else if (!symbol.attrs().test(semantics::Attr::INTRINSIC)) {
207       if (symbol.has<semantics::GenericDetails>()) {
208         Say("'%s' is not a specific procedure"_err_en_US, symbol.name());
209       } else {
210         return Expr<SomeType>{ProcedureDesignator{symbol}};
211       }
212     } else if (auto interface{context_.intrinsics().IsSpecificIntrinsicFunction(
213                    symbol.name().ToString())};
214                interface && !interface->isRestrictedSpecific) {
215       SpecificIntrinsic intrinsic{
216           symbol.name().ToString(), std::move(*interface)};
217       intrinsic.isRestrictedSpecific = interface->isRestrictedSpecific;
218       return Expr<SomeType>{ProcedureDesignator{std::move(intrinsic)}};
219     } else {
220       Say("'%s' is not an unrestricted specific intrinsic procedure"_err_en_US,
221           symbol.name());
222     }
223     return std::nullopt;
224   } else if (MaybeExpr result{AsGenericExpr(std::move(ref))}) {
225     return result;
226   } else {
227     if (!context_.HasError(last) && !context_.HasError(symbol)) {
228       AttachDeclaration(
229           Say("'%s' is not an object that can appear in an expression"_err_en_US,
230               last.name()),
231           symbol);
232       context_.SetError(last);
233     }
234     return std::nullopt;
235   }
236 }
237 
238 // Some subscript semantic checks must be deferred until all of the
239 // subscripts are in hand.
240 MaybeExpr ExpressionAnalyzer::CompleteSubscripts(ArrayRef &&ref) {
241   const Symbol &symbol{ref.GetLastSymbol().GetUltimate()};
242   int symbolRank{symbol.Rank()};
243   int subscripts{static_cast<int>(ref.size())};
244   if (subscripts == 0) {
245     return std::nullopt; // error recovery
246   } else if (subscripts != symbolRank) {
247     if (symbolRank != 0) {
248       Say("Reference to rank-%d object '%s' has %d subscripts"_err_en_US,
249           symbolRank, symbol.name(), subscripts);
250     }
251     return std::nullopt;
252   } else if (Component * component{ref.base().UnwrapComponent()}) {
253     int baseRank{component->base().Rank()};
254     if (baseRank > 0) {
255       int subscriptRank{0};
256       for (const auto &expr : ref.subscript()) {
257         subscriptRank += expr.Rank();
258       }
259       if (subscriptRank > 0) { // C919a
260         Say("Subscripts of component '%s' of rank-%d derived type "
261             "array have rank %d but must all be scalar"_err_en_US,
262             symbol.name(), baseRank, subscriptRank);
263         return std::nullopt;
264       }
265     }
266   } else if (const auto *object{
267                  symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
268     // C928 & C1002
269     if (Triplet * last{std::get_if<Triplet>(&ref.subscript().back().u)}) {
270       if (!last->upper() && object->IsAssumedSize()) {
271         Say("Assumed-size array '%s' must have explicit final "
272             "subscript upper bound value"_err_en_US,
273             symbol.name());
274         return std::nullopt;
275       }
276     }
277   } else {
278     // Shouldn't get here from Analyze(ArrayElement) without a valid base,
279     // which, if not an object, must be a construct entity from
280     // SELECT TYPE/RANK or ASSOCIATE.
281     CHECK(symbol.has<semantics::AssocEntityDetails>());
282   }
283   return Designate(DataRef{std::move(ref)});
284 }
285 
286 // Applies subscripts to a data reference.
287 MaybeExpr ExpressionAnalyzer::ApplySubscripts(
288     DataRef &&dataRef, std::vector<Subscript> &&subscripts) {
289   if (subscripts.empty()) {
290     return std::nullopt; // error recovery
291   }
292   return common::visit(
293       common::visitors{
294           [&](SymbolRef &&symbol) {
295             return CompleteSubscripts(ArrayRef{symbol, std::move(subscripts)});
296           },
297           [&](Component &&c) {
298             return CompleteSubscripts(
299                 ArrayRef{std::move(c), std::move(subscripts)});
300           },
301           [&](auto &&) -> MaybeExpr {
302             DIE("bad base for ArrayRef");
303             return std::nullopt;
304           },
305       },
306       std::move(dataRef.u));
307 }
308 
309 // Top-level checks for data references.
310 MaybeExpr ExpressionAnalyzer::TopLevelChecks(DataRef &&dataRef) {
311   if (Component * component{std::get_if<Component>(&dataRef.u)}) {
312     const Symbol &symbol{component->GetLastSymbol()};
313     int componentRank{symbol.Rank()};
314     if (componentRank > 0) {
315       int baseRank{component->base().Rank()};
316       if (baseRank > 0) { // C919a
317         Say("Reference to whole rank-%d component '%%%s' of "
318             "rank-%d array of derived type is not allowed"_err_en_US,
319             componentRank, symbol.name(), baseRank);
320       }
321     }
322   }
323   return Designate(std::move(dataRef));
324 }
325 
326 // Parse tree correction after a substring S(j:k) was misparsed as an
327 // array section.  N.B. Fortran substrings have to have a range, not a
328 // single index.
329 static void FixMisparsedSubstring(const parser::Designator &d) {
330   auto &mutate{const_cast<parser::Designator &>(d)};
331   if (auto *dataRef{std::get_if<parser::DataRef>(&mutate.u)}) {
332     if (auto *ae{std::get_if<common::Indirection<parser::ArrayElement>>(
333             &dataRef->u)}) {
334       parser::ArrayElement &arrElement{ae->value()};
335       if (!arrElement.subscripts.empty()) {
336         auto iter{arrElement.subscripts.begin()};
337         if (auto *triplet{std::get_if<parser::SubscriptTriplet>(&iter->u)}) {
338           if (!std::get<2>(triplet->t) /* no stride */ &&
339               ++iter == arrElement.subscripts.end() /* one subscript */) {
340             if (Symbol *
341                 symbol{common::visit(
342                     common::visitors{
343                         [](parser::Name &n) { return n.symbol; },
344                         [](common::Indirection<parser::StructureComponent>
345                                 &sc) { return sc.value().component.symbol; },
346                         [](auto &) -> Symbol * { return nullptr; },
347                     },
348                     arrElement.base.u)}) {
349               const Symbol &ultimate{symbol->GetUltimate()};
350               if (const semantics::DeclTypeSpec * type{ultimate.GetType()}) {
351                 if (!ultimate.IsObjectArray() &&
352                     type->category() == semantics::DeclTypeSpec::Character) {
353                   // The ambiguous S(j:k) was parsed as an array section
354                   // reference, but it's now clear that it's a substring.
355                   // Fix the parse tree in situ.
356                   mutate.u = arrElement.ConvertToSubstring();
357                 }
358               }
359             }
360           }
361         }
362       }
363     }
364   }
365 }
366 
367 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Designator &d) {
368   auto restorer{GetContextualMessages().SetLocation(d.source)};
369   FixMisparsedSubstring(d);
370   // These checks have to be deferred to these "top level" data-refs where
371   // we can be sure that there are no following subscripts (yet).
372   // Substrings have already been run through TopLevelChecks() and
373   // won't be returned by ExtractDataRef().
374   if (MaybeExpr result{Analyze(d.u)}) {
375     if (std::optional<DataRef> dataRef{ExtractDataRef(std::move(result))}) {
376       return TopLevelChecks(std::move(*dataRef));
377     }
378     return result;
379   }
380   return std::nullopt;
381 }
382 
383 // A utility subroutine to repackage optional expressions of various levels
384 // of type specificity as fully general MaybeExpr values.
385 template <typename A> common::IfNoLvalue<MaybeExpr, A> AsMaybeExpr(A &&x) {
386   return AsGenericExpr(std::move(x));
387 }
388 template <typename A> MaybeExpr AsMaybeExpr(std::optional<A> &&x) {
389   if (x) {
390     return AsMaybeExpr(std::move(*x));
391   }
392   return std::nullopt;
393 }
394 
395 // Type kind parameter values for literal constants.
396 int ExpressionAnalyzer::AnalyzeKindParam(
397     const std::optional<parser::KindParam> &kindParam, int defaultKind) {
398   if (!kindParam) {
399     return defaultKind;
400   }
401   return common::visit(
402       common::visitors{
403           [](std::uint64_t k) { return static_cast<int>(k); },
404           [&](const parser::Scalar<
405               parser::Integer<parser::Constant<parser::Name>>> &n) {
406             if (MaybeExpr ie{Analyze(n)}) {
407               if (std::optional<std::int64_t> i64{ToInt64(*ie)}) {
408                 int iv = *i64;
409                 if (iv == *i64) {
410                   return iv;
411                 }
412               }
413             }
414             return defaultKind;
415           },
416       },
417       kindParam->u);
418 }
419 
420 // Common handling of parser::IntLiteralConstant and SignedIntLiteralConstant
421 struct IntTypeVisitor {
422   using Result = MaybeExpr;
423   using Types = IntegerTypes;
424   template <typename T> Result Test() {
425     if (T::kind >= kind) {
426       const char *p{digits.begin()};
427       using Int = typename T::Scalar;
428       typename Int::ValueWithOverflow num{0, false};
429       if (isNegated) {
430         auto unsignedNum{Int::Read(p, 10, false /*unsigned*/)};
431         num.value = unsignedNum.value.Negate().value;
432         num.overflow = unsignedNum.overflow || num.value > Int{0};
433         if (!num.overflow && num.value.Negate().overflow &&
434             !analyzer.context().IsInModuleFile(digits)) {
435           analyzer.Say(digits,
436               "negated maximum INTEGER(KIND=%d) literal"_port_en_US, T::kind);
437         }
438       } else {
439         num = Int::Read(p, 10, true /*signed*/);
440       }
441       if (!num.overflow) {
442         if (T::kind > kind) {
443           if (!isDefaultKind ||
444               !analyzer.context().IsEnabled(LanguageFeature::BigIntLiterals)) {
445             return std::nullopt;
446           } else if (analyzer.context().ShouldWarn(
447                          LanguageFeature::BigIntLiterals)) {
448             analyzer.Say(digits,
449                 "Integer literal is too large for default INTEGER(KIND=%d); "
450                 "assuming INTEGER(KIND=%d)"_port_en_US,
451                 kind, T::kind);
452           }
453         }
454         return Expr<SomeType>{
455             Expr<SomeInteger>{Expr<T>{Constant<T>{std::move(num.value)}}}};
456       }
457     }
458     return std::nullopt;
459   }
460   ExpressionAnalyzer &analyzer;
461   parser::CharBlock digits;
462   int kind;
463   bool isDefaultKind;
464   bool isNegated;
465 };
466 
467 template <typename PARSED>
468 MaybeExpr ExpressionAnalyzer::IntLiteralConstant(
469     const PARSED &x, bool isNegated) {
470   const auto &kindParam{std::get<std::optional<parser::KindParam>>(x.t)};
471   bool isDefaultKind{!kindParam};
472   int kind{AnalyzeKindParam(kindParam, GetDefaultKind(TypeCategory::Integer))};
473   if (CheckIntrinsicKind(TypeCategory::Integer, kind)) {
474     auto digits{std::get<parser::CharBlock>(x.t)};
475     if (MaybeExpr result{common::SearchTypes(
476             IntTypeVisitor{*this, digits, kind, isDefaultKind, isNegated})}) {
477       return result;
478     } else if (isDefaultKind) {
479       Say(digits,
480           "Integer literal is too large for any allowable "
481           "kind of INTEGER"_err_en_US);
482     } else {
483       Say(digits, "Integer literal is too large for INTEGER(KIND=%d)"_err_en_US,
484           kind);
485     }
486   }
487   return std::nullopt;
488 }
489 
490 MaybeExpr ExpressionAnalyzer::Analyze(
491     const parser::IntLiteralConstant &x, bool isNegated) {
492   auto restorer{
493       GetContextualMessages().SetLocation(std::get<parser::CharBlock>(x.t))};
494   return IntLiteralConstant(x, isNegated);
495 }
496 
497 MaybeExpr ExpressionAnalyzer::Analyze(
498     const parser::SignedIntLiteralConstant &x) {
499   auto restorer{GetContextualMessages().SetLocation(x.source)};
500   return IntLiteralConstant(x);
501 }
502 
503 template <typename TYPE>
504 Constant<TYPE> ReadRealLiteral(
505     parser::CharBlock source, FoldingContext &context) {
506   const char *p{source.begin()};
507   auto valWithFlags{Scalar<TYPE>::Read(p, context.rounding())};
508   CHECK(p == source.end());
509   RealFlagWarnings(context, valWithFlags.flags, "conversion of REAL literal");
510   auto value{valWithFlags.value};
511   if (context.flushSubnormalsToZero()) {
512     value = value.FlushSubnormalToZero();
513   }
514   return {value};
515 }
516 
517 struct RealTypeVisitor {
518   using Result = std::optional<Expr<SomeReal>>;
519   using Types = RealTypes;
520 
521   RealTypeVisitor(int k, parser::CharBlock lit, FoldingContext &ctx)
522       : kind{k}, literal{lit}, context{ctx} {}
523 
524   template <typename T> Result Test() {
525     if (kind == T::kind) {
526       return {AsCategoryExpr(ReadRealLiteral<T>(literal, context))};
527     }
528     return std::nullopt;
529   }
530 
531   int kind;
532   parser::CharBlock literal;
533   FoldingContext &context;
534 };
535 
536 // Reads a real literal constant and encodes it with the right kind.
537 MaybeExpr ExpressionAnalyzer::Analyze(const parser::RealLiteralConstant &x) {
538   // Use a local message context around the real literal for better
539   // provenance on any messages.
540   auto restorer{GetContextualMessages().SetLocation(x.real.source)};
541   // If a kind parameter appears, it defines the kind of the literal and the
542   // letter used in an exponent part must be 'E' (e.g., the 'E' in
543   // "6.02214E+23").  In the absence of an explicit kind parameter, any
544   // exponent letter determines the kind.  Otherwise, defaults apply.
545   auto &defaults{context_.defaultKinds()};
546   int defaultKind{defaults.GetDefaultKind(TypeCategory::Real)};
547   const char *end{x.real.source.end()};
548   char expoLetter{' '};
549   std::optional<int> letterKind;
550   for (const char *p{x.real.source.begin()}; p < end; ++p) {
551     if (parser::IsLetter(*p)) {
552       expoLetter = *p;
553       switch (expoLetter) {
554       case 'e':
555         letterKind = defaults.GetDefaultKind(TypeCategory::Real);
556         break;
557       case 'd':
558         letterKind = defaults.doublePrecisionKind();
559         break;
560       case 'q':
561         letterKind = defaults.quadPrecisionKind();
562         break;
563       default:
564         Say("Unknown exponent letter '%c'"_err_en_US, expoLetter);
565       }
566       break;
567     }
568   }
569   if (letterKind) {
570     defaultKind = *letterKind;
571   }
572   // C716 requires 'E' as an exponent, but this is more useful
573   auto kind{AnalyzeKindParam(x.kind, defaultKind)};
574   if (letterKind && kind != *letterKind && expoLetter != 'e') {
575     Say("Explicit kind parameter on real constant disagrees with "
576         "exponent letter '%c'"_port_en_US,
577         expoLetter);
578   }
579   auto result{common::SearchTypes(
580       RealTypeVisitor{kind, x.real.source, GetFoldingContext()})};
581   if (!result) { // C717
582     Say("Unsupported REAL(KIND=%d)"_err_en_US, kind);
583   }
584   return AsMaybeExpr(std::move(result));
585 }
586 
587 MaybeExpr ExpressionAnalyzer::Analyze(
588     const parser::SignedRealLiteralConstant &x) {
589   if (auto result{Analyze(std::get<parser::RealLiteralConstant>(x.t))}) {
590     auto &realExpr{std::get<Expr<SomeReal>>(result->u)};
591     if (auto sign{std::get<std::optional<parser::Sign>>(x.t)}) {
592       if (sign == parser::Sign::Negative) {
593         return AsGenericExpr(-std::move(realExpr));
594       }
595     }
596     return result;
597   }
598   return std::nullopt;
599 }
600 
601 MaybeExpr ExpressionAnalyzer::Analyze(
602     const parser::SignedComplexLiteralConstant &x) {
603   auto result{Analyze(std::get<parser::ComplexLiteralConstant>(x.t))};
604   if (!result) {
605     return std::nullopt;
606   } else if (std::get<parser::Sign>(x.t) == parser::Sign::Negative) {
607     return AsGenericExpr(-std::move(std::get<Expr<SomeComplex>>(result->u)));
608   } else {
609     return result;
610   }
611 }
612 
613 MaybeExpr ExpressionAnalyzer::Analyze(const parser::ComplexPart &x) {
614   return Analyze(x.u);
615 }
616 
617 MaybeExpr ExpressionAnalyzer::Analyze(const parser::ComplexLiteralConstant &z) {
618   return AsMaybeExpr(
619       ConstructComplex(GetContextualMessages(), Analyze(std::get<0>(z.t)),
620           Analyze(std::get<1>(z.t)), GetDefaultKind(TypeCategory::Real)));
621 }
622 
623 // CHARACTER literal processing.
624 MaybeExpr ExpressionAnalyzer::AnalyzeString(std::string &&string, int kind) {
625   if (!CheckIntrinsicKind(TypeCategory::Character, kind)) {
626     return std::nullopt;
627   }
628   switch (kind) {
629   case 1:
630     return AsGenericExpr(Constant<Type<TypeCategory::Character, 1>>{
631         parser::DecodeString<std::string, parser::Encoding::LATIN_1>(
632             string, true)});
633   case 2:
634     return AsGenericExpr(Constant<Type<TypeCategory::Character, 2>>{
635         parser::DecodeString<std::u16string, parser::Encoding::UTF_8>(
636             string, true)});
637   case 4:
638     return AsGenericExpr(Constant<Type<TypeCategory::Character, 4>>{
639         parser::DecodeString<std::u32string, parser::Encoding::UTF_8>(
640             string, true)});
641   default:
642     CRASH_NO_CASE;
643   }
644 }
645 
646 MaybeExpr ExpressionAnalyzer::Analyze(const parser::CharLiteralConstant &x) {
647   int kind{
648       AnalyzeKindParam(std::get<std::optional<parser::KindParam>>(x.t), 1)};
649   auto value{std::get<std::string>(x.t)};
650   return AnalyzeString(std::move(value), kind);
651 }
652 
653 MaybeExpr ExpressionAnalyzer::Analyze(
654     const parser::HollerithLiteralConstant &x) {
655   int kind{GetDefaultKind(TypeCategory::Character)};
656   auto value{x.v};
657   return AnalyzeString(std::move(value), kind);
658 }
659 
660 // .TRUE. and .FALSE. of various kinds
661 MaybeExpr ExpressionAnalyzer::Analyze(const parser::LogicalLiteralConstant &x) {
662   auto kind{AnalyzeKindParam(std::get<std::optional<parser::KindParam>>(x.t),
663       GetDefaultKind(TypeCategory::Logical))};
664   bool value{std::get<bool>(x.t)};
665   auto result{common::SearchTypes(
666       TypeKindVisitor<TypeCategory::Logical, Constant, bool>{
667           kind, std::move(value)})};
668   if (!result) {
669     Say("unsupported LOGICAL(KIND=%d)"_err_en_US, kind); // C728
670   }
671   return result;
672 }
673 
674 // BOZ typeless literals
675 MaybeExpr ExpressionAnalyzer::Analyze(const parser::BOZLiteralConstant &x) {
676   const char *p{x.v.c_str()};
677   std::uint64_t base{16};
678   switch (*p++) {
679   case 'b':
680     base = 2;
681     break;
682   case 'o':
683     base = 8;
684     break;
685   case 'z':
686     break;
687   case 'x':
688     break;
689   default:
690     CRASH_NO_CASE;
691   }
692   CHECK(*p == '"');
693   ++p;
694   auto value{BOZLiteralConstant::Read(p, base, false /*unsigned*/)};
695   if (*p != '"') {
696     Say("Invalid digit ('%c') in BOZ literal '%s'"_err_en_US, *p,
697         x.v); // C7107, C7108
698     return std::nullopt;
699   }
700   if (value.overflow) {
701     Say("BOZ literal '%s' too large"_err_en_US, x.v);
702     return std::nullopt;
703   }
704   return AsGenericExpr(std::move(value.value));
705 }
706 
707 // Names and named constants
708 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Name &n) {
709   auto restorer{GetContextualMessages().SetLocation(n.source)};
710   if (std::optional<int> kind{IsImpliedDo(n.source)}) {
711     return AsMaybeExpr(ConvertToKind<TypeCategory::Integer>(
712         *kind, AsExpr(ImpliedDoIndex{n.source})));
713   }
714   if (context_.HasError(n.symbol)) { // includes case of no symbol
715     return std::nullopt;
716   } else {
717     const Symbol &ultimate{n.symbol->GetUltimate()};
718     if (ultimate.has<semantics::TypeParamDetails>()) {
719       // A bare reference to a derived type parameter (within a parameterized
720       // derived type definition)
721       return Fold(ConvertToType(
722           ultimate, AsGenericExpr(TypeParamInquiry{std::nullopt, ultimate})));
723     } else {
724       if (n.symbol->attrs().test(semantics::Attr::VOLATILE)) {
725         if (const semantics::Scope *
726             pure{semantics::FindPureProcedureContaining(
727                 context_.FindScope(n.source))}) {
728           SayAt(n,
729               "VOLATILE variable '%s' may not be referenced in pure subprogram '%s'"_err_en_US,
730               n.source, DEREF(pure->symbol()).name());
731           n.symbol->attrs().reset(semantics::Attr::VOLATILE);
732         }
733       }
734       if (!isWholeAssumedSizeArrayOk_ &&
735           semantics::IsAssumedSizeArray(*n.symbol)) { // C1002, C1014, C1231
736         AttachDeclaration(
737             SayAt(n,
738                 "Whole assumed-size array '%s' may not appear here without subscripts"_err_en_US,
739                 n.source),
740             *n.symbol);
741       }
742       return Designate(DataRef{*n.symbol});
743     }
744   }
745 }
746 
747 MaybeExpr ExpressionAnalyzer::Analyze(const parser::NamedConstant &n) {
748   auto restorer{GetContextualMessages().SetLocation(n.v.source)};
749   if (MaybeExpr value{Analyze(n.v)}) {
750     Expr<SomeType> folded{Fold(std::move(*value))};
751     if (IsConstantExpr(folded)) {
752       return folded;
753     }
754     Say(n.v.source, "must be a constant"_err_en_US); // C718
755   }
756   return std::nullopt;
757 }
758 
759 MaybeExpr ExpressionAnalyzer::Analyze(const parser::NullInit &n) {
760   if (MaybeExpr value{Analyze(n.v)}) {
761     // Subtle: when the NullInit is a DataStmtConstant, it might
762     // be a misparse of a structure constructor without parameters
763     // or components (e.g., T()).  Checking the result to ensure
764     // that a "=>" data entity initializer actually resolved to
765     // a null pointer has to be done by the caller.
766     return Fold(std::move(*value));
767   }
768   return std::nullopt;
769 }
770 
771 MaybeExpr ExpressionAnalyzer::Analyze(const parser::InitialDataTarget &x) {
772   return Analyze(x.value());
773 }
774 
775 MaybeExpr ExpressionAnalyzer::Analyze(const parser::DataStmtValue &x) {
776   if (const auto &repeat{
777           std::get<std::optional<parser::DataStmtRepeat>>(x.t)}) {
778     x.repetitions = -1;
779     if (MaybeExpr expr{Analyze(repeat->u)}) {
780       Expr<SomeType> folded{Fold(std::move(*expr))};
781       if (auto value{ToInt64(folded)}) {
782         if (*value >= 0) { // C882
783           x.repetitions = *value;
784         } else {
785           Say(FindSourceLocation(repeat),
786               "Repeat count (%jd) for data value must not be negative"_err_en_US,
787               *value);
788         }
789       }
790     }
791   }
792   return Analyze(std::get<parser::DataStmtConstant>(x.t));
793 }
794 
795 // Substring references
796 std::optional<Expr<SubscriptInteger>> ExpressionAnalyzer::GetSubstringBound(
797     const std::optional<parser::ScalarIntExpr> &bound) {
798   if (bound) {
799     if (MaybeExpr expr{Analyze(*bound)}) {
800       if (expr->Rank() > 1) {
801         Say("substring bound expression has rank %d"_err_en_US, expr->Rank());
802       }
803       if (auto *intExpr{std::get_if<Expr<SomeInteger>>(&expr->u)}) {
804         if (auto *ssIntExpr{std::get_if<Expr<SubscriptInteger>>(&intExpr->u)}) {
805           return {std::move(*ssIntExpr)};
806         }
807         return {Expr<SubscriptInteger>{
808             Convert<SubscriptInteger, TypeCategory::Integer>{
809                 std::move(*intExpr)}}};
810       } else {
811         Say("substring bound expression is not INTEGER"_err_en_US);
812       }
813     }
814   }
815   return std::nullopt;
816 }
817 
818 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Substring &ss) {
819   if (MaybeExpr baseExpr{Analyze(std::get<parser::DataRef>(ss.t))}) {
820     if (std::optional<DataRef> dataRef{ExtractDataRef(std::move(*baseExpr))}) {
821       if (MaybeExpr newBaseExpr{TopLevelChecks(std::move(*dataRef))}) {
822         if (std::optional<DataRef> checked{
823                 ExtractDataRef(std::move(*newBaseExpr))}) {
824           const parser::SubstringRange &range{
825               std::get<parser::SubstringRange>(ss.t)};
826           std::optional<Expr<SubscriptInteger>> first{
827               GetSubstringBound(std::get<0>(range.t))};
828           std::optional<Expr<SubscriptInteger>> last{
829               GetSubstringBound(std::get<1>(range.t))};
830           const Symbol &symbol{checked->GetLastSymbol()};
831           if (std::optional<DynamicType> dynamicType{
832                   DynamicType::From(symbol)}) {
833             if (dynamicType->category() == TypeCategory::Character) {
834               return WrapperHelper<TypeCategory::Character, Designator,
835                   Substring>(dynamicType->kind(),
836                   Substring{std::move(checked.value()), std::move(first),
837                       std::move(last)});
838             }
839           }
840           Say("substring may apply only to CHARACTER"_err_en_US);
841         }
842       }
843     }
844   }
845   return std::nullopt;
846 }
847 
848 // CHARACTER literal substrings
849 MaybeExpr ExpressionAnalyzer::Analyze(
850     const parser::CharLiteralConstantSubstring &x) {
851   const parser::SubstringRange &range{std::get<parser::SubstringRange>(x.t)};
852   std::optional<Expr<SubscriptInteger>> lower{
853       GetSubstringBound(std::get<0>(range.t))};
854   std::optional<Expr<SubscriptInteger>> upper{
855       GetSubstringBound(std::get<1>(range.t))};
856   if (MaybeExpr string{Analyze(std::get<parser::CharLiteralConstant>(x.t))}) {
857     if (auto *charExpr{std::get_if<Expr<SomeCharacter>>(&string->u)}) {
858       Expr<SubscriptInteger> length{
859           common::visit([](const auto &ckExpr) { return ckExpr.LEN().value(); },
860               charExpr->u)};
861       if (!lower) {
862         lower = Expr<SubscriptInteger>{1};
863       }
864       if (!upper) {
865         upper = Expr<SubscriptInteger>{
866             static_cast<std::int64_t>(ToInt64(length).value())};
867       }
868       return common::visit(
869           [&](auto &&ckExpr) -> MaybeExpr {
870             using Result = ResultType<decltype(ckExpr)>;
871             auto *cp{std::get_if<Constant<Result>>(&ckExpr.u)};
872             CHECK(DEREF(cp).size() == 1);
873             StaticDataObject::Pointer staticData{StaticDataObject::Create()};
874             staticData->set_alignment(Result::kind)
875                 .set_itemBytes(Result::kind)
876                 .Push(cp->GetScalarValue().value());
877             Substring substring{std::move(staticData), std::move(lower.value()),
878                 std::move(upper.value())};
879             return AsGenericExpr(
880                 Expr<Result>{Designator<Result>{std::move(substring)}});
881           },
882           std::move(charExpr->u));
883     }
884   }
885   return std::nullopt;
886 }
887 
888 // Subscripted array references
889 std::optional<Expr<SubscriptInteger>> ExpressionAnalyzer::AsSubscript(
890     MaybeExpr &&expr) {
891   if (expr) {
892     if (expr->Rank() > 1) {
893       Say("Subscript expression has rank %d greater than 1"_err_en_US,
894           expr->Rank());
895     }
896     if (auto *intExpr{std::get_if<Expr<SomeInteger>>(&expr->u)}) {
897       if (auto *ssIntExpr{std::get_if<Expr<SubscriptInteger>>(&intExpr->u)}) {
898         return std::move(*ssIntExpr);
899       } else {
900         return Expr<SubscriptInteger>{
901             Convert<SubscriptInteger, TypeCategory::Integer>{
902                 std::move(*intExpr)}};
903       }
904     } else {
905       Say("Subscript expression is not INTEGER"_err_en_US);
906     }
907   }
908   return std::nullopt;
909 }
910 
911 std::optional<Expr<SubscriptInteger>> ExpressionAnalyzer::TripletPart(
912     const std::optional<parser::Subscript> &s) {
913   if (s) {
914     return AsSubscript(Analyze(*s));
915   } else {
916     return std::nullopt;
917   }
918 }
919 
920 std::optional<Subscript> ExpressionAnalyzer::AnalyzeSectionSubscript(
921     const parser::SectionSubscript &ss) {
922   return common::visit(
923       common::visitors{
924           [&](const parser::SubscriptTriplet &t) -> std::optional<Subscript> {
925             const auto &lower{std::get<0>(t.t)};
926             const auto &upper{std::get<1>(t.t)};
927             const auto &stride{std::get<2>(t.t)};
928             auto result{Triplet{
929                 TripletPart(lower), TripletPart(upper), TripletPart(stride)}};
930             if ((lower && !result.lower()) || (upper && !result.upper())) {
931               return std::nullopt;
932             } else {
933               return std::make_optional<Subscript>(result);
934             }
935           },
936           [&](const auto &s) -> std::optional<Subscript> {
937             if (auto subscriptExpr{AsSubscript(Analyze(s))}) {
938               return Subscript{std::move(*subscriptExpr)};
939             } else {
940               return std::nullopt;
941             }
942           },
943       },
944       ss.u);
945 }
946 
947 // Empty result means an error occurred
948 std::vector<Subscript> ExpressionAnalyzer::AnalyzeSectionSubscripts(
949     const std::list<parser::SectionSubscript> &sss) {
950   bool error{false};
951   std::vector<Subscript> subscripts;
952   for (const auto &s : sss) {
953     if (auto subscript{AnalyzeSectionSubscript(s)}) {
954       subscripts.emplace_back(std::move(*subscript));
955     } else {
956       error = true;
957     }
958   }
959   return !error ? subscripts : std::vector<Subscript>{};
960 }
961 
962 MaybeExpr ExpressionAnalyzer::Analyze(const parser::ArrayElement &ae) {
963   MaybeExpr baseExpr;
964   {
965     auto restorer{AllowWholeAssumedSizeArray()};
966     baseExpr = Analyze(ae.base);
967   }
968   if (baseExpr) {
969     if (ae.subscripts.empty()) {
970       // will be converted to function call later or error reported
971     } else if (baseExpr->Rank() == 0) {
972       if (const Symbol * symbol{GetLastSymbol(*baseExpr)}) {
973         if (!context_.HasError(symbol)) {
974           if (inDataStmtConstant_) {
975             // Better error for NULL(X) with a MOLD= argument
976             Say("'%s' must be an array or structure constructor if used with non-empty parentheses as a DATA statement constant"_err_en_US,
977                 symbol->name());
978           } else {
979             Say("'%s' is not an array"_err_en_US, symbol->name());
980           }
981           context_.SetError(*symbol);
982         }
983       }
984     } else if (std::optional<DataRef> dataRef{
985                    ExtractDataRef(std::move(*baseExpr))}) {
986       return ApplySubscripts(
987           std::move(*dataRef), AnalyzeSectionSubscripts(ae.subscripts));
988     } else {
989       Say("Subscripts may be applied only to an object, component, or array constant"_err_en_US);
990     }
991   }
992   // error was reported: analyze subscripts without reporting more errors
993   auto restorer{GetContextualMessages().DiscardMessages()};
994   AnalyzeSectionSubscripts(ae.subscripts);
995   return std::nullopt;
996 }
997 
998 // Type parameter inquiries apply to data references, but don't depend
999 // on any trailing (co)subscripts.
1000 static NamedEntity IgnoreAnySubscripts(Designator<SomeDerived> &&designator) {
1001   return common::visit(
1002       common::visitors{
1003           [](SymbolRef &&symbol) { return NamedEntity{symbol}; },
1004           [](Component &&component) {
1005             return NamedEntity{std::move(component)};
1006           },
1007           [](ArrayRef &&arrayRef) { return std::move(arrayRef.base()); },
1008           [](CoarrayRef &&coarrayRef) {
1009             return NamedEntity{coarrayRef.GetLastSymbol()};
1010           },
1011       },
1012       std::move(designator.u));
1013 }
1014 
1015 // Components of parent derived types are explicitly represented as such.
1016 std::optional<Component> ExpressionAnalyzer::CreateComponent(
1017     DataRef &&base, const Symbol &component, const semantics::Scope &scope) {
1018   if (IsAllocatableOrPointer(component) && base.Rank() > 0) { // C919b
1019     Say("An allocatable or pointer component reference must be applied to a scalar base"_err_en_US);
1020   }
1021   if (&component.owner() == &scope) {
1022     return Component{std::move(base), component};
1023   }
1024   if (const Symbol * typeSymbol{scope.GetSymbol()}) {
1025     if (const Symbol *
1026         parentComponent{typeSymbol->GetParentComponent(&scope)}) {
1027       if (const auto *object{
1028               parentComponent->detailsIf<semantics::ObjectEntityDetails>()}) {
1029         if (const auto *parentType{object->type()}) {
1030           if (const semantics::Scope *
1031               parentScope{parentType->derivedTypeSpec().scope()}) {
1032             return CreateComponent(
1033                 DataRef{Component{std::move(base), *parentComponent}},
1034                 component, *parentScope);
1035           }
1036         }
1037       }
1038     }
1039   }
1040   return std::nullopt;
1041 }
1042 
1043 // Derived type component references and type parameter inquiries
1044 MaybeExpr ExpressionAnalyzer::Analyze(const parser::StructureComponent &sc) {
1045   MaybeExpr base{Analyze(sc.base)};
1046   Symbol *sym{sc.component.symbol};
1047   if (!base || !sym || context_.HasError(sym)) {
1048     return std::nullopt;
1049   }
1050   const auto &name{sc.component.source};
1051   if (auto *dtExpr{UnwrapExpr<Expr<SomeDerived>>(*base)}) {
1052     const auto *dtSpec{GetDerivedTypeSpec(dtExpr->GetType())};
1053     if (sym->detailsIf<semantics::TypeParamDetails>()) {
1054       if (auto *designator{UnwrapExpr<Designator<SomeDerived>>(*dtExpr)}) {
1055         if (std::optional<DynamicType> dyType{DynamicType::From(*sym)}) {
1056           if (dyType->category() == TypeCategory::Integer) {
1057             auto restorer{GetContextualMessages().SetLocation(name)};
1058             return Fold(ConvertToType(*dyType,
1059                 AsGenericExpr(TypeParamInquiry{
1060                     IgnoreAnySubscripts(std::move(*designator)), *sym})));
1061           }
1062         }
1063         Say(name, "Type parameter is not INTEGER"_err_en_US);
1064       } else {
1065         Say(name,
1066             "A type parameter inquiry must be applied to "
1067             "a designator"_err_en_US);
1068       }
1069     } else if (!dtSpec || !dtSpec->scope()) {
1070       CHECK(context_.AnyFatalError() || !foldingContext_.messages().empty());
1071       return std::nullopt;
1072     } else if (std::optional<DataRef> dataRef{
1073                    ExtractDataRef(std::move(*dtExpr))}) {
1074       if (auto component{
1075               CreateComponent(std::move(*dataRef), *sym, *dtSpec->scope())}) {
1076         return Designate(DataRef{std::move(*component)});
1077       } else {
1078         Say(name, "Component is not in scope of derived TYPE(%s)"_err_en_US,
1079             dtSpec->typeSymbol().name());
1080       }
1081     } else {
1082       Say(name,
1083           "Base of component reference must be a data reference"_err_en_US);
1084     }
1085   } else if (auto *details{sym->detailsIf<semantics::MiscDetails>()}) {
1086     // special part-ref: %re, %im, %kind, %len
1087     // Type errors on the base of %re/%im/%len are detected and
1088     // reported in name resolution.
1089     using MiscKind = semantics::MiscDetails::Kind;
1090     MiscKind kind{details->kind()};
1091     if (kind == MiscKind::ComplexPartRe || kind == MiscKind::ComplexPartIm) {
1092       if (auto *zExpr{std::get_if<Expr<SomeComplex>>(&base->u)}) {
1093         if (std::optional<DataRef> dataRef{ExtractDataRef(*zExpr)}) {
1094           // Represent %RE/%IM as a designator
1095           Expr<SomeReal> realExpr{common::visit(
1096               [&](const auto &z) {
1097                 using PartType = typename ResultType<decltype(z)>::Part;
1098                 auto part{kind == MiscKind::ComplexPartRe
1099                         ? ComplexPart::Part::RE
1100                         : ComplexPart::Part::IM};
1101                 return AsCategoryExpr(Designator<PartType>{
1102                     ComplexPart{std::move(*dataRef), part}});
1103               },
1104               zExpr->u)};
1105           return AsGenericExpr(std::move(realExpr));
1106         }
1107       }
1108     } else if (kind == MiscKind::KindParamInquiry ||
1109         kind == MiscKind::LenParamInquiry) {
1110       ActualArgument arg{std::move(*base)};
1111       SetArgSourceLocation(arg, name);
1112       return MakeFunctionRef(name, ActualArguments{std::move(arg)});
1113     } else {
1114       DIE("unexpected MiscDetails::Kind");
1115     }
1116   } else {
1117     Say(name, "derived type required before component reference"_err_en_US);
1118   }
1119   return std::nullopt;
1120 }
1121 
1122 MaybeExpr ExpressionAnalyzer::Analyze(const parser::CoindexedNamedObject &x) {
1123   if (auto maybeDataRef{ExtractDataRef(Analyze(x.base))}) {
1124     DataRef *dataRef{&*maybeDataRef};
1125     std::vector<Subscript> subscripts;
1126     SymbolVector reversed;
1127     if (auto *aRef{std::get_if<ArrayRef>(&dataRef->u)}) {
1128       subscripts = std::move(aRef->subscript());
1129       reversed.push_back(aRef->GetLastSymbol());
1130       if (Component * component{aRef->base().UnwrapComponent()}) {
1131         dataRef = &component->base();
1132       } else {
1133         dataRef = nullptr;
1134       }
1135     }
1136     if (dataRef) {
1137       while (auto *component{std::get_if<Component>(&dataRef->u)}) {
1138         reversed.push_back(component->GetLastSymbol());
1139         dataRef = &component->base();
1140       }
1141       if (auto *baseSym{std::get_if<SymbolRef>(&dataRef->u)}) {
1142         reversed.push_back(*baseSym);
1143       } else {
1144         Say("Base of coindexed named object has subscripts or cosubscripts"_err_en_US);
1145       }
1146     }
1147     std::vector<Expr<SubscriptInteger>> cosubscripts;
1148     bool cosubsOk{true};
1149     for (const auto &cosub :
1150         std::get<std::list<parser::Cosubscript>>(x.imageSelector.t)) {
1151       MaybeExpr coex{Analyze(cosub)};
1152       if (auto *intExpr{UnwrapExpr<Expr<SomeInteger>>(coex)}) {
1153         cosubscripts.push_back(
1154             ConvertToType<SubscriptInteger>(std::move(*intExpr)));
1155       } else {
1156         cosubsOk = false;
1157       }
1158     }
1159     if (cosubsOk && !reversed.empty()) {
1160       int numCosubscripts{static_cast<int>(cosubscripts.size())};
1161       const Symbol &symbol{reversed.front()};
1162       if (numCosubscripts != symbol.Corank()) {
1163         Say("'%s' has corank %d, but coindexed reference has %d cosubscripts"_err_en_US,
1164             symbol.name(), symbol.Corank(), numCosubscripts);
1165       }
1166     }
1167     for (const auto &imageSelSpec :
1168         std::get<std::list<parser::ImageSelectorSpec>>(x.imageSelector.t)) {
1169       common::visit(
1170           common::visitors{
1171               [&](const auto &x) { Analyze(x.v); },
1172           },
1173           imageSelSpec.u);
1174     }
1175     // Reverse the chain of symbols so that the base is first and coarray
1176     // ultimate component is last.
1177     if (cosubsOk) {
1178       return Designate(
1179           DataRef{CoarrayRef{SymbolVector{reversed.crbegin(), reversed.crend()},
1180               std::move(subscripts), std::move(cosubscripts)}});
1181     }
1182   }
1183   return std::nullopt;
1184 }
1185 
1186 int ExpressionAnalyzer::IntegerTypeSpecKind(
1187     const parser::IntegerTypeSpec &spec) {
1188   Expr<SubscriptInteger> value{
1189       AnalyzeKindSelector(TypeCategory::Integer, spec.v)};
1190   if (auto kind{ToInt64(value)}) {
1191     return static_cast<int>(*kind);
1192   }
1193   SayAt(spec, "Constant INTEGER kind value required here"_err_en_US);
1194   return GetDefaultKind(TypeCategory::Integer);
1195 }
1196 
1197 // Array constructors
1198 
1199 // Inverts a collection of generic ArrayConstructorValues<SomeType> that
1200 // all happen to have the same actual type T into one ArrayConstructor<T>.
1201 template <typename T>
1202 ArrayConstructorValues<T> MakeSpecific(
1203     ArrayConstructorValues<SomeType> &&from) {
1204   ArrayConstructorValues<T> to;
1205   for (ArrayConstructorValue<SomeType> &x : from) {
1206     common::visit(
1207         common::visitors{
1208             [&](common::CopyableIndirection<Expr<SomeType>> &&expr) {
1209               auto *typed{UnwrapExpr<Expr<T>>(expr.value())};
1210               to.Push(std::move(DEREF(typed)));
1211             },
1212             [&](ImpliedDo<SomeType> &&impliedDo) {
1213               to.Push(ImpliedDo<T>{impliedDo.name(),
1214                   std::move(impliedDo.lower()), std::move(impliedDo.upper()),
1215                   std::move(impliedDo.stride()),
1216                   MakeSpecific<T>(std::move(impliedDo.values()))});
1217             },
1218         },
1219         std::move(x.u));
1220   }
1221   return to;
1222 }
1223 
1224 class ArrayConstructorContext {
1225 public:
1226   ArrayConstructorContext(
1227       ExpressionAnalyzer &c, std::optional<DynamicTypeWithLength> &&t)
1228       : exprAnalyzer_{c}, type_{std::move(t)} {}
1229 
1230   void Add(const parser::AcValue &);
1231   MaybeExpr ToExpr();
1232 
1233   // These interfaces allow *this to be used as a type visitor argument to
1234   // common::SearchTypes() to convert the array constructor to a typed
1235   // expression in ToExpr().
1236   using Result = MaybeExpr;
1237   using Types = AllTypes;
1238   template <typename T> Result Test() {
1239     if (type_ && type_->category() == T::category) {
1240       if constexpr (T::category == TypeCategory::Derived) {
1241         if (!type_->IsUnlimitedPolymorphic()) {
1242           return AsMaybeExpr(ArrayConstructor<T>{type_->GetDerivedTypeSpec(),
1243               MakeSpecific<T>(std::move(values_))});
1244         }
1245       } else if (type_->kind() == T::kind) {
1246         if constexpr (T::category == TypeCategory::Character) {
1247           if (auto len{type_->LEN()}) {
1248             return AsMaybeExpr(ArrayConstructor<T>{
1249                 *std::move(len), MakeSpecific<T>(std::move(values_))});
1250           }
1251         } else {
1252           return AsMaybeExpr(
1253               ArrayConstructor<T>{MakeSpecific<T>(std::move(values_))});
1254         }
1255       }
1256     }
1257     return std::nullopt;
1258   }
1259 
1260 private:
1261   using ImpliedDoIntType = ResultType<ImpliedDoIndex>;
1262 
1263   void Push(MaybeExpr &&);
1264   void Add(const parser::AcValue::Triplet &);
1265   void Add(const parser::Expr &);
1266   void Add(const parser::AcImpliedDo &);
1267   void UnrollConstantImpliedDo(const parser::AcImpliedDo &,
1268       parser::CharBlock name, std::int64_t lower, std::int64_t upper,
1269       std::int64_t stride);
1270 
1271   template <int KIND, typename A>
1272   std::optional<Expr<Type<TypeCategory::Integer, KIND>>> GetSpecificIntExpr(
1273       const A &x) {
1274     if (MaybeExpr y{exprAnalyzer_.Analyze(x)}) {
1275       Expr<SomeInteger> *intExpr{UnwrapExpr<Expr<SomeInteger>>(*y)};
1276       return Fold(exprAnalyzer_.GetFoldingContext(),
1277           ConvertToType<Type<TypeCategory::Integer, KIND>>(
1278               std::move(DEREF(intExpr))));
1279     }
1280     return std::nullopt;
1281   }
1282 
1283   // Nested array constructors all reference the same ExpressionAnalyzer,
1284   // which represents the nest of active implied DO loop indices.
1285   ExpressionAnalyzer &exprAnalyzer_;
1286   std::optional<DynamicTypeWithLength> type_;
1287   bool explicitType_{type_.has_value()};
1288   std::optional<std::int64_t> constantLength_;
1289   ArrayConstructorValues<SomeType> values_;
1290   std::uint64_t messageDisplayedSet_{0};
1291 };
1292 
1293 void ArrayConstructorContext::Push(MaybeExpr &&x) {
1294   if (!x) {
1295     return;
1296   }
1297   if (!type_) {
1298     if (auto *boz{std::get_if<BOZLiteralConstant>(&x->u)}) {
1299       // Treat an array constructor of BOZ as if default integer.
1300       if (exprAnalyzer_.context().ShouldWarn(
1301               common::LanguageFeature::BOZAsDefaultInteger)) {
1302         exprAnalyzer_.Say(
1303             "BOZ literal in array constructor without explicit type is assumed to be default INTEGER"_port_en_US);
1304       }
1305       x = AsGenericExpr(ConvertToKind<TypeCategory::Integer>(
1306           exprAnalyzer_.GetDefaultKind(TypeCategory::Integer),
1307           std::move(*boz)));
1308     }
1309   }
1310   std::optional<DynamicType> dyType{x->GetType()};
1311   if (!dyType) {
1312     if (auto *boz{std::get_if<BOZLiteralConstant>(&x->u)}) {
1313       if (!type_) {
1314         // Treat an array constructor of BOZ as if default integer.
1315         if (exprAnalyzer_.context().ShouldWarn(
1316                 common::LanguageFeature::BOZAsDefaultInteger)) {
1317           exprAnalyzer_.Say(
1318               "BOZ literal in array constructor without explicit type is assumed to be default INTEGER"_port_en_US);
1319         }
1320         x = AsGenericExpr(ConvertToKind<TypeCategory::Integer>(
1321             exprAnalyzer_.GetDefaultKind(TypeCategory::Integer),
1322             std::move(*boz)));
1323         dyType = x.value().GetType();
1324       } else if (auto cast{ConvertToType(*type_, std::move(*x))}) {
1325         x = std::move(cast);
1326         dyType = *type_;
1327       } else {
1328         if (!(messageDisplayedSet_ & 0x80)) {
1329           exprAnalyzer_.Say(
1330               "BOZ literal is not suitable for use in this array constructor"_err_en_US);
1331           messageDisplayedSet_ |= 0x80;
1332         }
1333         return;
1334       }
1335     } else { // procedure name, &c.
1336       if (!(messageDisplayedSet_ & 0x40)) {
1337         exprAnalyzer_.Say(
1338             "Item is not suitable for use in an array constructor"_err_en_US);
1339         messageDisplayedSet_ |= 0x40;
1340       }
1341       return;
1342     }
1343   } else if (dyType->IsUnlimitedPolymorphic()) {
1344     if (!(messageDisplayedSet_ & 8)) {
1345       exprAnalyzer_.Say("Cannot have an unlimited polymorphic value in an "
1346                         "array constructor"_err_en_US); // C7113
1347       messageDisplayedSet_ |= 8;
1348     }
1349     return;
1350   }
1351   DynamicTypeWithLength xType{dyType.value()};
1352   if (Expr<SomeCharacter> * charExpr{UnwrapExpr<Expr<SomeCharacter>>(*x)}) {
1353     CHECK(xType.category() == TypeCategory::Character);
1354     xType.length =
1355         common::visit([](const auto &kc) { return kc.LEN(); }, charExpr->u);
1356   }
1357   if (!type_) {
1358     // If there is no explicit type-spec in an array constructor, the type
1359     // of the array is the declared type of all of the elements, which must
1360     // be well-defined and all match.
1361     // TODO: Possible language extension: use the most general type of
1362     // the values as the type of a numeric constructed array, convert all
1363     // of the other values to that type.  Alternative: let the first value
1364     // determine the type, and convert the others to that type.
1365     CHECK(!explicitType_);
1366     type_ = std::move(xType);
1367     constantLength_ = ToInt64(type_->length);
1368     values_.Push(std::move(*x));
1369   } else if (!explicitType_) {
1370     if (type_->IsTkCompatibleWith(xType) && xType.IsTkCompatibleWith(*type_)) {
1371       values_.Push(std::move(*x));
1372       if (auto thisLen{ToInt64(xType.LEN())}) {
1373         if (constantLength_) {
1374           if (exprAnalyzer_.context().warnOnNonstandardUsage() &&
1375               *thisLen != *constantLength_) {
1376             if (!(messageDisplayedSet_ & 1)) {
1377               exprAnalyzer_.Say(
1378                   "Character literal in array constructor without explicit "
1379                   "type has different length than earlier elements"_port_en_US);
1380               messageDisplayedSet_ |= 1;
1381             }
1382           }
1383           if (*thisLen > *constantLength_) {
1384             // Language extension: use the longest literal to determine the
1385             // length of the array constructor's character elements, not the
1386             // first, when there is no explicit type.
1387             *constantLength_ = *thisLen;
1388             type_->length = xType.LEN();
1389           }
1390         } else {
1391           constantLength_ = *thisLen;
1392           type_->length = xType.LEN();
1393         }
1394       }
1395     } else {
1396       if (!(messageDisplayedSet_ & 2)) {
1397         exprAnalyzer_.Say(
1398             "Values in array constructor must have the same declared type "
1399             "when no explicit type appears"_err_en_US); // C7110
1400         messageDisplayedSet_ |= 2;
1401       }
1402     }
1403   } else {
1404     if (auto cast{ConvertToType(*type_, std::move(*x))}) {
1405       values_.Push(std::move(*cast));
1406     } else if (!(messageDisplayedSet_ & 4)) {
1407       exprAnalyzer_.Say("Value in array constructor of type '%s' could not "
1408                         "be converted to the type of the array '%s'"_err_en_US,
1409           x->GetType()->AsFortran(), type_->AsFortran()); // C7111, C7112
1410       messageDisplayedSet_ |= 4;
1411     }
1412   }
1413 }
1414 
1415 void ArrayConstructorContext::Add(const parser::AcValue &x) {
1416   common::visit(
1417       common::visitors{
1418           [&](const parser::AcValue::Triplet &triplet) { Add(triplet); },
1419           [&](const common::Indirection<parser::Expr> &expr) {
1420             Add(expr.value());
1421           },
1422           [&](const common::Indirection<parser::AcImpliedDo> &impliedDo) {
1423             Add(impliedDo.value());
1424           },
1425       },
1426       x.u);
1427 }
1428 
1429 // Transforms l:u(:s) into (_,_=l,u(,s)) with an anonymous index '_'
1430 void ArrayConstructorContext::Add(const parser::AcValue::Triplet &triplet) {
1431   std::optional<Expr<ImpliedDoIntType>> lower{
1432       GetSpecificIntExpr<ImpliedDoIntType::kind>(std::get<0>(triplet.t))};
1433   std::optional<Expr<ImpliedDoIntType>> upper{
1434       GetSpecificIntExpr<ImpliedDoIntType::kind>(std::get<1>(triplet.t))};
1435   std::optional<Expr<ImpliedDoIntType>> stride{
1436       GetSpecificIntExpr<ImpliedDoIntType::kind>(std::get<2>(triplet.t))};
1437   if (lower && upper) {
1438     if (!stride) {
1439       stride = Expr<ImpliedDoIntType>{1};
1440     }
1441     if (!type_) {
1442       type_ = DynamicTypeWithLength{ImpliedDoIntType::GetType()};
1443     }
1444     auto v{std::move(values_)};
1445     parser::CharBlock anonymous;
1446     Push(Expr<SomeType>{
1447         Expr<SomeInteger>{Expr<ImpliedDoIntType>{ImpliedDoIndex{anonymous}}}});
1448     std::swap(v, values_);
1449     values_.Push(ImpliedDo<SomeType>{anonymous, std::move(*lower),
1450         std::move(*upper), std::move(*stride), std::move(v)});
1451   }
1452 }
1453 
1454 void ArrayConstructorContext::Add(const parser::Expr &expr) {
1455   auto restorer{exprAnalyzer_.GetContextualMessages().SetLocation(expr.source)};
1456   Push(exprAnalyzer_.Analyze(expr));
1457 }
1458 
1459 void ArrayConstructorContext::Add(const parser::AcImpliedDo &impliedDo) {
1460   const auto &control{std::get<parser::AcImpliedDoControl>(impliedDo.t)};
1461   const auto &bounds{std::get<parser::AcImpliedDoControl::Bounds>(control.t)};
1462   exprAnalyzer_.Analyze(bounds.name);
1463   parser::CharBlock name{bounds.name.thing.thing.source};
1464   const Symbol *symbol{bounds.name.thing.thing.symbol};
1465   int kind{ImpliedDoIntType::kind};
1466   if (const auto dynamicType{DynamicType::From(symbol)}) {
1467     kind = dynamicType->kind();
1468   }
1469   std::optional<Expr<ImpliedDoIntType>> lower{
1470       GetSpecificIntExpr<ImpliedDoIntType::kind>(bounds.lower)};
1471   std::optional<Expr<ImpliedDoIntType>> upper{
1472       GetSpecificIntExpr<ImpliedDoIntType::kind>(bounds.upper)};
1473   if (lower && upper) {
1474     std::optional<Expr<ImpliedDoIntType>> stride{
1475         GetSpecificIntExpr<ImpliedDoIntType::kind>(bounds.step)};
1476     if (!stride) {
1477       stride = Expr<ImpliedDoIntType>{1};
1478     }
1479     if (exprAnalyzer_.AddImpliedDo(name, kind)) {
1480       // Check for constant bounds; the loop may require complete unrolling
1481       // of the parse tree if all bounds are constant in order to allow the
1482       // implied DO loop index to qualify as a constant expression.
1483       auto cLower{ToInt64(lower)};
1484       auto cUpper{ToInt64(upper)};
1485       auto cStride{ToInt64(stride)};
1486       if (!(messageDisplayedSet_ & 0x10) && cStride && *cStride == 0) {
1487         exprAnalyzer_.SayAt(bounds.step.value().thing.thing.value().source,
1488             "The stride of an implied DO loop must not be zero"_err_en_US);
1489         messageDisplayedSet_ |= 0x10;
1490       }
1491       bool isConstant{cLower && cUpper && cStride && *cStride != 0};
1492       bool isNonemptyConstant{isConstant &&
1493           ((*cStride > 0 && *cLower <= *cUpper) ||
1494               (*cStride < 0 && *cLower >= *cUpper))};
1495       bool unrollConstantLoop{false};
1496       parser::Messages buffer;
1497       auto saveMessagesDisplayed{messageDisplayedSet_};
1498       {
1499         auto messageRestorer{
1500             exprAnalyzer_.GetContextualMessages().SetMessages(buffer)};
1501         auto v{std::move(values_)};
1502         for (const auto &value :
1503             std::get<std::list<parser::AcValue>>(impliedDo.t)) {
1504           Add(value);
1505         }
1506         std::swap(v, values_);
1507         if (isNonemptyConstant && buffer.AnyFatalError()) {
1508           unrollConstantLoop = true;
1509         } else {
1510           values_.Push(ImpliedDo<SomeType>{name, std::move(*lower),
1511               std::move(*upper), std::move(*stride), std::move(v)});
1512         }
1513       }
1514       if (unrollConstantLoop) {
1515         messageDisplayedSet_ = saveMessagesDisplayed;
1516         UnrollConstantImpliedDo(impliedDo, name, *cLower, *cUpper, *cStride);
1517       } else if (auto *messages{
1518                      exprAnalyzer_.GetContextualMessages().messages()}) {
1519         messages->Annex(std::move(buffer));
1520       }
1521       exprAnalyzer_.RemoveImpliedDo(name);
1522     } else if (!(messageDisplayedSet_ & 0x20)) {
1523       exprAnalyzer_.SayAt(name,
1524           "Implied DO index '%s' is active in a surrounding implied DO loop "
1525           "and may not have the same name"_err_en_US,
1526           name); // C7115
1527       messageDisplayedSet_ |= 0x20;
1528     }
1529   }
1530 }
1531 
1532 // Fortran considers an implied DO index of an array constructor to be
1533 // a constant expression if the bounds of the implied DO loop are constant.
1534 // Usually this doesn't matter, but if we emitted spurious messages as a
1535 // result of not using constant values for the index while analyzing the
1536 // items, we need to do it again the "hard" way with multiple iterations over
1537 // the parse tree.
1538 void ArrayConstructorContext::UnrollConstantImpliedDo(
1539     const parser::AcImpliedDo &impliedDo, parser::CharBlock name,
1540     std::int64_t lower, std::int64_t upper, std::int64_t stride) {
1541   auto &foldingContext{exprAnalyzer_.GetFoldingContext()};
1542   auto restorer{exprAnalyzer_.DoNotUseSavedTypedExprs()};
1543   for (auto &at{foldingContext.StartImpliedDo(name, lower)};
1544        (stride > 0 && at <= upper) || (stride < 0 && at >= upper);
1545        at += stride) {
1546     for (const auto &value :
1547         std::get<std::list<parser::AcValue>>(impliedDo.t)) {
1548       Add(value);
1549     }
1550   }
1551   foldingContext.EndImpliedDo(name);
1552 }
1553 
1554 MaybeExpr ArrayConstructorContext::ToExpr() {
1555   return common::SearchTypes(std::move(*this));
1556 }
1557 
1558 MaybeExpr ExpressionAnalyzer::Analyze(const parser::ArrayConstructor &array) {
1559   const parser::AcSpec &acSpec{array.v};
1560   ArrayConstructorContext acContext{*this, AnalyzeTypeSpec(acSpec.type)};
1561   for (const parser::AcValue &value : acSpec.values) {
1562     acContext.Add(value);
1563   }
1564   return acContext.ToExpr();
1565 }
1566 
1567 MaybeExpr ExpressionAnalyzer::Analyze(
1568     const parser::StructureConstructor &structure) {
1569   auto &parsedType{std::get<parser::DerivedTypeSpec>(structure.t)};
1570   parser::Name structureType{std::get<parser::Name>(parsedType.t)};
1571   parser::CharBlock &typeName{structureType.source};
1572   if (semantics::Symbol * typeSymbol{structureType.symbol}) {
1573     if (typeSymbol->has<semantics::DerivedTypeDetails>()) {
1574       semantics::DerivedTypeSpec dtSpec{typeName, typeSymbol->GetUltimate()};
1575       if (!CheckIsValidForwardReference(dtSpec)) {
1576         return std::nullopt;
1577       }
1578     }
1579   }
1580   if (!parsedType.derivedTypeSpec) {
1581     return std::nullopt;
1582   }
1583   const auto &spec{*parsedType.derivedTypeSpec};
1584   const Symbol &typeSymbol{spec.typeSymbol()};
1585   if (!spec.scope() || !typeSymbol.has<semantics::DerivedTypeDetails>()) {
1586     return std::nullopt; // error recovery
1587   }
1588   const auto &typeDetails{typeSymbol.get<semantics::DerivedTypeDetails>()};
1589   const Symbol *parentComponent{typeDetails.GetParentComponent(*spec.scope())};
1590 
1591   if (typeSymbol.attrs().test(semantics::Attr::ABSTRACT)) { // C796
1592     AttachDeclaration(Say(typeName,
1593                           "ABSTRACT derived type '%s' may not be used in a "
1594                           "structure constructor"_err_en_US,
1595                           typeName),
1596         typeSymbol); // C7114
1597   }
1598 
1599   // This iterator traverses all of the components in the derived type and its
1600   // parents.  The symbols for whole parent components appear after their
1601   // own components and before the components of the types that extend them.
1602   // E.g., TYPE :: A; REAL X; END TYPE
1603   //       TYPE, EXTENDS(A) :: B; REAL Y; END TYPE
1604   // produces the component list X, A, Y.
1605   // The order is important below because a structure constructor can
1606   // initialize X or A by name, but not both.
1607   auto components{semantics::OrderedComponentIterator{spec}};
1608   auto nextAnonymous{components.begin()};
1609 
1610   std::set<parser::CharBlock> unavailable;
1611   bool anyKeyword{false};
1612   StructureConstructor result{spec};
1613   bool checkConflicts{true}; // until we hit one
1614   auto &messages{GetContextualMessages()};
1615 
1616   for (const auto &component :
1617       std::get<std::list<parser::ComponentSpec>>(structure.t)) {
1618     const parser::Expr &expr{
1619         std::get<parser::ComponentDataSource>(component.t).v.value()};
1620     parser::CharBlock source{expr.source};
1621     auto restorer{messages.SetLocation(source)};
1622     const Symbol *symbol{nullptr};
1623     MaybeExpr value{Analyze(expr)};
1624     std::optional<DynamicType> valueType{DynamicType::From(value)};
1625     if (const auto &kw{std::get<std::optional<parser::Keyword>>(component.t)}) {
1626       anyKeyword = true;
1627       source = kw->v.source;
1628       symbol = kw->v.symbol;
1629       if (!symbol) {
1630         auto componentIter{std::find_if(components.begin(), components.end(),
1631             [=](const Symbol &symbol) { return symbol.name() == source; })};
1632         if (componentIter != components.end()) {
1633           symbol = &*componentIter;
1634         }
1635       }
1636       if (!symbol) { // C7101
1637         Say(source,
1638             "Keyword '%s=' does not name a component of derived type '%s'"_err_en_US,
1639             source, typeName);
1640       }
1641     } else {
1642       if (anyKeyword) { // C7100
1643         Say(source,
1644             "Value in structure constructor lacks a component name"_err_en_US);
1645         checkConflicts = false; // stem cascade
1646       }
1647       // Here's a regrettably common extension of the standard: anonymous
1648       // initialization of parent components, e.g., T(PT(1)) rather than
1649       // T(1) or T(PT=PT(1)).
1650       if (nextAnonymous == components.begin() && parentComponent &&
1651           valueType == DynamicType::From(*parentComponent) &&
1652           context().IsEnabled(LanguageFeature::AnonymousParents)) {
1653         auto iter{
1654             std::find(components.begin(), components.end(), *parentComponent)};
1655         if (iter != components.end()) {
1656           symbol = parentComponent;
1657           nextAnonymous = ++iter;
1658           if (context().ShouldWarn(LanguageFeature::AnonymousParents)) {
1659             Say(source,
1660                 "Whole parent component '%s' in structure "
1661                 "constructor should not be anonymous"_port_en_US,
1662                 symbol->name());
1663           }
1664         }
1665       }
1666       while (!symbol && nextAnonymous != components.end()) {
1667         const Symbol &next{*nextAnonymous};
1668         ++nextAnonymous;
1669         if (!next.test(Symbol::Flag::ParentComp)) {
1670           symbol = &next;
1671         }
1672       }
1673       if (!symbol) {
1674         Say(source, "Unexpected value in structure constructor"_err_en_US);
1675       }
1676     }
1677     if (symbol) {
1678       if (const auto *currScope{context_.globalScope().FindScope(source)}) {
1679         if (auto msg{CheckAccessibleComponent(*currScope, *symbol)}) {
1680           Say(source, *msg);
1681         }
1682       }
1683       if (checkConflicts) {
1684         auto componentIter{
1685             std::find(components.begin(), components.end(), *symbol)};
1686         if (unavailable.find(symbol->name()) != unavailable.cend()) {
1687           // C797, C798
1688           Say(source,
1689               "Component '%s' conflicts with another component earlier in "
1690               "this structure constructor"_err_en_US,
1691               symbol->name());
1692         } else if (symbol->test(Symbol::Flag::ParentComp)) {
1693           // Make earlier components unavailable once a whole parent appears.
1694           for (auto it{components.begin()}; it != componentIter; ++it) {
1695             unavailable.insert(it->name());
1696           }
1697         } else {
1698           // Make whole parent components unavailable after any of their
1699           // constituents appear.
1700           for (auto it{componentIter}; it != components.end(); ++it) {
1701             if (it->test(Symbol::Flag::ParentComp)) {
1702               unavailable.insert(it->name());
1703             }
1704           }
1705         }
1706       }
1707       unavailable.insert(symbol->name());
1708       if (value) {
1709         if (symbol->has<semantics::ProcEntityDetails>()) {
1710           CHECK(IsPointer(*symbol));
1711         } else if (symbol->has<semantics::ObjectEntityDetails>()) {
1712           // C1594(4)
1713           const auto &innermost{context_.FindScope(expr.source)};
1714           if (const auto *pureProc{FindPureProcedureContaining(innermost)}) {
1715             if (const Symbol * pointer{FindPointerComponent(*symbol)}) {
1716               if (const Symbol *
1717                   object{FindExternallyVisibleObject(*value, *pureProc)}) {
1718                 if (auto *msg{Say(expr.source,
1719                         "Externally visible object '%s' may not be "
1720                         "associated with pointer component '%s' in a "
1721                         "pure procedure"_err_en_US,
1722                         object->name(), pointer->name())}) {
1723                   msg->Attach(object->name(), "Object declaration"_en_US)
1724                       .Attach(pointer->name(), "Pointer declaration"_en_US);
1725                 }
1726               }
1727             }
1728           }
1729         } else if (symbol->has<semantics::TypeParamDetails>()) {
1730           Say(expr.source,
1731               "Type parameter '%s' may not appear as a component "
1732               "of a structure constructor"_err_en_US,
1733               symbol->name());
1734           continue;
1735         } else {
1736           Say(expr.source,
1737               "Component '%s' is neither a procedure pointer "
1738               "nor a data object"_err_en_US,
1739               symbol->name());
1740           continue;
1741         }
1742         if (IsPointer(*symbol)) {
1743           semantics::CheckPointerAssignment(
1744               GetFoldingContext(), *symbol, *value); // C7104, C7105
1745           result.Add(*symbol, Fold(std::move(*value)));
1746         } else if (MaybeExpr converted{
1747                        ConvertToType(*symbol, std::move(*value))}) {
1748           if (auto componentShape{GetShape(GetFoldingContext(), *symbol)}) {
1749             if (auto valueShape{GetShape(GetFoldingContext(), *converted)}) {
1750               if (GetRank(*componentShape) == 0 && GetRank(*valueShape) > 0) {
1751                 AttachDeclaration(
1752                     Say(expr.source,
1753                         "Rank-%d array value is not compatible with scalar component '%s'"_err_en_US,
1754                         GetRank(*valueShape), symbol->name()),
1755                     *symbol);
1756               } else {
1757                 auto checked{
1758                     CheckConformance(messages, *componentShape, *valueShape,
1759                         CheckConformanceFlags::RightIsExpandableDeferred,
1760                         "component", "value")};
1761                 if (checked && *checked && GetRank(*componentShape) > 0 &&
1762                     GetRank(*valueShape) == 0 &&
1763                     !IsExpandableScalar(*converted)) {
1764                   AttachDeclaration(
1765                       Say(expr.source,
1766                           "Scalar value cannot be expanded to shape of array component '%s'"_err_en_US,
1767                           symbol->name()),
1768                       *symbol);
1769                 }
1770                 if (checked.value_or(true)) {
1771                   result.Add(*symbol, std::move(*converted));
1772                 }
1773               }
1774             } else {
1775               Say(expr.source, "Shape of value cannot be determined"_err_en_US);
1776             }
1777           } else {
1778             AttachDeclaration(
1779                 Say(expr.source,
1780                     "Shape of component '%s' cannot be determined"_err_en_US,
1781                     symbol->name()),
1782                 *symbol);
1783           }
1784         } else if (IsAllocatable(*symbol) && IsBareNullPointer(&*value)) {
1785           // NULL() with no arguments allowed by 7.5.10 para 6 for ALLOCATABLE.
1786           result.Add(*symbol, Expr<SomeType>{NullPointer{}});
1787         } else if (auto symType{DynamicType::From(symbol)}) {
1788           if (IsAllocatable(*symbol) && symType->IsUnlimitedPolymorphic() &&
1789               valueType) {
1790             // ok
1791           } else if (valueType) {
1792             AttachDeclaration(
1793                 Say(expr.source,
1794                     "Value in structure constructor of type '%s' is "
1795                     "incompatible with component '%s' of type '%s'"_err_en_US,
1796                     valueType->AsFortran(), symbol->name(),
1797                     symType->AsFortran()),
1798                 *symbol);
1799           } else {
1800             AttachDeclaration(
1801                 Say(expr.source,
1802                     "Value in structure constructor is incompatible with "
1803                     "component '%s' of type %s"_err_en_US,
1804                     symbol->name(), symType->AsFortran()),
1805                 *symbol);
1806           }
1807         }
1808       }
1809     }
1810   }
1811 
1812   // Ensure that unmentioned component objects have default initializers.
1813   for (const Symbol &symbol : components) {
1814     if (!symbol.test(Symbol::Flag::ParentComp) &&
1815         unavailable.find(symbol.name()) == unavailable.cend()) {
1816       if (IsAllocatable(symbol)) {
1817         // Set all remaining allocatables to explicit NULL()
1818         result.Add(symbol, Expr<SomeType>{NullPointer{}});
1819       } else if (const auto *details{
1820                      symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
1821         if (details->init()) {
1822           result.Add(symbol, common::Clone(*details->init()));
1823         } else { // C799
1824           AttachDeclaration(Say(typeName,
1825                                 "Structure constructor lacks a value for "
1826                                 "component '%s'"_err_en_US,
1827                                 symbol.name()),
1828               symbol);
1829         }
1830       }
1831     }
1832   }
1833 
1834   return AsMaybeExpr(Expr<SomeDerived>{std::move(result)});
1835 }
1836 
1837 static std::optional<parser::CharBlock> GetPassName(
1838     const semantics::Symbol &proc) {
1839   return common::visit(
1840       [](const auto &details) {
1841         if constexpr (std::is_base_of_v<semantics::WithPassArg,
1842                           std::decay_t<decltype(details)>>) {
1843           return details.passName();
1844         } else {
1845           return std::optional<parser::CharBlock>{};
1846         }
1847       },
1848       proc.details());
1849 }
1850 
1851 static int GetPassIndex(const Symbol &proc) {
1852   CHECK(!proc.attrs().test(semantics::Attr::NOPASS));
1853   std::optional<parser::CharBlock> passName{GetPassName(proc)};
1854   const auto *interface { semantics::FindInterface(proc) };
1855   if (!passName || !interface) {
1856     return 0; // first argument is passed-object
1857   }
1858   const auto &subp{interface->get<semantics::SubprogramDetails>()};
1859   int index{0};
1860   for (const auto *arg : subp.dummyArgs()) {
1861     if (arg && arg->name() == passName) {
1862       return index;
1863     }
1864     ++index;
1865   }
1866   DIE("PASS argument name not in dummy argument list");
1867 }
1868 
1869 // Injects an expression into an actual argument list as the "passed object"
1870 // for a type-bound procedure reference that is not NOPASS.  Adds an
1871 // argument keyword if possible, but not when the passed object goes
1872 // before a positional argument.
1873 // e.g., obj%tbp(x) -> tbp(obj,x).
1874 static void AddPassArg(ActualArguments &actuals, const Expr<SomeDerived> &expr,
1875     const Symbol &component, bool isPassedObject = true) {
1876   if (component.attrs().test(semantics::Attr::NOPASS)) {
1877     return;
1878   }
1879   int passIndex{GetPassIndex(component)};
1880   auto iter{actuals.begin()};
1881   int at{0};
1882   while (iter < actuals.end() && at < passIndex) {
1883     if (*iter && (*iter)->keyword()) {
1884       iter = actuals.end();
1885       break;
1886     }
1887     ++iter;
1888     ++at;
1889   }
1890   ActualArgument passed{AsGenericExpr(common::Clone(expr))};
1891   passed.set_isPassedObject(isPassedObject);
1892   if (iter == actuals.end()) {
1893     if (auto passName{GetPassName(component)}) {
1894       passed.set_keyword(*passName);
1895     }
1896   }
1897   actuals.emplace(iter, std::move(passed));
1898 }
1899 
1900 // Return the compile-time resolution of a procedure binding, if possible.
1901 static const Symbol *GetBindingResolution(
1902     const std::optional<DynamicType> &baseType, const Symbol &component) {
1903   const auto *binding{component.detailsIf<semantics::ProcBindingDetails>()};
1904   if (!binding) {
1905     return nullptr;
1906   }
1907   if (!component.attrs().test(semantics::Attr::NON_OVERRIDABLE) &&
1908       (!baseType || baseType->IsPolymorphic())) {
1909     return nullptr;
1910   }
1911   return &binding->symbol();
1912 }
1913 
1914 auto ExpressionAnalyzer::AnalyzeProcedureComponentRef(
1915     const parser::ProcComponentRef &pcr, ActualArguments &&arguments,
1916     bool isSubroutine) -> std::optional<CalleeAndArguments> {
1917   const parser::StructureComponent &sc{pcr.v.thing};
1918   if (MaybeExpr base{Analyze(sc.base)}) {
1919     if (const Symbol * sym{sc.component.symbol}) {
1920       if (context_.HasError(sym)) {
1921         return std::nullopt;
1922       }
1923       if (!IsProcedure(*sym)) {
1924         AttachDeclaration(
1925             Say(sc.component.source, "'%s' is not a procedure"_err_en_US,
1926                 sc.component.source),
1927             *sym);
1928         return std::nullopt;
1929       }
1930       if (auto *dtExpr{UnwrapExpr<Expr<SomeDerived>>(*base)}) {
1931         if (sym->has<semantics::GenericDetails>()) {
1932           AdjustActuals adjustment{
1933               [&](const Symbol &proc, ActualArguments &actuals) {
1934                 if (!proc.attrs().test(semantics::Attr::NOPASS)) {
1935                   AddPassArg(actuals, std::move(*dtExpr), proc);
1936                 }
1937                 return true;
1938               }};
1939           auto pair{ResolveGeneric(*sym, arguments, adjustment, isSubroutine)};
1940           sym = pair.first;
1941           if (sym) {
1942             // re-resolve the name to the specific binding
1943             sc.component.symbol = const_cast<Symbol *>(sym);
1944           } else {
1945             EmitGenericResolutionError(*sc.component.symbol, pair.second);
1946             return std::nullopt;
1947           }
1948         }
1949         if (const Symbol *
1950             resolution{GetBindingResolution(dtExpr->GetType(), *sym)}) {
1951           AddPassArg(arguments, std::move(*dtExpr), *sym, false);
1952           return CalleeAndArguments{
1953               ProcedureDesignator{*resolution}, std::move(arguments)};
1954         } else if (std::optional<DataRef> dataRef{
1955                        ExtractDataRef(std::move(*dtExpr))}) {
1956           if (sym->attrs().test(semantics::Attr::NOPASS)) {
1957             return CalleeAndArguments{
1958                 ProcedureDesignator{Component{std::move(*dataRef), *sym}},
1959                 std::move(arguments)};
1960           } else {
1961             AddPassArg(arguments,
1962                 Expr<SomeDerived>{Designator<SomeDerived>{std::move(*dataRef)}},
1963                 *sym);
1964             return CalleeAndArguments{
1965                 ProcedureDesignator{*sym}, std::move(arguments)};
1966           }
1967         }
1968       }
1969       Say(sc.component.source,
1970           "Base of procedure component reference is not a derived-type object"_err_en_US);
1971     }
1972   }
1973   CHECK(context_.AnyFatalError());
1974   return std::nullopt;
1975 }
1976 
1977 // Can actual be argument associated with dummy?
1978 static bool CheckCompatibleArgument(bool isElemental,
1979     const ActualArgument &actual, const characteristics::DummyArgument &dummy) {
1980   const auto *expr{actual.UnwrapExpr()};
1981   return common::visit(
1982       common::visitors{
1983           [&](const characteristics::DummyDataObject &x) {
1984             if (x.attrs.test(characteristics::DummyDataObject::Attr::Pointer) &&
1985                 IsBareNullPointer(expr)) {
1986               // NULL() without MOLD= is compatible with any dummy data pointer
1987               // but cannot be allowed to lead to ambiguity.
1988               return true;
1989             } else if (!isElemental && actual.Rank() != x.type.Rank() &&
1990                 !x.type.attrs().test(
1991                     characteristics::TypeAndShape::Attr::AssumedRank)) {
1992               return false;
1993             } else if (auto actualType{actual.GetType()}) {
1994               return x.type.type().IsTkCompatibleWith(*actualType);
1995             }
1996             return false;
1997           },
1998           [&](const characteristics::DummyProcedure &) {
1999             return expr && IsProcedurePointerTarget(*expr);
2000           },
2001           [&](const characteristics::AlternateReturn &) {
2002             return actual.isAlternateReturn();
2003           },
2004       },
2005       dummy.u);
2006 }
2007 
2008 // Are the actual arguments compatible with the dummy arguments of procedure?
2009 static bool CheckCompatibleArguments(
2010     const characteristics::Procedure &procedure,
2011     const ActualArguments &actuals) {
2012   bool isElemental{procedure.IsElemental()};
2013   const auto &dummies{procedure.dummyArguments};
2014   CHECK(dummies.size() == actuals.size());
2015   for (std::size_t i{0}; i < dummies.size(); ++i) {
2016     const characteristics::DummyArgument &dummy{dummies[i]};
2017     const std::optional<ActualArgument> &actual{actuals[i]};
2018     if (actual && !CheckCompatibleArgument(isElemental, *actual, dummy)) {
2019       return false;
2020     }
2021   }
2022   return true;
2023 }
2024 
2025 // Handles a forward reference to a module function from what must
2026 // be a specification expression.  Return false if the symbol is
2027 // an invalid forward reference.
2028 bool ExpressionAnalyzer::ResolveForward(const Symbol &symbol) {
2029   if (context_.HasError(symbol)) {
2030     return false;
2031   }
2032   if (const auto *details{
2033           symbol.detailsIf<semantics::SubprogramNameDetails>()}) {
2034     if (details->kind() == semantics::SubprogramKind::Module) {
2035       // If this symbol is still a SubprogramNameDetails, we must be
2036       // checking a specification expression in a sibling module
2037       // procedure.  Resolve its names now so that its interface
2038       // is known.
2039       semantics::ResolveSpecificationParts(context_, symbol);
2040       if (symbol.has<semantics::SubprogramNameDetails>()) {
2041         // When the symbol hasn't had its details updated, we must have
2042         // already been in the process of resolving the function's
2043         // specification part; but recursive function calls are not
2044         // allowed in specification parts (10.1.11 para 5).
2045         Say("The module function '%s' may not be referenced recursively in a specification expression"_err_en_US,
2046             symbol.name());
2047         context_.SetError(symbol);
2048         return false;
2049       }
2050     } else { // 10.1.11 para 4
2051       Say("The internal function '%s' may not be referenced in a specification expression"_err_en_US,
2052           symbol.name());
2053       context_.SetError(symbol);
2054       return false;
2055     }
2056   }
2057   return true;
2058 }
2059 
2060 // Resolve a call to a generic procedure with given actual arguments.
2061 // adjustActuals is called on procedure bindings to handle pass arg.
2062 std::pair<const Symbol *, bool> ExpressionAnalyzer::ResolveGeneric(
2063     const Symbol &symbol, const ActualArguments &actuals,
2064     const AdjustActuals &adjustActuals, bool isSubroutine,
2065     bool mightBeStructureConstructor) {
2066   const Symbol *elemental{nullptr}; // matching elemental specific proc
2067   const Symbol *nonElemental{nullptr}; // matching non-elemental specific
2068   const Symbol &ultimate{symbol.GetUltimate()};
2069   // Check for a match with an explicit INTRINSIC
2070   if (ultimate.attrs().test(semantics::Attr::INTRINSIC)) {
2071     parser::Messages buffer;
2072     auto restorer{foldingContext_.messages().SetMessages(buffer)};
2073     ActualArguments localActuals{actuals};
2074     if (context_.intrinsics().Probe(
2075             CallCharacteristics{ultimate.name().ToString(), isSubroutine},
2076             localActuals, foldingContext_) &&
2077         !buffer.AnyFatalError()) {
2078       return {&ultimate, false};
2079     }
2080   }
2081   if (const auto *details{ultimate.detailsIf<semantics::GenericDetails>()}) {
2082     bool anyBareNullActual{
2083         std::find_if(actuals.begin(), actuals.end(), [](auto iter) {
2084           return IsBareNullPointer(iter->UnwrapExpr());
2085         }) != actuals.end()};
2086     for (const Symbol &specific : details->specificProcs()) {
2087       if (!ResolveForward(specific)) {
2088         continue;
2089       }
2090       if (std::optional<characteristics::Procedure> procedure{
2091               characteristics::Procedure::Characterize(
2092                   ProcedureDesignator{specific}, context_.foldingContext())}) {
2093         ActualArguments localActuals{actuals};
2094         if (specific.has<semantics::ProcBindingDetails>()) {
2095           if (!adjustActuals.value()(specific, localActuals)) {
2096             continue;
2097           }
2098         }
2099         if (semantics::CheckInterfaceForGeneric(*procedure, localActuals,
2100                 GetFoldingContext(), false /* no integer conversions */) &&
2101             CheckCompatibleArguments(*procedure, localActuals)) {
2102           if ((procedure->IsElemental() && elemental) ||
2103               (!procedure->IsElemental() && nonElemental)) {
2104             // 16.9.144(6): a bare NULL() is not allowed as an actual
2105             // argument to a generic procedure if the specific procedure
2106             // cannot be unambiguously distinguished
2107             return {nullptr, true /* due to NULL actuals */};
2108           }
2109           if (!procedure->IsElemental()) {
2110             // takes priority over elemental match
2111             nonElemental = &specific;
2112             if (!anyBareNullActual) {
2113               break; // unambiguous case
2114             }
2115           } else {
2116             elemental = &specific;
2117           }
2118         }
2119       }
2120     }
2121     if (nonElemental) {
2122       return {&AccessSpecific(symbol, *nonElemental), false};
2123     } else if (elemental) {
2124       return {&AccessSpecific(symbol, *elemental), false};
2125     }
2126     // Check parent derived type
2127     if (const auto *parentScope{symbol.owner().GetDerivedTypeParent()}) {
2128       if (const Symbol * extended{parentScope->FindComponent(symbol.name())}) {
2129         auto pair{ResolveGeneric(
2130             *extended, actuals, adjustActuals, isSubroutine, false)};
2131         if (pair.first) {
2132           return pair;
2133         }
2134       }
2135     }
2136     if (mightBeStructureConstructor && details->derivedType()) {
2137       return {details->derivedType(), false};
2138     }
2139   }
2140   // Check for generic or explicit INTRINSIC of the same name in outer scopes.
2141   // See 15.5.5.2 for details.
2142   if (!symbol.owner().IsGlobal() && !symbol.owner().IsDerivedType()) {
2143     for (const std::string &n : GetAllNames(context_, symbol.name())) {
2144       if (const Symbol * outer{symbol.owner().parent().FindSymbol(n)}) {
2145         auto pair{ResolveGeneric(*outer, actuals, adjustActuals, isSubroutine,
2146             mightBeStructureConstructor)};
2147         if (pair.first) {
2148           return pair;
2149         }
2150       }
2151     }
2152   }
2153   return {nullptr, false};
2154 }
2155 
2156 const Symbol &ExpressionAnalyzer::AccessSpecific(
2157     const Symbol &originalGeneric, const Symbol &specific) {
2158   if (const auto *hosted{
2159           originalGeneric.detailsIf<semantics::HostAssocDetails>()}) {
2160     return AccessSpecific(hosted->symbol(), specific);
2161   } else if (const auto *used{
2162                  originalGeneric.detailsIf<semantics::UseDetails>()}) {
2163     const auto &scope{originalGeneric.owner()};
2164     if (auto iter{scope.find(specific.name())}; iter != scope.end()) {
2165       if (const auto *useDetails{
2166               iter->second->detailsIf<semantics::UseDetails>()}) {
2167         const Symbol &usedSymbol{useDetails->symbol()};
2168         const auto *usedGeneric{
2169             usedSymbol.detailsIf<semantics::GenericDetails>()};
2170         if (&usedSymbol == &specific ||
2171             (usedGeneric && usedGeneric->specific() == &specific)) {
2172           return specific;
2173         }
2174       }
2175     }
2176     // Create a renaming USE of the specific procedure.
2177     auto rename{context_.SaveTempName(
2178         used->symbol().owner().GetName().value().ToString() + "$" +
2179         specific.name().ToString())};
2180     return *const_cast<semantics::Scope &>(scope)
2181                 .try_emplace(rename, specific.attrs(),
2182                     semantics::UseDetails{rename, specific})
2183                 .first->second;
2184   } else {
2185     return specific;
2186   }
2187 }
2188 
2189 void ExpressionAnalyzer::EmitGenericResolutionError(
2190     const Symbol &symbol, bool dueToNullActuals) {
2191   Say(dueToNullActuals
2192           ? "One or more NULL() actual arguments to the generic procedure '%s' requires a MOLD= for disambiguation"_err_en_US
2193           : semantics::IsGenericDefinedOp(symbol)
2194           ? "No specific procedure of generic operator '%s' matches the actual arguments"_err_en_US
2195           : "No specific procedure of generic '%s' matches the actual arguments"_err_en_US,
2196       symbol.name());
2197 }
2198 
2199 auto ExpressionAnalyzer::GetCalleeAndArguments(
2200     const parser::ProcedureDesignator &pd, ActualArguments &&arguments,
2201     bool isSubroutine, bool mightBeStructureConstructor)
2202     -> std::optional<CalleeAndArguments> {
2203   return common::visit(
2204       common::visitors{
2205           [&](const parser::Name &name) {
2206             return GetCalleeAndArguments(name, std::move(arguments),
2207                 isSubroutine, mightBeStructureConstructor);
2208           },
2209           [&](const parser::ProcComponentRef &pcr) {
2210             return AnalyzeProcedureComponentRef(
2211                 pcr, std::move(arguments), isSubroutine);
2212           },
2213       },
2214       pd.u);
2215 }
2216 
2217 auto ExpressionAnalyzer::GetCalleeAndArguments(const parser::Name &name,
2218     ActualArguments &&arguments, bool isSubroutine,
2219     bool mightBeStructureConstructor) -> std::optional<CalleeAndArguments> {
2220   const Symbol *symbol{name.symbol};
2221   if (context_.HasError(symbol)) {
2222     return std::nullopt; // also handles null symbol
2223   }
2224   const Symbol &ultimate{DEREF(symbol).GetUltimate()};
2225   CheckForBadRecursion(name.source, ultimate);
2226   bool dueToNullActual{false};
2227   bool isGenericInterface{ultimate.has<semantics::GenericDetails>()};
2228   bool isExplicitIntrinsic{ultimate.attrs().test(semantics::Attr::INTRINSIC)};
2229   const Symbol *resolution{nullptr};
2230   if (isGenericInterface || isExplicitIntrinsic) {
2231     ExpressionAnalyzer::AdjustActuals noAdjustment;
2232     auto pair{ResolveGeneric(*symbol, arguments, noAdjustment, isSubroutine,
2233         mightBeStructureConstructor)};
2234     resolution = pair.first;
2235     dueToNullActual = pair.second;
2236     if (resolution) {
2237       // re-resolve name to the specific procedure
2238       name.symbol = const_cast<Symbol *>(resolution);
2239     }
2240   } else {
2241     resolution = symbol;
2242   }
2243   if (!resolution || resolution->attrs().test(semantics::Attr::INTRINSIC)) {
2244     // Not generic, or no resolution; may be intrinsic
2245     if (std::optional<SpecificCall> specificCall{context_.intrinsics().Probe(
2246             CallCharacteristics{ultimate.name().ToString(), isSubroutine},
2247             arguments, GetFoldingContext())}) {
2248       CheckBadExplicitType(*specificCall, *symbol);
2249       return CalleeAndArguments{
2250           ProcedureDesignator{std::move(specificCall->specificIntrinsic)},
2251           std::move(specificCall->arguments)};
2252     } else {
2253       if (isGenericInterface) {
2254         EmitGenericResolutionError(*symbol, dueToNullActual);
2255       }
2256       return std::nullopt;
2257     }
2258   }
2259   if (resolution->GetUltimate().has<semantics::DerivedTypeDetails>()) {
2260     if (mightBeStructureConstructor) {
2261       return CalleeAndArguments{
2262           semantics::SymbolRef{*resolution}, std::move(arguments)};
2263     }
2264   } else if (IsProcedure(*resolution)) {
2265     return CalleeAndArguments{
2266         ProcedureDesignator{*resolution}, std::move(arguments)};
2267   }
2268   if (!context_.HasError(*resolution)) {
2269     AttachDeclaration(
2270         Say(name.source, "'%s' is not a callable procedure"_err_en_US,
2271             name.source),
2272         *resolution);
2273   }
2274   return std::nullopt;
2275 }
2276 
2277 // Fortran 2018 expressly states (8.2 p3) that any declared type for a
2278 // generic intrinsic function "has no effect" on the result type of a
2279 // call to that intrinsic.  So one can declare "character*8 cos" and
2280 // still get a real result from "cos(1.)".  This is a dangerous feature,
2281 // especially since implementations are free to extend their sets of
2282 // intrinsics, and in doing so might clash with a name in a program.
2283 // So we emit a warning in this situation, and perhaps it should be an
2284 // error -- any correctly working program can silence the message by
2285 // simply deleting the pointless type declaration.
2286 void ExpressionAnalyzer::CheckBadExplicitType(
2287     const SpecificCall &call, const Symbol &intrinsic) {
2288   if (intrinsic.GetUltimate().GetType()) {
2289     const auto &procedure{call.specificIntrinsic.characteristics.value()};
2290     if (const auto &result{procedure.functionResult}) {
2291       if (const auto *typeAndShape{result->GetTypeAndShape()}) {
2292         if (auto declared{
2293                 typeAndShape->Characterize(intrinsic, GetFoldingContext())}) {
2294           if (!declared->type().IsTkCompatibleWith(typeAndShape->type())) {
2295             if (auto *msg{Say(
2296                     "The result type '%s' of the intrinsic function '%s' is not the explicit declared type '%s'"_warn_en_US,
2297                     typeAndShape->AsFortran(), intrinsic.name(),
2298                     declared->AsFortran())}) {
2299               msg->Attach(intrinsic.name(),
2300                   "Ignored declaration of intrinsic function '%s'"_en_US,
2301                   intrinsic.name());
2302             }
2303           }
2304         }
2305       }
2306     }
2307   }
2308 }
2309 
2310 void ExpressionAnalyzer::CheckForBadRecursion(
2311     parser::CharBlock callSite, const semantics::Symbol &proc) {
2312   if (const auto *scope{proc.scope()}) {
2313     if (scope->sourceRange().Contains(callSite)) {
2314       parser::Message *msg{nullptr};
2315       if (proc.attrs().test(semantics::Attr::NON_RECURSIVE)) { // 15.6.2.1(3)
2316         msg = Say("NON_RECURSIVE procedure '%s' cannot call itself"_err_en_US,
2317             callSite);
2318       } else if (IsAssumedLengthCharacter(proc) && IsExternal(proc)) {
2319         // TODO: Also catch assumed PDT type parameters
2320         msg = Say( // 15.6.2.1(3)
2321             "Assumed-length CHARACTER(*) function '%s' cannot call itself"_err_en_US,
2322             callSite);
2323       }
2324       AttachDeclaration(msg, proc);
2325     }
2326   }
2327 }
2328 
2329 template <typename A> static const Symbol *AssumedTypeDummy(const A &x) {
2330   if (const auto *designator{
2331           std::get_if<common::Indirection<parser::Designator>>(&x.u)}) {
2332     if (const auto *dataRef{
2333             std::get_if<parser::DataRef>(&designator->value().u)}) {
2334       if (const auto *name{std::get_if<parser::Name>(&dataRef->u)}) {
2335         return AssumedTypeDummy(*name);
2336       }
2337     }
2338   }
2339   return nullptr;
2340 }
2341 template <>
2342 const Symbol *AssumedTypeDummy<parser::Name>(const parser::Name &name) {
2343   if (const Symbol * symbol{name.symbol}) {
2344     if (const auto *type{symbol->GetType()}) {
2345       if (type->category() == semantics::DeclTypeSpec::TypeStar) {
2346         return symbol;
2347       }
2348     }
2349   }
2350   return nullptr;
2351 }
2352 template <typename A>
2353 static const Symbol *AssumedTypePointerOrAllocatableDummy(const A &object) {
2354   // It is illegal for allocatable of pointer objects to be TYPE(*), but at that
2355   // point it is is not guaranteed that it has been checked the object has
2356   // POINTER or ALLOCATABLE attribute, so do not assume nullptr can be directly
2357   // returned.
2358   return common::visit(
2359       common::visitors{
2360           [&](const parser::StructureComponent &x) {
2361             return AssumedTypeDummy(x.component);
2362           },
2363           [&](const parser::Name &x) { return AssumedTypeDummy(x); },
2364       },
2365       object.u);
2366 }
2367 template <>
2368 const Symbol *AssumedTypeDummy<parser::AllocateObject>(
2369     const parser::AllocateObject &x) {
2370   return AssumedTypePointerOrAllocatableDummy(x);
2371 }
2372 template <>
2373 const Symbol *AssumedTypeDummy<parser::PointerObject>(
2374     const parser::PointerObject &x) {
2375   return AssumedTypePointerOrAllocatableDummy(x);
2376 }
2377 
2378 bool ExpressionAnalyzer::CheckIsValidForwardReference(
2379     const semantics::DerivedTypeSpec &dtSpec) {
2380   if (dtSpec.IsForwardReferenced()) {
2381     Say("Cannot construct value for derived type '%s' "
2382         "before it is defined"_err_en_US,
2383         dtSpec.name());
2384     return false;
2385   }
2386   return true;
2387 }
2388 
2389 MaybeExpr ExpressionAnalyzer::Analyze(const parser::FunctionReference &funcRef,
2390     std::optional<parser::StructureConstructor> *structureConstructor) {
2391   const parser::Call &call{funcRef.v};
2392   auto restorer{GetContextualMessages().SetLocation(call.source)};
2393   ArgumentAnalyzer analyzer{*this, call.source, true /* isProcedureCall */};
2394   for (const auto &arg : std::get<std::list<parser::ActualArgSpec>>(call.t)) {
2395     analyzer.Analyze(arg, false /* not subroutine call */);
2396   }
2397   if (analyzer.fatalErrors()) {
2398     return std::nullopt;
2399   }
2400   if (std::optional<CalleeAndArguments> callee{
2401           GetCalleeAndArguments(std::get<parser::ProcedureDesignator>(call.t),
2402               analyzer.GetActuals(), false /* not subroutine */,
2403               true /* might be structure constructor */)}) {
2404     if (auto *proc{std::get_if<ProcedureDesignator>(&callee->u)}) {
2405       return MakeFunctionRef(
2406           call.source, std::move(*proc), std::move(callee->arguments));
2407     }
2408     CHECK(std::holds_alternative<semantics::SymbolRef>(callee->u));
2409     const Symbol &symbol{*std::get<semantics::SymbolRef>(callee->u)};
2410     if (structureConstructor) {
2411       // Structure constructor misparsed as function reference?
2412       const auto &designator{std::get<parser::ProcedureDesignator>(call.t)};
2413       if (const auto *name{std::get_if<parser::Name>(&designator.u)}) {
2414         semantics::Scope &scope{context_.FindScope(name->source)};
2415         semantics::DerivedTypeSpec dtSpec{name->source, symbol.GetUltimate()};
2416         if (!CheckIsValidForwardReference(dtSpec)) {
2417           return std::nullopt;
2418         }
2419         const semantics::DeclTypeSpec &type{
2420             semantics::FindOrInstantiateDerivedType(scope, std::move(dtSpec))};
2421         auto &mutableRef{const_cast<parser::FunctionReference &>(funcRef)};
2422         *structureConstructor =
2423             mutableRef.ConvertToStructureConstructor(type.derivedTypeSpec());
2424         return Analyze(structureConstructor->value());
2425       }
2426     }
2427     if (!context_.HasError(symbol)) {
2428       AttachDeclaration(
2429           Say("'%s' is called like a function but is not a procedure"_err_en_US,
2430               symbol.name()),
2431           symbol);
2432       context_.SetError(symbol);
2433     }
2434   }
2435   return std::nullopt;
2436 }
2437 
2438 static bool HasAlternateReturns(const evaluate::ActualArguments &args) {
2439   for (const auto &arg : args) {
2440     if (arg && arg->isAlternateReturn()) {
2441       return true;
2442     }
2443   }
2444   return false;
2445 }
2446 
2447 void ExpressionAnalyzer::Analyze(const parser::CallStmt &callStmt) {
2448   const parser::Call &call{callStmt.v};
2449   auto restorer{GetContextualMessages().SetLocation(call.source)};
2450   ArgumentAnalyzer analyzer{*this, call.source, true /* isProcedureCall */};
2451   const auto &actualArgList{std::get<std::list<parser::ActualArgSpec>>(call.t)};
2452   for (const auto &arg : actualArgList) {
2453     analyzer.Analyze(arg, true /* is subroutine call */);
2454   }
2455   if (!analyzer.fatalErrors()) {
2456     if (std::optional<CalleeAndArguments> callee{
2457             GetCalleeAndArguments(std::get<parser::ProcedureDesignator>(call.t),
2458                 analyzer.GetActuals(), true /* subroutine */)}) {
2459       ProcedureDesignator *proc{std::get_if<ProcedureDesignator>(&callee->u)};
2460       CHECK(proc);
2461       if (CheckCall(call.source, *proc, callee->arguments)) {
2462         callStmt.typedCall.Reset(
2463             new ProcedureRef{std::move(*proc), std::move(callee->arguments),
2464                 HasAlternateReturns(callee->arguments)},
2465             ProcedureRef::Deleter);
2466         return;
2467       }
2468     }
2469     if (!context_.AnyFatalError()) {
2470       std::string buf;
2471       llvm::raw_string_ostream dump{buf};
2472       parser::DumpTree(dump, callStmt);
2473       Say("Internal error: Expression analysis failed on CALL statement: %s"_err_en_US,
2474           dump.str());
2475     }
2476   }
2477 }
2478 
2479 const Assignment *ExpressionAnalyzer::Analyze(const parser::AssignmentStmt &x) {
2480   if (!x.typedAssignment) {
2481     ArgumentAnalyzer analyzer{*this};
2482     analyzer.Analyze(std::get<parser::Variable>(x.t));
2483     analyzer.Analyze(std::get<parser::Expr>(x.t));
2484     std::optional<Assignment> assignment;
2485     if (!analyzer.fatalErrors()) {
2486       std::optional<ProcedureRef> procRef{analyzer.TryDefinedAssignment()};
2487       if (!procRef) {
2488         analyzer.CheckForNullPointer(
2489             "in a non-pointer intrinsic assignment statement");
2490       }
2491       assignment.emplace(analyzer.MoveExpr(0), analyzer.MoveExpr(1));
2492       if (procRef) {
2493         assignment->u = std::move(*procRef);
2494       }
2495     }
2496     x.typedAssignment.Reset(new GenericAssignmentWrapper{std::move(assignment)},
2497         GenericAssignmentWrapper::Deleter);
2498   }
2499   return common::GetPtrFromOptional(x.typedAssignment->v);
2500 }
2501 
2502 const Assignment *ExpressionAnalyzer::Analyze(
2503     const parser::PointerAssignmentStmt &x) {
2504   if (!x.typedAssignment) {
2505     MaybeExpr lhs{Analyze(std::get<parser::DataRef>(x.t))};
2506     MaybeExpr rhs{Analyze(std::get<parser::Expr>(x.t))};
2507     if (!lhs || !rhs) {
2508       x.typedAssignment.Reset(
2509           new GenericAssignmentWrapper{}, GenericAssignmentWrapper::Deleter);
2510     } else {
2511       Assignment assignment{std::move(*lhs), std::move(*rhs)};
2512       common::visit(
2513           common::visitors{
2514               [&](const std::list<parser::BoundsRemapping> &list) {
2515                 Assignment::BoundsRemapping bounds;
2516                 for (const auto &elem : list) {
2517                   auto lower{AsSubscript(Analyze(std::get<0>(elem.t)))};
2518                   auto upper{AsSubscript(Analyze(std::get<1>(elem.t)))};
2519                   if (lower && upper) {
2520                     bounds.emplace_back(
2521                         Fold(std::move(*lower)), Fold(std::move(*upper)));
2522                   }
2523                 }
2524                 assignment.u = std::move(bounds);
2525               },
2526               [&](const std::list<parser::BoundsSpec> &list) {
2527                 Assignment::BoundsSpec bounds;
2528                 for (const auto &bound : list) {
2529                   if (auto lower{AsSubscript(Analyze(bound.v))}) {
2530                     bounds.emplace_back(Fold(std::move(*lower)));
2531                   }
2532                 }
2533                 assignment.u = std::move(bounds);
2534               },
2535           },
2536           std::get<parser::PointerAssignmentStmt::Bounds>(x.t).u);
2537       x.typedAssignment.Reset(
2538           new GenericAssignmentWrapper{std::move(assignment)},
2539           GenericAssignmentWrapper::Deleter);
2540     }
2541   }
2542   return common::GetPtrFromOptional(x.typedAssignment->v);
2543 }
2544 
2545 static bool IsExternalCalledImplicitly(
2546     parser::CharBlock callSite, const ProcedureDesignator &proc) {
2547   if (const auto *symbol{proc.GetSymbol()}) {
2548     return symbol->has<semantics::SubprogramDetails>() &&
2549         symbol->owner().IsGlobal() &&
2550         (!symbol->scope() /*ENTRY*/ ||
2551             !symbol->scope()->sourceRange().Contains(callSite));
2552   } else {
2553     return false;
2554   }
2555 }
2556 
2557 std::optional<characteristics::Procedure> ExpressionAnalyzer::CheckCall(
2558     parser::CharBlock callSite, const ProcedureDesignator &proc,
2559     ActualArguments &arguments) {
2560   auto chars{characteristics::Procedure::Characterize(
2561       proc, context_.foldingContext())};
2562   if (chars) {
2563     bool treatExternalAsImplicit{IsExternalCalledImplicitly(callSite, proc)};
2564     if (treatExternalAsImplicit && !chars->CanBeCalledViaImplicitInterface()) {
2565       Say(callSite,
2566           "References to the procedure '%s' require an explicit interface"_err_en_US,
2567           DEREF(proc.GetSymbol()).name());
2568     }
2569     // Checks for ASSOCIATED() are done in intrinsic table processing
2570     const SpecificIntrinsic *specificIntrinsic{proc.GetSpecificIntrinsic()};
2571     bool procIsAssociated{
2572         specificIntrinsic && specificIntrinsic->name == "associated"};
2573     if (!procIsAssociated) {
2574       const Symbol *procSymbol{proc.GetSymbol()};
2575       bool procIsDummy{procSymbol && IsDummy(*procSymbol)};
2576       if (chars->functionResult &&
2577           chars->functionResult->IsAssumedLengthCharacter() &&
2578           !specificIntrinsic && !procIsDummy) {
2579         Say(callSite,
2580             "Assumed-length character function must be defined with a length to be called"_err_en_US);
2581       }
2582       semantics::CheckArguments(*chars, arguments, GetFoldingContext(),
2583           context_.FindScope(callSite), treatExternalAsImplicit,
2584           specificIntrinsic);
2585       if (procSymbol && !IsPureProcedure(*procSymbol)) {
2586         if (const semantics::Scope *
2587             pure{semantics::FindPureProcedureContaining(
2588                 context_.FindScope(callSite))}) {
2589           Say(callSite,
2590               "Procedure '%s' referenced in pure subprogram '%s' must be pure too"_err_en_US,
2591               procSymbol->name(), DEREF(pure->symbol()).name());
2592         }
2593       }
2594     }
2595   }
2596   return chars;
2597 }
2598 
2599 // Unary operations
2600 
2601 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Parentheses &x) {
2602   if (MaybeExpr operand{Analyze(x.v.value())}) {
2603     if (const semantics::Symbol * symbol{GetLastSymbol(*operand)}) {
2604       if (const semantics::Symbol * result{FindFunctionResult(*symbol)}) {
2605         if (semantics::IsProcedurePointer(*result)) {
2606           Say("A function reference that returns a procedure "
2607               "pointer may not be parenthesized"_err_en_US); // C1003
2608         }
2609       }
2610     }
2611     return Parenthesize(std::move(*operand));
2612   }
2613   return std::nullopt;
2614 }
2615 
2616 static MaybeExpr NumericUnaryHelper(ExpressionAnalyzer &context,
2617     NumericOperator opr, const parser::Expr::IntrinsicUnary &x) {
2618   ArgumentAnalyzer analyzer{context};
2619   analyzer.Analyze(x.v);
2620   if (!analyzer.fatalErrors()) {
2621     if (analyzer.IsIntrinsicNumeric(opr)) {
2622       analyzer.CheckForNullPointer();
2623       if (opr == NumericOperator::Add) {
2624         return analyzer.MoveExpr(0);
2625       } else {
2626         return Negation(context.GetContextualMessages(), analyzer.MoveExpr(0));
2627       }
2628     } else {
2629       return analyzer.TryDefinedOp(AsFortran(opr),
2630           "Operand of unary %s must be numeric; have %s"_err_en_US);
2631     }
2632   }
2633   return std::nullopt;
2634 }
2635 
2636 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::UnaryPlus &x) {
2637   return NumericUnaryHelper(*this, NumericOperator::Add, x);
2638 }
2639 
2640 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Negate &x) {
2641   if (const auto *litConst{
2642           std::get_if<parser::LiteralConstant>(&x.v.value().u)}) {
2643     if (const auto *intConst{
2644             std::get_if<parser::IntLiteralConstant>(&litConst->u)}) {
2645       return Analyze(*intConst, true);
2646     }
2647   }
2648   return NumericUnaryHelper(*this, NumericOperator::Subtract, x);
2649 }
2650 
2651 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::NOT &x) {
2652   ArgumentAnalyzer analyzer{*this};
2653   analyzer.Analyze(x.v);
2654   if (!analyzer.fatalErrors()) {
2655     if (analyzer.IsIntrinsicLogical()) {
2656       analyzer.CheckForNullPointer();
2657       return AsGenericExpr(
2658           LogicalNegation(std::get<Expr<SomeLogical>>(analyzer.MoveExpr(0).u)));
2659     } else {
2660       return analyzer.TryDefinedOp(LogicalOperator::Not,
2661           "Operand of %s must be LOGICAL; have %s"_err_en_US);
2662     }
2663   }
2664   return std::nullopt;
2665 }
2666 
2667 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::PercentLoc &x) {
2668   // Represent %LOC() exactly as if it had been a call to the LOC() extension
2669   // intrinsic function.
2670   // Use the actual source for the name of the call for error reporting.
2671   std::optional<ActualArgument> arg;
2672   if (const Symbol * assumedTypeDummy{AssumedTypeDummy(x.v.value())}) {
2673     arg = ActualArgument{ActualArgument::AssumedType{*assumedTypeDummy}};
2674   } else if (MaybeExpr argExpr{Analyze(x.v.value())}) {
2675     arg = ActualArgument{std::move(*argExpr)};
2676   } else {
2677     return std::nullopt;
2678   }
2679   parser::CharBlock at{GetContextualMessages().at()};
2680   CHECK(at.size() >= 4);
2681   parser::CharBlock loc{at.begin() + 1, 3};
2682   CHECK(loc == "loc");
2683   return MakeFunctionRef(loc, ActualArguments{std::move(*arg)});
2684 }
2685 
2686 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::DefinedUnary &x) {
2687   const auto &name{std::get<parser::DefinedOpName>(x.t).v};
2688   ArgumentAnalyzer analyzer{*this, name.source};
2689   analyzer.Analyze(std::get<1>(x.t));
2690   return analyzer.TryDefinedOp(name.source.ToString().c_str(),
2691       "No operator %s defined for %s"_err_en_US, nullptr, true);
2692 }
2693 
2694 // Binary (dyadic) operations
2695 
2696 template <template <typename> class OPR>
2697 MaybeExpr NumericBinaryHelper(ExpressionAnalyzer &context, NumericOperator opr,
2698     const parser::Expr::IntrinsicBinary &x) {
2699   ArgumentAnalyzer analyzer{context};
2700   analyzer.Analyze(std::get<0>(x.t));
2701   analyzer.Analyze(std::get<1>(x.t));
2702   if (!analyzer.fatalErrors()) {
2703     if (analyzer.IsIntrinsicNumeric(opr)) {
2704       analyzer.CheckForNullPointer();
2705       analyzer.CheckConformance();
2706       return NumericOperation<OPR>(context.GetContextualMessages(),
2707           analyzer.MoveExpr(0), analyzer.MoveExpr(1),
2708           context.GetDefaultKind(TypeCategory::Real));
2709     } else {
2710       return analyzer.TryDefinedOp(AsFortran(opr),
2711           "Operands of %s must be numeric; have %s and %s"_err_en_US);
2712     }
2713   }
2714   return std::nullopt;
2715 }
2716 
2717 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Power &x) {
2718   return NumericBinaryHelper<Power>(*this, NumericOperator::Power, x);
2719 }
2720 
2721 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Multiply &x) {
2722   return NumericBinaryHelper<Multiply>(*this, NumericOperator::Multiply, x);
2723 }
2724 
2725 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Divide &x) {
2726   return NumericBinaryHelper<Divide>(*this, NumericOperator::Divide, x);
2727 }
2728 
2729 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Add &x) {
2730   return NumericBinaryHelper<Add>(*this, NumericOperator::Add, x);
2731 }
2732 
2733 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Subtract &x) {
2734   return NumericBinaryHelper<Subtract>(*this, NumericOperator::Subtract, x);
2735 }
2736 
2737 MaybeExpr ExpressionAnalyzer::Analyze(
2738     const parser::Expr::ComplexConstructor &x) {
2739   auto re{Analyze(std::get<0>(x.t).value())};
2740   auto im{Analyze(std::get<1>(x.t).value())};
2741   if (re && im) {
2742     ConformabilityCheck(GetContextualMessages(), *re, *im);
2743   }
2744   return AsMaybeExpr(ConstructComplex(GetContextualMessages(), std::move(re),
2745       std::move(im), GetDefaultKind(TypeCategory::Real)));
2746 }
2747 
2748 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Concat &x) {
2749   ArgumentAnalyzer analyzer{*this};
2750   analyzer.Analyze(std::get<0>(x.t));
2751   analyzer.Analyze(std::get<1>(x.t));
2752   if (!analyzer.fatalErrors()) {
2753     if (analyzer.IsIntrinsicConcat()) {
2754       analyzer.CheckForNullPointer();
2755       return common::visit(
2756           [&](auto &&x, auto &&y) -> MaybeExpr {
2757             using T = ResultType<decltype(x)>;
2758             if constexpr (std::is_same_v<T, ResultType<decltype(y)>>) {
2759               return AsGenericExpr(Concat<T::kind>{std::move(x), std::move(y)});
2760             } else {
2761               DIE("different types for intrinsic concat");
2762             }
2763           },
2764           std::move(std::get<Expr<SomeCharacter>>(analyzer.MoveExpr(0).u).u),
2765           std::move(std::get<Expr<SomeCharacter>>(analyzer.MoveExpr(1).u).u));
2766     } else {
2767       return analyzer.TryDefinedOp("//",
2768           "Operands of %s must be CHARACTER with the same kind; have %s and %s"_err_en_US);
2769     }
2770   }
2771   return std::nullopt;
2772 }
2773 
2774 // The Name represents a user-defined intrinsic operator.
2775 // If the actuals match one of the specific procedures, return a function ref.
2776 // Otherwise report the error in messages.
2777 MaybeExpr ExpressionAnalyzer::AnalyzeDefinedOp(
2778     const parser::Name &name, ActualArguments &&actuals) {
2779   if (auto callee{GetCalleeAndArguments(name, std::move(actuals))}) {
2780     CHECK(std::holds_alternative<ProcedureDesignator>(callee->u));
2781     return MakeFunctionRef(name.source,
2782         std::move(std::get<ProcedureDesignator>(callee->u)),
2783         std::move(callee->arguments));
2784   } else {
2785     return std::nullopt;
2786   }
2787 }
2788 
2789 MaybeExpr RelationHelper(ExpressionAnalyzer &context, RelationalOperator opr,
2790     const parser::Expr::IntrinsicBinary &x) {
2791   ArgumentAnalyzer analyzer{context};
2792   analyzer.Analyze(std::get<0>(x.t));
2793   analyzer.Analyze(std::get<1>(x.t));
2794   if (!analyzer.fatalErrors()) {
2795     std::optional<DynamicType> leftType{analyzer.GetType(0)};
2796     std::optional<DynamicType> rightType{analyzer.GetType(1)};
2797     analyzer.ConvertBOZ(leftType, 0, rightType);
2798     analyzer.ConvertBOZ(rightType, 1, leftType);
2799     if (leftType && rightType &&
2800         analyzer.IsIntrinsicRelational(opr, *leftType, *rightType)) {
2801       analyzer.CheckForNullPointer("as a relational operand");
2802       return AsMaybeExpr(Relate(context.GetContextualMessages(), opr,
2803           analyzer.MoveExpr(0), analyzer.MoveExpr(1)));
2804     } else {
2805       return analyzer.TryDefinedOp(opr,
2806           leftType && leftType->category() == TypeCategory::Logical &&
2807                   rightType && rightType->category() == TypeCategory::Logical
2808               ? "LOGICAL operands must be compared using .EQV. or .NEQV."_err_en_US
2809               : "Operands of %s must have comparable types; have %s and %s"_err_en_US);
2810     }
2811   }
2812   return std::nullopt;
2813 }
2814 
2815 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::LT &x) {
2816   return RelationHelper(*this, RelationalOperator::LT, x);
2817 }
2818 
2819 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::LE &x) {
2820   return RelationHelper(*this, RelationalOperator::LE, x);
2821 }
2822 
2823 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::EQ &x) {
2824   return RelationHelper(*this, RelationalOperator::EQ, x);
2825 }
2826 
2827 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::NE &x) {
2828   return RelationHelper(*this, RelationalOperator::NE, x);
2829 }
2830 
2831 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::GE &x) {
2832   return RelationHelper(*this, RelationalOperator::GE, x);
2833 }
2834 
2835 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::GT &x) {
2836   return RelationHelper(*this, RelationalOperator::GT, x);
2837 }
2838 
2839 MaybeExpr LogicalBinaryHelper(ExpressionAnalyzer &context, LogicalOperator opr,
2840     const parser::Expr::IntrinsicBinary &x) {
2841   ArgumentAnalyzer analyzer{context};
2842   analyzer.Analyze(std::get<0>(x.t));
2843   analyzer.Analyze(std::get<1>(x.t));
2844   if (!analyzer.fatalErrors()) {
2845     if (analyzer.IsIntrinsicLogical()) {
2846       analyzer.CheckForNullPointer("as a logical operand");
2847       return AsGenericExpr(BinaryLogicalOperation(opr,
2848           std::get<Expr<SomeLogical>>(analyzer.MoveExpr(0).u),
2849           std::get<Expr<SomeLogical>>(analyzer.MoveExpr(1).u)));
2850     } else {
2851       return analyzer.TryDefinedOp(
2852           opr, "Operands of %s must be LOGICAL; have %s and %s"_err_en_US);
2853     }
2854   }
2855   return std::nullopt;
2856 }
2857 
2858 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::AND &x) {
2859   return LogicalBinaryHelper(*this, LogicalOperator::And, x);
2860 }
2861 
2862 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::OR &x) {
2863   return LogicalBinaryHelper(*this, LogicalOperator::Or, x);
2864 }
2865 
2866 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::EQV &x) {
2867   return LogicalBinaryHelper(*this, LogicalOperator::Eqv, x);
2868 }
2869 
2870 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::NEQV &x) {
2871   return LogicalBinaryHelper(*this, LogicalOperator::Neqv, x);
2872 }
2873 
2874 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::DefinedBinary &x) {
2875   const auto &name{std::get<parser::DefinedOpName>(x.t).v};
2876   ArgumentAnalyzer analyzer{*this, name.source};
2877   analyzer.Analyze(std::get<1>(x.t));
2878   analyzer.Analyze(std::get<2>(x.t));
2879   return analyzer.TryDefinedOp(name.source.ToString().c_str(),
2880       "No operator %s defined for %s and %s"_err_en_US, nullptr, true);
2881 }
2882 
2883 // Returns true if a parsed function reference should be converted
2884 // into an array element reference.
2885 static bool CheckFuncRefToArrayElement(semantics::SemanticsContext &context,
2886     const parser::FunctionReference &funcRef) {
2887   // Emit message if the function reference fix will end up an array element
2888   // reference with no subscripts, or subscripts on a scalar, because it will
2889   // not be possible to later distinguish in expressions between an empty
2890   // subscript list due to bad subscripts error recovery or because the
2891   // user did not put any.
2892   auto &proc{std::get<parser::ProcedureDesignator>(funcRef.v.t)};
2893   const auto *name{std::get_if<parser::Name>(&proc.u)};
2894   if (!name) {
2895     name = &std::get<parser::ProcComponentRef>(proc.u).v.thing.component;
2896   }
2897   if (!name->symbol) {
2898     return false;
2899   } else if (name->symbol->Rank() == 0) {
2900     if (const Symbol *
2901         function{
2902             semantics::IsFunctionResultWithSameNameAsFunction(*name->symbol)}) {
2903       auto &msg{context.Say(funcRef.v.source,
2904           "Recursive call to '%s' requires a distinct RESULT in its declaration"_err_en_US,
2905           name->source)};
2906       AttachDeclaration(&msg, *function);
2907       name->symbol = const_cast<Symbol *>(function);
2908     }
2909     return false;
2910   } else {
2911     if (std::get<std::list<parser::ActualArgSpec>>(funcRef.v.t).empty()) {
2912       auto &msg{context.Say(funcRef.v.source,
2913           "Reference to array '%s' with empty subscript list"_err_en_US,
2914           name->source)};
2915       if (name->symbol) {
2916         AttachDeclaration(&msg, *name->symbol);
2917       }
2918     }
2919     return true;
2920   }
2921 }
2922 
2923 // Converts, if appropriate, an original misparse of ambiguous syntax like
2924 // A(1) as a function reference into an array reference.
2925 // Misparsed structure constructors are detected elsewhere after generic
2926 // function call resolution fails.
2927 template <typename... A>
2928 static void FixMisparsedFunctionReference(
2929     semantics::SemanticsContext &context, const std::variant<A...> &constU) {
2930   // The parse tree is updated in situ when resolving an ambiguous parse.
2931   using uType = std::decay_t<decltype(constU)>;
2932   auto &u{const_cast<uType &>(constU)};
2933   if (auto *func{
2934           std::get_if<common::Indirection<parser::FunctionReference>>(&u)}) {
2935     parser::FunctionReference &funcRef{func->value()};
2936     auto &proc{std::get<parser::ProcedureDesignator>(funcRef.v.t)};
2937     if (Symbol *
2938         origSymbol{
2939             common::visit(common::visitors{
2940                               [&](parser::Name &name) { return name.symbol; },
2941                               [&](parser::ProcComponentRef &pcr) {
2942                                 return pcr.v.thing.component.symbol;
2943                               },
2944                           },
2945                 proc.u)}) {
2946       Symbol &symbol{origSymbol->GetUltimate()};
2947       if (symbol.has<semantics::ObjectEntityDetails>() ||
2948           symbol.has<semantics::AssocEntityDetails>()) {
2949         // Note that expression in AssocEntityDetails cannot be a procedure
2950         // pointer as per C1105 so this cannot be a function reference.
2951         if constexpr (common::HasMember<common::Indirection<parser::Designator>,
2952                           uType>) {
2953           if (CheckFuncRefToArrayElement(context, funcRef)) {
2954             u = common::Indirection{funcRef.ConvertToArrayElementRef()};
2955           }
2956         } else {
2957           DIE("can't fix misparsed function as array reference");
2958         }
2959       }
2960     }
2961   }
2962 }
2963 
2964 // Common handling of parse tree node types that retain the
2965 // representation of the analyzed expression.
2966 template <typename PARSED>
2967 MaybeExpr ExpressionAnalyzer::ExprOrVariable(
2968     const PARSED &x, parser::CharBlock source) {
2969   if (useSavedTypedExprs_ && x.typedExpr) {
2970     return x.typedExpr->v;
2971   }
2972   auto restorer{GetContextualMessages().SetLocation(source)};
2973   if constexpr (std::is_same_v<PARSED, parser::Expr> ||
2974       std::is_same_v<PARSED, parser::Variable>) {
2975     FixMisparsedFunctionReference(context_, x.u);
2976   }
2977   if (AssumedTypeDummy(x)) { // C710
2978     Say("TYPE(*) dummy argument may only be used as an actual argument"_err_en_US);
2979     ResetExpr(x);
2980     return std::nullopt;
2981   }
2982   MaybeExpr result;
2983   if constexpr (common::HasMember<parser::StructureConstructor,
2984                     std::decay_t<decltype(x.u)>> &&
2985       common::HasMember<common::Indirection<parser::FunctionReference>,
2986           std::decay_t<decltype(x.u)>>) {
2987     if (const auto *funcRef{
2988             std::get_if<common::Indirection<parser::FunctionReference>>(
2989                 &x.u)}) {
2990       // Function references in Exprs might turn out to be misparsed structure
2991       // constructors; we have to try generic procedure resolution
2992       // first to be sure.
2993       std::optional<parser::StructureConstructor> ctor;
2994       result = Analyze(funcRef->value(), &ctor);
2995       if (result && ctor) {
2996         // A misparsed function reference is really a structure
2997         // constructor.  Repair the parse tree in situ.
2998         const_cast<PARSED &>(x).u = std::move(*ctor);
2999       }
3000     } else {
3001       result = Analyze(x.u);
3002     }
3003   } else {
3004     result = Analyze(x.u);
3005   }
3006   if (result) {
3007     SetExpr(x, Fold(std::move(*result)));
3008     return x.typedExpr->v;
3009   } else {
3010     ResetExpr(x);
3011     if (!context_.AnyFatalError()) {
3012       std::string buf;
3013       llvm::raw_string_ostream dump{buf};
3014       parser::DumpTree(dump, x);
3015       Say("Internal error: Expression analysis failed on: %s"_err_en_US,
3016           dump.str());
3017     }
3018     return std::nullopt;
3019   }
3020 }
3021 
3022 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr &expr) {
3023   return ExprOrVariable(expr, expr.source);
3024 }
3025 
3026 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Variable &variable) {
3027   return ExprOrVariable(variable, variable.GetSource());
3028 }
3029 
3030 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Selector &selector) {
3031   if (const auto *var{std::get_if<parser::Variable>(&selector.u)}) {
3032     if (!useSavedTypedExprs_ || !var->typedExpr) {
3033       parser::CharBlock source{var->GetSource()};
3034       auto restorer{GetContextualMessages().SetLocation(source)};
3035       FixMisparsedFunctionReference(context_, var->u);
3036       if (const auto *funcRef{
3037               std::get_if<common::Indirection<parser::FunctionReference>>(
3038                   &var->u)}) {
3039         // A Selector that parsed as a Variable might turn out during analysis
3040         // to actually be a structure constructor.  In that case, repair the
3041         // Variable parse tree node into an Expr
3042         std::optional<parser::StructureConstructor> ctor;
3043         if (MaybeExpr result{Analyze(funcRef->value(), &ctor)}) {
3044           if (ctor) {
3045             auto &writable{const_cast<parser::Selector &>(selector)};
3046             writable.u = parser::Expr{std::move(*ctor)};
3047             auto &expr{std::get<parser::Expr>(writable.u)};
3048             expr.source = source;
3049             SetExpr(expr, Fold(std::move(*result)));
3050             return expr.typedExpr->v;
3051           } else {
3052             SetExpr(*var, Fold(std::move(*result)));
3053             return var->typedExpr->v;
3054           }
3055         } else {
3056           ResetExpr(*var);
3057           if (context_.AnyFatalError()) {
3058             return std::nullopt;
3059           }
3060         }
3061       }
3062     }
3063   }
3064   // Not a Variable -> FunctionReference; handle normally as Variable or Expr
3065   return Analyze(selector.u);
3066 }
3067 
3068 MaybeExpr ExpressionAnalyzer::Analyze(const parser::DataStmtConstant &x) {
3069   auto restorer{common::ScopedSet(inDataStmtConstant_, true)};
3070   return ExprOrVariable(x, x.source);
3071 }
3072 
3073 MaybeExpr ExpressionAnalyzer::Analyze(const parser::AllocateObject &x) {
3074   return ExprOrVariable(x, parser::FindSourceLocation(x));
3075 }
3076 
3077 MaybeExpr ExpressionAnalyzer::Analyze(const parser::PointerObject &x) {
3078   return ExprOrVariable(x, parser::FindSourceLocation(x));
3079 }
3080 
3081 Expr<SubscriptInteger> ExpressionAnalyzer::AnalyzeKindSelector(
3082     TypeCategory category,
3083     const std::optional<parser::KindSelector> &selector) {
3084   int defaultKind{GetDefaultKind(category)};
3085   if (!selector) {
3086     return Expr<SubscriptInteger>{defaultKind};
3087   }
3088   return common::visit(
3089       common::visitors{
3090           [&](const parser::ScalarIntConstantExpr &x) {
3091             if (MaybeExpr kind{Analyze(x)}) {
3092               if (std::optional<std::int64_t> code{ToInt64(*kind)}) {
3093                 if (CheckIntrinsicKind(category, *code)) {
3094                   return Expr<SubscriptInteger>{*code};
3095                 }
3096               } else if (auto *intExpr{UnwrapExpr<Expr<SomeInteger>>(*kind)}) {
3097                 return ConvertToType<SubscriptInteger>(std::move(*intExpr));
3098               }
3099             }
3100             return Expr<SubscriptInteger>{defaultKind};
3101           },
3102           [&](const parser::KindSelector::StarSize &x) {
3103             std::intmax_t size = x.v;
3104             if (!CheckIntrinsicSize(category, size)) {
3105               size = defaultKind;
3106             } else if (category == TypeCategory::Complex) {
3107               size /= 2;
3108             }
3109             return Expr<SubscriptInteger>{size};
3110           },
3111       },
3112       selector->u);
3113 }
3114 
3115 int ExpressionAnalyzer::GetDefaultKind(common::TypeCategory category) {
3116   return context_.GetDefaultKind(category);
3117 }
3118 
3119 DynamicType ExpressionAnalyzer::GetDefaultKindOfType(
3120     common::TypeCategory category) {
3121   return {category, GetDefaultKind(category)};
3122 }
3123 
3124 bool ExpressionAnalyzer::CheckIntrinsicKind(
3125     TypeCategory category, std::int64_t kind) {
3126   if (IsValidKindOfIntrinsicType(category, kind)) { // C712, C714, C715, C727
3127     return true;
3128   } else {
3129     Say("%s(KIND=%jd) is not a supported type"_err_en_US,
3130         ToUpperCase(EnumToString(category)), kind);
3131     return false;
3132   }
3133 }
3134 
3135 bool ExpressionAnalyzer::CheckIntrinsicSize(
3136     TypeCategory category, std::int64_t size) {
3137   if (category == TypeCategory::Complex) {
3138     // COMPLEX*16 == COMPLEX(KIND=8)
3139     if (size % 2 == 0 && IsValidKindOfIntrinsicType(category, size / 2)) {
3140       return true;
3141     }
3142   } else if (IsValidKindOfIntrinsicType(category, size)) {
3143     return true;
3144   }
3145   Say("%s*%jd is not a supported type"_err_en_US,
3146       ToUpperCase(EnumToString(category)), size);
3147   return false;
3148 }
3149 
3150 bool ExpressionAnalyzer::AddImpliedDo(parser::CharBlock name, int kind) {
3151   return impliedDos_.insert(std::make_pair(name, kind)).second;
3152 }
3153 
3154 void ExpressionAnalyzer::RemoveImpliedDo(parser::CharBlock name) {
3155   auto iter{impliedDos_.find(name)};
3156   if (iter != impliedDos_.end()) {
3157     impliedDos_.erase(iter);
3158   }
3159 }
3160 
3161 std::optional<int> ExpressionAnalyzer::IsImpliedDo(
3162     parser::CharBlock name) const {
3163   auto iter{impliedDos_.find(name)};
3164   if (iter != impliedDos_.cend()) {
3165     return {iter->second};
3166   } else {
3167     return std::nullopt;
3168   }
3169 }
3170 
3171 bool ExpressionAnalyzer::EnforceTypeConstraint(parser::CharBlock at,
3172     const MaybeExpr &result, TypeCategory category, bool defaultKind) {
3173   if (result) {
3174     if (auto type{result->GetType()}) {
3175       if (type->category() != category) { // C885
3176         Say(at, "Must have %s type, but is %s"_err_en_US,
3177             ToUpperCase(EnumToString(category)),
3178             ToUpperCase(type->AsFortran()));
3179         return false;
3180       } else if (defaultKind) {
3181         int kind{context_.GetDefaultKind(category)};
3182         if (type->kind() != kind) {
3183           Say(at, "Must have default kind(%d) of %s type, but is %s"_err_en_US,
3184               kind, ToUpperCase(EnumToString(category)),
3185               ToUpperCase(type->AsFortran()));
3186           return false;
3187         }
3188       }
3189     } else {
3190       Say(at, "Must have %s type, but is typeless"_err_en_US,
3191           ToUpperCase(EnumToString(category)));
3192       return false;
3193     }
3194   }
3195   return true;
3196 }
3197 
3198 MaybeExpr ExpressionAnalyzer::MakeFunctionRef(parser::CharBlock callSite,
3199     ProcedureDesignator &&proc, ActualArguments &&arguments) {
3200   if (const auto *intrinsic{std::get_if<SpecificIntrinsic>(&proc.u)}) {
3201     if (intrinsic->characteristics.value().attrs.test(
3202             characteristics::Procedure::Attr::NullPointer) &&
3203         arguments.empty()) {
3204       return Expr<SomeType>{NullPointer{}};
3205     }
3206   }
3207   if (const Symbol * symbol{proc.GetSymbol()}) {
3208     if (!ResolveForward(*symbol)) {
3209       return std::nullopt;
3210     }
3211   }
3212   if (auto chars{CheckCall(callSite, proc, arguments)}) {
3213     if (chars->functionResult) {
3214       const auto &result{*chars->functionResult};
3215       if (result.IsProcedurePointer()) {
3216         return Expr<SomeType>{
3217             ProcedureRef{std::move(proc), std::move(arguments)}};
3218       } else {
3219         // Not a procedure pointer, so type and shape are known.
3220         return TypedWrapper<FunctionRef, ProcedureRef>(
3221             DEREF(result.GetTypeAndShape()).type(),
3222             ProcedureRef{std::move(proc), std::move(arguments)});
3223       }
3224     } else {
3225       Say("Function result characteristics are not known"_err_en_US);
3226     }
3227   }
3228   return std::nullopt;
3229 }
3230 
3231 MaybeExpr ExpressionAnalyzer::MakeFunctionRef(
3232     parser::CharBlock intrinsic, ActualArguments &&arguments) {
3233   if (std::optional<SpecificCall> specificCall{
3234           context_.intrinsics().Probe(CallCharacteristics{intrinsic.ToString()},
3235               arguments, GetFoldingContext())}) {
3236     return MakeFunctionRef(intrinsic,
3237         ProcedureDesignator{std::move(specificCall->specificIntrinsic)},
3238         std::move(specificCall->arguments));
3239   } else {
3240     return std::nullopt;
3241   }
3242 }
3243 
3244 void ArgumentAnalyzer::Analyze(const parser::Variable &x) {
3245   source_.ExtendToCover(x.GetSource());
3246   if (MaybeExpr expr{context_.Analyze(x)}) {
3247     if (!IsConstantExpr(*expr)) {
3248       actuals_.emplace_back(std::move(*expr));
3249       SetArgSourceLocation(actuals_.back(), x.GetSource());
3250       return;
3251     }
3252     const Symbol *symbol{GetLastSymbol(*expr)};
3253     if (!symbol) {
3254       context_.SayAt(x, "Assignment to constant '%s' is not allowed"_err_en_US,
3255           x.GetSource());
3256     } else if (auto *subp{symbol->detailsIf<semantics::SubprogramDetails>()}) {
3257       auto *msg{context_.SayAt(x,
3258           "Assignment to subprogram '%s' is not allowed"_err_en_US,
3259           symbol->name())};
3260       if (subp->isFunction()) {
3261         const auto &result{subp->result().name()};
3262         msg->Attach(result, "Function result is '%s'"_en_US, result);
3263       }
3264     } else {
3265       context_.SayAt(x, "Assignment to constant '%s' is not allowed"_err_en_US,
3266           symbol->name());
3267     }
3268   }
3269   fatalErrors_ = true;
3270 }
3271 
3272 void ArgumentAnalyzer::Analyze(
3273     const parser::ActualArgSpec &arg, bool isSubroutine) {
3274   // TODO: Actual arguments that are procedures and procedure pointers need to
3275   // be detected and represented (they're not expressions).
3276   // TODO: C1534: Don't allow a "restricted" specific intrinsic to be passed.
3277   std::optional<ActualArgument> actual;
3278   common::visit(
3279       common::visitors{
3280           [&](const common::Indirection<parser::Expr> &x) {
3281             actual = AnalyzeExpr(x.value());
3282             SetArgSourceLocation(actual, x.value().source);
3283           },
3284           [&](const parser::AltReturnSpec &label) {
3285             if (!isSubroutine) {
3286               context_.Say("alternate return specification may not appear on"
3287                            " function reference"_err_en_US);
3288             }
3289             actual = ActualArgument(label.v);
3290           },
3291           [&](const parser::ActualArg::PercentRef &) {
3292             context_.Say("%REF() intrinsic for arguments"_todo_en_US);
3293           },
3294           [&](const parser::ActualArg::PercentVal &) {
3295             context_.Say("%VAL() intrinsic for arguments"_todo_en_US);
3296           },
3297       },
3298       std::get<parser::ActualArg>(arg.t).u);
3299   if (actual) {
3300     if (const auto &argKW{std::get<std::optional<parser::Keyword>>(arg.t)}) {
3301       actual->set_keyword(argKW->v.source);
3302     }
3303     actuals_.emplace_back(std::move(*actual));
3304   } else {
3305     fatalErrors_ = true;
3306   }
3307 }
3308 
3309 bool ArgumentAnalyzer::IsIntrinsicRelational(RelationalOperator opr,
3310     const DynamicType &leftType, const DynamicType &rightType) const {
3311   CHECK(actuals_.size() == 2);
3312   return semantics::IsIntrinsicRelational(
3313       opr, leftType, GetRank(0), rightType, GetRank(1));
3314 }
3315 
3316 bool ArgumentAnalyzer::IsIntrinsicNumeric(NumericOperator opr) const {
3317   std::optional<DynamicType> leftType{GetType(0)};
3318   if (actuals_.size() == 1) {
3319     if (IsBOZLiteral(0)) {
3320       return opr == NumericOperator::Add; // unary '+'
3321     } else {
3322       return leftType && semantics::IsIntrinsicNumeric(*leftType);
3323     }
3324   } else {
3325     std::optional<DynamicType> rightType{GetType(1)};
3326     if (IsBOZLiteral(0) && rightType) { // BOZ opr Integer/Real
3327       auto cat1{rightType->category()};
3328       return cat1 == TypeCategory::Integer || cat1 == TypeCategory::Real;
3329     } else if (IsBOZLiteral(1) && leftType) { // Integer/Real opr BOZ
3330       auto cat0{leftType->category()};
3331       return cat0 == TypeCategory::Integer || cat0 == TypeCategory::Real;
3332     } else {
3333       return leftType && rightType &&
3334           semantics::IsIntrinsicNumeric(
3335               *leftType, GetRank(0), *rightType, GetRank(1));
3336     }
3337   }
3338 }
3339 
3340 bool ArgumentAnalyzer::IsIntrinsicLogical() const {
3341   if (std::optional<DynamicType> leftType{GetType(0)}) {
3342     if (actuals_.size() == 1) {
3343       return semantics::IsIntrinsicLogical(*leftType);
3344     } else if (std::optional<DynamicType> rightType{GetType(1)}) {
3345       return semantics::IsIntrinsicLogical(
3346           *leftType, GetRank(0), *rightType, GetRank(1));
3347     }
3348   }
3349   return false;
3350 }
3351 
3352 bool ArgumentAnalyzer::IsIntrinsicConcat() const {
3353   if (std::optional<DynamicType> leftType{GetType(0)}) {
3354     if (std::optional<DynamicType> rightType{GetType(1)}) {
3355       return semantics::IsIntrinsicConcat(
3356           *leftType, GetRank(0), *rightType, GetRank(1));
3357     }
3358   }
3359   return false;
3360 }
3361 
3362 bool ArgumentAnalyzer::CheckConformance() {
3363   if (actuals_.size() == 2) {
3364     const auto *lhs{actuals_.at(0).value().UnwrapExpr()};
3365     const auto *rhs{actuals_.at(1).value().UnwrapExpr()};
3366     if (lhs && rhs) {
3367       auto &foldingContext{context_.GetFoldingContext()};
3368       auto lhShape{GetShape(foldingContext, *lhs)};
3369       auto rhShape{GetShape(foldingContext, *rhs)};
3370       if (lhShape && rhShape) {
3371         if (!evaluate::CheckConformance(foldingContext.messages(), *lhShape,
3372                 *rhShape, CheckConformanceFlags::EitherScalarExpandable,
3373                 "left operand", "right operand")
3374                  .value_or(false /*fail when conformance is not known now*/)) {
3375           fatalErrors_ = true;
3376           return false;
3377         }
3378       }
3379     }
3380   }
3381   return true; // no proven problem
3382 }
3383 
3384 bool ArgumentAnalyzer::CheckForNullPointer(const char *where) {
3385   for (const std::optional<ActualArgument> &arg : actuals_) {
3386     if (arg) {
3387       if (const Expr<SomeType> *expr{arg->UnwrapExpr()}) {
3388         if (IsNullPointer(*expr)) {
3389           context_.Say(
3390               source_, "A NULL() pointer is not allowed %s"_err_en_US, where);
3391           fatalErrors_ = true;
3392           return false;
3393         }
3394       }
3395     }
3396   }
3397   return true;
3398 }
3399 
3400 MaybeExpr ArgumentAnalyzer::TryDefinedOp(const char *opr,
3401     parser::MessageFixedText error, const Symbol **definedOpSymbolPtr,
3402     bool isUserOp) {
3403   if (AnyUntypedOrMissingOperand()) {
3404     context_.Say(error, ToUpperCase(opr), TypeAsFortran(0), TypeAsFortran(1));
3405     return std::nullopt;
3406   }
3407   const Symbol *localDefinedOpSymbolPtr{nullptr};
3408   if (!definedOpSymbolPtr) {
3409     definedOpSymbolPtr = &localDefinedOpSymbolPtr;
3410   }
3411   {
3412     auto restorer{context_.GetContextualMessages().DiscardMessages()};
3413     std::string oprNameString{
3414         isUserOp ? std::string{opr} : "operator("s + opr + ')'};
3415     parser::CharBlock oprName{oprNameString};
3416     const auto &scope{context_.context().FindScope(source_)};
3417     if (Symbol * symbol{scope.FindSymbol(oprName)}) {
3418       *definedOpSymbolPtr = symbol;
3419       parser::Name name{symbol->name(), symbol};
3420       if (auto result{context_.AnalyzeDefinedOp(name, GetActuals())}) {
3421         return result;
3422       }
3423     }
3424     for (std::size_t passIndex{0}; passIndex < actuals_.size(); ++passIndex) {
3425       if (const Symbol *
3426           symbol{FindBoundOp(oprName, passIndex, *definedOpSymbolPtr)}) {
3427         if (MaybeExpr result{TryBoundOp(*symbol, passIndex)}) {
3428           return result;
3429         }
3430       }
3431     }
3432   }
3433   if (*definedOpSymbolPtr) {
3434     SayNoMatch(ToUpperCase((*definedOpSymbolPtr)->name().ToString()));
3435   } else if (actuals_.size() == 1 || AreConformable()) {
3436     if (CheckForNullPointer()) {
3437       context_.Say(error, ToUpperCase(opr), TypeAsFortran(0), TypeAsFortran(1));
3438     }
3439   } else {
3440     context_.Say(
3441         "Operands of %s are not conformable; have rank %d and rank %d"_err_en_US,
3442         ToUpperCase(opr), actuals_[0]->Rank(), actuals_[1]->Rank());
3443   }
3444   return std::nullopt;
3445 }
3446 
3447 MaybeExpr ArgumentAnalyzer::TryDefinedOp(
3448     std::vector<const char *> oprs, parser::MessageFixedText error) {
3449   const Symbol *definedOpSymbolPtr{nullptr};
3450   for (std::size_t i{1}; i < oprs.size(); ++i) {
3451     auto restorer{context_.GetContextualMessages().DiscardMessages()};
3452     if (auto result{TryDefinedOp(oprs[i], error, &definedOpSymbolPtr)}) {
3453       return result;
3454     }
3455   }
3456   return TryDefinedOp(oprs[0], error, &definedOpSymbolPtr);
3457 }
3458 
3459 MaybeExpr ArgumentAnalyzer::TryBoundOp(const Symbol &symbol, int passIndex) {
3460   ActualArguments localActuals{actuals_};
3461   const Symbol *proc{GetBindingResolution(GetType(passIndex), symbol)};
3462   if (!proc) {
3463     proc = &symbol;
3464     localActuals.at(passIndex).value().set_isPassedObject();
3465   }
3466   CheckConformance();
3467   return context_.MakeFunctionRef(
3468       source_, ProcedureDesignator{*proc}, std::move(localActuals));
3469 }
3470 
3471 std::optional<ProcedureRef> ArgumentAnalyzer::TryDefinedAssignment() {
3472   using semantics::Tristate;
3473   const Expr<SomeType> &lhs{GetExpr(0)};
3474   const Expr<SomeType> &rhs{GetExpr(1)};
3475   std::optional<DynamicType> lhsType{lhs.GetType()};
3476   std::optional<DynamicType> rhsType{rhs.GetType()};
3477   int lhsRank{lhs.Rank()};
3478   int rhsRank{rhs.Rank()};
3479   Tristate isDefined{
3480       semantics::IsDefinedAssignment(lhsType, lhsRank, rhsType, rhsRank)};
3481   if (isDefined == Tristate::No) {
3482     if (lhsType && rhsType) {
3483       AddAssignmentConversion(*lhsType, *rhsType);
3484     }
3485     return std::nullopt; // user-defined assignment not allowed for these args
3486   }
3487   auto restorer{context_.GetContextualMessages().SetLocation(source_)};
3488   if (std::optional<ProcedureRef> procRef{GetDefinedAssignmentProc()}) {
3489     if (context_.inWhereBody() && !procRef->proc().IsElemental()) { // C1032
3490       context_.Say(
3491           "Defined assignment in WHERE must be elemental, but '%s' is not"_err_en_US,
3492           DEREF(procRef->proc().GetSymbol()).name());
3493     }
3494     context_.CheckCall(source_, procRef->proc(), procRef->arguments());
3495     return std::move(*procRef);
3496   }
3497   if (isDefined == Tristate::Yes) {
3498     if (!lhsType || !rhsType || (lhsRank != rhsRank && rhsRank != 0) ||
3499         !OkLogicalIntegerAssignment(lhsType->category(), rhsType->category())) {
3500       SayNoMatch("ASSIGNMENT(=)", true);
3501     }
3502   }
3503   return std::nullopt;
3504 }
3505 
3506 bool ArgumentAnalyzer::OkLogicalIntegerAssignment(
3507     TypeCategory lhs, TypeCategory rhs) {
3508   if (!context_.context().languageFeatures().IsEnabled(
3509           common::LanguageFeature::LogicalIntegerAssignment)) {
3510     return false;
3511   }
3512   std::optional<parser::MessageFixedText> msg;
3513   if (lhs == TypeCategory::Integer && rhs == TypeCategory::Logical) {
3514     // allow assignment to LOGICAL from INTEGER as a legacy extension
3515     msg = "assignment of LOGICAL to INTEGER"_port_en_US;
3516   } else if (lhs == TypeCategory::Logical && rhs == TypeCategory::Integer) {
3517     // ... and assignment to LOGICAL from INTEGER
3518     msg = "assignment of INTEGER to LOGICAL"_port_en_US;
3519   } else {
3520     return false;
3521   }
3522   if (context_.context().languageFeatures().ShouldWarn(
3523           common::LanguageFeature::LogicalIntegerAssignment)) {
3524     context_.Say(std::move(*msg));
3525   }
3526   return true;
3527 }
3528 
3529 std::optional<ProcedureRef> ArgumentAnalyzer::GetDefinedAssignmentProc() {
3530   auto restorer{context_.GetContextualMessages().DiscardMessages()};
3531   std::string oprNameString{"assignment(=)"};
3532   parser::CharBlock oprName{oprNameString};
3533   const Symbol *proc{nullptr};
3534   const auto &scope{context_.context().FindScope(source_)};
3535   if (const Symbol * symbol{scope.FindSymbol(oprName)}) {
3536     ExpressionAnalyzer::AdjustActuals noAdjustment;
3537     auto pair{context_.ResolveGeneric(*symbol, actuals_, noAdjustment, true)};
3538     if (pair.first) {
3539       proc = pair.first;
3540     } else {
3541       context_.EmitGenericResolutionError(*symbol, pair.second);
3542     }
3543   }
3544   int passedObjectIndex{-1};
3545   const Symbol *definedOpSymbol{nullptr};
3546   for (std::size_t i{0}; i < actuals_.size(); ++i) {
3547     if (const Symbol * specific{FindBoundOp(oprName, i, definedOpSymbol)}) {
3548       if (const Symbol *
3549           resolution{GetBindingResolution(GetType(i), *specific)}) {
3550         proc = resolution;
3551       } else {
3552         proc = specific;
3553         passedObjectIndex = i;
3554       }
3555     }
3556   }
3557   if (!proc) {
3558     return std::nullopt;
3559   }
3560   ActualArguments actualsCopy{actuals_};
3561   if (passedObjectIndex >= 0) {
3562     actualsCopy[passedObjectIndex]->set_isPassedObject();
3563   }
3564   return ProcedureRef{ProcedureDesignator{*proc}, std::move(actualsCopy)};
3565 }
3566 
3567 void ArgumentAnalyzer::Dump(llvm::raw_ostream &os) {
3568   os << "source_: " << source_.ToString() << " fatalErrors_ = " << fatalErrors_
3569      << '\n';
3570   for (const auto &actual : actuals_) {
3571     if (!actual.has_value()) {
3572       os << "- error\n";
3573     } else if (const Symbol * symbol{actual->GetAssumedTypeDummy()}) {
3574       os << "- assumed type: " << symbol->name().ToString() << '\n';
3575     } else if (const Expr<SomeType> *expr{actual->UnwrapExpr()}) {
3576       expr->AsFortran(os << "- expr: ") << '\n';
3577     } else {
3578       DIE("bad ActualArgument");
3579     }
3580   }
3581 }
3582 
3583 std::optional<ActualArgument> ArgumentAnalyzer::AnalyzeExpr(
3584     const parser::Expr &expr) {
3585   source_.ExtendToCover(expr.source);
3586   if (const Symbol * assumedTypeDummy{AssumedTypeDummy(expr)}) {
3587     expr.typedExpr.Reset(new GenericExprWrapper{}, GenericExprWrapper::Deleter);
3588     if (isProcedureCall_) {
3589       ActualArgument arg{ActualArgument::AssumedType{*assumedTypeDummy}};
3590       SetArgSourceLocation(arg, expr.source);
3591       return std::move(arg);
3592     }
3593     context_.SayAt(expr.source,
3594         "TYPE(*) dummy argument may only be used as an actual argument"_err_en_US);
3595   } else if (MaybeExpr argExpr{AnalyzeExprOrWholeAssumedSizeArray(expr)}) {
3596     if (isProcedureCall_ || !IsProcedure(*argExpr)) {
3597       ActualArgument arg{std::move(*argExpr)};
3598       SetArgSourceLocation(arg, expr.source);
3599       return std::move(arg);
3600     }
3601     context_.SayAt(expr.source,
3602         IsFunction(*argExpr) ? "Function call must have argument list"_err_en_US
3603                              : "Subroutine name is not allowed here"_err_en_US);
3604   }
3605   return std::nullopt;
3606 }
3607 
3608 MaybeExpr ArgumentAnalyzer::AnalyzeExprOrWholeAssumedSizeArray(
3609     const parser::Expr &expr) {
3610   // If an expression's parse tree is a whole assumed-size array:
3611   //   Expr -> Designator -> DataRef -> Name
3612   // treat it as a special case for argument passing and bypass
3613   // the C1002/C1014 constraint checking in expression semantics.
3614   if (const auto *name{parser::Unwrap<parser::Name>(expr)}) {
3615     if (name->symbol && semantics::IsAssumedSizeArray(*name->symbol)) {
3616       auto restorer{context_.AllowWholeAssumedSizeArray()};
3617       return context_.Analyze(expr);
3618     }
3619   }
3620   return context_.Analyze(expr);
3621 }
3622 
3623 bool ArgumentAnalyzer::AreConformable() const {
3624   CHECK(actuals_.size() == 2);
3625   return actuals_[0] && actuals_[1] &&
3626       evaluate::AreConformable(*actuals_[0], *actuals_[1]);
3627 }
3628 
3629 // Look for a type-bound operator in the type of arg number passIndex.
3630 const Symbol *ArgumentAnalyzer::FindBoundOp(
3631     parser::CharBlock oprName, int passIndex, const Symbol *&definedOp) {
3632   const auto *type{GetDerivedTypeSpec(GetType(passIndex))};
3633   if (!type || !type->scope()) {
3634     return nullptr;
3635   }
3636   const Symbol *symbol{type->scope()->FindComponent(oprName)};
3637   if (!symbol) {
3638     return nullptr;
3639   }
3640   definedOp = symbol;
3641   ExpressionAnalyzer::AdjustActuals adjustment{
3642       [&](const Symbol &proc, ActualArguments &) {
3643         return passIndex == GetPassIndex(proc);
3644       }};
3645   auto pair{context_.ResolveGeneric(*symbol, actuals_, adjustment, false)};
3646   if (!pair.first) {
3647     context_.EmitGenericResolutionError(*symbol, pair.second);
3648   }
3649   return pair.first;
3650 }
3651 
3652 // If there is an implicit conversion between intrinsic types, make it explicit
3653 void ArgumentAnalyzer::AddAssignmentConversion(
3654     const DynamicType &lhsType, const DynamicType &rhsType) {
3655   if (lhsType.category() == rhsType.category() &&
3656       (lhsType.category() == TypeCategory::Derived ||
3657           lhsType.kind() == rhsType.kind())) {
3658     // no conversion necessary
3659   } else if (auto rhsExpr{evaluate::ConvertToType(lhsType, MoveExpr(1))}) {
3660     std::optional<parser::CharBlock> source;
3661     if (actuals_[1]) {
3662       source = actuals_[1]->sourceLocation();
3663     }
3664     actuals_[1] = ActualArgument{*rhsExpr};
3665     SetArgSourceLocation(actuals_[1], source);
3666   } else {
3667     actuals_[1] = std::nullopt;
3668   }
3669 }
3670 
3671 std::optional<DynamicType> ArgumentAnalyzer::GetType(std::size_t i) const {
3672   return i < actuals_.size() ? actuals_[i].value().GetType() : std::nullopt;
3673 }
3674 int ArgumentAnalyzer::GetRank(std::size_t i) const {
3675   return i < actuals_.size() ? actuals_[i].value().Rank() : 0;
3676 }
3677 
3678 // If the argument at index i is a BOZ literal, convert its type to match the
3679 // otherType.  If it's REAL convert to REAL, otherwise convert to INTEGER.
3680 // Note that IBM supports comparing BOZ literals to CHARACTER operands.  That
3681 // is not currently supported.
3682 void ArgumentAnalyzer::ConvertBOZ(std::optional<DynamicType> &thisType,
3683     std::size_t i, std::optional<DynamicType> otherType) {
3684   if (IsBOZLiteral(i)) {
3685     Expr<SomeType> &&argExpr{MoveExpr(i)};
3686     auto *boz{std::get_if<BOZLiteralConstant>(&argExpr.u)};
3687     if (otherType && otherType->category() == TypeCategory::Real) {
3688       int kind{context_.context().GetDefaultKind(TypeCategory::Real)};
3689       MaybeExpr realExpr{
3690           ConvertToKind<TypeCategory::Real>(kind, std::move(*boz))};
3691       actuals_[i] = std::move(*realExpr);
3692       thisType.emplace(TypeCategory::Real, kind);
3693     } else {
3694       int kind{context_.context().GetDefaultKind(TypeCategory::Integer)};
3695       MaybeExpr intExpr{
3696           ConvertToKind<TypeCategory::Integer>(kind, std::move(*boz))};
3697       actuals_[i] = std::move(*intExpr);
3698       thisType.emplace(TypeCategory::Integer, kind);
3699     }
3700   }
3701 }
3702 
3703 // Report error resolving opr when there is a user-defined one available
3704 void ArgumentAnalyzer::SayNoMatch(const std::string &opr, bool isAssignment) {
3705   std::string type0{TypeAsFortran(0)};
3706   auto rank0{actuals_[0]->Rank()};
3707   if (actuals_.size() == 1) {
3708     if (rank0 > 0) {
3709       context_.Say("No intrinsic or user-defined %s matches "
3710                    "rank %d array of %s"_err_en_US,
3711           opr, rank0, type0);
3712     } else {
3713       context_.Say("No intrinsic or user-defined %s matches "
3714                    "operand type %s"_err_en_US,
3715           opr, type0);
3716     }
3717   } else {
3718     std::string type1{TypeAsFortran(1)};
3719     auto rank1{actuals_[1]->Rank()};
3720     if (rank0 > 0 && rank1 > 0 && rank0 != rank1) {
3721       context_.Say("No intrinsic or user-defined %s matches "
3722                    "rank %d array of %s and rank %d array of %s"_err_en_US,
3723           opr, rank0, type0, rank1, type1);
3724     } else if (isAssignment && rank0 != rank1) {
3725       if (rank0 == 0) {
3726         context_.Say("No intrinsic or user-defined %s matches "
3727                      "scalar %s and rank %d array of %s"_err_en_US,
3728             opr, type0, rank1, type1);
3729       } else {
3730         context_.Say("No intrinsic or user-defined %s matches "
3731                      "rank %d array of %s and scalar %s"_err_en_US,
3732             opr, rank0, type0, type1);
3733       }
3734     } else {
3735       context_.Say("No intrinsic or user-defined %s matches "
3736                    "operand types %s and %s"_err_en_US,
3737           opr, type0, type1);
3738     }
3739   }
3740 }
3741 
3742 std::string ArgumentAnalyzer::TypeAsFortran(std::size_t i) {
3743   if (i >= actuals_.size() || !actuals_[i]) {
3744     return "missing argument";
3745   } else if (std::optional<DynamicType> type{GetType(i)}) {
3746     return type->IsAssumedType()         ? "TYPE(*)"s
3747         : type->IsUnlimitedPolymorphic() ? "CLASS(*)"s
3748         : type->IsPolymorphic()          ? "CLASS("s + type->AsFortran() + ')'
3749         : type->category() == TypeCategory::Derived
3750         ? "TYPE("s + type->AsFortran() + ')'
3751         : type->category() == TypeCategory::Character
3752         ? "CHARACTER(KIND="s + std::to_string(type->kind()) + ')'
3753         : ToUpperCase(type->AsFortran());
3754   } else {
3755     return "untyped";
3756   }
3757 }
3758 
3759 bool ArgumentAnalyzer::AnyUntypedOrMissingOperand() {
3760   for (const auto &actual : actuals_) {
3761     if (!actual ||
3762         (!actual->GetType() && !IsBareNullPointer(actual->UnwrapExpr()))) {
3763       return true;
3764     }
3765   }
3766   return false;
3767 }
3768 } // namespace Fortran::evaluate
3769 
3770 namespace Fortran::semantics {
3771 evaluate::Expr<evaluate::SubscriptInteger> AnalyzeKindSelector(
3772     SemanticsContext &context, common::TypeCategory category,
3773     const std::optional<parser::KindSelector> &selector) {
3774   evaluate::ExpressionAnalyzer analyzer{context};
3775   auto restorer{
3776       analyzer.GetContextualMessages().SetLocation(context.location().value())};
3777   return analyzer.AnalyzeKindSelector(category, selector);
3778 }
3779 
3780 ExprChecker::ExprChecker(SemanticsContext &context) : context_{context} {}
3781 
3782 bool ExprChecker::Pre(const parser::DataImpliedDo &ido) {
3783   parser::Walk(std::get<parser::DataImpliedDo::Bounds>(ido.t), *this);
3784   const auto &bounds{std::get<parser::DataImpliedDo::Bounds>(ido.t)};
3785   auto name{bounds.name.thing.thing};
3786   int kind{evaluate::ResultType<evaluate::ImpliedDoIndex>::kind};
3787   if (const auto dynamicType{evaluate::DynamicType::From(*name.symbol)}) {
3788     if (dynamicType->category() == TypeCategory::Integer) {
3789       kind = dynamicType->kind();
3790     }
3791   }
3792   exprAnalyzer_.AddImpliedDo(name.source, kind);
3793   parser::Walk(std::get<std::list<parser::DataIDoObject>>(ido.t), *this);
3794   exprAnalyzer_.RemoveImpliedDo(name.source);
3795   return false;
3796 }
3797 
3798 bool ExprChecker::Walk(const parser::Program &program) {
3799   parser::Walk(program, *this);
3800   return !context_.AnyFatalError();
3801 }
3802 } // namespace Fortran::semantics
3803