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