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