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