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