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