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