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