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