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