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