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