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