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