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