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