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         if (const Symbol *
1981             resolution{GetBindingResolution(dtExpr->GetType(), *sym)}) {
1982           AddPassArg(arguments, std::move(*dtExpr), *sym, false);
1983           return CalleeAndArguments{
1984               ProcedureDesignator{*resolution}, std::move(arguments)};
1985         } else if (std::optional<DataRef> dataRef{
1986                        ExtractDataRef(std::move(*dtExpr))}) {
1987           if (sym->attrs().test(semantics::Attr::NOPASS)) {
1988             return CalleeAndArguments{
1989                 ProcedureDesignator{Component{std::move(*dataRef), *sym}},
1990                 std::move(arguments)};
1991           } else {
1992             AddPassArg(arguments,
1993                 Expr<SomeDerived>{Designator<SomeDerived>{std::move(*dataRef)}},
1994                 *sym);
1995             return CalleeAndArguments{
1996                 ProcedureDesignator{*sym}, std::move(arguments)};
1997           }
1998         }
1999       }
2000       Say(sc.component.source,
2001           "Base of procedure component reference is not a derived-type object"_err_en_US);
2002     }
2003   }
2004   CHECK(context_.AnyFatalError());
2005   return std::nullopt;
2006 }
2007 
2008 // Can actual be argument associated with dummy?
2009 static bool CheckCompatibleArgument(bool isElemental,
2010     const ActualArgument &actual, const characteristics::DummyArgument &dummy) {
2011   const auto *expr{actual.UnwrapExpr()};
2012   return common::visit(
2013       common::visitors{
2014           [&](const characteristics::DummyDataObject &x) {
2015             if (x.attrs.test(characteristics::DummyDataObject::Attr::Pointer) &&
2016                 IsBareNullPointer(expr)) {
2017               // NULL() without MOLD= is compatible with any dummy data pointer
2018               // but cannot be allowed to lead to ambiguity.
2019               return true;
2020             } else if (!isElemental && actual.Rank() != x.type.Rank() &&
2021                 !x.type.attrs().test(
2022                     characteristics::TypeAndShape::Attr::AssumedRank)) {
2023               return false;
2024             } else if (auto actualType{actual.GetType()}) {
2025               return x.type.type().IsTkCompatibleWith(*actualType);
2026             }
2027             return false;
2028           },
2029           [&](const characteristics::DummyProcedure &) {
2030             return expr && IsProcedurePointerTarget(*expr);
2031           },
2032           [&](const characteristics::AlternateReturn &) {
2033             return actual.isAlternateReturn();
2034           },
2035       },
2036       dummy.u);
2037 }
2038 
2039 // Are the actual arguments compatible with the dummy arguments of procedure?
2040 static bool CheckCompatibleArguments(
2041     const characteristics::Procedure &procedure,
2042     const ActualArguments &actuals) {
2043   bool isElemental{procedure.IsElemental()};
2044   const auto &dummies{procedure.dummyArguments};
2045   CHECK(dummies.size() == actuals.size());
2046   for (std::size_t i{0}; i < dummies.size(); ++i) {
2047     const characteristics::DummyArgument &dummy{dummies[i]};
2048     const std::optional<ActualArgument> &actual{actuals[i]};
2049     if (actual && !CheckCompatibleArgument(isElemental, *actual, dummy)) {
2050       return false;
2051     }
2052   }
2053   return true;
2054 }
2055 
2056 // Handles a forward reference to a module function from what must
2057 // be a specification expression.  Return false if the symbol is
2058 // an invalid forward reference.
2059 bool ExpressionAnalyzer::ResolveForward(const Symbol &symbol) {
2060   if (context_.HasError(symbol)) {
2061     return false;
2062   }
2063   if (const auto *details{
2064           symbol.detailsIf<semantics::SubprogramNameDetails>()}) {
2065     if (details->kind() == semantics::SubprogramKind::Module) {
2066       // If this symbol is still a SubprogramNameDetails, we must be
2067       // checking a specification expression in a sibling module
2068       // procedure.  Resolve its names now so that its interface
2069       // is known.
2070       semantics::ResolveSpecificationParts(context_, symbol);
2071       if (symbol.has<semantics::SubprogramNameDetails>()) {
2072         // When the symbol hasn't had its details updated, we must have
2073         // already been in the process of resolving the function's
2074         // specification part; but recursive function calls are not
2075         // allowed in specification parts (10.1.11 para 5).
2076         Say("The module function '%s' may not be referenced recursively in a specification expression"_err_en_US,
2077             symbol.name());
2078         context_.SetError(symbol);
2079         return false;
2080       }
2081     } else { // 10.1.11 para 4
2082       Say("The internal function '%s' may not be referenced in a specification expression"_err_en_US,
2083           symbol.name());
2084       context_.SetError(symbol);
2085       return false;
2086     }
2087   }
2088   return true;
2089 }
2090 
2091 // Resolve a call to a generic procedure with given actual arguments.
2092 // adjustActuals is called on procedure bindings to handle pass arg.
2093 std::pair<const Symbol *, bool> ExpressionAnalyzer::ResolveGeneric(
2094     const Symbol &symbol, const ActualArguments &actuals,
2095     const AdjustActuals &adjustActuals, bool isSubroutine,
2096     bool mightBeStructureConstructor) {
2097   const Symbol *elemental{nullptr}; // matching elemental specific proc
2098   const Symbol *nonElemental{nullptr}; // matching non-elemental specific
2099   const Symbol &ultimate{symbol.GetUltimate()};
2100   // Check for a match with an explicit INTRINSIC
2101   if (ultimate.attrs().test(semantics::Attr::INTRINSIC)) {
2102     parser::Messages buffer;
2103     auto restorer{foldingContext_.messages().SetMessages(buffer)};
2104     ActualArguments localActuals{actuals};
2105     if (context_.intrinsics().Probe(
2106             CallCharacteristics{ultimate.name().ToString(), isSubroutine},
2107             localActuals, foldingContext_) &&
2108         !buffer.AnyFatalError()) {
2109       return {&ultimate, false};
2110     }
2111   }
2112   if (const auto *details{ultimate.detailsIf<semantics::GenericDetails>()}) {
2113     bool anyBareNullActual{
2114         std::find_if(actuals.begin(), actuals.end(), [](auto iter) {
2115           return IsBareNullPointer(iter->UnwrapExpr());
2116         }) != actuals.end()};
2117     for (const Symbol &specific : details->specificProcs()) {
2118       if (!ResolveForward(specific)) {
2119         continue;
2120       }
2121       if (std::optional<characteristics::Procedure> procedure{
2122               characteristics::Procedure::Characterize(
2123                   ProcedureDesignator{specific}, context_.foldingContext())}) {
2124         ActualArguments localActuals{actuals};
2125         if (specific.has<semantics::ProcBindingDetails>()) {
2126           if (!adjustActuals.value()(specific, localActuals)) {
2127             continue;
2128           }
2129         }
2130         if (semantics::CheckInterfaceForGeneric(*procedure, localActuals,
2131                 GetFoldingContext(), false /* no integer conversions */) &&
2132             CheckCompatibleArguments(*procedure, localActuals)) {
2133           if ((procedure->IsElemental() && elemental) ||
2134               (!procedure->IsElemental() && nonElemental)) {
2135             // 16.9.144(6): a bare NULL() is not allowed as an actual
2136             // argument to a generic procedure if the specific procedure
2137             // cannot be unambiguously distinguished
2138             return {nullptr, true /* due to NULL actuals */};
2139           }
2140           if (!procedure->IsElemental()) {
2141             // takes priority over elemental match
2142             nonElemental = &specific;
2143             if (!anyBareNullActual) {
2144               break; // unambiguous case
2145             }
2146           } else {
2147             elemental = &specific;
2148           }
2149         }
2150       }
2151     }
2152     if (nonElemental) {
2153       return {&AccessSpecific(symbol, *nonElemental), false};
2154     } else if (elemental) {
2155       return {&AccessSpecific(symbol, *elemental), false};
2156     }
2157     // Check parent derived type
2158     if (const auto *parentScope{symbol.owner().GetDerivedTypeParent()}) {
2159       if (const Symbol * extended{parentScope->FindComponent(symbol.name())}) {
2160         auto pair{ResolveGeneric(
2161             *extended, actuals, adjustActuals, isSubroutine, false)};
2162         if (pair.first) {
2163           return pair;
2164         }
2165       }
2166     }
2167     if (mightBeStructureConstructor && details->derivedType()) {
2168       return {details->derivedType(), false};
2169     }
2170   }
2171   // Check for generic or explicit INTRINSIC of the same name in outer scopes.
2172   // See 15.5.5.2 for details.
2173   if (!symbol.owner().IsGlobal() && !symbol.owner().IsDerivedType()) {
2174     for (const std::string &n : GetAllNames(context_, symbol.name())) {
2175       if (const Symbol * outer{symbol.owner().parent().FindSymbol(n)}) {
2176         auto pair{ResolveGeneric(*outer, actuals, adjustActuals, isSubroutine,
2177             mightBeStructureConstructor)};
2178         if (pair.first) {
2179           return pair;
2180         }
2181       }
2182     }
2183   }
2184   return {nullptr, false};
2185 }
2186 
2187 const Symbol &ExpressionAnalyzer::AccessSpecific(
2188     const Symbol &originalGeneric, const Symbol &specific) {
2189   if (const auto *hosted{
2190           originalGeneric.detailsIf<semantics::HostAssocDetails>()}) {
2191     return AccessSpecific(hosted->symbol(), specific);
2192   } else if (const auto *used{
2193                  originalGeneric.detailsIf<semantics::UseDetails>()}) {
2194     const auto &scope{originalGeneric.owner()};
2195     if (auto iter{scope.find(specific.name())}; iter != scope.end()) {
2196       if (const auto *useDetails{
2197               iter->second->detailsIf<semantics::UseDetails>()}) {
2198         const Symbol &usedSymbol{useDetails->symbol()};
2199         const auto *usedGeneric{
2200             usedSymbol.detailsIf<semantics::GenericDetails>()};
2201         if (&usedSymbol == &specific ||
2202             (usedGeneric && usedGeneric->specific() == &specific)) {
2203           return specific;
2204         }
2205       }
2206     }
2207     // Create a renaming USE of the specific procedure.
2208     auto rename{context_.SaveTempName(
2209         used->symbol().owner().GetName().value().ToString() + "$" +
2210         specific.name().ToString())};
2211     return *const_cast<semantics::Scope &>(scope)
2212                 .try_emplace(rename, specific.attrs(),
2213                     semantics::UseDetails{rename, specific})
2214                 .first->second;
2215   } else {
2216     return specific;
2217   }
2218 }
2219 
2220 void ExpressionAnalyzer::EmitGenericResolutionError(
2221     const Symbol &symbol, bool dueToNullActuals) {
2222   Say(dueToNullActuals
2223           ? "One or more NULL() actual arguments to the generic procedure '%s' requires a MOLD= for disambiguation"_err_en_US
2224           : semantics::IsGenericDefinedOp(symbol)
2225           ? "No specific procedure of generic operator '%s' matches the actual arguments"_err_en_US
2226           : "No specific procedure of generic '%s' matches the actual arguments"_err_en_US,
2227       symbol.name());
2228 }
2229 
2230 auto ExpressionAnalyzer::GetCalleeAndArguments(
2231     const parser::ProcedureDesignator &pd, ActualArguments &&arguments,
2232     bool isSubroutine, bool mightBeStructureConstructor)
2233     -> std::optional<CalleeAndArguments> {
2234   return common::visit(
2235       common::visitors{
2236           [&](const parser::Name &name) {
2237             return GetCalleeAndArguments(name, std::move(arguments),
2238                 isSubroutine, mightBeStructureConstructor);
2239           },
2240           [&](const parser::ProcComponentRef &pcr) {
2241             return AnalyzeProcedureComponentRef(
2242                 pcr, std::move(arguments), isSubroutine);
2243           },
2244       },
2245       pd.u);
2246 }
2247 
2248 auto ExpressionAnalyzer::GetCalleeAndArguments(const parser::Name &name,
2249     ActualArguments &&arguments, bool isSubroutine,
2250     bool mightBeStructureConstructor) -> std::optional<CalleeAndArguments> {
2251   const Symbol *symbol{name.symbol};
2252   if (context_.HasError(symbol)) {
2253     return std::nullopt; // also handles null symbol
2254   }
2255   const Symbol &ultimate{DEREF(symbol).GetUltimate()};
2256   CheckForBadRecursion(name.source, ultimate);
2257   bool dueToNullActual{false};
2258   bool isGenericInterface{ultimate.has<semantics::GenericDetails>()};
2259   bool isExplicitIntrinsic{ultimate.attrs().test(semantics::Attr::INTRINSIC)};
2260   const Symbol *resolution{nullptr};
2261   if (isGenericInterface || isExplicitIntrinsic) {
2262     ExpressionAnalyzer::AdjustActuals noAdjustment;
2263     auto pair{ResolveGeneric(*symbol, arguments, noAdjustment, isSubroutine,
2264         mightBeStructureConstructor)};
2265     resolution = pair.first;
2266     dueToNullActual = pair.second;
2267     if (resolution) {
2268       // re-resolve name to the specific procedure
2269       name.symbol = const_cast<Symbol *>(resolution);
2270     }
2271   } else {
2272     resolution = symbol;
2273   }
2274   if (!resolution || resolution->attrs().test(semantics::Attr::INTRINSIC)) {
2275     // Not generic, or no resolution; may be intrinsic
2276     if (std::optional<SpecificCall> specificCall{context_.intrinsics().Probe(
2277             CallCharacteristics{ultimate.name().ToString(), isSubroutine},
2278             arguments, GetFoldingContext())}) {
2279       CheckBadExplicitType(*specificCall, *symbol);
2280       return CalleeAndArguments{
2281           ProcedureDesignator{std::move(specificCall->specificIntrinsic)},
2282           std::move(specificCall->arguments)};
2283     } else {
2284       if (isGenericInterface) {
2285         EmitGenericResolutionError(*symbol, dueToNullActual);
2286       }
2287       return std::nullopt;
2288     }
2289   }
2290   if (resolution->GetUltimate().has<semantics::DerivedTypeDetails>()) {
2291     if (mightBeStructureConstructor) {
2292       return CalleeAndArguments{
2293           semantics::SymbolRef{*resolution}, std::move(arguments)};
2294     }
2295   } else if (IsProcedure(*resolution)) {
2296     return CalleeAndArguments{
2297         ProcedureDesignator{*resolution}, std::move(arguments)};
2298   }
2299   if (!context_.HasError(*resolution)) {
2300     AttachDeclaration(
2301         Say(name.source, "'%s' is not a callable procedure"_err_en_US,
2302             name.source),
2303         *resolution);
2304   }
2305   return std::nullopt;
2306 }
2307 
2308 // Fortran 2018 expressly states (8.2 p3) that any declared type for a
2309 // generic intrinsic function "has no effect" on the result type of a
2310 // call to that intrinsic.  So one can declare "character*8 cos" and
2311 // still get a real result from "cos(1.)".  This is a dangerous feature,
2312 // especially since implementations are free to extend their sets of
2313 // intrinsics, and in doing so might clash with a name in a program.
2314 // So we emit a warning in this situation, and perhaps it should be an
2315 // error -- any correctly working program can silence the message by
2316 // simply deleting the pointless type declaration.
2317 void ExpressionAnalyzer::CheckBadExplicitType(
2318     const SpecificCall &call, const Symbol &intrinsic) {
2319   if (intrinsic.GetUltimate().GetType()) {
2320     const auto &procedure{call.specificIntrinsic.characteristics.value()};
2321     if (const auto &result{procedure.functionResult}) {
2322       if (const auto *typeAndShape{result->GetTypeAndShape()}) {
2323         if (auto declared{
2324                 typeAndShape->Characterize(intrinsic, GetFoldingContext())}) {
2325           if (!declared->type().IsTkCompatibleWith(typeAndShape->type())) {
2326             if (auto *msg{Say(
2327                     "The result type '%s' of the intrinsic function '%s' is not the explicit declared type '%s'"_warn_en_US,
2328                     typeAndShape->AsFortran(), intrinsic.name(),
2329                     declared->AsFortran())}) {
2330               msg->Attach(intrinsic.name(),
2331                   "Ignored declaration of intrinsic function '%s'"_en_US,
2332                   intrinsic.name());
2333             }
2334           }
2335         }
2336       }
2337     }
2338   }
2339 }
2340 
2341 void ExpressionAnalyzer::CheckForBadRecursion(
2342     parser::CharBlock callSite, const semantics::Symbol &proc) {
2343   if (const auto *scope{proc.scope()}) {
2344     if (scope->sourceRange().Contains(callSite)) {
2345       parser::Message *msg{nullptr};
2346       if (proc.attrs().test(semantics::Attr::NON_RECURSIVE)) { // 15.6.2.1(3)
2347         msg = Say("NON_RECURSIVE procedure '%s' cannot call itself"_err_en_US,
2348             callSite);
2349       } else if (IsAssumedLengthCharacter(proc) && IsExternal(proc)) {
2350         // TODO: Also catch assumed PDT type parameters
2351         msg = Say( // 15.6.2.1(3)
2352             "Assumed-length CHARACTER(*) function '%s' cannot call itself"_err_en_US,
2353             callSite);
2354       }
2355       AttachDeclaration(msg, proc);
2356     }
2357   }
2358 }
2359 
2360 template <typename A> static const Symbol *AssumedTypeDummy(const A &x) {
2361   if (const auto *designator{
2362           std::get_if<common::Indirection<parser::Designator>>(&x.u)}) {
2363     if (const auto *dataRef{
2364             std::get_if<parser::DataRef>(&designator->value().u)}) {
2365       if (const auto *name{std::get_if<parser::Name>(&dataRef->u)}) {
2366         return AssumedTypeDummy(*name);
2367       }
2368     }
2369   }
2370   return nullptr;
2371 }
2372 template <>
2373 const Symbol *AssumedTypeDummy<parser::Name>(const parser::Name &name) {
2374   if (const Symbol * symbol{name.symbol}) {
2375     if (const auto *type{symbol->GetType()}) {
2376       if (type->category() == semantics::DeclTypeSpec::TypeStar) {
2377         return symbol;
2378       }
2379     }
2380   }
2381   return nullptr;
2382 }
2383 template <typename A>
2384 static const Symbol *AssumedTypePointerOrAllocatableDummy(const A &object) {
2385   // It is illegal for allocatable of pointer objects to be TYPE(*), but at that
2386   // point it is is not guaranteed that it has been checked the object has
2387   // POINTER or ALLOCATABLE attribute, so do not assume nullptr can be directly
2388   // returned.
2389   return common::visit(
2390       common::visitors{
2391           [&](const parser::StructureComponent &x) {
2392             return AssumedTypeDummy(x.component);
2393           },
2394           [&](const parser::Name &x) { return AssumedTypeDummy(x); },
2395       },
2396       object.u);
2397 }
2398 template <>
2399 const Symbol *AssumedTypeDummy<parser::AllocateObject>(
2400     const parser::AllocateObject &x) {
2401   return AssumedTypePointerOrAllocatableDummy(x);
2402 }
2403 template <>
2404 const Symbol *AssumedTypeDummy<parser::PointerObject>(
2405     const parser::PointerObject &x) {
2406   return AssumedTypePointerOrAllocatableDummy(x);
2407 }
2408 
2409 bool ExpressionAnalyzer::CheckIsValidForwardReference(
2410     const semantics::DerivedTypeSpec &dtSpec) {
2411   if (dtSpec.IsForwardReferenced()) {
2412     Say("Cannot construct value for derived type '%s' "
2413         "before it is defined"_err_en_US,
2414         dtSpec.name());
2415     return false;
2416   }
2417   return true;
2418 }
2419 
2420 MaybeExpr ExpressionAnalyzer::Analyze(const parser::FunctionReference &funcRef,
2421     std::optional<parser::StructureConstructor> *structureConstructor) {
2422   const parser::Call &call{funcRef.v};
2423   auto restorer{GetContextualMessages().SetLocation(call.source)};
2424   ArgumentAnalyzer analyzer{*this, call.source, true /* isProcedureCall */};
2425   for (const auto &arg : std::get<std::list<parser::ActualArgSpec>>(call.t)) {
2426     analyzer.Analyze(arg, false /* not subroutine call */);
2427   }
2428   if (analyzer.fatalErrors()) {
2429     return std::nullopt;
2430   }
2431   if (std::optional<CalleeAndArguments> callee{
2432           GetCalleeAndArguments(std::get<parser::ProcedureDesignator>(call.t),
2433               analyzer.GetActuals(), false /* not subroutine */,
2434               true /* might be structure constructor */)}) {
2435     if (auto *proc{std::get_if<ProcedureDesignator>(&callee->u)}) {
2436       return MakeFunctionRef(
2437           call.source, std::move(*proc), std::move(callee->arguments));
2438     }
2439     CHECK(std::holds_alternative<semantics::SymbolRef>(callee->u));
2440     const Symbol &symbol{*std::get<semantics::SymbolRef>(callee->u)};
2441     if (structureConstructor) {
2442       // Structure constructor misparsed as function reference?
2443       const auto &designator{std::get<parser::ProcedureDesignator>(call.t)};
2444       if (const auto *name{std::get_if<parser::Name>(&designator.u)}) {
2445         semantics::Scope &scope{context_.FindScope(name->source)};
2446         semantics::DerivedTypeSpec dtSpec{name->source, symbol.GetUltimate()};
2447         if (!CheckIsValidForwardReference(dtSpec)) {
2448           return std::nullopt;
2449         }
2450         const semantics::DeclTypeSpec &type{
2451             semantics::FindOrInstantiateDerivedType(scope, std::move(dtSpec))};
2452         auto &mutableRef{const_cast<parser::FunctionReference &>(funcRef)};
2453         *structureConstructor =
2454             mutableRef.ConvertToStructureConstructor(type.derivedTypeSpec());
2455         return Analyze(structureConstructor->value());
2456       }
2457     }
2458     if (!context_.HasError(symbol)) {
2459       AttachDeclaration(
2460           Say("'%s' is called like a function but is not a procedure"_err_en_US,
2461               symbol.name()),
2462           symbol);
2463       context_.SetError(symbol);
2464     }
2465   }
2466   return std::nullopt;
2467 }
2468 
2469 static bool HasAlternateReturns(const evaluate::ActualArguments &args) {
2470   for (const auto &arg : args) {
2471     if (arg && arg->isAlternateReturn()) {
2472       return true;
2473     }
2474   }
2475   return false;
2476 }
2477 
2478 void ExpressionAnalyzer::Analyze(const parser::CallStmt &callStmt) {
2479   const parser::Call &call{callStmt.v};
2480   auto restorer{GetContextualMessages().SetLocation(call.source)};
2481   ArgumentAnalyzer analyzer{*this, call.source, true /* isProcedureCall */};
2482   const auto &actualArgList{std::get<std::list<parser::ActualArgSpec>>(call.t)};
2483   for (const auto &arg : actualArgList) {
2484     analyzer.Analyze(arg, true /* is subroutine call */);
2485   }
2486   if (!analyzer.fatalErrors()) {
2487     if (std::optional<CalleeAndArguments> callee{
2488             GetCalleeAndArguments(std::get<parser::ProcedureDesignator>(call.t),
2489                 analyzer.GetActuals(), true /* subroutine */)}) {
2490       ProcedureDesignator *proc{std::get_if<ProcedureDesignator>(&callee->u)};
2491       CHECK(proc);
2492       if (CheckCall(call.source, *proc, callee->arguments)) {
2493         callStmt.typedCall.Reset(
2494             new ProcedureRef{std::move(*proc), std::move(callee->arguments),
2495                 HasAlternateReturns(callee->arguments)},
2496             ProcedureRef::Deleter);
2497         return;
2498       }
2499     }
2500     if (!context_.AnyFatalError()) {
2501       std::string buf;
2502       llvm::raw_string_ostream dump{buf};
2503       parser::DumpTree(dump, callStmt);
2504       Say("Internal error: Expression analysis failed on CALL statement: %s"_err_en_US,
2505           dump.str());
2506     }
2507   }
2508 }
2509 
2510 const Assignment *ExpressionAnalyzer::Analyze(const parser::AssignmentStmt &x) {
2511   if (!x.typedAssignment) {
2512     ArgumentAnalyzer analyzer{*this};
2513     analyzer.Analyze(std::get<parser::Variable>(x.t));
2514     analyzer.Analyze(std::get<parser::Expr>(x.t));
2515     std::optional<Assignment> assignment;
2516     if (!analyzer.fatalErrors()) {
2517       std::optional<ProcedureRef> procRef{analyzer.TryDefinedAssignment()};
2518       if (!procRef) {
2519         analyzer.CheckForNullPointer(
2520             "in a non-pointer intrinsic assignment statement");
2521       }
2522       assignment.emplace(analyzer.MoveExpr(0), analyzer.MoveExpr(1));
2523       if (procRef) {
2524         assignment->u = std::move(*procRef);
2525       }
2526     }
2527     x.typedAssignment.Reset(new GenericAssignmentWrapper{std::move(assignment)},
2528         GenericAssignmentWrapper::Deleter);
2529   }
2530   return common::GetPtrFromOptional(x.typedAssignment->v);
2531 }
2532 
2533 const Assignment *ExpressionAnalyzer::Analyze(
2534     const parser::PointerAssignmentStmt &x) {
2535   if (!x.typedAssignment) {
2536     MaybeExpr lhs{Analyze(std::get<parser::DataRef>(x.t))};
2537     MaybeExpr rhs{Analyze(std::get<parser::Expr>(x.t))};
2538     if (!lhs || !rhs) {
2539       x.typedAssignment.Reset(
2540           new GenericAssignmentWrapper{}, GenericAssignmentWrapper::Deleter);
2541     } else {
2542       Assignment assignment{std::move(*lhs), std::move(*rhs)};
2543       common::visit(
2544           common::visitors{
2545               [&](const std::list<parser::BoundsRemapping> &list) {
2546                 Assignment::BoundsRemapping bounds;
2547                 for (const auto &elem : list) {
2548                   auto lower{AsSubscript(Analyze(std::get<0>(elem.t)))};
2549                   auto upper{AsSubscript(Analyze(std::get<1>(elem.t)))};
2550                   if (lower && upper) {
2551                     bounds.emplace_back(
2552                         Fold(std::move(*lower)), Fold(std::move(*upper)));
2553                   }
2554                 }
2555                 assignment.u = std::move(bounds);
2556               },
2557               [&](const std::list<parser::BoundsSpec> &list) {
2558                 Assignment::BoundsSpec bounds;
2559                 for (const auto &bound : list) {
2560                   if (auto lower{AsSubscript(Analyze(bound.v))}) {
2561                     bounds.emplace_back(Fold(std::move(*lower)));
2562                   }
2563                 }
2564                 assignment.u = std::move(bounds);
2565               },
2566           },
2567           std::get<parser::PointerAssignmentStmt::Bounds>(x.t).u);
2568       x.typedAssignment.Reset(
2569           new GenericAssignmentWrapper{std::move(assignment)},
2570           GenericAssignmentWrapper::Deleter);
2571     }
2572   }
2573   return common::GetPtrFromOptional(x.typedAssignment->v);
2574 }
2575 
2576 static bool IsExternalCalledImplicitly(
2577     parser::CharBlock callSite, const ProcedureDesignator &proc) {
2578   if (const auto *symbol{proc.GetSymbol()}) {
2579     return symbol->has<semantics::SubprogramDetails>() &&
2580         symbol->owner().IsGlobal() &&
2581         (!symbol->scope() /*ENTRY*/ ||
2582             !symbol->scope()->sourceRange().Contains(callSite));
2583   } else {
2584     return false;
2585   }
2586 }
2587 
2588 std::optional<characteristics::Procedure> ExpressionAnalyzer::CheckCall(
2589     parser::CharBlock callSite, const ProcedureDesignator &proc,
2590     ActualArguments &arguments) {
2591   auto chars{characteristics::Procedure::Characterize(
2592       proc, context_.foldingContext())};
2593   if (chars) {
2594     bool treatExternalAsImplicit{IsExternalCalledImplicitly(callSite, proc)};
2595     if (treatExternalAsImplicit && !chars->CanBeCalledViaImplicitInterface()) {
2596       Say(callSite,
2597           "References to the procedure '%s' require an explicit interface"_err_en_US,
2598           DEREF(proc.GetSymbol()).name());
2599     }
2600     // Checks for ASSOCIATED() are done in intrinsic table processing
2601     const SpecificIntrinsic *specificIntrinsic{proc.GetSpecificIntrinsic()};
2602     bool procIsAssociated{
2603         specificIntrinsic && specificIntrinsic->name == "associated"};
2604     if (!procIsAssociated) {
2605       const Symbol *procSymbol{proc.GetSymbol()};
2606       bool procIsDummy{procSymbol && IsDummy(*procSymbol)};
2607       if (chars->functionResult &&
2608           chars->functionResult->IsAssumedLengthCharacter() &&
2609           !specificIntrinsic && !procIsDummy) {
2610         Say(callSite,
2611             "Assumed-length character function must be defined with a length to be called"_err_en_US);
2612       }
2613       semantics::CheckArguments(*chars, arguments, GetFoldingContext(),
2614           context_.FindScope(callSite), treatExternalAsImplicit,
2615           specificIntrinsic);
2616       if (procSymbol && !IsPureProcedure(*procSymbol)) {
2617         if (const semantics::Scope *
2618             pure{semantics::FindPureProcedureContaining(
2619                 context_.FindScope(callSite))}) {
2620           Say(callSite,
2621               "Procedure '%s' referenced in pure subprogram '%s' must be pure too"_err_en_US,
2622               procSymbol->name(), DEREF(pure->symbol()).name());
2623         }
2624       }
2625     }
2626   }
2627   return chars;
2628 }
2629 
2630 // Unary operations
2631 
2632 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Parentheses &x) {
2633   if (MaybeExpr operand{Analyze(x.v.value())}) {
2634     if (const semantics::Symbol * symbol{GetLastSymbol(*operand)}) {
2635       if (const semantics::Symbol * result{FindFunctionResult(*symbol)}) {
2636         if (semantics::IsProcedurePointer(*result)) {
2637           Say("A function reference that returns a procedure "
2638               "pointer may not be parenthesized"_err_en_US); // C1003
2639         }
2640       }
2641     }
2642     return Parenthesize(std::move(*operand));
2643   }
2644   return std::nullopt;
2645 }
2646 
2647 static MaybeExpr NumericUnaryHelper(ExpressionAnalyzer &context,
2648     NumericOperator opr, const parser::Expr::IntrinsicUnary &x) {
2649   ArgumentAnalyzer analyzer{context};
2650   analyzer.Analyze(x.v);
2651   if (!analyzer.fatalErrors()) {
2652     if (analyzer.IsIntrinsicNumeric(opr)) {
2653       analyzer.CheckForNullPointer();
2654       if (opr == NumericOperator::Add) {
2655         return analyzer.MoveExpr(0);
2656       } else {
2657         return Negation(context.GetContextualMessages(), analyzer.MoveExpr(0));
2658       }
2659     } else {
2660       return analyzer.TryDefinedOp(AsFortran(opr),
2661           "Operand of unary %s must be numeric; have %s"_err_en_US);
2662     }
2663   }
2664   return std::nullopt;
2665 }
2666 
2667 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::UnaryPlus &x) {
2668   return NumericUnaryHelper(*this, NumericOperator::Add, x);
2669 }
2670 
2671 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Negate &x) {
2672   if (const auto *litConst{
2673           std::get_if<parser::LiteralConstant>(&x.v.value().u)}) {
2674     if (const auto *intConst{
2675             std::get_if<parser::IntLiteralConstant>(&litConst->u)}) {
2676       return Analyze(*intConst, true);
2677     }
2678   }
2679   return NumericUnaryHelper(*this, NumericOperator::Subtract, x);
2680 }
2681 
2682 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::NOT &x) {
2683   ArgumentAnalyzer analyzer{*this};
2684   analyzer.Analyze(x.v);
2685   if (!analyzer.fatalErrors()) {
2686     if (analyzer.IsIntrinsicLogical()) {
2687       analyzer.CheckForNullPointer();
2688       return AsGenericExpr(
2689           LogicalNegation(std::get<Expr<SomeLogical>>(analyzer.MoveExpr(0).u)));
2690     } else {
2691       return analyzer.TryDefinedOp(LogicalOperator::Not,
2692           "Operand of %s must be LOGICAL; have %s"_err_en_US);
2693     }
2694   }
2695   return std::nullopt;
2696 }
2697 
2698 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::PercentLoc &x) {
2699   // Represent %LOC() exactly as if it had been a call to the LOC() extension
2700   // intrinsic function.
2701   // Use the actual source for the name of the call for error reporting.
2702   std::optional<ActualArgument> arg;
2703   if (const Symbol * assumedTypeDummy{AssumedTypeDummy(x.v.value())}) {
2704     arg = ActualArgument{ActualArgument::AssumedType{*assumedTypeDummy}};
2705   } else if (MaybeExpr argExpr{Analyze(x.v.value())}) {
2706     arg = ActualArgument{std::move(*argExpr)};
2707   } else {
2708     return std::nullopt;
2709   }
2710   parser::CharBlock at{GetContextualMessages().at()};
2711   CHECK(at.size() >= 4);
2712   parser::CharBlock loc{at.begin() + 1, 3};
2713   CHECK(loc == "loc");
2714   return MakeFunctionRef(loc, ActualArguments{std::move(*arg)});
2715 }
2716 
2717 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::DefinedUnary &x) {
2718   const auto &name{std::get<parser::DefinedOpName>(x.t).v};
2719   ArgumentAnalyzer analyzer{*this, name.source};
2720   analyzer.Analyze(std::get<1>(x.t));
2721   return analyzer.TryDefinedOp(name.source.ToString().c_str(),
2722       "No operator %s defined for %s"_err_en_US, nullptr, true);
2723 }
2724 
2725 // Binary (dyadic) operations
2726 
2727 template <template <typename> class OPR>
2728 MaybeExpr NumericBinaryHelper(ExpressionAnalyzer &context, NumericOperator opr,
2729     const parser::Expr::IntrinsicBinary &x) {
2730   ArgumentAnalyzer analyzer{context};
2731   analyzer.Analyze(std::get<0>(x.t));
2732   analyzer.Analyze(std::get<1>(x.t));
2733   if (!analyzer.fatalErrors()) {
2734     if (analyzer.IsIntrinsicNumeric(opr)) {
2735       analyzer.CheckForNullPointer();
2736       analyzer.CheckConformance();
2737       return NumericOperation<OPR>(context.GetContextualMessages(),
2738           analyzer.MoveExpr(0), analyzer.MoveExpr(1),
2739           context.GetDefaultKind(TypeCategory::Real));
2740     } else {
2741       return analyzer.TryDefinedOp(AsFortran(opr),
2742           "Operands of %s must be numeric; have %s and %s"_err_en_US);
2743     }
2744   }
2745   return std::nullopt;
2746 }
2747 
2748 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Power &x) {
2749   return NumericBinaryHelper<Power>(*this, NumericOperator::Power, x);
2750 }
2751 
2752 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Multiply &x) {
2753   return NumericBinaryHelper<Multiply>(*this, NumericOperator::Multiply, x);
2754 }
2755 
2756 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Divide &x) {
2757   return NumericBinaryHelper<Divide>(*this, NumericOperator::Divide, x);
2758 }
2759 
2760 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Add &x) {
2761   return NumericBinaryHelper<Add>(*this, NumericOperator::Add, x);
2762 }
2763 
2764 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Subtract &x) {
2765   return NumericBinaryHelper<Subtract>(*this, NumericOperator::Subtract, x);
2766 }
2767 
2768 MaybeExpr ExpressionAnalyzer::Analyze(
2769     const parser::Expr::ComplexConstructor &x) {
2770   auto re{Analyze(std::get<0>(x.t).value())};
2771   auto im{Analyze(std::get<1>(x.t).value())};
2772   if (re && im) {
2773     ConformabilityCheck(GetContextualMessages(), *re, *im);
2774   }
2775   return AsMaybeExpr(ConstructComplex(GetContextualMessages(), std::move(re),
2776       std::move(im), GetDefaultKind(TypeCategory::Real)));
2777 }
2778 
2779 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Concat &x) {
2780   ArgumentAnalyzer analyzer{*this};
2781   analyzer.Analyze(std::get<0>(x.t));
2782   analyzer.Analyze(std::get<1>(x.t));
2783   if (!analyzer.fatalErrors()) {
2784     if (analyzer.IsIntrinsicConcat()) {
2785       analyzer.CheckForNullPointer();
2786       return common::visit(
2787           [&](auto &&x, auto &&y) -> MaybeExpr {
2788             using T = ResultType<decltype(x)>;
2789             if constexpr (std::is_same_v<T, ResultType<decltype(y)>>) {
2790               return AsGenericExpr(Concat<T::kind>{std::move(x), std::move(y)});
2791             } else {
2792               DIE("different types for intrinsic concat");
2793             }
2794           },
2795           std::move(std::get<Expr<SomeCharacter>>(analyzer.MoveExpr(0).u).u),
2796           std::move(std::get<Expr<SomeCharacter>>(analyzer.MoveExpr(1).u).u));
2797     } else {
2798       return analyzer.TryDefinedOp("//",
2799           "Operands of %s must be CHARACTER with the same kind; have %s and %s"_err_en_US);
2800     }
2801   }
2802   return std::nullopt;
2803 }
2804 
2805 // The Name represents a user-defined intrinsic operator.
2806 // If the actuals match one of the specific procedures, return a function ref.
2807 // Otherwise report the error in messages.
2808 MaybeExpr ExpressionAnalyzer::AnalyzeDefinedOp(
2809     const parser::Name &name, ActualArguments &&actuals) {
2810   if (auto callee{GetCalleeAndArguments(name, std::move(actuals))}) {
2811     CHECK(std::holds_alternative<ProcedureDesignator>(callee->u));
2812     return MakeFunctionRef(name.source,
2813         std::move(std::get<ProcedureDesignator>(callee->u)),
2814         std::move(callee->arguments));
2815   } else {
2816     return std::nullopt;
2817   }
2818 }
2819 
2820 MaybeExpr RelationHelper(ExpressionAnalyzer &context, RelationalOperator opr,
2821     const parser::Expr::IntrinsicBinary &x) {
2822   ArgumentAnalyzer analyzer{context};
2823   analyzer.Analyze(std::get<0>(x.t));
2824   analyzer.Analyze(std::get<1>(x.t));
2825   if (!analyzer.fatalErrors()) {
2826     std::optional<DynamicType> leftType{analyzer.GetType(0)};
2827     std::optional<DynamicType> rightType{analyzer.GetType(1)};
2828     analyzer.ConvertBOZ(leftType, 0, rightType);
2829     analyzer.ConvertBOZ(rightType, 1, leftType);
2830     if (leftType && rightType &&
2831         analyzer.IsIntrinsicRelational(opr, *leftType, *rightType)) {
2832       analyzer.CheckForNullPointer("as a relational operand");
2833       return AsMaybeExpr(Relate(context.GetContextualMessages(), opr,
2834           analyzer.MoveExpr(0), analyzer.MoveExpr(1)));
2835     } else {
2836       return analyzer.TryDefinedOp(opr,
2837           leftType && leftType->category() == TypeCategory::Logical &&
2838                   rightType && rightType->category() == TypeCategory::Logical
2839               ? "LOGICAL operands must be compared using .EQV. or .NEQV."_err_en_US
2840               : "Operands of %s must have comparable types; have %s and %s"_err_en_US);
2841     }
2842   }
2843   return std::nullopt;
2844 }
2845 
2846 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::LT &x) {
2847   return RelationHelper(*this, RelationalOperator::LT, x);
2848 }
2849 
2850 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::LE &x) {
2851   return RelationHelper(*this, RelationalOperator::LE, x);
2852 }
2853 
2854 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::EQ &x) {
2855   return RelationHelper(*this, RelationalOperator::EQ, x);
2856 }
2857 
2858 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::NE &x) {
2859   return RelationHelper(*this, RelationalOperator::NE, x);
2860 }
2861 
2862 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::GE &x) {
2863   return RelationHelper(*this, RelationalOperator::GE, x);
2864 }
2865 
2866 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::GT &x) {
2867   return RelationHelper(*this, RelationalOperator::GT, x);
2868 }
2869 
2870 MaybeExpr LogicalBinaryHelper(ExpressionAnalyzer &context, LogicalOperator opr,
2871     const parser::Expr::IntrinsicBinary &x) {
2872   ArgumentAnalyzer analyzer{context};
2873   analyzer.Analyze(std::get<0>(x.t));
2874   analyzer.Analyze(std::get<1>(x.t));
2875   if (!analyzer.fatalErrors()) {
2876     if (analyzer.IsIntrinsicLogical()) {
2877       analyzer.CheckForNullPointer("as a logical operand");
2878       return AsGenericExpr(BinaryLogicalOperation(opr,
2879           std::get<Expr<SomeLogical>>(analyzer.MoveExpr(0).u),
2880           std::get<Expr<SomeLogical>>(analyzer.MoveExpr(1).u)));
2881     } else {
2882       return analyzer.TryDefinedOp(
2883           opr, "Operands of %s must be LOGICAL; have %s and %s"_err_en_US);
2884     }
2885   }
2886   return std::nullopt;
2887 }
2888 
2889 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::AND &x) {
2890   return LogicalBinaryHelper(*this, LogicalOperator::And, x);
2891 }
2892 
2893 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::OR &x) {
2894   return LogicalBinaryHelper(*this, LogicalOperator::Or, x);
2895 }
2896 
2897 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::EQV &x) {
2898   return LogicalBinaryHelper(*this, LogicalOperator::Eqv, x);
2899 }
2900 
2901 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::NEQV &x) {
2902   return LogicalBinaryHelper(*this, LogicalOperator::Neqv, x);
2903 }
2904 
2905 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::DefinedBinary &x) {
2906   const auto &name{std::get<parser::DefinedOpName>(x.t).v};
2907   ArgumentAnalyzer analyzer{*this, name.source};
2908   analyzer.Analyze(std::get<1>(x.t));
2909   analyzer.Analyze(std::get<2>(x.t));
2910   return analyzer.TryDefinedOp(name.source.ToString().c_str(),
2911       "No operator %s defined for %s and %s"_err_en_US, nullptr, true);
2912 }
2913 
2914 // Returns true if a parsed function reference should be converted
2915 // into an array element reference.
2916 static bool CheckFuncRefToArrayElement(semantics::SemanticsContext &context,
2917     const parser::FunctionReference &funcRef) {
2918   // Emit message if the function reference fix will end up an array element
2919   // reference with no subscripts, or subscripts on a scalar, because it will
2920   // not be possible to later distinguish in expressions between an empty
2921   // subscript list due to bad subscripts error recovery or because the
2922   // user did not put any.
2923   auto &proc{std::get<parser::ProcedureDesignator>(funcRef.v.t)};
2924   const auto *name{std::get_if<parser::Name>(&proc.u)};
2925   if (!name) {
2926     name = &std::get<parser::ProcComponentRef>(proc.u).v.thing.component;
2927   }
2928   if (!name->symbol) {
2929     return false;
2930   } else if (name->symbol->Rank() == 0) {
2931     if (const Symbol *
2932         function{
2933             semantics::IsFunctionResultWithSameNameAsFunction(*name->symbol)}) {
2934       auto &msg{context.Say(funcRef.v.source,
2935           "Recursive call to '%s' requires a distinct RESULT in its declaration"_err_en_US,
2936           name->source)};
2937       AttachDeclaration(&msg, *function);
2938       name->symbol = const_cast<Symbol *>(function);
2939     }
2940     return false;
2941   } else {
2942     if (std::get<std::list<parser::ActualArgSpec>>(funcRef.v.t).empty()) {
2943       auto &msg{context.Say(funcRef.v.source,
2944           "Reference to array '%s' with empty subscript list"_err_en_US,
2945           name->source)};
2946       if (name->symbol) {
2947         AttachDeclaration(&msg, *name->symbol);
2948       }
2949     }
2950     return true;
2951   }
2952 }
2953 
2954 // Converts, if appropriate, an original misparse of ambiguous syntax like
2955 // A(1) as a function reference into an array reference.
2956 // Misparsed structure constructors are detected elsewhere after generic
2957 // function call resolution fails.
2958 template <typename... A>
2959 static void FixMisparsedFunctionReference(
2960     semantics::SemanticsContext &context, const std::variant<A...> &constU) {
2961   // The parse tree is updated in situ when resolving an ambiguous parse.
2962   using uType = std::decay_t<decltype(constU)>;
2963   auto &u{const_cast<uType &>(constU)};
2964   if (auto *func{
2965           std::get_if<common::Indirection<parser::FunctionReference>>(&u)}) {
2966     parser::FunctionReference &funcRef{func->value()};
2967     auto &proc{std::get<parser::ProcedureDesignator>(funcRef.v.t)};
2968     if (Symbol *
2969         origSymbol{
2970             common::visit(common::visitors{
2971                               [&](parser::Name &name) { return name.symbol; },
2972                               [&](parser::ProcComponentRef &pcr) {
2973                                 return pcr.v.thing.component.symbol;
2974                               },
2975                           },
2976                 proc.u)}) {
2977       Symbol &symbol{origSymbol->GetUltimate()};
2978       if (symbol.has<semantics::ObjectEntityDetails>() ||
2979           symbol.has<semantics::AssocEntityDetails>()) {
2980         // Note that expression in AssocEntityDetails cannot be a procedure
2981         // pointer as per C1105 so this cannot be a function reference.
2982         if constexpr (common::HasMember<common::Indirection<parser::Designator>,
2983                           uType>) {
2984           if (CheckFuncRefToArrayElement(context, funcRef)) {
2985             u = common::Indirection{funcRef.ConvertToArrayElementRef()};
2986           }
2987         } else {
2988           DIE("can't fix misparsed function as array reference");
2989         }
2990       }
2991     }
2992   }
2993 }
2994 
2995 // Common handling of parse tree node types that retain the
2996 // representation of the analyzed expression.
2997 template <typename PARSED>
2998 MaybeExpr ExpressionAnalyzer::ExprOrVariable(
2999     const PARSED &x, parser::CharBlock source) {
3000   if (useSavedTypedExprs_ && x.typedExpr) {
3001     return x.typedExpr->v;
3002   }
3003   auto restorer{GetContextualMessages().SetLocation(source)};
3004   if constexpr (std::is_same_v<PARSED, parser::Expr> ||
3005       std::is_same_v<PARSED, parser::Variable>) {
3006     FixMisparsedFunctionReference(context_, x.u);
3007   }
3008   if (AssumedTypeDummy(x)) { // C710
3009     Say("TYPE(*) dummy argument may only be used as an actual argument"_err_en_US);
3010     ResetExpr(x);
3011     return std::nullopt;
3012   }
3013   MaybeExpr result;
3014   if constexpr (common::HasMember<parser::StructureConstructor,
3015                     std::decay_t<decltype(x.u)>> &&
3016       common::HasMember<common::Indirection<parser::FunctionReference>,
3017           std::decay_t<decltype(x.u)>>) {
3018     if (const auto *funcRef{
3019             std::get_if<common::Indirection<parser::FunctionReference>>(
3020                 &x.u)}) {
3021       // Function references in Exprs might turn out to be misparsed structure
3022       // constructors; we have to try generic procedure resolution
3023       // first to be sure.
3024       std::optional<parser::StructureConstructor> ctor;
3025       result = Analyze(funcRef->value(), &ctor);
3026       if (result && ctor) {
3027         // A misparsed function reference is really a structure
3028         // constructor.  Repair the parse tree in situ.
3029         const_cast<PARSED &>(x).u = std::move(*ctor);
3030       }
3031     } else {
3032       result = Analyze(x.u);
3033     }
3034   } else {
3035     result = Analyze(x.u);
3036   }
3037   if (result) {
3038     SetExpr(x, Fold(std::move(*result)));
3039     return x.typedExpr->v;
3040   } else {
3041     ResetExpr(x);
3042     if (!context_.AnyFatalError()) {
3043       std::string buf;
3044       llvm::raw_string_ostream dump{buf};
3045       parser::DumpTree(dump, x);
3046       Say("Internal error: Expression analysis failed on: %s"_err_en_US,
3047           dump.str());
3048     }
3049     return std::nullopt;
3050   }
3051 }
3052 
3053 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr &expr) {
3054   return ExprOrVariable(expr, expr.source);
3055 }
3056 
3057 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Variable &variable) {
3058   return ExprOrVariable(variable, variable.GetSource());
3059 }
3060 
3061 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Selector &selector) {
3062   if (const auto *var{std::get_if<parser::Variable>(&selector.u)}) {
3063     if (!useSavedTypedExprs_ || !var->typedExpr) {
3064       parser::CharBlock source{var->GetSource()};
3065       auto restorer{GetContextualMessages().SetLocation(source)};
3066       FixMisparsedFunctionReference(context_, var->u);
3067       if (const auto *funcRef{
3068               std::get_if<common::Indirection<parser::FunctionReference>>(
3069                   &var->u)}) {
3070         // A Selector that parsed as a Variable might turn out during analysis
3071         // to actually be a structure constructor.  In that case, repair the
3072         // Variable parse tree node into an Expr
3073         std::optional<parser::StructureConstructor> ctor;
3074         if (MaybeExpr result{Analyze(funcRef->value(), &ctor)}) {
3075           if (ctor) {
3076             auto &writable{const_cast<parser::Selector &>(selector)};
3077             writable.u = parser::Expr{std::move(*ctor)};
3078             auto &expr{std::get<parser::Expr>(writable.u)};
3079             expr.source = source;
3080             SetExpr(expr, Fold(std::move(*result)));
3081             return expr.typedExpr->v;
3082           } else {
3083             SetExpr(*var, Fold(std::move(*result)));
3084             return var->typedExpr->v;
3085           }
3086         } else {
3087           ResetExpr(*var);
3088           if (context_.AnyFatalError()) {
3089             return std::nullopt;
3090           }
3091         }
3092       }
3093     }
3094   }
3095   // Not a Variable -> FunctionReference; handle normally as Variable or Expr
3096   return Analyze(selector.u);
3097 }
3098 
3099 MaybeExpr ExpressionAnalyzer::Analyze(const parser::DataStmtConstant &x) {
3100   auto restorer{common::ScopedSet(inDataStmtConstant_, true)};
3101   return ExprOrVariable(x, x.source);
3102 }
3103 
3104 MaybeExpr ExpressionAnalyzer::Analyze(const parser::AllocateObject &x) {
3105   return ExprOrVariable(x, parser::FindSourceLocation(x));
3106 }
3107 
3108 MaybeExpr ExpressionAnalyzer::Analyze(const parser::PointerObject &x) {
3109   return ExprOrVariable(x, parser::FindSourceLocation(x));
3110 }
3111 
3112 Expr<SubscriptInteger> ExpressionAnalyzer::AnalyzeKindSelector(
3113     TypeCategory category,
3114     const std::optional<parser::KindSelector> &selector) {
3115   int defaultKind{GetDefaultKind(category)};
3116   if (!selector) {
3117     return Expr<SubscriptInteger>{defaultKind};
3118   }
3119   return common::visit(
3120       common::visitors{
3121           [&](const parser::ScalarIntConstantExpr &x) {
3122             if (MaybeExpr kind{Analyze(x)}) {
3123               if (std::optional<std::int64_t> code{ToInt64(*kind)}) {
3124                 if (CheckIntrinsicKind(category, *code)) {
3125                   return Expr<SubscriptInteger>{*code};
3126                 }
3127               } else if (auto *intExpr{UnwrapExpr<Expr<SomeInteger>>(*kind)}) {
3128                 return ConvertToType<SubscriptInteger>(std::move(*intExpr));
3129               }
3130             }
3131             return Expr<SubscriptInteger>{defaultKind};
3132           },
3133           [&](const parser::KindSelector::StarSize &x) {
3134             std::intmax_t size = x.v;
3135             if (!CheckIntrinsicSize(category, size)) {
3136               size = defaultKind;
3137             } else if (category == TypeCategory::Complex) {
3138               size /= 2;
3139             }
3140             return Expr<SubscriptInteger>{size};
3141           },
3142       },
3143       selector->u);
3144 }
3145 
3146 int ExpressionAnalyzer::GetDefaultKind(common::TypeCategory category) {
3147   return context_.GetDefaultKind(category);
3148 }
3149 
3150 DynamicType ExpressionAnalyzer::GetDefaultKindOfType(
3151     common::TypeCategory category) {
3152   return {category, GetDefaultKind(category)};
3153 }
3154 
3155 bool ExpressionAnalyzer::CheckIntrinsicKind(
3156     TypeCategory category, std::int64_t kind) {
3157   if (IsValidKindOfIntrinsicType(category, kind)) { // C712, C714, C715, C727
3158     return true;
3159   } else {
3160     Say("%s(KIND=%jd) is not a supported type"_err_en_US,
3161         ToUpperCase(EnumToString(category)), kind);
3162     return false;
3163   }
3164 }
3165 
3166 bool ExpressionAnalyzer::CheckIntrinsicSize(
3167     TypeCategory category, std::int64_t size) {
3168   if (category == TypeCategory::Complex) {
3169     // COMPLEX*16 == COMPLEX(KIND=8)
3170     if (size % 2 == 0 && IsValidKindOfIntrinsicType(category, size / 2)) {
3171       return true;
3172     }
3173   } else if (IsValidKindOfIntrinsicType(category, size)) {
3174     return true;
3175   }
3176   Say("%s*%jd is not a supported type"_err_en_US,
3177       ToUpperCase(EnumToString(category)), size);
3178   return false;
3179 }
3180 
3181 bool ExpressionAnalyzer::AddImpliedDo(parser::CharBlock name, int kind) {
3182   return impliedDos_.insert(std::make_pair(name, kind)).second;
3183 }
3184 
3185 void ExpressionAnalyzer::RemoveImpliedDo(parser::CharBlock name) {
3186   auto iter{impliedDos_.find(name)};
3187   if (iter != impliedDos_.end()) {
3188     impliedDos_.erase(iter);
3189   }
3190 }
3191 
3192 std::optional<int> ExpressionAnalyzer::IsImpliedDo(
3193     parser::CharBlock name) const {
3194   auto iter{impliedDos_.find(name)};
3195   if (iter != impliedDos_.cend()) {
3196     return {iter->second};
3197   } else {
3198     return std::nullopt;
3199   }
3200 }
3201 
3202 bool ExpressionAnalyzer::EnforceTypeConstraint(parser::CharBlock at,
3203     const MaybeExpr &result, TypeCategory category, bool defaultKind) {
3204   if (result) {
3205     if (auto type{result->GetType()}) {
3206       if (type->category() != category) { // C885
3207         Say(at, "Must have %s type, but is %s"_err_en_US,
3208             ToUpperCase(EnumToString(category)),
3209             ToUpperCase(type->AsFortran()));
3210         return false;
3211       } else if (defaultKind) {
3212         int kind{context_.GetDefaultKind(category)};
3213         if (type->kind() != kind) {
3214           Say(at, "Must have default kind(%d) of %s type, but is %s"_err_en_US,
3215               kind, ToUpperCase(EnumToString(category)),
3216               ToUpperCase(type->AsFortran()));
3217           return false;
3218         }
3219       }
3220     } else {
3221       Say(at, "Must have %s type, but is typeless"_err_en_US,
3222           ToUpperCase(EnumToString(category)));
3223       return false;
3224     }
3225   }
3226   return true;
3227 }
3228 
3229 MaybeExpr ExpressionAnalyzer::MakeFunctionRef(parser::CharBlock callSite,
3230     ProcedureDesignator &&proc, ActualArguments &&arguments) {
3231   if (const auto *intrinsic{std::get_if<SpecificIntrinsic>(&proc.u)}) {
3232     if (intrinsic->characteristics.value().attrs.test(
3233             characteristics::Procedure::Attr::NullPointer) &&
3234         arguments.empty()) {
3235       return Expr<SomeType>{NullPointer{}};
3236     }
3237   }
3238   if (const Symbol * symbol{proc.GetSymbol()}) {
3239     if (!ResolveForward(*symbol)) {
3240       return std::nullopt;
3241     }
3242   }
3243   if (auto chars{CheckCall(callSite, proc, arguments)}) {
3244     if (chars->functionResult) {
3245       const auto &result{*chars->functionResult};
3246       if (result.IsProcedurePointer()) {
3247         return Expr<SomeType>{
3248             ProcedureRef{std::move(proc), std::move(arguments)}};
3249       } else {
3250         // Not a procedure pointer, so type and shape are known.
3251         return TypedWrapper<FunctionRef, ProcedureRef>(
3252             DEREF(result.GetTypeAndShape()).type(),
3253             ProcedureRef{std::move(proc), std::move(arguments)});
3254       }
3255     } else {
3256       Say("Function result characteristics are not known"_err_en_US);
3257     }
3258   }
3259   return std::nullopt;
3260 }
3261 
3262 MaybeExpr ExpressionAnalyzer::MakeFunctionRef(
3263     parser::CharBlock intrinsic, ActualArguments &&arguments) {
3264   if (std::optional<SpecificCall> specificCall{
3265           context_.intrinsics().Probe(CallCharacteristics{intrinsic.ToString()},
3266               arguments, GetFoldingContext())}) {
3267     return MakeFunctionRef(intrinsic,
3268         ProcedureDesignator{std::move(specificCall->specificIntrinsic)},
3269         std::move(specificCall->arguments));
3270   } else {
3271     return std::nullopt;
3272   }
3273 }
3274 
3275 void ArgumentAnalyzer::Analyze(const parser::Variable &x) {
3276   source_.ExtendToCover(x.GetSource());
3277   if (MaybeExpr expr{context_.Analyze(x)}) {
3278     if (!IsConstantExpr(*expr)) {
3279       actuals_.emplace_back(std::move(*expr));
3280       SetArgSourceLocation(actuals_.back(), x.GetSource());
3281       return;
3282     }
3283     const Symbol *symbol{GetLastSymbol(*expr)};
3284     if (!symbol) {
3285       context_.SayAt(x, "Assignment to constant '%s' is not allowed"_err_en_US,
3286           x.GetSource());
3287     } else if (auto *subp{symbol->detailsIf<semantics::SubprogramDetails>()}) {
3288       auto *msg{context_.SayAt(x,
3289           "Assignment to subprogram '%s' is not allowed"_err_en_US,
3290           symbol->name())};
3291       if (subp->isFunction()) {
3292         const auto &result{subp->result().name()};
3293         msg->Attach(result, "Function result is '%s'"_en_US, result);
3294       }
3295     } else {
3296       context_.SayAt(x, "Assignment to constant '%s' is not allowed"_err_en_US,
3297           symbol->name());
3298     }
3299   }
3300   fatalErrors_ = true;
3301 }
3302 
3303 void ArgumentAnalyzer::Analyze(
3304     const parser::ActualArgSpec &arg, bool isSubroutine) {
3305   // TODO: Actual arguments that are procedures and procedure pointers need to
3306   // be detected and represented (they're not expressions).
3307   // TODO: C1534: Don't allow a "restricted" specific intrinsic to be passed.
3308   std::optional<ActualArgument> actual;
3309   common::visit(
3310       common::visitors{
3311           [&](const common::Indirection<parser::Expr> &x) {
3312             actual = AnalyzeExpr(x.value());
3313             SetArgSourceLocation(actual, x.value().source);
3314           },
3315           [&](const parser::AltReturnSpec &label) {
3316             if (!isSubroutine) {
3317               context_.Say("alternate return specification may not appear on"
3318                            " function reference"_err_en_US);
3319             }
3320             actual = ActualArgument(label.v);
3321           },
3322           [&](const parser::ActualArg::PercentRef &) {
3323             context_.Say("%REF() intrinsic for arguments"_todo_en_US);
3324           },
3325           [&](const parser::ActualArg::PercentVal &) {
3326             context_.Say("%VAL() intrinsic for arguments"_todo_en_US);
3327           },
3328       },
3329       std::get<parser::ActualArg>(arg.t).u);
3330   if (actual) {
3331     if (const auto &argKW{std::get<std::optional<parser::Keyword>>(arg.t)}) {
3332       actual->set_keyword(argKW->v.source);
3333     }
3334     actuals_.emplace_back(std::move(*actual));
3335   } else {
3336     fatalErrors_ = true;
3337   }
3338 }
3339 
3340 bool ArgumentAnalyzer::IsIntrinsicRelational(RelationalOperator opr,
3341     const DynamicType &leftType, const DynamicType &rightType) const {
3342   CHECK(actuals_.size() == 2);
3343   return semantics::IsIntrinsicRelational(
3344       opr, leftType, GetRank(0), rightType, GetRank(1));
3345 }
3346 
3347 bool ArgumentAnalyzer::IsIntrinsicNumeric(NumericOperator opr) const {
3348   std::optional<DynamicType> leftType{GetType(0)};
3349   if (actuals_.size() == 1) {
3350     if (IsBOZLiteral(0)) {
3351       return opr == NumericOperator::Add; // unary '+'
3352     } else {
3353       return leftType && semantics::IsIntrinsicNumeric(*leftType);
3354     }
3355   } else {
3356     std::optional<DynamicType> rightType{GetType(1)};
3357     if (IsBOZLiteral(0) && rightType) { // BOZ opr Integer/Real
3358       auto cat1{rightType->category()};
3359       return cat1 == TypeCategory::Integer || cat1 == TypeCategory::Real;
3360     } else if (IsBOZLiteral(1) && leftType) { // Integer/Real opr BOZ
3361       auto cat0{leftType->category()};
3362       return cat0 == TypeCategory::Integer || cat0 == TypeCategory::Real;
3363     } else {
3364       return leftType && rightType &&
3365           semantics::IsIntrinsicNumeric(
3366               *leftType, GetRank(0), *rightType, GetRank(1));
3367     }
3368   }
3369 }
3370 
3371 bool ArgumentAnalyzer::IsIntrinsicLogical() const {
3372   if (std::optional<DynamicType> leftType{GetType(0)}) {
3373     if (actuals_.size() == 1) {
3374       return semantics::IsIntrinsicLogical(*leftType);
3375     } else if (std::optional<DynamicType> rightType{GetType(1)}) {
3376       return semantics::IsIntrinsicLogical(
3377           *leftType, GetRank(0), *rightType, GetRank(1));
3378     }
3379   }
3380   return false;
3381 }
3382 
3383 bool ArgumentAnalyzer::IsIntrinsicConcat() const {
3384   if (std::optional<DynamicType> leftType{GetType(0)}) {
3385     if (std::optional<DynamicType> rightType{GetType(1)}) {
3386       return semantics::IsIntrinsicConcat(
3387           *leftType, GetRank(0), *rightType, GetRank(1));
3388     }
3389   }
3390   return false;
3391 }
3392 
3393 bool ArgumentAnalyzer::CheckConformance() {
3394   if (actuals_.size() == 2) {
3395     const auto *lhs{actuals_.at(0).value().UnwrapExpr()};
3396     const auto *rhs{actuals_.at(1).value().UnwrapExpr()};
3397     if (lhs && rhs) {
3398       auto &foldingContext{context_.GetFoldingContext()};
3399       auto lhShape{GetShape(foldingContext, *lhs)};
3400       auto rhShape{GetShape(foldingContext, *rhs)};
3401       if (lhShape && rhShape) {
3402         if (!evaluate::CheckConformance(foldingContext.messages(), *lhShape,
3403                 *rhShape, CheckConformanceFlags::EitherScalarExpandable,
3404                 "left operand", "right operand")
3405                  .value_or(false /*fail when conformance is not known now*/)) {
3406           fatalErrors_ = true;
3407           return false;
3408         }
3409       }
3410     }
3411   }
3412   return true; // no proven problem
3413 }
3414 
3415 bool ArgumentAnalyzer::CheckForNullPointer(const char *where) {
3416   for (const std::optional<ActualArgument> &arg : actuals_) {
3417     if (arg) {
3418       if (const Expr<SomeType> *expr{arg->UnwrapExpr()}) {
3419         if (IsNullPointer(*expr)) {
3420           context_.Say(
3421               source_, "A NULL() pointer is not allowed %s"_err_en_US, where);
3422           fatalErrors_ = true;
3423           return false;
3424         }
3425       }
3426     }
3427   }
3428   return true;
3429 }
3430 
3431 MaybeExpr ArgumentAnalyzer::TryDefinedOp(const char *opr,
3432     parser::MessageFixedText error, const Symbol **definedOpSymbolPtr,
3433     bool isUserOp) {
3434   if (AnyUntypedOrMissingOperand()) {
3435     context_.Say(error, ToUpperCase(opr), TypeAsFortran(0), TypeAsFortran(1));
3436     return std::nullopt;
3437   }
3438   const Symbol *localDefinedOpSymbolPtr{nullptr};
3439   if (!definedOpSymbolPtr) {
3440     definedOpSymbolPtr = &localDefinedOpSymbolPtr;
3441   }
3442   {
3443     auto restorer{context_.GetContextualMessages().DiscardMessages()};
3444     std::string oprNameString{
3445         isUserOp ? std::string{opr} : "operator("s + opr + ')'};
3446     parser::CharBlock oprName{oprNameString};
3447     const auto &scope{context_.context().FindScope(source_)};
3448     if (Symbol * symbol{scope.FindSymbol(oprName)}) {
3449       *definedOpSymbolPtr = symbol;
3450       parser::Name name{symbol->name(), symbol};
3451       if (auto result{context_.AnalyzeDefinedOp(name, GetActuals())}) {
3452         return result;
3453       }
3454     }
3455     for (std::size_t passIndex{0}; passIndex < actuals_.size(); ++passIndex) {
3456       if (const Symbol *
3457           symbol{FindBoundOp(oprName, passIndex, *definedOpSymbolPtr)}) {
3458         if (MaybeExpr result{TryBoundOp(*symbol, passIndex)}) {
3459           return result;
3460         }
3461       }
3462     }
3463   }
3464   if (*definedOpSymbolPtr) {
3465     SayNoMatch(ToUpperCase((*definedOpSymbolPtr)->name().ToString()));
3466   } else if (actuals_.size() == 1 || AreConformable()) {
3467     if (CheckForNullPointer()) {
3468       context_.Say(error, ToUpperCase(opr), TypeAsFortran(0), TypeAsFortran(1));
3469     }
3470   } else {
3471     context_.Say(
3472         "Operands of %s are not conformable; have rank %d and rank %d"_err_en_US,
3473         ToUpperCase(opr), actuals_[0]->Rank(), actuals_[1]->Rank());
3474   }
3475   return std::nullopt;
3476 }
3477 
3478 MaybeExpr ArgumentAnalyzer::TryDefinedOp(
3479     std::vector<const char *> oprs, parser::MessageFixedText error) {
3480   const Symbol *definedOpSymbolPtr{nullptr};
3481   for (std::size_t i{1}; i < oprs.size(); ++i) {
3482     auto restorer{context_.GetContextualMessages().DiscardMessages()};
3483     if (auto result{TryDefinedOp(oprs[i], error, &definedOpSymbolPtr)}) {
3484       return result;
3485     }
3486   }
3487   return TryDefinedOp(oprs[0], error, &definedOpSymbolPtr);
3488 }
3489 
3490 MaybeExpr ArgumentAnalyzer::TryBoundOp(const Symbol &symbol, int passIndex) {
3491   ActualArguments localActuals{actuals_};
3492   const Symbol *proc{GetBindingResolution(GetType(passIndex), symbol)};
3493   if (!proc) {
3494     proc = &symbol;
3495     localActuals.at(passIndex).value().set_isPassedObject();
3496   }
3497   CheckConformance();
3498   return context_.MakeFunctionRef(
3499       source_, ProcedureDesignator{*proc}, std::move(localActuals));
3500 }
3501 
3502 std::optional<ProcedureRef> ArgumentAnalyzer::TryDefinedAssignment() {
3503   using semantics::Tristate;
3504   const Expr<SomeType> &lhs{GetExpr(0)};
3505   const Expr<SomeType> &rhs{GetExpr(1)};
3506   std::optional<DynamicType> lhsType{lhs.GetType()};
3507   std::optional<DynamicType> rhsType{rhs.GetType()};
3508   int lhsRank{lhs.Rank()};
3509   int rhsRank{rhs.Rank()};
3510   Tristate isDefined{
3511       semantics::IsDefinedAssignment(lhsType, lhsRank, rhsType, rhsRank)};
3512   if (isDefined == Tristate::No) {
3513     if (lhsType && rhsType) {
3514       AddAssignmentConversion(*lhsType, *rhsType);
3515     }
3516     return std::nullopt; // user-defined assignment not allowed for these args
3517   }
3518   auto restorer{context_.GetContextualMessages().SetLocation(source_)};
3519   if (std::optional<ProcedureRef> procRef{GetDefinedAssignmentProc()}) {
3520     if (context_.inWhereBody() && !procRef->proc().IsElemental()) { // C1032
3521       context_.Say(
3522           "Defined assignment in WHERE must be elemental, but '%s' is not"_err_en_US,
3523           DEREF(procRef->proc().GetSymbol()).name());
3524     }
3525     context_.CheckCall(source_, procRef->proc(), procRef->arguments());
3526     return std::move(*procRef);
3527   }
3528   if (isDefined == Tristate::Yes) {
3529     if (!lhsType || !rhsType || (lhsRank != rhsRank && rhsRank != 0) ||
3530         !OkLogicalIntegerAssignment(lhsType->category(), rhsType->category())) {
3531       SayNoMatch("ASSIGNMENT(=)", true);
3532     }
3533   }
3534   return std::nullopt;
3535 }
3536 
3537 bool ArgumentAnalyzer::OkLogicalIntegerAssignment(
3538     TypeCategory lhs, TypeCategory rhs) {
3539   if (!context_.context().languageFeatures().IsEnabled(
3540           common::LanguageFeature::LogicalIntegerAssignment)) {
3541     return false;
3542   }
3543   std::optional<parser::MessageFixedText> msg;
3544   if (lhs == TypeCategory::Integer && rhs == TypeCategory::Logical) {
3545     // allow assignment to LOGICAL from INTEGER as a legacy extension
3546     msg = "assignment of LOGICAL to INTEGER"_port_en_US;
3547   } else if (lhs == TypeCategory::Logical && rhs == TypeCategory::Integer) {
3548     // ... and assignment to LOGICAL from INTEGER
3549     msg = "assignment of INTEGER to LOGICAL"_port_en_US;
3550   } else {
3551     return false;
3552   }
3553   if (context_.context().languageFeatures().ShouldWarn(
3554           common::LanguageFeature::LogicalIntegerAssignment)) {
3555     context_.Say(std::move(*msg));
3556   }
3557   return true;
3558 }
3559 
3560 std::optional<ProcedureRef> ArgumentAnalyzer::GetDefinedAssignmentProc() {
3561   auto restorer{context_.GetContextualMessages().DiscardMessages()};
3562   std::string oprNameString{"assignment(=)"};
3563   parser::CharBlock oprName{oprNameString};
3564   const Symbol *proc{nullptr};
3565   const auto &scope{context_.context().FindScope(source_)};
3566   if (const Symbol * symbol{scope.FindSymbol(oprName)}) {
3567     ExpressionAnalyzer::AdjustActuals noAdjustment;
3568     auto pair{context_.ResolveGeneric(*symbol, actuals_, noAdjustment, true)};
3569     if (pair.first) {
3570       proc = pair.first;
3571     } else {
3572       context_.EmitGenericResolutionError(*symbol, pair.second);
3573     }
3574   }
3575   int passedObjectIndex{-1};
3576   const Symbol *definedOpSymbol{nullptr};
3577   for (std::size_t i{0}; i < actuals_.size(); ++i) {
3578     if (const Symbol * specific{FindBoundOp(oprName, i, definedOpSymbol)}) {
3579       if (const Symbol *
3580           resolution{GetBindingResolution(GetType(i), *specific)}) {
3581         proc = resolution;
3582       } else {
3583         proc = specific;
3584         passedObjectIndex = i;
3585       }
3586     }
3587   }
3588   if (!proc) {
3589     return std::nullopt;
3590   }
3591   ActualArguments actualsCopy{actuals_};
3592   if (passedObjectIndex >= 0) {
3593     actualsCopy[passedObjectIndex]->set_isPassedObject();
3594   }
3595   return ProcedureRef{ProcedureDesignator{*proc}, std::move(actualsCopy)};
3596 }
3597 
3598 void ArgumentAnalyzer::Dump(llvm::raw_ostream &os) {
3599   os << "source_: " << source_.ToString() << " fatalErrors_ = " << fatalErrors_
3600      << '\n';
3601   for (const auto &actual : actuals_) {
3602     if (!actual.has_value()) {
3603       os << "- error\n";
3604     } else if (const Symbol * symbol{actual->GetAssumedTypeDummy()}) {
3605       os << "- assumed type: " << symbol->name().ToString() << '\n';
3606     } else if (const Expr<SomeType> *expr{actual->UnwrapExpr()}) {
3607       expr->AsFortran(os << "- expr: ") << '\n';
3608     } else {
3609       DIE("bad ActualArgument");
3610     }
3611   }
3612 }
3613 
3614 std::optional<ActualArgument> ArgumentAnalyzer::AnalyzeExpr(
3615     const parser::Expr &expr) {
3616   source_.ExtendToCover(expr.source);
3617   if (const Symbol * assumedTypeDummy{AssumedTypeDummy(expr)}) {
3618     expr.typedExpr.Reset(new GenericExprWrapper{}, GenericExprWrapper::Deleter);
3619     if (isProcedureCall_) {
3620       ActualArgument arg{ActualArgument::AssumedType{*assumedTypeDummy}};
3621       SetArgSourceLocation(arg, expr.source);
3622       return std::move(arg);
3623     }
3624     context_.SayAt(expr.source,
3625         "TYPE(*) dummy argument may only be used as an actual argument"_err_en_US);
3626   } else if (MaybeExpr argExpr{AnalyzeExprOrWholeAssumedSizeArray(expr)}) {
3627     if (isProcedureCall_ || !IsProcedure(*argExpr)) {
3628       ActualArgument arg{std::move(*argExpr)};
3629       SetArgSourceLocation(arg, expr.source);
3630       return std::move(arg);
3631     }
3632     context_.SayAt(expr.source,
3633         IsFunction(*argExpr) ? "Function call must have argument list"_err_en_US
3634                              : "Subroutine name is not allowed here"_err_en_US);
3635   }
3636   return std::nullopt;
3637 }
3638 
3639 MaybeExpr ArgumentAnalyzer::AnalyzeExprOrWholeAssumedSizeArray(
3640     const parser::Expr &expr) {
3641   // If an expression's parse tree is a whole assumed-size array:
3642   //   Expr -> Designator -> DataRef -> Name
3643   // treat it as a special case for argument passing and bypass
3644   // the C1002/C1014 constraint checking in expression semantics.
3645   if (const auto *name{parser::Unwrap<parser::Name>(expr)}) {
3646     if (name->symbol && semantics::IsAssumedSizeArray(*name->symbol)) {
3647       auto restorer{context_.AllowWholeAssumedSizeArray()};
3648       return context_.Analyze(expr);
3649     }
3650   }
3651   return context_.Analyze(expr);
3652 }
3653 
3654 bool ArgumentAnalyzer::AreConformable() const {
3655   CHECK(actuals_.size() == 2);
3656   return actuals_[0] && actuals_[1] &&
3657       evaluate::AreConformable(*actuals_[0], *actuals_[1]);
3658 }
3659 
3660 // Look for a type-bound operator in the type of arg number passIndex.
3661 const Symbol *ArgumentAnalyzer::FindBoundOp(
3662     parser::CharBlock oprName, int passIndex, const Symbol *&definedOp) {
3663   const auto *type{GetDerivedTypeSpec(GetType(passIndex))};
3664   if (!type || !type->scope()) {
3665     return nullptr;
3666   }
3667   const Symbol *symbol{type->scope()->FindComponent(oprName)};
3668   if (!symbol) {
3669     return nullptr;
3670   }
3671   definedOp = symbol;
3672   ExpressionAnalyzer::AdjustActuals adjustment{
3673       [&](const Symbol &proc, ActualArguments &) {
3674         return passIndex == GetPassIndex(proc);
3675       }};
3676   auto pair{context_.ResolveGeneric(*symbol, actuals_, adjustment, false)};
3677   if (!pair.first) {
3678     context_.EmitGenericResolutionError(*symbol, pair.second);
3679   }
3680   return pair.first;
3681 }
3682 
3683 // If there is an implicit conversion between intrinsic types, make it explicit
3684 void ArgumentAnalyzer::AddAssignmentConversion(
3685     const DynamicType &lhsType, const DynamicType &rhsType) {
3686   if (lhsType.category() == rhsType.category() &&
3687       (lhsType.category() == TypeCategory::Derived ||
3688           lhsType.kind() == rhsType.kind())) {
3689     // no conversion necessary
3690   } else if (auto rhsExpr{evaluate::ConvertToType(lhsType, MoveExpr(1))}) {
3691     std::optional<parser::CharBlock> source;
3692     if (actuals_[1]) {
3693       source = actuals_[1]->sourceLocation();
3694     }
3695     actuals_[1] = ActualArgument{*rhsExpr};
3696     SetArgSourceLocation(actuals_[1], source);
3697   } else {
3698     actuals_[1] = std::nullopt;
3699   }
3700 }
3701 
3702 std::optional<DynamicType> ArgumentAnalyzer::GetType(std::size_t i) const {
3703   return i < actuals_.size() ? actuals_[i].value().GetType() : std::nullopt;
3704 }
3705 int ArgumentAnalyzer::GetRank(std::size_t i) const {
3706   return i < actuals_.size() ? actuals_[i].value().Rank() : 0;
3707 }
3708 
3709 // If the argument at index i is a BOZ literal, convert its type to match the
3710 // otherType.  If it's REAL convert to REAL, otherwise convert to INTEGER.
3711 // Note that IBM supports comparing BOZ literals to CHARACTER operands.  That
3712 // is not currently supported.
3713 void ArgumentAnalyzer::ConvertBOZ(std::optional<DynamicType> &thisType,
3714     std::size_t i, std::optional<DynamicType> otherType) {
3715   if (IsBOZLiteral(i)) {
3716     Expr<SomeType> &&argExpr{MoveExpr(i)};
3717     auto *boz{std::get_if<BOZLiteralConstant>(&argExpr.u)};
3718     if (otherType && otherType->category() == TypeCategory::Real) {
3719       int kind{context_.context().GetDefaultKind(TypeCategory::Real)};
3720       MaybeExpr realExpr{
3721           ConvertToKind<TypeCategory::Real>(kind, std::move(*boz))};
3722       actuals_[i] = std::move(*realExpr);
3723       thisType.emplace(TypeCategory::Real, kind);
3724     } else {
3725       int kind{context_.context().GetDefaultKind(TypeCategory::Integer)};
3726       MaybeExpr intExpr{
3727           ConvertToKind<TypeCategory::Integer>(kind, std::move(*boz))};
3728       actuals_[i] = std::move(*intExpr);
3729       thisType.emplace(TypeCategory::Integer, kind);
3730     }
3731   }
3732 }
3733 
3734 // Report error resolving opr when there is a user-defined one available
3735 void ArgumentAnalyzer::SayNoMatch(const std::string &opr, bool isAssignment) {
3736   std::string type0{TypeAsFortran(0)};
3737   auto rank0{actuals_[0]->Rank()};
3738   if (actuals_.size() == 1) {
3739     if (rank0 > 0) {
3740       context_.Say("No intrinsic or user-defined %s matches "
3741                    "rank %d array of %s"_err_en_US,
3742           opr, rank0, type0);
3743     } else {
3744       context_.Say("No intrinsic or user-defined %s matches "
3745                    "operand type %s"_err_en_US,
3746           opr, type0);
3747     }
3748   } else {
3749     std::string type1{TypeAsFortran(1)};
3750     auto rank1{actuals_[1]->Rank()};
3751     if (rank0 > 0 && rank1 > 0 && rank0 != rank1) {
3752       context_.Say("No intrinsic or user-defined %s matches "
3753                    "rank %d array of %s and rank %d array of %s"_err_en_US,
3754           opr, rank0, type0, rank1, type1);
3755     } else if (isAssignment && rank0 != rank1) {
3756       if (rank0 == 0) {
3757         context_.Say("No intrinsic or user-defined %s matches "
3758                      "scalar %s and rank %d array of %s"_err_en_US,
3759             opr, type0, rank1, type1);
3760       } else {
3761         context_.Say("No intrinsic or user-defined %s matches "
3762                      "rank %d array of %s and scalar %s"_err_en_US,
3763             opr, rank0, type0, type1);
3764       }
3765     } else {
3766       context_.Say("No intrinsic or user-defined %s matches "
3767                    "operand types %s and %s"_err_en_US,
3768           opr, type0, type1);
3769     }
3770   }
3771 }
3772 
3773 std::string ArgumentAnalyzer::TypeAsFortran(std::size_t i) {
3774   if (i >= actuals_.size() || !actuals_[i]) {
3775     return "missing argument";
3776   } else if (std::optional<DynamicType> type{GetType(i)}) {
3777     return type->IsAssumedType()         ? "TYPE(*)"s
3778         : type->IsUnlimitedPolymorphic() ? "CLASS(*)"s
3779         : type->IsPolymorphic()          ? "CLASS("s + type->AsFortran() + ')'
3780         : type->category() == TypeCategory::Derived
3781         ? "TYPE("s + type->AsFortran() + ')'
3782         : type->category() == TypeCategory::Character
3783         ? "CHARACTER(KIND="s + std::to_string(type->kind()) + ')'
3784         : ToUpperCase(type->AsFortran());
3785   } else {
3786     return "untyped";
3787   }
3788 }
3789 
3790 bool ArgumentAnalyzer::AnyUntypedOrMissingOperand() {
3791   for (const auto &actual : actuals_) {
3792     if (!actual ||
3793         (!actual->GetType() && !IsBareNullPointer(actual->UnwrapExpr()))) {
3794       return true;
3795     }
3796   }
3797   return false;
3798 }
3799 } // namespace Fortran::evaluate
3800 
3801 namespace Fortran::semantics {
3802 evaluate::Expr<evaluate::SubscriptInteger> AnalyzeKindSelector(
3803     SemanticsContext &context, common::TypeCategory category,
3804     const std::optional<parser::KindSelector> &selector) {
3805   evaluate::ExpressionAnalyzer analyzer{context};
3806   auto restorer{
3807       analyzer.GetContextualMessages().SetLocation(context.location().value())};
3808   return analyzer.AnalyzeKindSelector(category, selector);
3809 }
3810 
3811 ExprChecker::ExprChecker(SemanticsContext &context) : context_{context} {}
3812 
3813 bool ExprChecker::Pre(const parser::DataImpliedDo &ido) {
3814   parser::Walk(std::get<parser::DataImpliedDo::Bounds>(ido.t), *this);
3815   const auto &bounds{std::get<parser::DataImpliedDo::Bounds>(ido.t)};
3816   auto name{bounds.name.thing.thing};
3817   int kind{evaluate::ResultType<evaluate::ImpliedDoIndex>::kind};
3818   if (const auto dynamicType{evaluate::DynamicType::From(*name.symbol)}) {
3819     if (dynamicType->category() == TypeCategory::Integer) {
3820       kind = dynamicType->kind();
3821     }
3822   }
3823   exprAnalyzer_.AddImpliedDo(name.source, kind);
3824   parser::Walk(std::get<std::list<parser::DataIDoObject>>(ido.t), *this);
3825   exprAnalyzer_.RemoveImpliedDo(name.source);
3826   return false;
3827 }
3828 
3829 bool ExprChecker::Walk(const parser::Program &program) {
3830   parser::Walk(program, *this);
3831   return !context_.AnyFatalError();
3832 }
3833 } // namespace Fortran::semantics
3834