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 (context_.HasError(sym)) { 1704 return std::nullopt; 1705 } 1706 if (auto *dtExpr{UnwrapExpr<Expr<SomeDerived>>(*base)}) { 1707 if (sym->has<semantics::GenericDetails>()) { 1708 AdjustActuals adjustment{ 1709 [&](const Symbol &proc, ActualArguments &actuals) { 1710 if (!proc.attrs().test(semantics::Attr::NOPASS)) { 1711 AddPassArg(actuals, std::move(*dtExpr), proc); 1712 } 1713 return true; 1714 }}; 1715 sym = ResolveGeneric(*sym, arguments, adjustment); 1716 if (!sym) { 1717 EmitGenericResolutionError(*sc.component.symbol); 1718 return std::nullopt; 1719 } 1720 } 1721 if (const Symbol * 1722 resolution{GetBindingResolution(dtExpr->GetType(), *sym)}) { 1723 AddPassArg(arguments, std::move(*dtExpr), *sym, false); 1724 return CalleeAndArguments{ 1725 ProcedureDesignator{*resolution}, std::move(arguments)}; 1726 } else if (std::optional<DataRef> dataRef{ 1727 ExtractDataRef(std::move(*dtExpr))}) { 1728 if (sym->attrs().test(semantics::Attr::NOPASS)) { 1729 return CalleeAndArguments{ 1730 ProcedureDesignator{Component{std::move(*dataRef), *sym}}, 1731 std::move(arguments)}; 1732 } else { 1733 AddPassArg(arguments, 1734 Expr<SomeDerived>{Designator<SomeDerived>{std::move(*dataRef)}}, 1735 *sym); 1736 return CalleeAndArguments{ 1737 ProcedureDesignator{*sym}, std::move(arguments)}; 1738 } 1739 } 1740 } 1741 Say(sc.component.source, 1742 "Base of procedure component reference is not a derived-type object"_err_en_US); 1743 } 1744 } 1745 CHECK(!GetContextualMessages().empty()); 1746 return std::nullopt; 1747 } 1748 1749 // Can actual be argument associated with dummy? 1750 static bool CheckCompatibleArgument(bool isElemental, 1751 const ActualArgument &actual, const characteristics::DummyArgument &dummy) { 1752 return std::visit( 1753 common::visitors{ 1754 [&](const characteristics::DummyDataObject &x) { 1755 characteristics::TypeAndShape dummyTypeAndShape{x.type}; 1756 if (!isElemental && actual.Rank() != dummyTypeAndShape.Rank()) { 1757 return false; 1758 } else if (auto actualType{actual.GetType()}) { 1759 return dummyTypeAndShape.type().IsTkCompatibleWith(*actualType); 1760 } else { 1761 return false; 1762 } 1763 }, 1764 [&](const characteristics::DummyProcedure &) { 1765 const auto *expr{actual.UnwrapExpr()}; 1766 return expr && IsProcedurePointer(*expr); 1767 }, 1768 [&](const characteristics::AlternateReturn &) { 1769 return actual.isAlternateReturn(); 1770 }, 1771 }, 1772 dummy.u); 1773 } 1774 1775 // Are the actual arguments compatible with the dummy arguments of procedure? 1776 static bool CheckCompatibleArguments( 1777 const characteristics::Procedure &procedure, 1778 const ActualArguments &actuals) { 1779 bool isElemental{procedure.IsElemental()}; 1780 const auto &dummies{procedure.dummyArguments}; 1781 CHECK(dummies.size() == actuals.size()); 1782 for (std::size_t i{0}; i < dummies.size(); ++i) { 1783 const characteristics::DummyArgument &dummy{dummies[i]}; 1784 const std::optional<ActualArgument> &actual{actuals[i]}; 1785 if (actual && !CheckCompatibleArgument(isElemental, *actual, dummy)) { 1786 return false; 1787 } 1788 } 1789 return true; 1790 } 1791 1792 // Handles a forward reference to a module function from what must 1793 // be a specification expression. Return false if the symbol is 1794 // an invalid forward reference. 1795 bool ExpressionAnalyzer::ResolveForward(const Symbol &symbol) { 1796 if (context_.HasError(symbol)) { 1797 return false; 1798 } 1799 if (const auto *details{ 1800 symbol.detailsIf<semantics::SubprogramNameDetails>()}) { 1801 if (details->kind() == semantics::SubprogramKind::Module) { 1802 // If this symbol is still a SubprogramNameDetails, we must be 1803 // checking a specification expression in a sibling module 1804 // procedure. Resolve its names now so that its interface 1805 // is known. 1806 semantics::ResolveSpecificationParts(context_, symbol); 1807 if (symbol.has<semantics::SubprogramNameDetails>()) { 1808 // When the symbol hasn't had its details updated, we must have 1809 // already been in the process of resolving the function's 1810 // specification part; but recursive function calls are not 1811 // allowed in specification parts (10.1.11 para 5). 1812 Say("The module function '%s' may not be referenced recursively in a specification expression"_err_en_US, 1813 symbol.name()); 1814 context_.SetError(symbol); 1815 return false; 1816 } 1817 } else { // 10.1.11 para 4 1818 Say("The internal function '%s' may not be referenced in a specification expression"_err_en_US, 1819 symbol.name()); 1820 context_.SetError(symbol); 1821 return false; 1822 } 1823 } 1824 return true; 1825 } 1826 1827 // Resolve a call to a generic procedure with given actual arguments. 1828 // adjustActuals is called on procedure bindings to handle pass arg. 1829 const Symbol *ExpressionAnalyzer::ResolveGeneric(const Symbol &symbol, 1830 const ActualArguments &actuals, const AdjustActuals &adjustActuals, 1831 bool mightBeStructureConstructor) { 1832 const Symbol *elemental{nullptr}; // matching elemental specific proc 1833 const auto &details{symbol.GetUltimate().get<semantics::GenericDetails>()}; 1834 for (const Symbol &specific : details.specificProcs()) { 1835 if (!ResolveForward(specific)) { 1836 continue; 1837 } 1838 if (std::optional<characteristics::Procedure> procedure{ 1839 characteristics::Procedure::Characterize( 1840 ProcedureDesignator{specific}, context_.intrinsics())}) { 1841 ActualArguments localActuals{actuals}; 1842 if (specific.has<semantics::ProcBindingDetails>()) { 1843 if (!adjustActuals.value()(specific, localActuals)) { 1844 continue; 1845 } 1846 } 1847 if (semantics::CheckInterfaceForGeneric( 1848 *procedure, localActuals, GetFoldingContext())) { 1849 if (CheckCompatibleArguments(*procedure, localActuals)) { 1850 if (!procedure->IsElemental()) { 1851 return &specific; // takes priority over elemental match 1852 } 1853 elemental = &specific; 1854 } 1855 } 1856 } 1857 } 1858 if (elemental) { 1859 return elemental; 1860 } 1861 // Check parent derived type 1862 if (const auto *parentScope{symbol.owner().GetDerivedTypeParent()}) { 1863 if (const Symbol * extended{parentScope->FindComponent(symbol.name())}) { 1864 if (extended->GetUltimate().has<semantics::GenericDetails>()) { 1865 if (const Symbol * 1866 result{ResolveGeneric(*extended, actuals, adjustActuals, false)}) { 1867 return result; 1868 } 1869 } 1870 } 1871 } 1872 if (mightBeStructureConstructor && details.derivedType()) { 1873 return details.derivedType(); 1874 } 1875 return nullptr; 1876 } 1877 1878 void ExpressionAnalyzer::EmitGenericResolutionError(const Symbol &symbol) { 1879 if (semantics::IsGenericDefinedOp(symbol)) { 1880 Say("No specific procedure of generic operator '%s' matches the actual arguments"_err_en_US, 1881 symbol.name()); 1882 } else { 1883 Say("No specific procedure of generic '%s' matches the actual arguments"_err_en_US, 1884 symbol.name()); 1885 } 1886 } 1887 1888 auto ExpressionAnalyzer::GetCalleeAndArguments( 1889 const parser::ProcedureDesignator &pd, ActualArguments &&arguments, 1890 bool isSubroutine, bool mightBeStructureConstructor) 1891 -> std::optional<CalleeAndArguments> { 1892 return std::visit( 1893 common::visitors{ 1894 [&](const parser::Name &name) { 1895 return GetCalleeAndArguments(name, std::move(arguments), 1896 isSubroutine, mightBeStructureConstructor); 1897 }, 1898 [&](const parser::ProcComponentRef &pcr) { 1899 return AnalyzeProcedureComponentRef(pcr, std::move(arguments)); 1900 }, 1901 }, 1902 pd.u); 1903 } 1904 1905 auto ExpressionAnalyzer::GetCalleeAndArguments(const parser::Name &name, 1906 ActualArguments &&arguments, bool isSubroutine, 1907 bool mightBeStructureConstructor) -> std::optional<CalleeAndArguments> { 1908 const Symbol *symbol{name.symbol}; 1909 if (context_.HasError(symbol)) { 1910 return std::nullopt; // also handles null symbol 1911 } 1912 const Symbol &ultimate{DEREF(symbol).GetUltimate()}; 1913 if (ultimate.attrs().test(semantics::Attr::INTRINSIC)) { 1914 if (std::optional<SpecificCall> specificCall{context_.intrinsics().Probe( 1915 CallCharacteristics{ultimate.name().ToString(), isSubroutine}, 1916 arguments, GetFoldingContext())}) { 1917 return CalleeAndArguments{ 1918 ProcedureDesignator{std::move(specificCall->specificIntrinsic)}, 1919 std::move(specificCall->arguments)}; 1920 } 1921 } else { 1922 CheckForBadRecursion(name.source, ultimate); 1923 if (ultimate.has<semantics::GenericDetails>()) { 1924 ExpressionAnalyzer::AdjustActuals noAdjustment; 1925 symbol = ResolveGeneric( 1926 *symbol, arguments, noAdjustment, mightBeStructureConstructor); 1927 } 1928 if (symbol) { 1929 if (symbol->GetUltimate().has<semantics::DerivedTypeDetails>()) { 1930 if (mightBeStructureConstructor) { 1931 return CalleeAndArguments{ 1932 semantics::SymbolRef{*symbol}, std::move(arguments)}; 1933 } 1934 } else { 1935 return CalleeAndArguments{ 1936 ProcedureDesignator{*symbol}, std::move(arguments)}; 1937 } 1938 } else if (std::optional<SpecificCall> specificCall{ 1939 context_.intrinsics().Probe( 1940 CallCharacteristics{ 1941 ultimate.name().ToString(), isSubroutine}, 1942 arguments, GetFoldingContext())}) { 1943 // Generics can extend intrinsics 1944 return CalleeAndArguments{ 1945 ProcedureDesignator{std::move(specificCall->specificIntrinsic)}, 1946 std::move(specificCall->arguments)}; 1947 } else { 1948 EmitGenericResolutionError(*name.symbol); 1949 } 1950 } 1951 return std::nullopt; 1952 } 1953 1954 void ExpressionAnalyzer::CheckForBadRecursion( 1955 parser::CharBlock callSite, const semantics::Symbol &proc) { 1956 if (const auto *scope{proc.scope()}) { 1957 if (scope->sourceRange().Contains(callSite)) { 1958 parser::Message *msg{nullptr}; 1959 if (proc.attrs().test(semantics::Attr::NON_RECURSIVE)) { // 15.6.2.1(3) 1960 msg = Say("NON_RECURSIVE procedure '%s' cannot call itself"_err_en_US, 1961 callSite); 1962 } else if (IsAssumedLengthCharacter(proc) && IsExternal(proc)) { 1963 msg = Say( // 15.6.2.1(3) 1964 "Assumed-length CHARACTER(*) function '%s' cannot call itself"_err_en_US, 1965 callSite); 1966 } 1967 AttachDeclaration(msg, proc); 1968 } 1969 } 1970 } 1971 1972 template <typename A> static const Symbol *AssumedTypeDummy(const A &x) { 1973 if (const auto *designator{ 1974 std::get_if<common::Indirection<parser::Designator>>(&x.u)}) { 1975 if (const auto *dataRef{ 1976 std::get_if<parser::DataRef>(&designator->value().u)}) { 1977 if (const auto *name{std::get_if<parser::Name>(&dataRef->u)}) { 1978 if (const Symbol * symbol{name->symbol}) { 1979 if (const auto *type{symbol->GetType()}) { 1980 if (type->category() == semantics::DeclTypeSpec::TypeStar) { 1981 return symbol; 1982 } 1983 } 1984 } 1985 } 1986 } 1987 } 1988 return nullptr; 1989 } 1990 1991 MaybeExpr ExpressionAnalyzer::Analyze(const parser::FunctionReference &funcRef, 1992 std::optional<parser::StructureConstructor> *structureConstructor) { 1993 const parser::Call &call{funcRef.v}; 1994 auto restorer{GetContextualMessages().SetLocation(call.source)}; 1995 ArgumentAnalyzer analyzer{*this, call.source, true /* isProcedureCall */}; 1996 for (const auto &arg : std::get<std::list<parser::ActualArgSpec>>(call.t)) { 1997 analyzer.Analyze(arg, false /* not subroutine call */); 1998 } 1999 if (analyzer.fatalErrors()) { 2000 return std::nullopt; 2001 } 2002 if (std::optional<CalleeAndArguments> callee{ 2003 GetCalleeAndArguments(std::get<parser::ProcedureDesignator>(call.t), 2004 analyzer.GetActuals(), false /* not subroutine */, 2005 true /* might be structure constructor */)}) { 2006 if (auto *proc{std::get_if<ProcedureDesignator>(&callee->u)}) { 2007 return MakeFunctionRef( 2008 call.source, std::move(*proc), std::move(callee->arguments)); 2009 } else if (structureConstructor) { 2010 // Structure constructor misparsed as function reference? 2011 CHECK(std::holds_alternative<semantics::SymbolRef>(callee->u)); 2012 const Symbol &derivedType{*std::get<semantics::SymbolRef>(callee->u)}; 2013 const auto &designator{std::get<parser::ProcedureDesignator>(call.t)}; 2014 if (const auto *name{std::get_if<parser::Name>(&designator.u)}) { 2015 semantics::Scope &scope{context_.FindScope(name->source)}; 2016 semantics::DerivedTypeSpec dtSpec{ 2017 name->source, derivedType.GetUltimate()}; 2018 if (dtSpec.IsForwardReferenced()) { 2019 Say(call.source, 2020 "Cannot construct value for derived type '%s' " 2021 "before it is defined"_err_en_US, 2022 name->source); 2023 return std::nullopt; 2024 } 2025 const semantics::DeclTypeSpec &type{ 2026 semantics::FindOrInstantiateDerivedType( 2027 scope, std::move(dtSpec), context_)}; 2028 auto &mutableRef{const_cast<parser::FunctionReference &>(funcRef)}; 2029 *structureConstructor = 2030 mutableRef.ConvertToStructureConstructor(type.derivedTypeSpec()); 2031 return Analyze(structureConstructor->value()); 2032 } 2033 } 2034 } 2035 return std::nullopt; 2036 } 2037 2038 void ExpressionAnalyzer::Analyze(const parser::CallStmt &callStmt) { 2039 const parser::Call &call{callStmt.v}; 2040 auto restorer{GetContextualMessages().SetLocation(call.source)}; 2041 ArgumentAnalyzer analyzer{*this, call.source, true /* isProcedureCall */}; 2042 const auto &actualArgList{std::get<std::list<parser::ActualArgSpec>>(call.t)}; 2043 for (const auto &arg : actualArgList) { 2044 analyzer.Analyze(arg, true /* is subroutine call */); 2045 } 2046 if (!analyzer.fatalErrors()) { 2047 if (std::optional<CalleeAndArguments> callee{ 2048 GetCalleeAndArguments(std::get<parser::ProcedureDesignator>(call.t), 2049 analyzer.GetActuals(), true /* subroutine */)}) { 2050 ProcedureDesignator *proc{std::get_if<ProcedureDesignator>(&callee->u)}; 2051 CHECK(proc); 2052 if (CheckCall(call.source, *proc, callee->arguments)) { 2053 bool hasAlternateReturns{ 2054 callee->arguments.size() < actualArgList.size()}; 2055 callStmt.typedCall.Reset( 2056 new ProcedureRef{std::move(*proc), std::move(callee->arguments), 2057 hasAlternateReturns}, 2058 ProcedureRef::Deleter); 2059 } 2060 } 2061 } 2062 } 2063 2064 const Assignment *ExpressionAnalyzer::Analyze(const parser::AssignmentStmt &x) { 2065 if (!x.typedAssignment) { 2066 ArgumentAnalyzer analyzer{*this}; 2067 analyzer.Analyze(std::get<parser::Variable>(x.t)); 2068 analyzer.Analyze(std::get<parser::Expr>(x.t)); 2069 if (analyzer.fatalErrors()) { 2070 x.typedAssignment.Reset( 2071 new GenericAssignmentWrapper{}, GenericAssignmentWrapper::Deleter); 2072 } else { 2073 std::optional<ProcedureRef> procRef{analyzer.TryDefinedAssignment()}; 2074 Assignment assignment{ 2075 Fold(analyzer.MoveExpr(0)), Fold(analyzer.MoveExpr(1))}; 2076 if (procRef) { 2077 assignment.u = std::move(*procRef); 2078 } 2079 x.typedAssignment.Reset( 2080 new GenericAssignmentWrapper{std::move(assignment)}, 2081 GenericAssignmentWrapper::Deleter); 2082 } 2083 } 2084 return common::GetPtrFromOptional(x.typedAssignment->v); 2085 } 2086 2087 const Assignment *ExpressionAnalyzer::Analyze( 2088 const parser::PointerAssignmentStmt &x) { 2089 if (!x.typedAssignment) { 2090 MaybeExpr lhs{Analyze(std::get<parser::DataRef>(x.t))}; 2091 MaybeExpr rhs{Analyze(std::get<parser::Expr>(x.t))}; 2092 if (!lhs || !rhs) { 2093 x.typedAssignment.Reset( 2094 new GenericAssignmentWrapper{}, GenericAssignmentWrapper::Deleter); 2095 } else { 2096 Assignment assignment{std::move(*lhs), std::move(*rhs)}; 2097 std::visit(common::visitors{ 2098 [&](const std::list<parser::BoundsRemapping> &list) { 2099 Assignment::BoundsRemapping bounds; 2100 for (const auto &elem : list) { 2101 auto lower{AsSubscript(Analyze(std::get<0>(elem.t)))}; 2102 auto upper{AsSubscript(Analyze(std::get<1>(elem.t)))}; 2103 if (lower && upper) { 2104 bounds.emplace_back(Fold(std::move(*lower)), 2105 Fold(std::move(*upper))); 2106 } 2107 } 2108 assignment.u = std::move(bounds); 2109 }, 2110 [&](const std::list<parser::BoundsSpec> &list) { 2111 Assignment::BoundsSpec bounds; 2112 for (const auto &bound : list) { 2113 if (auto lower{AsSubscript(Analyze(bound.v))}) { 2114 bounds.emplace_back(Fold(std::move(*lower))); 2115 } 2116 } 2117 assignment.u = std::move(bounds); 2118 }, 2119 }, 2120 std::get<parser::PointerAssignmentStmt::Bounds>(x.t).u); 2121 x.typedAssignment.Reset( 2122 new GenericAssignmentWrapper{std::move(assignment)}, 2123 GenericAssignmentWrapper::Deleter); 2124 } 2125 } 2126 return common::GetPtrFromOptional(x.typedAssignment->v); 2127 } 2128 2129 static bool IsExternalCalledImplicitly( 2130 parser::CharBlock callSite, const ProcedureDesignator &proc) { 2131 if (const auto *symbol{proc.GetSymbol()}) { 2132 return symbol->has<semantics::SubprogramDetails>() && 2133 symbol->owner().IsGlobal() && 2134 (!symbol->scope() /*ENTRY*/ || 2135 !symbol->scope()->sourceRange().Contains(callSite)); 2136 } else { 2137 return false; 2138 } 2139 } 2140 2141 std::optional<characteristics::Procedure> ExpressionAnalyzer::CheckCall( 2142 parser::CharBlock callSite, const ProcedureDesignator &proc, 2143 ActualArguments &arguments) { 2144 auto chars{ 2145 characteristics::Procedure::Characterize(proc, context_.intrinsics())}; 2146 if (chars) { 2147 bool treatExternalAsImplicit{IsExternalCalledImplicitly(callSite, proc)}; 2148 if (treatExternalAsImplicit && !chars->CanBeCalledViaImplicitInterface()) { 2149 Say(callSite, 2150 "References to the procedure '%s' require an explicit interface"_en_US, 2151 DEREF(proc.GetSymbol()).name()); 2152 } 2153 // Checks for ASSOCIATED() are done in intrinsic table processing 2154 bool procIsAssociated{false}; 2155 if (const SpecificIntrinsic * 2156 specificIntrinsic{proc.GetSpecificIntrinsic()}) { 2157 if (specificIntrinsic->name == "associated") { 2158 procIsAssociated = true; 2159 } 2160 } 2161 if (!procIsAssociated) { 2162 semantics::CheckArguments(*chars, arguments, GetFoldingContext(), 2163 context_.FindScope(callSite), treatExternalAsImplicit, 2164 proc.GetSpecificIntrinsic()); 2165 const Symbol *procSymbol{proc.GetSymbol()}; 2166 if (procSymbol && !IsPureProcedure(*procSymbol)) { 2167 if (const semantics::Scope * 2168 pure{semantics::FindPureProcedureContaining( 2169 context_.FindScope(callSite))}) { 2170 Say(callSite, 2171 "Procedure '%s' referenced in pure subprogram '%s' must be pure too"_err_en_US, 2172 procSymbol->name(), DEREF(pure->symbol()).name()); 2173 } 2174 } 2175 } 2176 } 2177 return chars; 2178 } 2179 2180 // Unary operations 2181 2182 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Parentheses &x) { 2183 if (MaybeExpr operand{Analyze(x.v.value())}) { 2184 if (const semantics::Symbol * symbol{GetLastSymbol(*operand)}) { 2185 if (const semantics::Symbol * result{FindFunctionResult(*symbol)}) { 2186 if (semantics::IsProcedurePointer(*result)) { 2187 Say("A function reference that returns a procedure " 2188 "pointer may not be parenthesized"_err_en_US); // C1003 2189 } 2190 } 2191 } 2192 return Parenthesize(std::move(*operand)); 2193 } 2194 return std::nullopt; 2195 } 2196 2197 static MaybeExpr NumericUnaryHelper(ExpressionAnalyzer &context, 2198 NumericOperator opr, const parser::Expr::IntrinsicUnary &x) { 2199 ArgumentAnalyzer analyzer{context}; 2200 analyzer.Analyze(x.v); 2201 if (analyzer.fatalErrors()) { 2202 return std::nullopt; 2203 } else if (analyzer.IsIntrinsicNumeric(opr)) { 2204 if (opr == NumericOperator::Add) { 2205 return analyzer.MoveExpr(0); 2206 } else { 2207 return Negation(context.GetContextualMessages(), analyzer.MoveExpr(0)); 2208 } 2209 } else { 2210 return analyzer.TryDefinedOp(AsFortran(opr), 2211 "Operand of unary %s must be numeric; have %s"_err_en_US); 2212 } 2213 } 2214 2215 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::UnaryPlus &x) { 2216 return NumericUnaryHelper(*this, NumericOperator::Add, x); 2217 } 2218 2219 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Negate &x) { 2220 return NumericUnaryHelper(*this, NumericOperator::Subtract, x); 2221 } 2222 2223 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::NOT &x) { 2224 ArgumentAnalyzer analyzer{*this}; 2225 analyzer.Analyze(x.v); 2226 if (analyzer.fatalErrors()) { 2227 return std::nullopt; 2228 } else if (analyzer.IsIntrinsicLogical()) { 2229 return AsGenericExpr( 2230 LogicalNegation(std::get<Expr<SomeLogical>>(analyzer.MoveExpr(0).u))); 2231 } else { 2232 return analyzer.TryDefinedOp(LogicalOperator::Not, 2233 "Operand of %s must be LOGICAL; have %s"_err_en_US); 2234 } 2235 } 2236 2237 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::PercentLoc &x) { 2238 // Represent %LOC() exactly as if it had been a call to the LOC() extension 2239 // intrinsic function. 2240 // Use the actual source for the name of the call for error reporting. 2241 std::optional<ActualArgument> arg; 2242 if (const Symbol * assumedTypeDummy{AssumedTypeDummy(x.v.value())}) { 2243 arg = ActualArgument{ActualArgument::AssumedType{*assumedTypeDummy}}; 2244 } else if (MaybeExpr argExpr{Analyze(x.v.value())}) { 2245 arg = ActualArgument{std::move(*argExpr)}; 2246 } else { 2247 return std::nullopt; 2248 } 2249 parser::CharBlock at{GetContextualMessages().at()}; 2250 CHECK(at.size() >= 4); 2251 parser::CharBlock loc{at.begin() + 1, 3}; 2252 CHECK(loc == "loc"); 2253 return MakeFunctionRef(loc, ActualArguments{std::move(*arg)}); 2254 } 2255 2256 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::DefinedUnary &x) { 2257 const auto &name{std::get<parser::DefinedOpName>(x.t).v}; 2258 ArgumentAnalyzer analyzer{*this, name.source}; 2259 analyzer.Analyze(std::get<1>(x.t)); 2260 return analyzer.TryDefinedOp(name.source.ToString().c_str(), 2261 "No operator %s defined for %s"_err_en_US, true); 2262 } 2263 2264 // Binary (dyadic) operations 2265 2266 template <template <typename> class OPR> 2267 MaybeExpr NumericBinaryHelper(ExpressionAnalyzer &context, NumericOperator opr, 2268 const parser::Expr::IntrinsicBinary &x) { 2269 ArgumentAnalyzer analyzer{context}; 2270 analyzer.Analyze(std::get<0>(x.t)); 2271 analyzer.Analyze(std::get<1>(x.t)); 2272 if (analyzer.fatalErrors()) { 2273 return std::nullopt; 2274 } else if (analyzer.IsIntrinsicNumeric(opr)) { 2275 analyzer.CheckConformance(); 2276 return NumericOperation<OPR>(context.GetContextualMessages(), 2277 analyzer.MoveExpr(0), analyzer.MoveExpr(1), 2278 context.GetDefaultKind(TypeCategory::Real)); 2279 } else { 2280 return analyzer.TryDefinedOp(AsFortran(opr), 2281 "Operands of %s must be numeric; have %s and %s"_err_en_US); 2282 } 2283 } 2284 2285 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Power &x) { 2286 return NumericBinaryHelper<Power>(*this, NumericOperator::Power, x); 2287 } 2288 2289 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Multiply &x) { 2290 return NumericBinaryHelper<Multiply>(*this, NumericOperator::Multiply, x); 2291 } 2292 2293 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Divide &x) { 2294 return NumericBinaryHelper<Divide>(*this, NumericOperator::Divide, x); 2295 } 2296 2297 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Add &x) { 2298 return NumericBinaryHelper<Add>(*this, NumericOperator::Add, x); 2299 } 2300 2301 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Subtract &x) { 2302 return NumericBinaryHelper<Subtract>(*this, NumericOperator::Subtract, x); 2303 } 2304 2305 MaybeExpr ExpressionAnalyzer::Analyze( 2306 const parser::Expr::ComplexConstructor &x) { 2307 auto re{Analyze(std::get<0>(x.t).value())}; 2308 auto im{Analyze(std::get<1>(x.t).value())}; 2309 if (re && im) { 2310 ConformabilityCheck(GetContextualMessages(), *re, *im); 2311 } 2312 return AsMaybeExpr(ConstructComplex(GetContextualMessages(), std::move(re), 2313 std::move(im), GetDefaultKind(TypeCategory::Real))); 2314 } 2315 2316 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Concat &x) { 2317 ArgumentAnalyzer analyzer{*this}; 2318 analyzer.Analyze(std::get<0>(x.t)); 2319 analyzer.Analyze(std::get<1>(x.t)); 2320 if (analyzer.fatalErrors()) { 2321 return std::nullopt; 2322 } else if (analyzer.IsIntrinsicConcat()) { 2323 return std::visit( 2324 [&](auto &&x, auto &&y) -> MaybeExpr { 2325 using T = ResultType<decltype(x)>; 2326 if constexpr (std::is_same_v<T, ResultType<decltype(y)>>) { 2327 return AsGenericExpr(Concat<T::kind>{std::move(x), std::move(y)}); 2328 } else { 2329 DIE("different types for intrinsic concat"); 2330 } 2331 }, 2332 std::move(std::get<Expr<SomeCharacter>>(analyzer.MoveExpr(0).u).u), 2333 std::move(std::get<Expr<SomeCharacter>>(analyzer.MoveExpr(1).u).u)); 2334 } else { 2335 return analyzer.TryDefinedOp("//", 2336 "Operands of %s must be CHARACTER with the same kind; have %s and %s"_err_en_US); 2337 } 2338 } 2339 2340 // The Name represents a user-defined intrinsic operator. 2341 // If the actuals match one of the specific procedures, return a function ref. 2342 // Otherwise report the error in messages. 2343 MaybeExpr ExpressionAnalyzer::AnalyzeDefinedOp( 2344 const parser::Name &name, ActualArguments &&actuals) { 2345 if (auto callee{GetCalleeAndArguments(name, std::move(actuals))}) { 2346 CHECK(std::holds_alternative<ProcedureDesignator>(callee->u)); 2347 return MakeFunctionRef(name.source, 2348 std::move(std::get<ProcedureDesignator>(callee->u)), 2349 std::move(callee->arguments)); 2350 } else { 2351 return std::nullopt; 2352 } 2353 } 2354 2355 MaybeExpr RelationHelper(ExpressionAnalyzer &context, RelationalOperator opr, 2356 const parser::Expr::IntrinsicBinary &x) { 2357 ArgumentAnalyzer analyzer{context}; 2358 analyzer.Analyze(std::get<0>(x.t)); 2359 analyzer.Analyze(std::get<1>(x.t)); 2360 if (analyzer.fatalErrors()) { 2361 return std::nullopt; 2362 } else { 2363 if (IsNullPointer(analyzer.GetExpr(0)) || 2364 IsNullPointer(analyzer.GetExpr(1))) { 2365 context.Say("NULL() not allowed as an operand of a relational " 2366 "operator"_err_en_US); 2367 return std::nullopt; 2368 } 2369 analyzer.ConvertBOZ(0, analyzer.GetType(1)); 2370 analyzer.ConvertBOZ(1, analyzer.GetType(0)); 2371 if (analyzer.IsIntrinsicRelational(opr)) { 2372 return AsMaybeExpr(Relate(context.GetContextualMessages(), opr, 2373 analyzer.MoveExpr(0), analyzer.MoveExpr(1))); 2374 } else { 2375 return analyzer.TryDefinedOp(opr, 2376 "Operands of %s must have comparable types; have %s and %s"_err_en_US); 2377 } 2378 } 2379 } 2380 2381 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::LT &x) { 2382 return RelationHelper(*this, RelationalOperator::LT, x); 2383 } 2384 2385 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::LE &x) { 2386 return RelationHelper(*this, RelationalOperator::LE, x); 2387 } 2388 2389 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::EQ &x) { 2390 return RelationHelper(*this, RelationalOperator::EQ, x); 2391 } 2392 2393 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::NE &x) { 2394 return RelationHelper(*this, RelationalOperator::NE, x); 2395 } 2396 2397 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::GE &x) { 2398 return RelationHelper(*this, RelationalOperator::GE, x); 2399 } 2400 2401 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::GT &x) { 2402 return RelationHelper(*this, RelationalOperator::GT, x); 2403 } 2404 2405 MaybeExpr LogicalBinaryHelper(ExpressionAnalyzer &context, LogicalOperator opr, 2406 const parser::Expr::IntrinsicBinary &x) { 2407 ArgumentAnalyzer analyzer{context}; 2408 analyzer.Analyze(std::get<0>(x.t)); 2409 analyzer.Analyze(std::get<1>(x.t)); 2410 if (analyzer.fatalErrors()) { 2411 return std::nullopt; 2412 } else if (analyzer.IsIntrinsicLogical()) { 2413 return AsGenericExpr(BinaryLogicalOperation(opr, 2414 std::get<Expr<SomeLogical>>(analyzer.MoveExpr(0).u), 2415 std::get<Expr<SomeLogical>>(analyzer.MoveExpr(1).u))); 2416 } else { 2417 return analyzer.TryDefinedOp( 2418 opr, "Operands of %s must be LOGICAL; have %s and %s"_err_en_US); 2419 } 2420 } 2421 2422 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::AND &x) { 2423 return LogicalBinaryHelper(*this, LogicalOperator::And, x); 2424 } 2425 2426 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::OR &x) { 2427 return LogicalBinaryHelper(*this, LogicalOperator::Or, x); 2428 } 2429 2430 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::EQV &x) { 2431 return LogicalBinaryHelper(*this, LogicalOperator::Eqv, x); 2432 } 2433 2434 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::NEQV &x) { 2435 return LogicalBinaryHelper(*this, LogicalOperator::Neqv, x); 2436 } 2437 2438 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::DefinedBinary &x) { 2439 const auto &name{std::get<parser::DefinedOpName>(x.t).v}; 2440 ArgumentAnalyzer analyzer{*this, name.source}; 2441 analyzer.Analyze(std::get<1>(x.t)); 2442 analyzer.Analyze(std::get<2>(x.t)); 2443 return analyzer.TryDefinedOp(name.source.ToString().c_str(), 2444 "No operator %s defined for %s and %s"_err_en_US, true); 2445 } 2446 2447 static void CheckFuncRefToArrayElementRefHasSubscripts( 2448 semantics::SemanticsContext &context, 2449 const parser::FunctionReference &funcRef) { 2450 // Emit message if the function reference fix will end up an array element 2451 // reference with no subscripts because it will not be possible to later tell 2452 // the difference in expressions between empty subscript list due to bad 2453 // subscripts error recovery or because the user did not put any. 2454 if (std::get<std::list<parser::ActualArgSpec>>(funcRef.v.t).empty()) { 2455 auto &proc{std::get<parser::ProcedureDesignator>(funcRef.v.t)}; 2456 const auto *name{std::get_if<parser::Name>(&proc.u)}; 2457 if (!name) { 2458 name = &std::get<parser::ProcComponentRef>(proc.u).v.thing.component; 2459 } 2460 auto &msg{context.Say(funcRef.v.source, 2461 name->symbol && name->symbol->Rank() == 0 2462 ? "'%s' is not a function"_err_en_US 2463 : "Reference to array '%s' with empty subscript list"_err_en_US, 2464 name->source)}; 2465 if (name->symbol) { 2466 if (semantics::IsFunctionResultWithSameNameAsFunction(*name->symbol)) { 2467 msg.Attach(name->source, 2468 "A result variable must be declared with RESULT to allow recursive " 2469 "function calls"_en_US); 2470 } else { 2471 AttachDeclaration(&msg, *name->symbol); 2472 } 2473 } 2474 } 2475 } 2476 2477 // Converts, if appropriate, an original misparse of ambiguous syntax like 2478 // A(1) as a function reference into an array reference. 2479 // Misparse structure constructors are detected elsewhere after generic 2480 // function call resolution fails. 2481 template <typename... A> 2482 static void FixMisparsedFunctionReference( 2483 semantics::SemanticsContext &context, const std::variant<A...> &constU) { 2484 // The parse tree is updated in situ when resolving an ambiguous parse. 2485 using uType = std::decay_t<decltype(constU)>; 2486 auto &u{const_cast<uType &>(constU)}; 2487 if (auto *func{ 2488 std::get_if<common::Indirection<parser::FunctionReference>>(&u)}) { 2489 parser::FunctionReference &funcRef{func->value()}; 2490 auto &proc{std::get<parser::ProcedureDesignator>(funcRef.v.t)}; 2491 if (Symbol * 2492 origSymbol{ 2493 std::visit(common::visitors{ 2494 [&](parser::Name &name) { return name.symbol; }, 2495 [&](parser::ProcComponentRef &pcr) { 2496 return pcr.v.thing.component.symbol; 2497 }, 2498 }, 2499 proc.u)}) { 2500 Symbol &symbol{origSymbol->GetUltimate()}; 2501 if (symbol.has<semantics::ObjectEntityDetails>() || 2502 symbol.has<semantics::AssocEntityDetails>()) { 2503 // Note that expression in AssocEntityDetails cannot be a procedure 2504 // pointer as per C1105 so this cannot be a function reference. 2505 if constexpr (common::HasMember<common::Indirection<parser::Designator>, 2506 uType>) { 2507 CheckFuncRefToArrayElementRefHasSubscripts(context, funcRef); 2508 u = common::Indirection{funcRef.ConvertToArrayElementRef()}; 2509 } else { 2510 DIE("can't fix misparsed function as array reference"); 2511 } 2512 } 2513 } 2514 } 2515 } 2516 2517 // Common handling of parse tree node types that retain the 2518 // representation of the analyzed expression. 2519 template <typename PARSED> 2520 MaybeExpr ExpressionAnalyzer::ExprOrVariable(const PARSED &x) { 2521 if (x.typedExpr) { 2522 return x.typedExpr->v; 2523 } 2524 if constexpr (std::is_same_v<PARSED, parser::Expr> || 2525 std::is_same_v<PARSED, parser::Variable>) { 2526 FixMisparsedFunctionReference(context_, x.u); 2527 } 2528 if (AssumedTypeDummy(x)) { // C710 2529 Say("TYPE(*) dummy argument may only be used as an actual argument"_err_en_US); 2530 } else if (MaybeExpr result{evaluate::Fold(foldingContext_, Analyze(x.u))}) { 2531 SetExpr(x, std::move(*result)); 2532 return x.typedExpr->v; 2533 } 2534 ResetExpr(x); 2535 if (!context_.AnyFatalError()) { 2536 std::string buf; 2537 llvm::raw_string_ostream dump{buf}; 2538 parser::DumpTree(dump, x); 2539 Say("Internal error: Expression analysis failed on: %s"_err_en_US, 2540 dump.str()); 2541 } 2542 fatalErrors_ = true; 2543 return std::nullopt; 2544 } 2545 2546 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr &expr) { 2547 auto restorer{GetContextualMessages().SetLocation(expr.source)}; 2548 return ExprOrVariable(expr); 2549 } 2550 2551 MaybeExpr ExpressionAnalyzer::Analyze(const parser::Variable &variable) { 2552 auto restorer{GetContextualMessages().SetLocation(variable.GetSource())}; 2553 return ExprOrVariable(variable); 2554 } 2555 2556 MaybeExpr ExpressionAnalyzer::Analyze(const parser::DataStmtConstant &x) { 2557 auto restorer{GetContextualMessages().SetLocation(x.source)}; 2558 return ExprOrVariable(x); 2559 } 2560 2561 Expr<SubscriptInteger> ExpressionAnalyzer::AnalyzeKindSelector( 2562 TypeCategory category, 2563 const std::optional<parser::KindSelector> &selector) { 2564 int defaultKind{GetDefaultKind(category)}; 2565 if (!selector) { 2566 return Expr<SubscriptInteger>{defaultKind}; 2567 } 2568 return std::visit( 2569 common::visitors{ 2570 [&](const parser::ScalarIntConstantExpr &x) { 2571 if (MaybeExpr kind{Analyze(x)}) { 2572 Expr<SomeType> folded{Fold(std::move(*kind))}; 2573 if (std::optional<std::int64_t> code{ToInt64(folded)}) { 2574 if (CheckIntrinsicKind(category, *code)) { 2575 return Expr<SubscriptInteger>{*code}; 2576 } 2577 } else if (auto *intExpr{UnwrapExpr<Expr<SomeInteger>>(folded)}) { 2578 return ConvertToType<SubscriptInteger>(std::move(*intExpr)); 2579 } 2580 } 2581 return Expr<SubscriptInteger>{defaultKind}; 2582 }, 2583 [&](const parser::KindSelector::StarSize &x) { 2584 std::intmax_t size = x.v; 2585 if (!CheckIntrinsicSize(category, size)) { 2586 size = defaultKind; 2587 } else if (category == TypeCategory::Complex) { 2588 size /= 2; 2589 } 2590 return Expr<SubscriptInteger>{size}; 2591 }, 2592 }, 2593 selector->u); 2594 } 2595 2596 int ExpressionAnalyzer::GetDefaultKind(common::TypeCategory category) { 2597 return context_.GetDefaultKind(category); 2598 } 2599 2600 DynamicType ExpressionAnalyzer::GetDefaultKindOfType( 2601 common::TypeCategory category) { 2602 return {category, GetDefaultKind(category)}; 2603 } 2604 2605 bool ExpressionAnalyzer::CheckIntrinsicKind( 2606 TypeCategory category, std::int64_t kind) { 2607 if (IsValidKindOfIntrinsicType(category, kind)) { // C712, C714, C715, C727 2608 return true; 2609 } else { 2610 Say("%s(KIND=%jd) is not a supported type"_err_en_US, 2611 ToUpperCase(EnumToString(category)), kind); 2612 return false; 2613 } 2614 } 2615 2616 bool ExpressionAnalyzer::CheckIntrinsicSize( 2617 TypeCategory category, std::int64_t size) { 2618 if (category == TypeCategory::Complex) { 2619 // COMPLEX*16 == COMPLEX(KIND=8) 2620 if (size % 2 == 0 && IsValidKindOfIntrinsicType(category, size / 2)) { 2621 return true; 2622 } 2623 } else if (IsValidKindOfIntrinsicType(category, size)) { 2624 return true; 2625 } 2626 Say("%s*%jd is not a supported type"_err_en_US, 2627 ToUpperCase(EnumToString(category)), size); 2628 return false; 2629 } 2630 2631 bool ExpressionAnalyzer::AddImpliedDo(parser::CharBlock name, int kind) { 2632 return impliedDos_.insert(std::make_pair(name, kind)).second; 2633 } 2634 2635 void ExpressionAnalyzer::RemoveImpliedDo(parser::CharBlock name) { 2636 auto iter{impliedDos_.find(name)}; 2637 if (iter != impliedDos_.end()) { 2638 impliedDos_.erase(iter); 2639 } 2640 } 2641 2642 std::optional<int> ExpressionAnalyzer::IsImpliedDo( 2643 parser::CharBlock name) const { 2644 auto iter{impliedDos_.find(name)}; 2645 if (iter != impliedDos_.cend()) { 2646 return {iter->second}; 2647 } else { 2648 return std::nullopt; 2649 } 2650 } 2651 2652 bool ExpressionAnalyzer::EnforceTypeConstraint(parser::CharBlock at, 2653 const MaybeExpr &result, TypeCategory category, bool defaultKind) { 2654 if (result) { 2655 if (auto type{result->GetType()}) { 2656 if (type->category() != category) { // C885 2657 Say(at, "Must have %s type, but is %s"_err_en_US, 2658 ToUpperCase(EnumToString(category)), 2659 ToUpperCase(type->AsFortran())); 2660 return false; 2661 } else if (defaultKind) { 2662 int kind{context_.GetDefaultKind(category)}; 2663 if (type->kind() != kind) { 2664 Say(at, "Must have default kind(%d) of %s type, but is %s"_err_en_US, 2665 kind, ToUpperCase(EnumToString(category)), 2666 ToUpperCase(type->AsFortran())); 2667 return false; 2668 } 2669 } 2670 } else { 2671 Say(at, "Must have %s type, but is typeless"_err_en_US, 2672 ToUpperCase(EnumToString(category))); 2673 return false; 2674 } 2675 } 2676 return true; 2677 } 2678 2679 MaybeExpr ExpressionAnalyzer::MakeFunctionRef(parser::CharBlock callSite, 2680 ProcedureDesignator &&proc, ActualArguments &&arguments) { 2681 if (const auto *intrinsic{std::get_if<SpecificIntrinsic>(&proc.u)}) { 2682 if (intrinsic->name == "null" && arguments.empty()) { 2683 return Expr<SomeType>{NullPointer{}}; 2684 } 2685 } 2686 if (const Symbol * symbol{proc.GetSymbol()}) { 2687 if (!ResolveForward(*symbol)) { 2688 return std::nullopt; 2689 } 2690 } 2691 if (auto chars{CheckCall(callSite, proc, arguments)}) { 2692 if (chars->functionResult) { 2693 const auto &result{*chars->functionResult}; 2694 if (result.IsProcedurePointer()) { 2695 return Expr<SomeType>{ 2696 ProcedureRef{std::move(proc), std::move(arguments)}}; 2697 } else { 2698 // Not a procedure pointer, so type and shape are known. 2699 return TypedWrapper<FunctionRef, ProcedureRef>( 2700 DEREF(result.GetTypeAndShape()).type(), 2701 ProcedureRef{std::move(proc), std::move(arguments)}); 2702 } 2703 } 2704 } 2705 return std::nullopt; 2706 } 2707 2708 MaybeExpr ExpressionAnalyzer::MakeFunctionRef( 2709 parser::CharBlock intrinsic, ActualArguments &&arguments) { 2710 if (std::optional<SpecificCall> specificCall{ 2711 context_.intrinsics().Probe(CallCharacteristics{intrinsic.ToString()}, 2712 arguments, context_.foldingContext())}) { 2713 return MakeFunctionRef(intrinsic, 2714 ProcedureDesignator{std::move(specificCall->specificIntrinsic)}, 2715 std::move(specificCall->arguments)); 2716 } else { 2717 return std::nullopt; 2718 } 2719 } 2720 2721 void ArgumentAnalyzer::Analyze(const parser::Variable &x) { 2722 source_.ExtendToCover(x.GetSource()); 2723 if (MaybeExpr expr{context_.Analyze(x)}) { 2724 if (!IsConstantExpr(*expr)) { 2725 actuals_.emplace_back(std::move(*expr)); 2726 return; 2727 } 2728 const Symbol *symbol{GetLastSymbol(*expr)}; 2729 if (!symbol) { 2730 context_.SayAt(x, "Assignment to constant '%s' is not allowed"_err_en_US, 2731 x.GetSource()); 2732 } else if (auto *subp{symbol->detailsIf<semantics::SubprogramDetails>()}) { 2733 auto *msg{context_.SayAt(x, 2734 "Assignment to subprogram '%s' is not allowed"_err_en_US, 2735 symbol->name())}; 2736 if (subp->isFunction()) { 2737 const auto &result{subp->result().name()}; 2738 msg->Attach(result, "Function result is '%s'"_err_en_US, result); 2739 } 2740 } else { 2741 context_.SayAt(x, "Assignment to constant '%s' is not allowed"_err_en_US, 2742 symbol->name()); 2743 } 2744 } 2745 fatalErrors_ = true; 2746 } 2747 2748 void ArgumentAnalyzer::Analyze( 2749 const parser::ActualArgSpec &arg, bool isSubroutine) { 2750 // TODO: Actual arguments that are procedures and procedure pointers need to 2751 // be detected and represented (they're not expressions). 2752 // TODO: C1534: Don't allow a "restricted" specific intrinsic to be passed. 2753 std::optional<ActualArgument> actual; 2754 bool isAltReturn{false}; 2755 std::visit(common::visitors{ 2756 [&](const common::Indirection<parser::Expr> &x) { 2757 // TODO: Distinguish & handle procedure name and 2758 // proc-component-ref 2759 actual = AnalyzeExpr(x.value()); 2760 }, 2761 [&](const parser::AltReturnSpec &) { 2762 if (!isSubroutine) { 2763 context_.Say( 2764 "alternate return specification may not appear on" 2765 " function reference"_err_en_US); 2766 } 2767 isAltReturn = true; 2768 }, 2769 [&](const parser::ActualArg::PercentRef &) { 2770 context_.Say("TODO: %REF() argument"_err_en_US); 2771 }, 2772 [&](const parser::ActualArg::PercentVal &) { 2773 context_.Say("TODO: %VAL() argument"_err_en_US); 2774 }, 2775 }, 2776 std::get<parser::ActualArg>(arg.t).u); 2777 if (actual) { 2778 if (const auto &argKW{std::get<std::optional<parser::Keyword>>(arg.t)}) { 2779 actual->set_keyword(argKW->v.source); 2780 } 2781 actuals_.emplace_back(std::move(*actual)); 2782 } else if (!isAltReturn) { 2783 fatalErrors_ = true; 2784 } 2785 } 2786 2787 bool ArgumentAnalyzer::IsIntrinsicRelational(RelationalOperator opr) const { 2788 CHECK(actuals_.size() == 2); 2789 return semantics::IsIntrinsicRelational( 2790 opr, *GetType(0), GetRank(0), *GetType(1), GetRank(1)); 2791 } 2792 2793 bool ArgumentAnalyzer::IsIntrinsicNumeric(NumericOperator opr) const { 2794 std::optional<DynamicType> type0{GetType(0)}; 2795 if (actuals_.size() == 1) { 2796 if (IsBOZLiteral(0)) { 2797 return opr == NumericOperator::Add; 2798 } else { 2799 return type0 && semantics::IsIntrinsicNumeric(*type0); 2800 } 2801 } else { 2802 std::optional<DynamicType> type1{GetType(1)}; 2803 if (IsBOZLiteral(0) && type1) { 2804 auto cat1{type1->category()}; 2805 return cat1 == TypeCategory::Integer || cat1 == TypeCategory::Real; 2806 } else if (IsBOZLiteral(1) && type0) { // Integer/Real opr BOZ 2807 auto cat0{type0->category()}; 2808 return cat0 == TypeCategory::Integer || cat0 == TypeCategory::Real; 2809 } else { 2810 return type0 && type1 && 2811 semantics::IsIntrinsicNumeric(*type0, GetRank(0), *type1, GetRank(1)); 2812 } 2813 } 2814 } 2815 2816 bool ArgumentAnalyzer::IsIntrinsicLogical() const { 2817 if (actuals_.size() == 1) { 2818 return semantics::IsIntrinsicLogical(*GetType(0)); 2819 return GetType(0)->category() == TypeCategory::Logical; 2820 } else { 2821 return semantics::IsIntrinsicLogical( 2822 *GetType(0), GetRank(0), *GetType(1), GetRank(1)); 2823 } 2824 } 2825 2826 bool ArgumentAnalyzer::IsIntrinsicConcat() const { 2827 return semantics::IsIntrinsicConcat( 2828 *GetType(0), GetRank(0), *GetType(1), GetRank(1)); 2829 } 2830 2831 bool ArgumentAnalyzer::CheckConformance() const { 2832 if (actuals_.size() == 2) { 2833 const auto *lhs{actuals_.at(0).value().UnwrapExpr()}; 2834 const auto *rhs{actuals_.at(1).value().UnwrapExpr()}; 2835 if (lhs && rhs) { 2836 auto &foldingContext{context_.GetFoldingContext()}; 2837 auto lhShape{GetShape(foldingContext, *lhs)}; 2838 auto rhShape{GetShape(foldingContext, *rhs)}; 2839 if (lhShape && rhShape) { 2840 return evaluate::CheckConformance(foldingContext.messages(), *lhShape, 2841 *rhShape, "left operand", "right operand"); 2842 } 2843 } 2844 } 2845 return true; // no proven problem 2846 } 2847 2848 MaybeExpr ArgumentAnalyzer::TryDefinedOp( 2849 const char *opr, parser::MessageFixedText &&error, bool isUserOp) { 2850 if (AnyUntypedOperand()) { 2851 context_.Say( 2852 std::move(error), ToUpperCase(opr), TypeAsFortran(0), TypeAsFortran(1)); 2853 return std::nullopt; 2854 } 2855 { 2856 auto restorer{context_.GetContextualMessages().DiscardMessages()}; 2857 std::string oprNameString{ 2858 isUserOp ? std::string{opr} : "operator("s + opr + ')'}; 2859 parser::CharBlock oprName{oprNameString}; 2860 const auto &scope{context_.context().FindScope(source_)}; 2861 if (Symbol * symbol{scope.FindSymbol(oprName)}) { 2862 parser::Name name{symbol->name(), symbol}; 2863 if (auto result{context_.AnalyzeDefinedOp(name, GetActuals())}) { 2864 return result; 2865 } 2866 sawDefinedOp_ = symbol; 2867 } 2868 for (std::size_t passIndex{0}; passIndex < actuals_.size(); ++passIndex) { 2869 if (const Symbol * symbol{FindBoundOp(oprName, passIndex)}) { 2870 if (MaybeExpr result{TryBoundOp(*symbol, passIndex)}) { 2871 return result; 2872 } 2873 } 2874 } 2875 } 2876 if (sawDefinedOp_) { 2877 SayNoMatch(ToUpperCase(sawDefinedOp_->name().ToString())); 2878 } else if (actuals_.size() == 1 || AreConformable()) { 2879 context_.Say( 2880 std::move(error), ToUpperCase(opr), TypeAsFortran(0), TypeAsFortran(1)); 2881 } else { 2882 context_.Say( 2883 "Operands of %s are not conformable; have rank %d and rank %d"_err_en_US, 2884 ToUpperCase(opr), actuals_[0]->Rank(), actuals_[1]->Rank()); 2885 } 2886 return std::nullopt; 2887 } 2888 2889 MaybeExpr ArgumentAnalyzer::TryDefinedOp( 2890 std::vector<const char *> oprs, parser::MessageFixedText &&error) { 2891 for (std::size_t i{1}; i < oprs.size(); ++i) { 2892 auto restorer{context_.GetContextualMessages().DiscardMessages()}; 2893 if (auto result{TryDefinedOp(oprs[i], std::move(error))}) { 2894 return result; 2895 } 2896 } 2897 return TryDefinedOp(oprs[0], std::move(error)); 2898 } 2899 2900 MaybeExpr ArgumentAnalyzer::TryBoundOp(const Symbol &symbol, int passIndex) { 2901 ActualArguments localActuals{actuals_}; 2902 const Symbol *proc{GetBindingResolution(GetType(passIndex), symbol)}; 2903 if (!proc) { 2904 proc = &symbol; 2905 localActuals.at(passIndex).value().set_isPassedObject(); 2906 } 2907 CheckConformance(); 2908 return context_.MakeFunctionRef( 2909 source_, ProcedureDesignator{*proc}, std::move(localActuals)); 2910 } 2911 2912 std::optional<ProcedureRef> ArgumentAnalyzer::TryDefinedAssignment() { 2913 using semantics::Tristate; 2914 const Expr<SomeType> &lhs{GetExpr(0)}; 2915 const Expr<SomeType> &rhs{GetExpr(1)}; 2916 std::optional<DynamicType> lhsType{lhs.GetType()}; 2917 std::optional<DynamicType> rhsType{rhs.GetType()}; 2918 int lhsRank{lhs.Rank()}; 2919 int rhsRank{rhs.Rank()}; 2920 Tristate isDefined{ 2921 semantics::IsDefinedAssignment(lhsType, lhsRank, rhsType, rhsRank)}; 2922 if (isDefined == Tristate::No) { 2923 if (lhsType && rhsType) { 2924 AddAssignmentConversion(*lhsType, *rhsType); 2925 } 2926 return std::nullopt; // user-defined assignment not allowed for these args 2927 } 2928 auto restorer{context_.GetContextualMessages().SetLocation(source_)}; 2929 if (std::optional<ProcedureRef> procRef{GetDefinedAssignmentProc()}) { 2930 context_.CheckCall(source_, procRef->proc(), procRef->arguments()); 2931 return std::move(*procRef); 2932 } 2933 if (isDefined == Tristate::Yes) { 2934 if (!lhsType || !rhsType || (lhsRank != rhsRank && rhsRank != 0) || 2935 !OkLogicalIntegerAssignment(lhsType->category(), rhsType->category())) { 2936 SayNoMatch("ASSIGNMENT(=)", true); 2937 } 2938 } 2939 return std::nullopt; 2940 } 2941 2942 bool ArgumentAnalyzer::OkLogicalIntegerAssignment( 2943 TypeCategory lhs, TypeCategory rhs) { 2944 if (!context_.context().languageFeatures().IsEnabled( 2945 common::LanguageFeature::LogicalIntegerAssignment)) { 2946 return false; 2947 } 2948 std::optional<parser::MessageFixedText> msg; 2949 if (lhs == TypeCategory::Integer && rhs == TypeCategory::Logical) { 2950 // allow assignment to LOGICAL from INTEGER as a legacy extension 2951 msg = "nonstandard usage: assignment of LOGICAL to INTEGER"_en_US; 2952 } else if (lhs == TypeCategory::Logical && rhs == TypeCategory::Integer) { 2953 // ... and assignment to LOGICAL from INTEGER 2954 msg = "nonstandard usage: assignment of INTEGER to LOGICAL"_en_US; 2955 } else { 2956 return false; 2957 } 2958 if (context_.context().languageFeatures().ShouldWarn( 2959 common::LanguageFeature::LogicalIntegerAssignment)) { 2960 context_.Say(std::move(*msg)); 2961 } 2962 return true; 2963 } 2964 2965 std::optional<ProcedureRef> ArgumentAnalyzer::GetDefinedAssignmentProc() { 2966 auto restorer{context_.GetContextualMessages().DiscardMessages()}; 2967 std::string oprNameString{"assignment(=)"}; 2968 parser::CharBlock oprName{oprNameString}; 2969 const Symbol *proc{nullptr}; 2970 const auto &scope{context_.context().FindScope(source_)}; 2971 if (const Symbol * symbol{scope.FindSymbol(oprName)}) { 2972 ExpressionAnalyzer::AdjustActuals noAdjustment; 2973 if (const Symbol * 2974 specific{context_.ResolveGeneric(*symbol, actuals_, noAdjustment)}) { 2975 proc = specific; 2976 } else { 2977 context_.EmitGenericResolutionError(*symbol); 2978 } 2979 } 2980 int passedObjectIndex{-1}; 2981 for (std::size_t i{0}; i < actuals_.size(); ++i) { 2982 if (const Symbol * specific{FindBoundOp(oprName, i)}) { 2983 if (const Symbol * 2984 resolution{GetBindingResolution(GetType(i), *specific)}) { 2985 proc = resolution; 2986 } else { 2987 proc = specific; 2988 passedObjectIndex = i; 2989 } 2990 } 2991 } 2992 if (!proc) { 2993 return std::nullopt; 2994 } 2995 ActualArguments actualsCopy{actuals_}; 2996 if (passedObjectIndex >= 0) { 2997 actualsCopy[passedObjectIndex]->set_isPassedObject(); 2998 } 2999 return ProcedureRef{ProcedureDesignator{*proc}, std::move(actualsCopy)}; 3000 } 3001 3002 void ArgumentAnalyzer::Dump(llvm::raw_ostream &os) { 3003 os << "source_: " << source_.ToString() << " fatalErrors_ = " << fatalErrors_ 3004 << '\n'; 3005 for (const auto &actual : actuals_) { 3006 if (!actual.has_value()) { 3007 os << "- error\n"; 3008 } else if (const Symbol * symbol{actual->GetAssumedTypeDummy()}) { 3009 os << "- assumed type: " << symbol->name().ToString() << '\n'; 3010 } else if (const Expr<SomeType> *expr{actual->UnwrapExpr()}) { 3011 expr->AsFortran(os << "- expr: ") << '\n'; 3012 } else { 3013 DIE("bad ActualArgument"); 3014 } 3015 } 3016 } 3017 3018 std::optional<ActualArgument> ArgumentAnalyzer::AnalyzeExpr( 3019 const parser::Expr &expr) { 3020 source_.ExtendToCover(expr.source); 3021 if (const Symbol * assumedTypeDummy{AssumedTypeDummy(expr)}) { 3022 expr.typedExpr.Reset(new GenericExprWrapper{}, GenericExprWrapper::Deleter); 3023 if (isProcedureCall_) { 3024 return ActualArgument{ActualArgument::AssumedType{*assumedTypeDummy}}; 3025 } 3026 context_.SayAt(expr.source, 3027 "TYPE(*) dummy argument may only be used as an actual argument"_err_en_US); 3028 } else if (MaybeExpr argExpr{AnalyzeExprOrWholeAssumedSizeArray(expr)}) { 3029 if (isProcedureCall_ || !IsProcedure(*argExpr)) { 3030 return ActualArgument{context_.Fold(std::move(*argExpr))}; 3031 } 3032 context_.SayAt(expr.source, 3033 IsFunction(*argExpr) ? "Function call must have argument list"_err_en_US 3034 : "Subroutine name is not allowed here"_err_en_US); 3035 } 3036 return std::nullopt; 3037 } 3038 3039 MaybeExpr ArgumentAnalyzer::AnalyzeExprOrWholeAssumedSizeArray( 3040 const parser::Expr &expr) { 3041 // If an expression's parse tree is a whole assumed-size array: 3042 // Expr -> Designator -> DataRef -> Name 3043 // treat it as a special case for argument passing and bypass 3044 // the C1002/C1014 constraint checking in expression semantics. 3045 if (const auto *name{parser::Unwrap<parser::Name>(expr)}) { 3046 if (name->symbol && semantics::IsAssumedSizeArray(*name->symbol)) { 3047 auto restorer{context_.AllowWholeAssumedSizeArray()}; 3048 return context_.Analyze(expr); 3049 } 3050 } 3051 return context_.Analyze(expr); 3052 } 3053 3054 bool ArgumentAnalyzer::AreConformable() const { 3055 CHECK(!fatalErrors_ && actuals_.size() == 2); 3056 return evaluate::AreConformable(*actuals_[0], *actuals_[1]); 3057 } 3058 3059 // Look for a type-bound operator in the type of arg number passIndex. 3060 const Symbol *ArgumentAnalyzer::FindBoundOp( 3061 parser::CharBlock oprName, int passIndex) { 3062 const auto *type{GetDerivedTypeSpec(GetType(passIndex))}; 3063 if (!type || !type->scope()) { 3064 return nullptr; 3065 } 3066 const Symbol *symbol{type->scope()->FindComponent(oprName)}; 3067 if (!symbol) { 3068 return nullptr; 3069 } 3070 sawDefinedOp_ = symbol; 3071 ExpressionAnalyzer::AdjustActuals adjustment{ 3072 [&](const Symbol &proc, ActualArguments &) { 3073 return passIndex == GetPassIndex(proc); 3074 }}; 3075 const Symbol *result{context_.ResolveGeneric(*symbol, actuals_, adjustment)}; 3076 if (!result) { 3077 context_.EmitGenericResolutionError(*symbol); 3078 } 3079 return result; 3080 } 3081 3082 // If there is an implicit conversion between intrinsic types, make it explicit 3083 void ArgumentAnalyzer::AddAssignmentConversion( 3084 const DynamicType &lhsType, const DynamicType &rhsType) { 3085 if (lhsType.category() == rhsType.category() && 3086 lhsType.kind() == rhsType.kind()) { 3087 // no conversion necessary 3088 } else if (auto rhsExpr{evaluate::ConvertToType(lhsType, MoveExpr(1))}) { 3089 actuals_[1] = ActualArgument{*rhsExpr}; 3090 } else { 3091 actuals_[1] = std::nullopt; 3092 } 3093 } 3094 3095 std::optional<DynamicType> ArgumentAnalyzer::GetType(std::size_t i) const { 3096 return i < actuals_.size() ? actuals_[i].value().GetType() : std::nullopt; 3097 } 3098 int ArgumentAnalyzer::GetRank(std::size_t i) const { 3099 return i < actuals_.size() ? actuals_[i].value().Rank() : 0; 3100 } 3101 3102 // If the argument at index i is a BOZ literal, convert its type to match the 3103 // otherType. It it's REAL convert to REAL, otherwise convert to INTEGER. 3104 // Note that IBM supports comparing BOZ literals to CHARACTER operands. That 3105 // is not currently supported. 3106 void ArgumentAnalyzer::ConvertBOZ( 3107 std::size_t i, std::optional<DynamicType> otherType) { 3108 if (IsBOZLiteral(i)) { 3109 Expr<SomeType> &&argExpr{MoveExpr(i)}; 3110 auto *boz{std::get_if<BOZLiteralConstant>(&argExpr.u)}; 3111 if (otherType && otherType->category() == TypeCategory::Real) { 3112 MaybeExpr realExpr{ConvertToKind<TypeCategory::Real>( 3113 context_.context().GetDefaultKind(TypeCategory::Real), 3114 std::move(*boz))}; 3115 actuals_[i] = std::move(*realExpr); 3116 } else { 3117 MaybeExpr intExpr{ConvertToKind<TypeCategory::Integer>( 3118 context_.context().GetDefaultKind(TypeCategory::Integer), 3119 std::move(*boz))}; 3120 actuals_[i] = std::move(*intExpr); 3121 } 3122 } 3123 } 3124 3125 // Report error resolving opr when there is a user-defined one available 3126 void ArgumentAnalyzer::SayNoMatch(const std::string &opr, bool isAssignment) { 3127 std::string type0{TypeAsFortran(0)}; 3128 auto rank0{actuals_[0]->Rank()}; 3129 if (actuals_.size() == 1) { 3130 if (rank0 > 0) { 3131 context_.Say("No intrinsic or user-defined %s matches " 3132 "rank %d array of %s"_err_en_US, 3133 opr, rank0, type0); 3134 } else { 3135 context_.Say("No intrinsic or user-defined %s matches " 3136 "operand type %s"_err_en_US, 3137 opr, type0); 3138 } 3139 } else { 3140 std::string type1{TypeAsFortran(1)}; 3141 auto rank1{actuals_[1]->Rank()}; 3142 if (rank0 > 0 && rank1 > 0 && rank0 != rank1) { 3143 context_.Say("No intrinsic or user-defined %s matches " 3144 "rank %d array of %s and rank %d array of %s"_err_en_US, 3145 opr, rank0, type0, rank1, type1); 3146 } else if (isAssignment && rank0 != rank1) { 3147 if (rank0 == 0) { 3148 context_.Say("No intrinsic or user-defined %s matches " 3149 "scalar %s and rank %d array of %s"_err_en_US, 3150 opr, type0, rank1, type1); 3151 } else { 3152 context_.Say("No intrinsic or user-defined %s matches " 3153 "rank %d array of %s and scalar %s"_err_en_US, 3154 opr, rank0, type0, type1); 3155 } 3156 } else { 3157 context_.Say("No intrinsic or user-defined %s matches " 3158 "operand types %s and %s"_err_en_US, 3159 opr, type0, type1); 3160 } 3161 } 3162 } 3163 3164 std::string ArgumentAnalyzer::TypeAsFortran(std::size_t i) { 3165 if (std::optional<DynamicType> type{GetType(i)}) { 3166 return type->category() == TypeCategory::Derived 3167 ? "TYPE("s + type->AsFortran() + ')' 3168 : type->category() == TypeCategory::Character 3169 ? "CHARACTER(KIND="s + std::to_string(type->kind()) + ')' 3170 : ToUpperCase(type->AsFortran()); 3171 } else { 3172 return "untyped"; 3173 } 3174 } 3175 3176 bool ArgumentAnalyzer::AnyUntypedOperand() { 3177 for (const auto &actual : actuals_) { 3178 if (!actual.value().GetType()) { 3179 return true; 3180 } 3181 } 3182 return false; 3183 } 3184 3185 } // namespace Fortran::evaluate 3186 3187 namespace Fortran::semantics { 3188 evaluate::Expr<evaluate::SubscriptInteger> AnalyzeKindSelector( 3189 SemanticsContext &context, common::TypeCategory category, 3190 const std::optional<parser::KindSelector> &selector) { 3191 evaluate::ExpressionAnalyzer analyzer{context}; 3192 auto restorer{ 3193 analyzer.GetContextualMessages().SetLocation(context.location().value())}; 3194 return analyzer.AnalyzeKindSelector(category, selector); 3195 } 3196 3197 void AnalyzeCallStmt(SemanticsContext &context, const parser::CallStmt &call) { 3198 evaluate::ExpressionAnalyzer{context}.Analyze(call); 3199 } 3200 3201 const evaluate::Assignment *AnalyzeAssignmentStmt( 3202 SemanticsContext &context, const parser::AssignmentStmt &stmt) { 3203 return evaluate::ExpressionAnalyzer{context}.Analyze(stmt); 3204 } 3205 const evaluate::Assignment *AnalyzePointerAssignmentStmt( 3206 SemanticsContext &context, const parser::PointerAssignmentStmt &stmt) { 3207 return evaluate::ExpressionAnalyzer{context}.Analyze(stmt); 3208 } 3209 3210 ExprChecker::ExprChecker(SemanticsContext &context) : context_{context} {} 3211 3212 bool ExprChecker::Pre(const parser::DataImpliedDo &ido) { 3213 parser::Walk(std::get<parser::DataImpliedDo::Bounds>(ido.t), *this); 3214 const auto &bounds{std::get<parser::DataImpliedDo::Bounds>(ido.t)}; 3215 auto name{bounds.name.thing.thing}; 3216 int kind{evaluate::ResultType<evaluate::ImpliedDoIndex>::kind}; 3217 if (const auto dynamicType{evaluate::DynamicType::From(*name.symbol)}) { 3218 if (dynamicType->category() == TypeCategory::Integer) { 3219 kind = dynamicType->kind(); 3220 } 3221 } 3222 exprAnalyzer_.AddImpliedDo(name.source, kind); 3223 parser::Walk(std::get<std::list<parser::DataIDoObject>>(ido.t), *this); 3224 exprAnalyzer_.RemoveImpliedDo(name.source); 3225 return false; 3226 } 3227 3228 bool ExprChecker::Walk(const parser::Program &program) { 3229 parser::Walk(program, *this); 3230 return !context_.AnyFatalError(); 3231 } 3232 } // namespace Fortran::semantics 3233