1 //===-- lib/Evaluate/check-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/Evaluate/check-expression.h" 10 #include "flang/Evaluate/characteristics.h" 11 #include "flang/Evaluate/intrinsics.h" 12 #include "flang/Evaluate/tools.h" 13 #include "flang/Evaluate/traverse.h" 14 #include "flang/Evaluate/type.h" 15 #include "flang/Semantics/semantics.h" 16 #include "flang/Semantics/symbol.h" 17 #include "flang/Semantics/tools.h" 18 #include <set> 19 #include <string> 20 21 namespace Fortran::evaluate { 22 23 // Constant expression predicates IsConstantExpr() & IsScopeInvariantExpr(). 24 // This code determines whether an expression is a "constant expression" 25 // in the sense of section 10.1.12. This is not the same thing as being 26 // able to fold it (yet) into a known constant value; specifically, 27 // the expression may reference derived type kind parameters whose values 28 // are not yet known. 29 // 30 // The variant form (IsScopeInvariantExpr()) also accepts symbols that are 31 // INTENT(IN) dummy arguments without the VALUE attribute. 32 template <bool INVARIANT> 33 class IsConstantExprHelper 34 : public AllTraverse<IsConstantExprHelper<INVARIANT>, true> { 35 public: 36 using Base = AllTraverse<IsConstantExprHelper, true>; 37 IsConstantExprHelper() : Base{*this} {} 38 using Base::operator(); 39 40 // A missing expression is not considered to be constant. 41 template <typename A> bool operator()(const std::optional<A> &x) const { 42 return x && (*this)(*x); 43 } 44 45 bool operator()(const TypeParamInquiry &inq) const { 46 return INVARIANT || semantics::IsKindTypeParameter(inq.parameter()); 47 } 48 bool operator()(const semantics::Symbol &symbol) const { 49 const auto &ultimate{GetAssociationRoot(symbol)}; 50 return IsNamedConstant(ultimate) || IsImpliedDoIndex(ultimate) || 51 IsInitialProcedureTarget(ultimate) || 52 ultimate.has<semantics::TypeParamDetails>() || 53 (INVARIANT && IsIntentIn(symbol) && !IsOptional(symbol) && 54 !symbol.attrs().test(semantics::Attr::VALUE)); 55 } 56 bool operator()(const CoarrayRef &) const { return false; } 57 bool operator()(const semantics::ParamValue ¶m) const { 58 return param.isExplicit() && (*this)(param.GetExplicit()); 59 } 60 bool operator()(const ProcedureRef &) const; 61 bool operator()(const StructureConstructor &constructor) const { 62 for (const auto &[symRef, expr] : constructor) { 63 if (!IsConstantStructureConstructorComponent(*symRef, expr.value())) { 64 return false; 65 } 66 } 67 return true; 68 } 69 bool operator()(const Component &component) const { 70 return (*this)(component.base()); 71 } 72 // Forbid integer division by zero in constants. 73 template <int KIND> 74 bool operator()( 75 const Divide<Type<TypeCategory::Integer, KIND>> &division) const { 76 using T = Type<TypeCategory::Integer, KIND>; 77 if (const auto divisor{GetScalarConstantValue<T>(division.right())}) { 78 return !divisor->IsZero() && (*this)(division.left()); 79 } else { 80 return false; 81 } 82 } 83 84 bool operator()(const Constant<SomeDerived> &) const { return true; } 85 bool operator()(const DescriptorInquiry &x) const { 86 const Symbol &sym{x.base().GetLastSymbol()}; 87 return INVARIANT && !IsAllocatable(sym) && 88 (!IsDummy(sym) || 89 (IsIntentIn(sym) && !IsOptional(sym) && 90 !sym.attrs().test(semantics::Attr::VALUE))); 91 } 92 93 private: 94 bool IsConstantStructureConstructorComponent( 95 const Symbol &, const Expr<SomeType> &) const; 96 bool IsConstantExprShape(const Shape &) const; 97 }; 98 99 template <bool INVARIANT> 100 bool IsConstantExprHelper<INVARIANT>::IsConstantStructureConstructorComponent( 101 const Symbol &component, const Expr<SomeType> &expr) const { 102 if (IsAllocatable(component)) { 103 return IsNullObjectPointer(expr); 104 } else if (IsPointer(component)) { 105 return IsNullPointer(expr) || IsInitialDataTarget(expr) || 106 IsInitialProcedureTarget(expr); 107 } else { 108 return (*this)(expr); 109 } 110 } 111 112 template <bool INVARIANT> 113 bool IsConstantExprHelper<INVARIANT>::operator()( 114 const ProcedureRef &call) const { 115 // LBOUND, UBOUND, and SIZE with truly constant DIM= arguments will have 116 // been rewritten into DescriptorInquiry operations. 117 if (const auto *intrinsic{std::get_if<SpecificIntrinsic>(&call.proc().u)}) { 118 const characteristics::Procedure &proc{intrinsic->characteristics.value()}; 119 if (intrinsic->name == "kind" || 120 intrinsic->name == IntrinsicProcTable::InvalidName || 121 call.arguments().empty() || !call.arguments()[0]) { 122 // kind is always a constant, and we avoid cascading errors by considering 123 // invalid calls to intrinsics to be constant 124 return true; 125 } else if (intrinsic->name == "lbound") { 126 auto base{ExtractNamedEntity(call.arguments()[0]->UnwrapExpr())}; 127 return base && IsConstantExprShape(GetLBOUNDs(*base)); 128 } else if (intrinsic->name == "ubound") { 129 auto base{ExtractNamedEntity(call.arguments()[0]->UnwrapExpr())}; 130 return base && IsConstantExprShape(GetUBOUNDs(*base)); 131 } else if (intrinsic->name == "shape" || intrinsic->name == "size") { 132 auto shape{GetShape(call.arguments()[0]->UnwrapExpr())}; 133 return shape && IsConstantExprShape(*shape); 134 } else if (proc.IsPure()) { 135 for (const auto &arg : call.arguments()) { 136 if (!arg) { 137 return false; 138 } else if (const auto *expr{arg->UnwrapExpr()}; 139 !expr || !(*this)(*expr)) { 140 return false; 141 } 142 } 143 return true; 144 } 145 // TODO: STORAGE_SIZE 146 } 147 return false; 148 } 149 150 template <bool INVARIANT> 151 bool IsConstantExprHelper<INVARIANT>::IsConstantExprShape( 152 const Shape &shape) const { 153 for (const auto &extent : shape) { 154 if (!(*this)(extent)) { 155 return false; 156 } 157 } 158 return true; 159 } 160 161 template <typename A> bool IsConstantExpr(const A &x) { 162 return IsConstantExprHelper<false>{}(x); 163 } 164 template bool IsConstantExpr(const Expr<SomeType> &); 165 template bool IsConstantExpr(const Expr<SomeInteger> &); 166 template bool IsConstantExpr(const Expr<SubscriptInteger> &); 167 template bool IsConstantExpr(const StructureConstructor &); 168 169 // IsScopeInvariantExpr() 170 template <typename A> bool IsScopeInvariantExpr(const A &x) { 171 return IsConstantExprHelper<true>{}(x); 172 } 173 template bool IsScopeInvariantExpr(const Expr<SomeType> &); 174 template bool IsScopeInvariantExpr(const Expr<SomeInteger> &); 175 template bool IsScopeInvariantExpr(const Expr<SubscriptInteger> &); 176 177 // IsActuallyConstant() 178 struct IsActuallyConstantHelper { 179 template <typename A> bool operator()(const A &) { return false; } 180 template <typename T> bool operator()(const Constant<T> &) { return true; } 181 template <typename T> bool operator()(const Parentheses<T> &x) { 182 return (*this)(x.left()); 183 } 184 template <typename T> bool operator()(const Expr<T> &x) { 185 return common::visit([=](const auto &y) { return (*this)(y); }, x.u); 186 } 187 bool operator()(const Expr<SomeType> &x) { 188 return common::visit([this](const auto &y) { return (*this)(y); }, x.u); 189 } 190 bool operator()(const StructureConstructor &x) { 191 for (const auto &pair : x) { 192 const Expr<SomeType> &y{pair.second.value()}; 193 const auto sym{pair.first}; 194 const bool compIsConstant{(*this)(y)}; 195 // If an allocatable component is initialized by a constant, 196 // the structure constructor is not a constant. 197 if ((!compIsConstant && !IsNullPointer(y)) || 198 (compIsConstant && IsAllocatable(sym))) { 199 return false; 200 } 201 } 202 return true; 203 } 204 template <typename A> bool operator()(const A *x) { return x && (*this)(*x); } 205 template <typename A> bool operator()(const std::optional<A> &x) { 206 return x && (*this)(*x); 207 } 208 }; 209 210 template <typename A> bool IsActuallyConstant(const A &x) { 211 return IsActuallyConstantHelper{}(x); 212 } 213 214 template bool IsActuallyConstant(const Expr<SomeType> &); 215 template bool IsActuallyConstant(const Expr<SomeInteger> &); 216 template bool IsActuallyConstant(const Expr<SubscriptInteger> &); 217 template bool IsActuallyConstant(const std::optional<Expr<SubscriptInteger>> &); 218 219 // Object pointer initialization checking predicate IsInitialDataTarget(). 220 // This code determines whether an expression is allowable as the static 221 // data address used to initialize a pointer with "=> x". See C765. 222 class IsInitialDataTargetHelper 223 : public AllTraverse<IsInitialDataTargetHelper, true> { 224 public: 225 using Base = AllTraverse<IsInitialDataTargetHelper, true>; 226 using Base::operator(); 227 explicit IsInitialDataTargetHelper(parser::ContextualMessages *m) 228 : Base{*this}, messages_{m} {} 229 230 bool emittedMessage() const { return emittedMessage_; } 231 232 bool operator()(const BOZLiteralConstant &) const { return false; } 233 bool operator()(const NullPointer &) const { return true; } 234 template <typename T> bool operator()(const Constant<T> &) const { 235 return false; 236 } 237 bool operator()(const semantics::Symbol &symbol) { 238 // This function checks only base symbols, not components. 239 const Symbol &ultimate{symbol.GetUltimate()}; 240 if (const auto *assoc{ 241 ultimate.detailsIf<semantics::AssocEntityDetails>()}) { 242 if (const auto &expr{assoc->expr()}) { 243 if (IsVariable(*expr)) { 244 return (*this)(*expr); 245 } else if (messages_) { 246 messages_->Say( 247 "An initial data target may not be an associated expression ('%s')"_err_en_US, 248 ultimate.name()); 249 emittedMessage_ = true; 250 } 251 } 252 return false; 253 } else if (!CheckVarOrComponent(ultimate)) { 254 return false; 255 } else if (!ultimate.attrs().test(semantics::Attr::TARGET)) { 256 if (messages_) { 257 messages_->Say( 258 "An initial data target may not be a reference to an object '%s' that lacks the TARGET attribute"_err_en_US, 259 ultimate.name()); 260 emittedMessage_ = true; 261 } 262 return false; 263 } else if (!IsSaved(ultimate)) { 264 if (messages_) { 265 messages_->Say( 266 "An initial data target may not be a reference to an object '%s' that lacks the SAVE attribute"_err_en_US, 267 ultimate.name()); 268 emittedMessage_ = true; 269 } 270 return false; 271 } else { 272 return true; 273 } 274 } 275 bool operator()(const StaticDataObject &) const { return false; } 276 bool operator()(const TypeParamInquiry &) const { return false; } 277 bool operator()(const Triplet &x) const { 278 return IsConstantExpr(x.lower()) && IsConstantExpr(x.upper()) && 279 IsConstantExpr(x.stride()); 280 } 281 bool operator()(const Subscript &x) const { 282 return common::visit(common::visitors{ 283 [&](const Triplet &t) { return (*this)(t); }, 284 [&](const auto &y) { 285 return y.value().Rank() == 0 && 286 IsConstantExpr(y.value()); 287 }, 288 }, 289 x.u); 290 } 291 bool operator()(const CoarrayRef &) const { return false; } 292 bool operator()(const Component &x) { 293 return CheckVarOrComponent(x.GetLastSymbol()) && (*this)(x.base()); 294 } 295 bool operator()(const Substring &x) const { 296 return IsConstantExpr(x.lower()) && IsConstantExpr(x.upper()) && 297 (*this)(x.parent()); 298 } 299 bool operator()(const DescriptorInquiry &) const { return false; } 300 template <typename T> bool operator()(const ArrayConstructor<T> &) const { 301 return false; 302 } 303 bool operator()(const StructureConstructor &) const { return false; } 304 template <typename D, typename R, typename... O> 305 bool operator()(const Operation<D, R, O...> &) const { 306 return false; 307 } 308 template <typename T> bool operator()(const Parentheses<T> &x) const { 309 return (*this)(x.left()); 310 } 311 bool operator()(const ProcedureRef &x) const { 312 if (const SpecificIntrinsic * intrinsic{x.proc().GetSpecificIntrinsic()}) { 313 return intrinsic->characteristics.value().attrs.test( 314 characteristics::Procedure::Attr::NullPointer); 315 } 316 return false; 317 } 318 bool operator()(const Relational<SomeType> &) const { return false; } 319 320 private: 321 bool CheckVarOrComponent(const semantics::Symbol &symbol) { 322 const Symbol &ultimate{symbol.GetUltimate()}; 323 const char *unacceptable{nullptr}; 324 if (ultimate.Corank() > 0) { 325 unacceptable = "a coarray"; 326 } else if (IsAllocatable(ultimate)) { 327 unacceptable = "an ALLOCATABLE"; 328 } else if (IsPointer(ultimate)) { 329 unacceptable = "a POINTER"; 330 } else { 331 return true; 332 } 333 if (messages_) { 334 messages_->Say( 335 "An initial data target may not be a reference to %s '%s'"_err_en_US, 336 unacceptable, ultimate.name()); 337 emittedMessage_ = true; 338 } 339 return false; 340 } 341 342 parser::ContextualMessages *messages_; 343 bool emittedMessage_{false}; 344 }; 345 346 bool IsInitialDataTarget( 347 const Expr<SomeType> &x, parser::ContextualMessages *messages) { 348 IsInitialDataTargetHelper helper{messages}; 349 bool result{helper(x)}; 350 if (!result && messages && !helper.emittedMessage()) { 351 messages->Say( 352 "An initial data target must be a designator with constant subscripts"_err_en_US); 353 } 354 return result; 355 } 356 357 bool IsInitialProcedureTarget(const semantics::Symbol &symbol) { 358 const auto &ultimate{symbol.GetUltimate()}; 359 return common::visit( 360 common::visitors{ 361 [&](const semantics::SubprogramDetails &subp) { 362 return !subp.isDummy() && !subp.stmtFunction() && 363 symbol.owner().kind() != semantics::Scope::Kind::MainProgram && 364 symbol.owner().kind() != semantics::Scope::Kind::Subprogram; 365 }, 366 [](const semantics::SubprogramNameDetails &x) { 367 return x.kind() != semantics::SubprogramKind::Internal; 368 }, 369 [&](const semantics::ProcEntityDetails &proc) { 370 return !semantics::IsPointer(ultimate) && !proc.isDummy(); 371 }, 372 [](const auto &) { return false; }, 373 }, 374 ultimate.details()); 375 } 376 377 bool IsInitialProcedureTarget(const ProcedureDesignator &proc) { 378 if (const auto *intrin{proc.GetSpecificIntrinsic()}) { 379 return !intrin->isRestrictedSpecific; 380 } else if (proc.GetComponent()) { 381 return false; 382 } else { 383 return IsInitialProcedureTarget(DEREF(proc.GetSymbol())); 384 } 385 } 386 387 bool IsInitialProcedureTarget(const Expr<SomeType> &expr) { 388 if (const auto *proc{std::get_if<ProcedureDesignator>(&expr.u)}) { 389 return IsInitialProcedureTarget(*proc); 390 } else { 391 return IsNullProcedurePointer(expr); 392 } 393 } 394 395 // Converts, folds, and then checks type, rank, and shape of an 396 // initialization expression for a named constant, a non-pointer 397 // variable static initialization, a component default initializer, 398 // a type parameter default value, or instantiated type parameter value. 399 std::optional<Expr<SomeType>> NonPointerInitializationExpr(const Symbol &symbol, 400 Expr<SomeType> &&x, FoldingContext &context, 401 const semantics::Scope *instantiation) { 402 CHECK(!IsPointer(symbol)); 403 if (auto symTS{ 404 characteristics::TypeAndShape::Characterize(symbol, context)}) { 405 auto xType{x.GetType()}; 406 auto converted{ConvertToType(symTS->type(), Expr<SomeType>{x})}; 407 if (!converted && 408 symbol.owner().context().IsEnabled( 409 common::LanguageFeature::LogicalIntegerAssignment)) { 410 converted = DataConstantConversionExtension(context, symTS->type(), x); 411 if (converted && 412 symbol.owner().context().ShouldWarn( 413 common::LanguageFeature::LogicalIntegerAssignment)) { 414 context.messages().Say( 415 common::LanguageFeature::LogicalIntegerAssignment, 416 "nonstandard usage: initialization of %s with %s"_port_en_US, 417 symTS->type().AsFortran(), x.GetType().value().AsFortran()); 418 } 419 } 420 if (converted) { 421 auto folded{Fold(context, std::move(*converted))}; 422 if (IsActuallyConstant(folded)) { 423 int symRank{symTS->Rank()}; 424 if (IsImpliedShape(symbol)) { 425 if (folded.Rank() == symRank) { 426 return ArrayConstantBoundChanger{ 427 std::move(*AsConstantExtents( 428 context, GetRawLowerBounds(context, NamedEntity{symbol})))} 429 .ChangeLbounds(std::move(folded)); 430 } else { 431 context.messages().Say( 432 "Implied-shape parameter '%s' has rank %d but its initializer has rank %d"_err_en_US, 433 symbol.name(), symRank, folded.Rank()); 434 } 435 } else if (auto extents{AsConstantExtents(context, symTS->shape())}) { 436 if (folded.Rank() == 0 && symRank == 0) { 437 // symbol and constant are both scalars 438 return {std::move(folded)}; 439 } else if (folded.Rank() == 0 && symRank > 0) { 440 // expand the scalar constant to an array 441 return ScalarConstantExpander{std::move(*extents), 442 AsConstantExtents( 443 context, GetRawLowerBounds(context, NamedEntity{symbol}))} 444 .Expand(std::move(folded)); 445 } else if (auto resultShape{GetShape(context, folded)}) { 446 CHECK(symTS->shape()); // Assumed-ranks cannot be initialized. 447 if (CheckConformance(context.messages(), *symTS->shape(), 448 *resultShape, CheckConformanceFlags::None, 449 "initialized object", "initialization expression") 450 .value_or(false /*fail if not known now to conform*/)) { 451 // make a constant array with adjusted lower bounds 452 return ArrayConstantBoundChanger{ 453 std::move(*AsConstantExtents(context, 454 GetRawLowerBounds(context, NamedEntity{symbol})))} 455 .ChangeLbounds(std::move(folded)); 456 } 457 } 458 } else if (IsNamedConstant(symbol)) { 459 if (IsExplicitShape(symbol)) { 460 context.messages().Say( 461 "Named constant '%s' array must have constant shape"_err_en_US, 462 symbol.name()); 463 } else { 464 // Declaration checking handles other cases 465 } 466 } else { 467 context.messages().Say( 468 "Shape of initialized object '%s' must be constant"_err_en_US, 469 symbol.name()); 470 } 471 } else if (IsErrorExpr(folded)) { 472 } else if (IsLenTypeParameter(symbol)) { 473 return {std::move(folded)}; 474 } else if (IsKindTypeParameter(symbol)) { 475 if (instantiation) { 476 context.messages().Say( 477 "Value of kind type parameter '%s' (%s) must be a scalar INTEGER constant"_err_en_US, 478 symbol.name(), folded.AsFortran()); 479 } else { 480 return {std::move(folded)}; 481 } 482 } else if (IsNamedConstant(symbol)) { 483 if (symbol.name() == "numeric_storage_size" && 484 symbol.owner().IsModule() && 485 DEREF(symbol.owner().symbol()).name() == "iso_fortran_env") { 486 // Very special case: numeric_storage_size is not folded until 487 // it read from the iso_fortran_env module file, as its value 488 // depends on compilation options. 489 return {std::move(folded)}; 490 } 491 context.messages().Say( 492 "Value of named constant '%s' (%s) cannot be computed as a constant value"_err_en_US, 493 symbol.name(), folded.AsFortran()); 494 } else { 495 context.messages().Say( 496 "Initialization expression for '%s' (%s) cannot be computed as a constant value"_err_en_US, 497 symbol.name(), x.AsFortran()); 498 } 499 } else if (xType) { 500 context.messages().Say( 501 "Initialization expression cannot be converted to declared type of '%s' from %s"_err_en_US, 502 symbol.name(), xType->AsFortran()); 503 } else { 504 context.messages().Say( 505 "Initialization expression cannot be converted to declared type of '%s'"_err_en_US, 506 symbol.name()); 507 } 508 } 509 return std::nullopt; 510 } 511 512 // Specification expression validation (10.1.11(2), C1010) 513 class CheckSpecificationExprHelper 514 : public AnyTraverse<CheckSpecificationExprHelper, 515 std::optional<std::string>> { 516 public: 517 using Result = std::optional<std::string>; 518 using Base = AnyTraverse<CheckSpecificationExprHelper, Result>; 519 explicit CheckSpecificationExprHelper(const semantics::Scope &s, 520 FoldingContext &context, bool forElementalFunctionResult) 521 : Base{*this}, scope_{s}, context_{context}, 522 forElementalFunctionResult_{forElementalFunctionResult} {} 523 using Base::operator(); 524 525 Result operator()(const CoarrayRef &) const { return "coindexed reference"; } 526 527 Result operator()(const semantics::Symbol &symbol) const { 528 const auto &ultimate{symbol.GetUltimate()}; 529 const auto *object{ultimate.detailsIf<semantics::ObjectEntityDetails>()}; 530 bool isInitialized{semantics::IsSaved(ultimate) && 531 !IsAllocatable(ultimate) && object && 532 (ultimate.test(Symbol::Flag::InDataStmt) || 533 object->init().has_value())}; 534 if (const auto *assoc{ 535 ultimate.detailsIf<semantics::AssocEntityDetails>()}) { 536 return (*this)(assoc->expr()); 537 } else if (semantics::IsNamedConstant(ultimate) || 538 ultimate.owner().IsModule() || ultimate.owner().IsSubmodule()) { 539 return std::nullopt; 540 } else if (scope_.IsDerivedType() && 541 IsVariableName(ultimate)) { // C750, C754 542 return "derived type component or type parameter value not allowed to " 543 "reference variable '"s + 544 ultimate.name().ToString() + "'"; 545 } else if (IsDummy(ultimate)) { 546 if (!inInquiry_ && forElementalFunctionResult_) { 547 return "dependence on value of dummy argument '"s + 548 ultimate.name().ToString() + "'"; 549 } else if (ultimate.attrs().test(semantics::Attr::OPTIONAL)) { 550 return "reference to OPTIONAL dummy argument '"s + 551 ultimate.name().ToString() + "'"; 552 } else if (!inInquiry_ && 553 ultimate.attrs().test(semantics::Attr::INTENT_OUT)) { 554 return "reference to INTENT(OUT) dummy argument '"s + 555 ultimate.name().ToString() + "'"; 556 } else if (ultimate.has<semantics::ObjectEntityDetails>()) { 557 return std::nullopt; 558 } else { 559 return "dummy procedure argument"; 560 } 561 } else if (&symbol.owner() != &scope_ || &ultimate.owner() != &scope_) { 562 return std::nullopt; // host association is in play 563 } else if (isInitialized && 564 context_.languageFeatures().IsEnabled( 565 common::LanguageFeature::SavedLocalInSpecExpr)) { 566 if (!scope_.IsModuleFile() && 567 context_.languageFeatures().ShouldWarn( 568 common::LanguageFeature::SavedLocalInSpecExpr)) { 569 context_.messages().Say(common::LanguageFeature::SavedLocalInSpecExpr, 570 "specification expression refers to local object '%s' (initialized and saved)"_port_en_US, 571 ultimate.name().ToString()); 572 } 573 return std::nullopt; 574 } else if (const auto *object{ 575 ultimate.detailsIf<semantics::ObjectEntityDetails>()}) { 576 if (object->commonBlock()) { 577 return std::nullopt; 578 } 579 } 580 if (inInquiry_) { 581 return std::nullopt; 582 } else { 583 return "reference to local entity '"s + ultimate.name().ToString() + "'"; 584 } 585 } 586 587 Result operator()(const Component &x) const { 588 // Don't look at the component symbol. 589 return (*this)(x.base()); 590 } 591 Result operator()(const ArrayRef &x) const { 592 if (auto result{(*this)(x.base())}) { 593 return result; 594 } 595 // The subscripts don't get special protection for being in a 596 // specification inquiry context; 597 auto restorer{common::ScopedSet(inInquiry_, false)}; 598 return (*this)(x.subscript()); 599 } 600 Result operator()(const Substring &x) const { 601 if (auto result{(*this)(x.parent())}) { 602 return result; 603 } 604 // The bounds don't get special protection for being in a 605 // specification inquiry context; 606 auto restorer{common::ScopedSet(inInquiry_, false)}; 607 if (auto result{(*this)(x.lower())}) { 608 return result; 609 } 610 return (*this)(x.upper()); 611 } 612 Result operator()(const DescriptorInquiry &x) const { 613 // Many uses of SIZE(), LBOUND(), &c. that are valid in specification 614 // expressions will have been converted to expressions over descriptor 615 // inquiries by Fold(). 616 // Catch REAL, ALLOCATABLE :: X(:); REAL :: Y(SIZE(X)) 617 if (IsPermissibleInquiry( 618 x.base().GetFirstSymbol(), x.base().GetLastSymbol(), x.field())) { 619 auto restorer{common::ScopedSet(inInquiry_, true)}; 620 return (*this)(x.base()); 621 } else if (IsConstantExpr(x)) { 622 return std::nullopt; 623 } else { 624 return "non-constant descriptor inquiry not allowed for local object"; 625 } 626 } 627 628 Result operator()(const TypeParamInquiry &inq) const { 629 if (scope_.IsDerivedType()) { 630 if (!IsConstantExpr(inq) && 631 inq.base() /* X%T, not local T */) { // C750, C754 632 return "non-constant reference to a type parameter inquiry not allowed " 633 "for derived type components or type parameter values"; 634 } 635 } else if (inq.base() && 636 IsInquiryAlwaysPermissible(inq.base()->GetFirstSymbol())) { 637 auto restorer{common::ScopedSet(inInquiry_, true)}; 638 return (*this)(inq.base()); 639 } else if (!IsConstantExpr(inq)) { 640 return "non-constant type parameter inquiry not allowed for local object"; 641 } 642 return std::nullopt; 643 } 644 645 Result operator()(const ProcedureRef &x) const { 646 bool inInquiry{false}; 647 if (const auto *symbol{x.proc().GetSymbol()}) { 648 const Symbol &ultimate{symbol->GetUltimate()}; 649 if (!semantics::IsPureProcedure(ultimate)) { 650 return "reference to impure function '"s + ultimate.name().ToString() + 651 "'"; 652 } 653 if (semantics::IsStmtFunction(ultimate)) { 654 return "reference to statement function '"s + 655 ultimate.name().ToString() + "'"; 656 } 657 if (scope_.IsDerivedType()) { // C750, C754 658 return "reference to function '"s + ultimate.name().ToString() + 659 "' not allowed for derived type components or type parameter" 660 " values"; 661 } 662 if (auto procChars{characteristics::Procedure::Characterize( 663 x.proc(), context_, /*emitError=*/true)}) { 664 const auto iter{std::find_if(procChars->dummyArguments.begin(), 665 procChars->dummyArguments.end(), 666 [](const characteristics::DummyArgument &dummy) { 667 return std::holds_alternative<characteristics::DummyProcedure>( 668 dummy.u); 669 })}; 670 if (iter != procChars->dummyArguments.end() && 671 ultimate.name().ToString() != "__builtin_c_funloc") { 672 return "reference to function '"s + ultimate.name().ToString() + 673 "' with dummy procedure argument '" + iter->name + '\''; 674 } 675 } 676 // References to internal functions are caught in expression semantics. 677 // TODO: other checks for standard module procedures 678 } else { // intrinsic 679 const SpecificIntrinsic &intrin{DEREF(x.proc().GetSpecificIntrinsic())}; 680 inInquiry = context_.intrinsics().GetIntrinsicClass(intrin.name) == 681 IntrinsicClass::inquiryFunction; 682 if (scope_.IsDerivedType()) { // C750, C754 683 if ((context_.intrinsics().IsIntrinsic(intrin.name) && 684 badIntrinsicsForComponents_.find(intrin.name) != 685 badIntrinsicsForComponents_.end())) { 686 return "reference to intrinsic '"s + intrin.name + 687 "' not allowed for derived type components or type parameter" 688 " values"; 689 } 690 if (inInquiry && !IsConstantExpr(x)) { 691 return "non-constant reference to inquiry intrinsic '"s + 692 intrin.name + 693 "' not allowed for derived type components or type" 694 " parameter values"; 695 } 696 } 697 // Type-determined inquiries (DIGITS, HUGE, &c.) will have already been 698 // folded and won't arrive here. Inquiries that are represented with 699 // DescriptorInquiry operations (LBOUND) are checked elsewhere. If a 700 // call that makes it to here satisfies the requirements of a constant 701 // expression (as Fortran defines it), it's fine. 702 if (IsConstantExpr(x)) { 703 return std::nullopt; 704 } 705 if (intrin.name == "present") { 706 return std::nullopt; // always ok 707 } 708 // Catch CHARACTER(:), ALLOCATABLE :: X; CHARACTER(LEN(X)) :: Y 709 if (inInquiry && x.arguments().size() >= 1) { 710 if (const auto &arg{x.arguments().at(0)}) { 711 if (auto dataRef{ExtractDataRef(*arg, true, true)}) { 712 if (intrin.name == "allocated" || intrin.name == "associated" || 713 intrin.name == "is_contiguous") { // ok 714 } else if (intrin.name == "len" && 715 IsPermissibleInquiry(dataRef->GetFirstSymbol(), 716 dataRef->GetLastSymbol(), 717 DescriptorInquiry::Field::Len)) { // ok 718 } else if (intrin.name == "lbound" && 719 IsPermissibleInquiry(dataRef->GetFirstSymbol(), 720 dataRef->GetLastSymbol(), 721 DescriptorInquiry::Field::LowerBound)) { // ok 722 } else if ((intrin.name == "shape" || intrin.name == "size" || 723 intrin.name == "sizeof" || 724 intrin.name == "storage_size" || 725 intrin.name == "ubound") && 726 IsPermissibleInquiry(dataRef->GetFirstSymbol(), 727 dataRef->GetLastSymbol(), 728 DescriptorInquiry::Field::Extent)) { // ok 729 } else { 730 return "non-constant inquiry function '"s + intrin.name + 731 "' not allowed for local object"; 732 } 733 } 734 } 735 } 736 } 737 auto restorer{common::ScopedSet(inInquiry_, inInquiry)}; 738 return (*this)(x.arguments()); 739 } 740 741 private: 742 const semantics::Scope &scope_; 743 FoldingContext &context_; 744 // Contextual information: this flag is true when in an argument to 745 // an inquiry intrinsic like SIZE(). 746 mutable bool inInquiry_{false}; 747 bool forElementalFunctionResult_{false}; // F'2023 C15121 748 const std::set<std::string> badIntrinsicsForComponents_{ 749 "allocated", "associated", "extends_type_of", "present", "same_type_as"}; 750 751 bool IsInquiryAlwaysPermissible(const semantics::Symbol &) const; 752 bool IsPermissibleInquiry(const semantics::Symbol &firstSymbol, 753 const semantics::Symbol &lastSymbol, 754 DescriptorInquiry::Field field) const; 755 }; 756 757 bool CheckSpecificationExprHelper::IsInquiryAlwaysPermissible( 758 const semantics::Symbol &symbol) const { 759 if (&symbol.owner() != &scope_ || symbol.has<semantics::UseDetails>() || 760 symbol.owner().kind() == semantics::Scope::Kind::Module || 761 semantics::FindCommonBlockContaining(symbol) || 762 symbol.has<semantics::HostAssocDetails>()) { 763 return true; // it's nonlocal 764 } else if (semantics::IsDummy(symbol) && !forElementalFunctionResult_) { 765 return true; 766 } else { 767 return false; 768 } 769 } 770 771 bool CheckSpecificationExprHelper::IsPermissibleInquiry( 772 const semantics::Symbol &firstSymbol, const semantics::Symbol &lastSymbol, 773 DescriptorInquiry::Field field) const { 774 if (IsInquiryAlwaysPermissible(firstSymbol)) { 775 return true; 776 } 777 // Inquiries on local objects may not access a deferred bound or length. 778 // (This code used to be a switch, but it proved impossible to write it 779 // thus without running afoul of bogus warnings from different C++ 780 // compilers.) 781 if (field == DescriptorInquiry::Field::Rank) { 782 return true; // always known 783 } 784 const auto *object{lastSymbol.detailsIf<semantics::ObjectEntityDetails>()}; 785 if (field == DescriptorInquiry::Field::LowerBound || 786 field == DescriptorInquiry::Field::Extent || 787 field == DescriptorInquiry::Field::Stride) { 788 return object && !object->shape().CanBeDeferredShape(); 789 } 790 if (field == DescriptorInquiry::Field::Len) { 791 return object && object->type() && 792 object->type()->category() == semantics::DeclTypeSpec::Character && 793 !object->type()->characterTypeSpec().length().isDeferred(); 794 } 795 return false; 796 } 797 798 template <typename A> 799 void CheckSpecificationExpr(const A &x, const semantics::Scope &scope, 800 FoldingContext &context, bool forElementalFunctionResult) { 801 CheckSpecificationExprHelper helper{ 802 scope, context, forElementalFunctionResult}; 803 if (auto why{helper(x)}) { 804 context.messages().Say("Invalid specification expression%s: %s"_err_en_US, 805 forElementalFunctionResult ? " for elemental function result" : "", 806 *why); 807 } 808 } 809 810 template void CheckSpecificationExpr(const Expr<SomeType> &, 811 const semantics::Scope &, FoldingContext &, 812 bool forElementalFunctionResult); 813 template void CheckSpecificationExpr(const Expr<SomeInteger> &, 814 const semantics::Scope &, FoldingContext &, 815 bool forElementalFunctionResult); 816 template void CheckSpecificationExpr(const Expr<SubscriptInteger> &, 817 const semantics::Scope &, FoldingContext &, 818 bool forElementalFunctionResult); 819 template void CheckSpecificationExpr(const std::optional<Expr<SomeType>> &, 820 const semantics::Scope &, FoldingContext &, 821 bool forElementalFunctionResult); 822 template void CheckSpecificationExpr(const std::optional<Expr<SomeInteger>> &, 823 const semantics::Scope &, FoldingContext &, 824 bool forElementalFunctionResult); 825 template void CheckSpecificationExpr( 826 const std::optional<Expr<SubscriptInteger>> &, const semantics::Scope &, 827 FoldingContext &, bool forElementalFunctionResult); 828 829 // IsContiguous() -- 9.5.4 830 class IsContiguousHelper 831 : public AnyTraverse<IsContiguousHelper, std::optional<bool>> { 832 public: 833 using Result = std::optional<bool>; // tri-state 834 using Base = AnyTraverse<IsContiguousHelper, Result>; 835 explicit IsContiguousHelper(FoldingContext &c) : Base{*this}, context_{c} {} 836 using Base::operator(); 837 838 template <typename T> Result operator()(const Constant<T> &) const { 839 return true; 840 } 841 Result operator()(const StaticDataObject &) const { return true; } 842 Result operator()(const semantics::Symbol &symbol) const { 843 const auto &ultimate{symbol.GetUltimate()}; 844 if (ultimate.attrs().test(semantics::Attr::CONTIGUOUS)) { 845 return true; 846 } else if (!IsVariable(symbol)) { 847 return true; 848 } else if (ultimate.Rank() == 0) { 849 // Extension: accept scalars as a degenerate case of 850 // simple contiguity to allow their use in contexts like 851 // data targets in pointer assignments with remapping. 852 return true; 853 } else if (const auto *details{ 854 ultimate.detailsIf<semantics::AssocEntityDetails>()}) { 855 // RANK(*) associating entity is contiguous. 856 if (details->IsAssumedSize()) { 857 return true; 858 } else { 859 return Base::operator()(ultimate); // use expr 860 } 861 } else if (semantics::IsPointer(ultimate) || 862 semantics::IsAssumedShape(ultimate) || IsAssumedRank(ultimate)) { 863 return std::nullopt; 864 } else if (ultimate.has<semantics::ObjectEntityDetails>()) { 865 return true; 866 } else { 867 return Base::operator()(ultimate); 868 } 869 } 870 871 Result operator()(const ArrayRef &x) const { 872 if (x.Rank() == 0) { 873 return true; // scalars considered contiguous 874 } 875 int subscriptRank{0}; 876 auto baseLbounds{GetLBOUNDs(context_, x.base())}; 877 auto baseUbounds{GetUBOUNDs(context_, x.base())}; 878 auto subscripts{CheckSubscripts( 879 x.subscript(), subscriptRank, &baseLbounds, &baseUbounds)}; 880 if (!subscripts.value_or(false)) { 881 return subscripts; // subscripts not known to be contiguous 882 } else if (subscriptRank > 0) { 883 // a(1)%b(:,:) is contiguous if and only if a(1)%b is contiguous. 884 return (*this)(x.base()); 885 } else { 886 // a(:)%b(1,1) is (probably) not contiguous. 887 return std::nullopt; 888 } 889 } 890 Result operator()(const CoarrayRef &x) const { 891 int rank{0}; 892 return CheckSubscripts(x.subscript(), rank).has_value(); 893 } 894 Result operator()(const Component &x) const { 895 if (x.base().Rank() == 0) { 896 return (*this)(x.GetLastSymbol()); 897 } else { 898 if (Result baseIsContiguous{(*this)(x.base())}) { 899 if (!*baseIsContiguous) { 900 return false; 901 } 902 // TODO could be true if base contiguous and this is only component, or 903 // if base has only one element? 904 } 905 return std::nullopt; 906 } 907 } 908 Result operator()(const ComplexPart &x) const { 909 return x.complex().Rank() == 0; 910 } 911 Result operator()(const Substring &) const { return std::nullopt; } 912 913 Result operator()(const ProcedureRef &x) const { 914 if (auto chars{characteristics::Procedure::Characterize( 915 x.proc(), context_, /*emitError=*/true)}) { 916 if (chars->functionResult) { 917 const auto &result{*chars->functionResult}; 918 if (!result.IsProcedurePointer()) { 919 if (result.attrs.test( 920 characteristics::FunctionResult::Attr::Contiguous)) { 921 return true; 922 } 923 if (!result.attrs.test( 924 characteristics::FunctionResult::Attr::Pointer)) { 925 return true; 926 } 927 if (const auto *type{result.GetTypeAndShape()}; 928 type && type->Rank() == 0) { 929 return true; // pointer to scalar 930 } 931 // Must be non-CONTIGUOUS pointer to array 932 } 933 } 934 } 935 return std::nullopt; 936 } 937 938 Result operator()(const NullPointer &) const { return true; } 939 940 private: 941 // Returns "true" for a provably empty or simply contiguous array section; 942 // return "false" for a provably nonempty discontiguous section or for use 943 // of a vector subscript. 944 std::optional<bool> CheckSubscripts(const std::vector<Subscript> &subscript, 945 int &rank, const Shape *baseLbounds = nullptr, 946 const Shape *baseUbounds = nullptr) const { 947 bool anyTriplet{false}; 948 rank = 0; 949 // Detect any provably empty dimension in this array section, which would 950 // render the whole section empty and therefore vacuously contiguous. 951 std::optional<bool> result; 952 bool mayBeEmpty{false}; 953 auto dims{subscript.size()}; 954 std::vector<bool> knownPartialSlice(dims, false); 955 for (auto j{dims}; j-- > 0;) { 956 std::optional<ConstantSubscript> dimLbound; 957 std::optional<ConstantSubscript> dimUbound; 958 std::optional<ConstantSubscript> dimExtent; 959 if (baseLbounds && j < baseLbounds->size()) { 960 if (const auto &lb{baseLbounds->at(j)}) { 961 dimLbound = ToInt64(Fold(context_, Expr<SubscriptInteger>{*lb})); 962 } 963 } 964 if (baseUbounds && j < baseUbounds->size()) { 965 if (const auto &ub{baseUbounds->at(j)}) { 966 dimUbound = ToInt64(Fold(context_, Expr<SubscriptInteger>{*ub})); 967 } 968 } 969 if (dimLbound && dimUbound) { 970 if (*dimLbound <= *dimUbound) { 971 dimExtent = *dimUbound - *dimLbound + 1; 972 } else { 973 // This is an empty dimension. 974 result = true; 975 dimExtent = 0; 976 } 977 } 978 979 if (const auto *triplet{std::get_if<Triplet>(&subscript[j].u)}) { 980 ++rank; 981 if (auto stride{ToInt64(triplet->stride())}) { 982 const Expr<SubscriptInteger> *lowerBound{triplet->GetLower()}; 983 const Expr<SubscriptInteger> *upperBound{triplet->GetUpper()}; 984 std::optional<ConstantSubscript> lowerVal{lowerBound 985 ? ToInt64(Fold(context_, Expr<SubscriptInteger>{*lowerBound})) 986 : dimLbound}; 987 std::optional<ConstantSubscript> upperVal{upperBound 988 ? ToInt64(Fold(context_, Expr<SubscriptInteger>{*upperBound})) 989 : dimUbound}; 990 if (lowerVal && upperVal) { 991 if (*lowerVal < *upperVal) { 992 if (*stride < 0) { 993 result = true; // empty dimension 994 } else if (!result && *stride > 1 && 995 *lowerVal + *stride <= *upperVal) { 996 result = false; // discontiguous if not empty 997 } 998 } else if (*lowerVal > *upperVal) { 999 if (*stride > 0) { 1000 result = true; // empty dimension 1001 } else if (!result && *stride < 0 && 1002 *lowerVal + *stride >= *upperVal) { 1003 result = false; // discontiguous if not empty 1004 } 1005 } else { 1006 mayBeEmpty = true; 1007 } 1008 } else { 1009 mayBeEmpty = true; 1010 } 1011 } else { 1012 mayBeEmpty = true; 1013 } 1014 } else if (subscript[j].Rank() > 0) { 1015 ++rank; 1016 if (!result) { 1017 result = false; // vector subscript 1018 } 1019 mayBeEmpty = true; 1020 } else { 1021 // Scalar subscript. 1022 if (dimExtent && *dimExtent > 1) { 1023 knownPartialSlice[j] = true; 1024 } 1025 } 1026 } 1027 if (rank == 0) { 1028 result = true; // scalar 1029 } 1030 if (result) { 1031 return result; 1032 } 1033 // Not provably discontiguous at this point. 1034 // Return "true" if simply contiguous, otherwise nullopt. 1035 for (auto j{subscript.size()}; j-- > 0;) { 1036 if (const auto *triplet{std::get_if<Triplet>(&subscript[j].u)}) { 1037 auto stride{ToInt64(triplet->stride())}; 1038 if (!stride || stride != 1) { 1039 return std::nullopt; 1040 } else if (anyTriplet) { 1041 if (triplet->GetLower() || triplet->GetUpper()) { 1042 // all triplets before the last one must be just ":" for 1043 // simple contiguity 1044 return std::nullopt; 1045 } 1046 } else { 1047 anyTriplet = true; 1048 } 1049 ++rank; 1050 } else if (anyTriplet) { 1051 // If the section cannot be empty, and this dimension's 1052 // scalar subscript is known not to cover the whole 1053 // dimension, then the array section is provably 1054 // discontiguous. 1055 return (mayBeEmpty || !knownPartialSlice[j]) 1056 ? std::nullopt 1057 : std::make_optional(false); 1058 } 1059 } 1060 return true; // simply contiguous 1061 } 1062 1063 FoldingContext &context_; 1064 }; 1065 1066 template <typename A> 1067 std::optional<bool> IsContiguous(const A &x, FoldingContext &context) { 1068 return IsContiguousHelper{context}(x); 1069 } 1070 1071 template std::optional<bool> IsContiguous( 1072 const Expr<SomeType> &, FoldingContext &); 1073 template std::optional<bool> IsContiguous(const ArrayRef &, FoldingContext &); 1074 template std::optional<bool> IsContiguous(const Substring &, FoldingContext &); 1075 template std::optional<bool> IsContiguous(const Component &, FoldingContext &); 1076 template std::optional<bool> IsContiguous( 1077 const ComplexPart &, FoldingContext &); 1078 template std::optional<bool> IsContiguous(const CoarrayRef &, FoldingContext &); 1079 template std::optional<bool> IsContiguous(const Symbol &, FoldingContext &); 1080 1081 // IsErrorExpr() 1082 struct IsErrorExprHelper : public AnyTraverse<IsErrorExprHelper, bool> { 1083 using Result = bool; 1084 using Base = AnyTraverse<IsErrorExprHelper, Result>; 1085 IsErrorExprHelper() : Base{*this} {} 1086 using Base::operator(); 1087 1088 bool operator()(const SpecificIntrinsic &x) { 1089 return x.name == IntrinsicProcTable::InvalidName; 1090 } 1091 }; 1092 1093 template <typename A> bool IsErrorExpr(const A &x) { 1094 return IsErrorExprHelper{}(x); 1095 } 1096 1097 template bool IsErrorExpr(const Expr<SomeType> &); 1098 1099 // C1577 1100 // TODO: Also check C1579 & C1582 here 1101 class StmtFunctionChecker 1102 : public AnyTraverse<StmtFunctionChecker, std::optional<parser::Message>> { 1103 public: 1104 using Result = std::optional<parser::Message>; 1105 using Base = AnyTraverse<StmtFunctionChecker, Result>; 1106 1107 static constexpr auto feature{ 1108 common::LanguageFeature::StatementFunctionExtensions}; 1109 1110 StmtFunctionChecker(const Symbol &sf, FoldingContext &context) 1111 : Base{*this}, sf_{sf}, context_{context} { 1112 if (!context_.languageFeatures().IsEnabled(feature)) { 1113 severity_ = parser::Severity::Error; 1114 } else if (context_.languageFeatures().ShouldWarn(feature)) { 1115 severity_ = parser::Severity::Portability; 1116 } 1117 } 1118 using Base::operator(); 1119 1120 Result Return(parser::Message &&msg) const { 1121 if (severity_) { 1122 msg.set_severity(*severity_); 1123 if (*severity_ != parser::Severity::Error) { 1124 msg.set_languageFeature(feature); 1125 } 1126 } 1127 return std::move(msg); 1128 } 1129 1130 template <typename T> Result operator()(const ArrayConstructor<T> &) const { 1131 if (severity_) { 1132 return Return(parser::Message{sf_.name(), 1133 "Statement function '%s' should not contain an array constructor"_port_en_US, 1134 sf_.name()}); 1135 } else { 1136 return std::nullopt; 1137 } 1138 } 1139 Result operator()(const StructureConstructor &) const { 1140 if (severity_) { 1141 return Return(parser::Message{sf_.name(), 1142 "Statement function '%s' should not contain a structure constructor"_port_en_US, 1143 sf_.name()}); 1144 } else { 1145 return std::nullopt; 1146 } 1147 } 1148 Result operator()(const TypeParamInquiry &) const { 1149 if (severity_) { 1150 return Return(parser::Message{sf_.name(), 1151 "Statement function '%s' should not contain a type parameter inquiry"_port_en_US, 1152 sf_.name()}); 1153 } else { 1154 return std::nullopt; 1155 } 1156 } 1157 Result operator()(const ProcedureDesignator &proc) const { 1158 if (const Symbol * symbol{proc.GetSymbol()}) { 1159 const Symbol &ultimate{symbol->GetUltimate()}; 1160 if (const auto *subp{ 1161 ultimate.detailsIf<semantics::SubprogramDetails>()}) { 1162 if (subp->stmtFunction() && &ultimate.owner() == &sf_.owner()) { 1163 if (ultimate.name().begin() > sf_.name().begin()) { 1164 return parser::Message{sf_.name(), 1165 "Statement function '%s' may not reference another statement function '%s' that is defined later"_err_en_US, 1166 sf_.name(), ultimate.name()}; 1167 } 1168 } 1169 } 1170 if (auto chars{characteristics::Procedure::Characterize( 1171 proc, context_, /*emitError=*/true)}) { 1172 if (!chars->CanBeCalledViaImplicitInterface()) { 1173 if (severity_) { 1174 return Return(parser::Message{sf_.name(), 1175 "Statement function '%s' should not reference function '%s' that requires an explicit interface"_port_en_US, 1176 sf_.name(), symbol->name()}); 1177 } 1178 } 1179 } 1180 } 1181 if (proc.Rank() > 0) { 1182 if (severity_) { 1183 return Return(parser::Message{sf_.name(), 1184 "Statement function '%s' should not reference a function that returns an array"_port_en_US, 1185 sf_.name()}); 1186 } 1187 } 1188 return std::nullopt; 1189 } 1190 Result operator()(const ActualArgument &arg) const { 1191 if (const auto *expr{arg.UnwrapExpr()}) { 1192 if (auto result{(*this)(*expr)}) { 1193 return result; 1194 } 1195 if (expr->Rank() > 0 && !UnwrapWholeSymbolOrComponentDataRef(*expr)) { 1196 if (severity_) { 1197 return Return(parser::Message{sf_.name(), 1198 "Statement function '%s' should not pass an array argument that is not a whole array"_port_en_US, 1199 sf_.name()}); 1200 } 1201 } 1202 } 1203 return std::nullopt; 1204 } 1205 1206 private: 1207 const Symbol &sf_; 1208 FoldingContext &context_; 1209 std::optional<parser::Severity> severity_; 1210 }; 1211 1212 std::optional<parser::Message> CheckStatementFunction( 1213 const Symbol &sf, const Expr<SomeType> &expr, FoldingContext &context) { 1214 return StmtFunctionChecker{sf, context}(expr); 1215 } 1216 1217 } // namespace Fortran::evaluate 1218