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