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