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