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