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