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