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