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