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