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