9#ifndef FORTRAN_EVALUATE_FOLD_IMPLEMENTATION_H_
10#define FORTRAN_EVALUATE_FOLD_IMPLEMENTATION_H_
15#include "flang/Common/indirection.h"
16#include "flang/Common/template.h"
17#include "flang/Common/unwrap.h"
18#include "flang/Evaluate/characteristics.h"
19#include "flang/Evaluate/check-expression.h"
20#include "flang/Evaluate/common.h"
21#include "flang/Evaluate/constant.h"
22#include "flang/Evaluate/expression.h"
23#include "flang/Evaluate/fold.h"
24#include "flang/Evaluate/intrinsics-library.h"
25#include "flang/Evaluate/intrinsics.h"
26#include "flang/Evaluate/shape.h"
27#include "flang/Evaluate/tools.h"
28#include "flang/Evaluate/traverse.h"
29#include "flang/Evaluate/type.h"
30#include "flang/Parser/message.h"
31#include "flang/Semantics/scope.h"
32#include "flang/Semantics/symbol.h"
33#include "flang/Semantics/tools.h"
51static constexpr bool useKahanSummation{
false};
54template <
typename T>
class Folder {
56 explicit Folder(
FoldingContext &c,
bool forOptionalArgument =
false)
57 : context_{c}, forOptionalArgument_{forOptionalArgument} {}
58 std::optional<Constant<T>> GetNamedConstant(
const Symbol &);
59 std::optional<Constant<T>> ApplySubscripts(
const Constant<T> &array,
64 std::optional<Constant<T>> GetConstantComponent(
66 std::optional<Constant<T>> Folding(
ArrayRef &);
67 std::optional<Constant<T>> Folding(
DataRef &);
69 Constant<T> *Folding(std::optional<ActualArgument> &);
84 bool forOptionalArgument_{
false};
87std::optional<Constant<SubscriptInteger>> GetConstantSubscript(
91template <
typename TR,
typename... TA>
92std::optional<std::function<Scalar<TR>(
FoldingContext &, Scalar<TA>...)>>
93GetHostRuntimeWrapper(
const std::string &name) {
94 std::vector<DynamicType> argTypes{TA{}.GetType()...};
95 if (
auto hostWrapper{GetHostRuntimeWrapper(name, TR{}.GetType(), argTypes)}) {
98 std::vector<Expr<SomeType>> genericArgs{
100 return GetScalarConstantValue<TR>(
101 (*hostWrapper)(context, std::move(genericArgs)))
116common::IfNoLvalue<Expr<ResultType<A>>, A> FoldOperation(
118 static_assert(!std::is_same_v<A, Expr<ResultType<A>>>,
119 "call Fold() instead for Expr<>");
136 return Folder<T>{context}.Folding(std::move(designator));
151std::optional<Constant<T>> Folder<T>::GetNamedConstant(
const Symbol &symbol0) {
152 const Symbol &symbol{ResolveAssociations(symbol0)};
153 if (IsNamedConstant(symbol)) {
154 if (
const auto *
object{
155 symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
156 if (
const auto *constant{UnwrapConstantValue<T>(object->init())}) {
165std::optional<Constant<T>> Folder<T>::Folding(
ArrayRef &aRef) {
166 std::vector<Constant<SubscriptInteger>> subscripts;
169 if (
auto constant{GetConstantSubscript(context_, ss, aRef.base(), dim++)}) {
170 subscripts.emplace_back(std::move(*constant));
175 if (
Component * component{aRef.base().UnwrapComponent()}) {
176 return GetConstantComponent(*component, &subscripts);
178 GetNamedConstant(aRef.base().GetLastSymbol())}) {
179 return ApplySubscripts(*array, subscripts);
186std::optional<Constant<T>> Folder<T>::Folding(
DataRef &ref) {
187 return common::visit(
189 [
this](SymbolRef &sym) {
return GetNamedConstant(*sym); },
191 comp = FoldOperation(context_, std::move(comp));
192 return GetConstantComponent(comp);
195 aRef = FoldOperation(context_, std::move(aRef));
196 return Folding(aRef);
198 [](
CoarrayRef &) {
return std::optional<Constant<T>>{}; },
205std::optional<Constant<T>> Folder<T>::ApplySubscripts(
const Constant<T> &array,
207 const auto &shape{array.shape()};
208 const auto &lbounds{array.lbounds()};
209 int rank{GetRank(shape)};
210 CHECK(rank ==
static_cast<int>(subscripts.size()));
211 std::size_t elements{1};
212 ConstantSubscripts resultShape;
213 ConstantSubscripts ssLB;
214 for (
const auto &ss : subscripts) {
215 if (ss.Rank() == 1) {
216 resultShape.push_back(
static_cast<ConstantSubscript
>(ss.size()));
217 elements *= ss.size();
218 ssLB.push_back(ss.lbounds().front());
219 }
else if (ss.Rank() > 1) {
223 ConstantSubscripts ssAt(rank, 0), at(rank, 0), tmp(1, 0);
224 std::vector<Scalar<T>> values;
225 while (elements-- > 0) {
226 bool increment{
true};
228 for (
int j{0}; j < rank; ++j) {
229 if (subscripts[j].Rank() == 0) {
230 at[j] = subscripts[j].GetScalarValue().value().ToInt64();
232 CHECK(k < GetRank(resultShape));
233 tmp[0] = ssLB.at(k) + ssAt.at(k);
234 at[j] = subscripts[j].At(tmp).ToInt64();
236 if (++ssAt[k] == resultShape[k]) {
244 if (at[j] < lbounds[j] || at[j] >= lbounds[j] + shape[j]) {
245 context_.messages().Say(
246 "Subscript value (%jd) is out of range on dimension %d in reference to a constant array value"_err_en_US,
251 values.emplace_back(array.At(at));
252 CHECK(!increment || elements == 0);
253 CHECK(k == GetRank(resultShape));
255 if constexpr (T::category == TypeCategory::Character) {
256 return Constant<T>{array.LEN(), std::move(values), std::move(resultShape)};
257 }
else if constexpr (std::is_same_v<T, SomeDerived>) {
258 return Constant<T>{array.result().derivedTypeSpec(), std::move(values),
259 std::move(resultShape)};
261 return Constant<T>{std::move(values), std::move(resultShape)};
266std::optional<Constant<T>> Folder<T>::ApplyComponent(
269 if (
auto scalar{structures.GetScalarValue()}) {
270 if (std::optional<
Expr<SomeType>> expr{scalar->Find(component)}) {
271 if (
const Constant<T> *value{UnwrapConstantValue<T>(*expr)}) {
273 return ApplySubscripts(*value, *subscripts);
281 std::unique_ptr<ArrayConstructor<T>> array;
282 if (structures.empty()) {
285 ConstantSubscripts at{structures.lbounds()};
289 if (
const Constant<T> *value{UnwrapConstantValue<T>(expr.value())}) {
293 auto *typedExpr{UnwrapExpr<Expr<T>>(expr.value())};
295 array = std::make_unique<ArrayConstructor<T>>(*typedExpr);
296 if constexpr (T::category == TypeCategory::Character) {
301 if (
auto element{ApplySubscripts(*value, *subscripts)}) {
302 CHECK(element->Rank() == 0);
303 array->Push(
Expr<T>{std::move(*element)});
308 CHECK(value->Rank() == 0);
315 }
while (structures.IncrementSubscripts(at));
319 if (
auto *constant{UnwrapConstantValue<T>(result)}) {
320 return constant->Reshape(common::Clone(structures.shape()));
327std::optional<Constant<T>> Folder<T>::GetConstantComponent(
Component &component,
331 [&](
const Symbol &symbol) {
341 return std::optional<Constant<SomeDerived>>{};
344 component.base().u)}) {
345 return ApplyComponent(
346 std::move(*structures), component.GetLastSymbol(), subscripts);
353 if constexpr (T::category == TypeCategory::Character) {
354 if (
auto *substring{common::Unwrap<Substring>(designator.u)}) {
356 substring->Fold(context_)}) {
357 if (
const auto *specific{std::get_if<Expr<T>>(&folded->u)}) {
358 return std::move(*specific);
365 }
else if constexpr (T::category == TypeCategory::Real) {
366 if (
auto *zPart{std::get_if<ComplexPart>(&designator.u)}) {
367 *zPart = FoldOperation(context_, std::move(*zPart));
370 return Fold(context_,
372 zPart->part() == ComplexPart::Part::IM,
379 return common::visit(
381 [&](SymbolRef &&symbol) {
382 if (
auto constant{GetNamedConstant(*symbol)}) {
383 return Expr<T>{std::move(*constant)};
385 return Expr<T>{std::move(designator)};
388 aRef = FoldOperation(context_, std::move(aRef));
389 if (
auto c{Folding(aRef)}) {
396 component = FoldOperation(context_, std::move(component));
397 if (
auto c{GetConstantComponent(component)}) {
408 std::move(designator.u));
414Constant<T> *Folder<T>::Folding(std::optional<ActualArgument> &arg) {
415 if (
auto *expr{UnwrapExpr<Expr<SomeType>>(arg)}) {
416 *expr = Fold(context_, std::move(*expr));
417 if constexpr (T::category != TypeCategory::Derived) {
418 if (!UnwrapExpr<
Expr<T>>(*expr)) {
420 var{forOptionalArgument_
421 ? UnwrapWholeSymbolOrComponentDataRef(*expr)
423 var && (IsOptional(*var) || IsAllocatableOrObjectPointer(var))) {
425 }
else if (
auto converted{
426 ConvertToType(T::GetType(), std::move(*expr))}) {
427 *expr = Fold(context_, std::move(*converted));
431 return UnwrapConstantValue<T>(*expr);
436template <
typename... A, std::size_t... I>
437std::optional<std::tuple<const Constant<A> *...>> GetConstantArgumentsHelper(
439 bool hasOptionalArgument, std::index_sequence<I...>) {
440 static_assert(
sizeof...(A) > 0);
441 std::tuple<const Constant<A> *...> args{
442 Folder<A>{context, hasOptionalArgument}.Folding(arguments.at(I))...};
443 if ((... && (std::get<I>(args)))) {
450template <
typename... A>
451std::optional<std::tuple<const Constant<A> *...>> GetConstantArguments(
452 FoldingContext &context, ActualArguments &args,
bool hasOptionalArgument) {
453 return GetConstantArgumentsHelper<A...>(
454 context, args, hasOptionalArgument, std::index_sequence_for<A...>{});
457template <
typename... A, std::size_t... I>
458std::optional<std::tuple<Scalar<A>...>> GetScalarConstantArgumentsHelper(
459 FoldingContext &context, ActualArguments &args,
bool hasOptionalArgument,
460 std::index_sequence<I...>) {
462 GetConstantArguments<A...>(context, args, hasOptionalArgument)}) {
463 return std::tuple<Scalar<A>...>{
464 std::get<I>(*constArgs)->GetScalarValue().value()...};
470template <
typename... A>
471std::optional<std::tuple<Scalar<A>...>> GetScalarConstantArguments(
472 FoldingContext &context, ActualArguments &args,
bool hasOptionalArgument) {
473 return GetScalarConstantArgumentsHelper<A...>(
474 context, args, hasOptionalArgument, std::index_sequence_for<A...>{});
481template <
typename TR,
typename... TArgs>
482using ScalarFunc = std::function<Scalar<TR>(
const Scalar<TArgs> &...)>;
483template <
typename TR,
typename... TArgs>
484using ScalarFuncWithContext =
485 std::function<Scalar<TR>(
FoldingContext &,
const Scalar<TArgs> &...)>;
487template <
template <
typename,
typename...>
typename WrapperType,
typename TR,
488 typename... TA, std::size_t... I>
491 bool hasOptionalArgument, std::index_sequence<I...>) {
492 if (std::optional<std::tuple<
const Constant<TA> *...>> args{
493 GetConstantArguments<TA...>(
494 context, funcRef.arguments(), hasOptionalArgument)}) {
496 ConstantSubscripts shape;
498 const ConstantSubscripts *shapes[]{&std::get<I>(*args)->shape()...};
499 const int ranks[]{std::get<I>(*args)->Rank()...};
500 for (
unsigned int i{0}; i <
sizeof...(TA); ++i) {
506 if (shape != *shapes[i]) {
511 context.messages().Say(
512 "Arguments in elemental intrinsic function are not conformable"_err_en_US);
513 return Expr<TR>{std::move(funcRef)};
518 CHECK(rank == GetRank(shape));
520 std::vector<Scalar<TR>> results;
521 std::optional<uint64_t> n{TotalElementCount(shape)};
523 context.messages().Say(
524 "Too many elements in elemental intrinsic function result"_err_en_US);
525 return Expr<TR>{std::move(funcRef)};
529 ConstantSubscripts resultIndex(rank, 1);
530 ConstantSubscripts argIndex[]{std::get<I>(*args)->lbounds()...};
532 if constexpr (std::is_same_v<WrapperType<TR, TA...>,
533 ScalarFuncWithContext<TR, TA...>>) {
534 results.emplace_back(
535 func(context, std::get<I>(*args)->At(argIndex[I])...));
536 }
else if constexpr (std::is_same_v<WrapperType<TR, TA...>,
537 ScalarFunc<TR, TA...>>) {
538 results.emplace_back(func(std::get<I>(*args)->At(argIndex[I])...));
540 (std::get<I>(*args)->IncrementSubscripts(argIndex[I]), ...);
541 }
while (bounds.IncrementSubscripts(resultIndex));
544 if constexpr (TR::category == TypeCategory::Character) {
545 auto len{
static_cast<ConstantSubscript
>(
546 results.empty() ? 0 : results[0].length())};
548 }
else if constexpr (TR::category == TypeCategory::Derived) {
549 if (!results.empty()) {
553 std::move(results), std::move(shape)}};
559 return Expr<TR>{std::move(funcRef)};
562template <
typename TR,
typename... TA>
565 bool hasOptionalArgument =
false) {
566 return FoldElementalIntrinsicHelper<ScalarFunc, TR, TA...>(context,
567 std::move(funcRef), func, hasOptionalArgument,
568 std::index_sequence_for<TA...>{});
570template <
typename TR,
typename... TA>
573 bool hasOptionalArgument =
false) {
574 return FoldElementalIntrinsicHelper<ScalarFuncWithContext, TR, TA...>(context,
575 std::move(funcRef), func, hasOptionalArgument,
576 std::index_sequence_for<TA...>{});
579std::optional<std::int64_t> GetInt64ArgOr(
580 const std::optional<ActualArgument> &, std::int64_t defaultValue);
582template <
typename A,
typename B>
583std::optional<std::vector<A>> GetIntegerVector(
const B &x) {
584 static_assert(std::is_integral_v<A>);
585 if (
const auto *someInteger{UnwrapExpr<Expr<SomeInteger>>(x)}) {
586 return common::visit(
587 [](
const auto &typedExpr) -> std::optional<std::vector<A>> {
588 using T = ResultType<
decltype(typedExpr)>;
589 if (
const auto *constant{UnwrapConstantValue<T>(typedExpr)}) {
590 if (constant->Rank() == 1) {
591 std::vector<A> result;
592 for (
const auto &value : constant->values()) {
593 result.push_back(
static_cast<A
>(value.ToInt64()));
611 invalid.name = IntrinsicProcTable::InvalidName;
613 ActualArguments{std::move(funcRef.arguments())}}};
617 auto args{funcRef.arguments()};
618 CHECK(args.size() == 3);
619 const auto *array{UnwrapConstantValue<T>(args[0])};
620 const auto *shiftExpr{UnwrapExpr<Expr<SomeInteger>>(args[1])};
621 auto dim{GetInt64ArgOr(args[2], 1)};
622 if (!array || !shiftExpr || !dim) {
623 return Expr<T>{std::move(funcRef)};
625 auto convertedShift{Fold(context_,
627 const auto *shift{UnwrapConstantValue<SubscriptInteger>(convertedShift)};
629 return Expr<T>{std::move(funcRef)};
632 if (*dim < 1 || *dim > array->Rank()) {
633 context_.messages().Say(
"Invalid 'dim=' argument (%jd) in CSHIFT"_err_en_US,
634 static_cast<std::intmax_t
>(*dim));
635 }
else if (shift->Rank() > 0 && shift->Rank() != array->Rank() - 1) {
638 int rank{array->Rank()};
639 int zbDim{
static_cast<int>(*dim) - 1};
641 if (shift->Rank() > 0) {
643 for (
int j{0}; j < rank; ++j) {
645 if (array->shape()[j] != shift->shape()[k]) {
646 context_.messages().Say(
647 "Invalid 'shift=' argument in CSHIFT: extent on dimension %d is %jd but must be %jd"_err_en_US,
648 k + 1,
static_cast<std::intmax_t
>(shift->shape()[k]),
649 static_cast<std::intmax_t
>(array->shape()[j]));
657 std::vector<Scalar<T>> resultElements;
658 ConstantSubscripts arrayLB{array->lbounds()};
659 ConstantSubscripts arrayAt{arrayLB};
660 ConstantSubscript &dimIndex{arrayAt[zbDim]};
661 ConstantSubscript dimLB{dimIndex};
662 ConstantSubscript dimExtent{array->shape()[zbDim]};
663 ConstantSubscripts shiftLB{shift->lbounds()};
664 for (
auto n{GetSize(array->shape())}; n > 0; --n) {
665 ConstantSubscript origDimIndex{dimIndex};
666 ConstantSubscripts shiftAt;
667 if (shift->Rank() > 0) {
669 for (
int j{0}; j < rank; ++j) {
671 shiftAt.emplace_back(shiftLB[k++] + arrayAt[j] - arrayLB[j]);
675 ConstantSubscript shiftCount{shift->At(shiftAt).ToInt64()};
676 dimIndex = dimLB + ((dimIndex - dimLB + shiftCount) % dimExtent);
677 if (dimIndex < dimLB) {
678 dimIndex += dimExtent;
679 }
else if (dimIndex >= dimLB + dimExtent) {
680 dimIndex -= dimExtent;
682 resultElements.push_back(array->At(arrayAt));
683 dimIndex = origDimIndex;
684 array->IncrementSubscripts(arrayAt);
686 return Expr<T>{PackageConstant<T>(
687 std::move(resultElements), *array, array->shape())};
691 return MakeInvalidIntrinsic(std::move(funcRef));
695 auto args{funcRef.arguments()};
696 CHECK(args.size() == 4);
697 const auto *array{UnwrapConstantValue<T>(args[0])};
698 const auto *shiftExpr{UnwrapExpr<Expr<SomeInteger>>(args[1])};
699 auto dim{GetInt64ArgOr(args[3], 1)};
700 if (!array || !shiftExpr || !dim) {
701 return Expr<T>{std::move(funcRef)};
704 auto convertedShift{Fold(context_,
706 const auto *shift{UnwrapConstantValue<SubscriptInteger>(convertedShift)};
708 return Expr<T>{std::move(funcRef)};
711 std::optional<Expr<SomeType>> convertedBoundary;
712 if (
const auto *boundaryExpr{UnwrapExpr<Expr<SomeType>>(args[2])}) {
713 convertedBoundary = Fold(context_,
715 boundary = UnwrapExpr<Constant<T>>(convertedBoundary);
717 return Expr<T>{std::move(funcRef)};
721 if (*dim < 1 || *dim > array->Rank()) {
722 context_.messages().Say(
723 "Invalid 'dim=' argument (%jd) in EOSHIFT"_err_en_US,
724 static_cast<std::intmax_t
>(*dim));
725 }
else if (shift->Rank() > 0 && shift->Rank() != array->Rank() - 1) {
727 }
else if (boundary && boundary->Rank() > 0 &&
728 boundary->Rank() != array->Rank() - 1) {
731 int rank{array->Rank()};
732 int zbDim{
static_cast<int>(*dim) - 1};
734 if (shift->Rank() > 0) {
736 for (
int j{0}; j < rank; ++j) {
738 if (array->shape()[j] != shift->shape()[k]) {
739 context_.messages().Say(
740 "Invalid 'shift=' argument in EOSHIFT: extent on dimension %d is %jd but must be %jd"_err_en_US,
741 k + 1,
static_cast<std::intmax_t
>(shift->shape()[k]),
742 static_cast<std::intmax_t
>(array->shape()[j]));
749 if (boundary && boundary->Rank() > 0) {
751 for (
int j{0}; j < rank; ++j) {
753 if (array->shape()[j] != boundary->shape()[k]) {
754 context_.messages().Say(
755 "Invalid 'boundary=' argument in EOSHIFT: extent on dimension %d is %jd but must be %jd"_err_en_US,
756 k + 1,
static_cast<std::intmax_t
>(boundary->shape()[k]),
757 static_cast<std::intmax_t
>(array->shape()[j]));
765 std::vector<Scalar<T>> resultElements;
766 ConstantSubscripts arrayLB{array->lbounds()};
767 ConstantSubscripts arrayAt{arrayLB};
768 ConstantSubscript &dimIndex{arrayAt[zbDim]};
769 ConstantSubscript dimLB{dimIndex};
770 ConstantSubscript dimExtent{array->shape()[zbDim]};
771 ConstantSubscripts shiftLB{shift->lbounds()};
772 ConstantSubscripts boundaryLB;
774 boundaryLB = boundary->lbounds();
776 for (
auto n{GetSize(array->shape())}; n > 0; --n) {
777 ConstantSubscript origDimIndex{dimIndex};
778 ConstantSubscripts shiftAt;
779 if (shift->Rank() > 0) {
781 for (
int j{0}; j < rank; ++j) {
783 shiftAt.emplace_back(shiftLB[k++] + arrayAt[j] - arrayLB[j]);
787 ConstantSubscript shiftCount{shift->At(shiftAt).ToInt64()};
788 dimIndex += shiftCount;
789 if (dimIndex >= dimLB && dimIndex < dimLB + dimExtent) {
790 resultElements.push_back(array->At(arrayAt));
791 }
else if (boundary) {
792 ConstantSubscripts boundaryAt;
793 if (boundary->Rank() > 0) {
794 for (
int j{0}; j < rank; ++j) {
797 boundaryAt.emplace_back(
798 boundaryLB[k++] + arrayAt[j] - arrayLB[j]);
802 resultElements.push_back(boundary->At(boundaryAt));
803 }
else if constexpr (T::category == TypeCategory::Integer ||
804 T::category == TypeCategory::Unsigned ||
805 T::category == TypeCategory::Real ||
806 T::category == TypeCategory::Complex ||
807 T::category == TypeCategory::Logical) {
808 resultElements.emplace_back();
809 }
else if constexpr (T::category == TypeCategory::Character) {
810 auto len{
static_cast<std::size_t
>(array->LEN())};
811 typename Scalar<T>::value_type space{
' '};
812 resultElements.emplace_back(len, space);
814 DIE(
"no derived type boundary");
816 dimIndex = origDimIndex;
817 array->IncrementSubscripts(arrayAt);
819 return Expr<T>{PackageConstant<T>(
820 std::move(resultElements), *array, array->shape())};
824 return MakeInvalidIntrinsic(std::move(funcRef));
828 return FoldElementalIntrinsic<T, T, T, LogicalResult>(context_,
830 ScalarFunc<T, T, T, LogicalResult>(
831 [](
const Scalar<T> &ifTrue,
const Scalar<T> &ifFalse,
832 const Scalar<LogicalResult> &predicate) -> Scalar<T> {
833 return predicate.IsTrue() ? ifTrue : ifFalse;
838 auto args{funcRef.arguments()};
839 CHECK(args.size() == 3);
840 const auto *array{UnwrapConstantValue<T>(args[0])};
841 const auto *vector{UnwrapConstantValue<T>(args[2])};
842 auto convertedMask{Fold(context_,
843 ConvertToType<LogicalResult>(
845 const auto *mask{UnwrapConstantValue<LogicalResult>(convertedMask)};
846 if (!array || !mask || (args[2] && !vector)) {
847 return Expr<T>{std::move(funcRef)};
850 ConstantSubscript arrayElements{GetSize(array->shape())};
851 ConstantSubscript truths{0};
852 ConstantSubscripts maskAt{mask->lbounds()};
853 if (mask->Rank() == 0) {
854 if (mask->At(maskAt).IsTrue()) {
855 truths = arrayElements;
857 }
else if (array->shape() != mask->shape()) {
859 return MakeInvalidIntrinsic(std::move(funcRef));
861 for (ConstantSubscript j{0}; j < arrayElements;
862 ++j, mask->IncrementSubscripts(maskAt)) {
863 if (mask->At(maskAt).IsTrue()) {
868 std::vector<Scalar<T>> resultElements;
869 ConstantSubscripts arrayAt{array->lbounds()};
870 ConstantSubscript resultSize{truths};
872 resultSize = vector->shape().at(0);
873 if (resultSize < truths) {
874 context_.messages().Say(
875 "Invalid 'vector=' argument in PACK: the 'mask=' argument has %jd true elements, but the vector has only %jd elements"_err_en_US,
876 static_cast<std::intmax_t
>(truths),
877 static_cast<std::intmax_t
>(resultSize));
878 return MakeInvalidIntrinsic(std::move(funcRef));
881 for (ConstantSubscript j{0}; j < truths;) {
882 if (mask->At(maskAt).IsTrue()) {
883 resultElements.push_back(array->At(arrayAt));
886 array->IncrementSubscripts(arrayAt);
887 mask->IncrementSubscripts(maskAt);
890 ConstantSubscripts vectorAt{vector->lbounds()};
891 vectorAt.at(0) += truths;
892 for (ConstantSubscript j{truths}; j < resultSize; ++j) {
893 resultElements.push_back(vector->At(vectorAt));
897 return Expr<T>{PackageConstant<T>(std::move(resultElements), *array,
898 ConstantSubscripts{
static_cast<ConstantSubscript
>(resultSize)})};
902 auto args{funcRef.arguments()};
903 CHECK(args.size() == 4);
904 const auto *source{UnwrapConstantValue<T>(args[0])};
905 const auto *pad{UnwrapConstantValue<T>(args[2])};
906 std::optional<std::vector<ConstantSubscript>> shape{
907 GetIntegerVector<ConstantSubscript>(args[1])};
908 std::optional<std::vector<int>> order{GetIntegerVector<int>(args[3])};
909 std::optional<uint64_t> optResultElement;
910 std::optional<std::vector<int>> dimOrder;
913 if (shape->size() > common::maxRank) {
914 context_.messages().Say(
915 "Size of 'shape=' argument (%zd) must not be greater than %d"_err_en_US,
916 shape->size(), common::maxRank);
918 }
else if (HasNegativeExtent(*shape)) {
919 context_.messages().Say(
920 "'shape=' argument (%s) must not have a negative extent"_err_en_US,
921 DEREF(args[1]->UnwrapExpr()).AsFortran());
924 optResultElement = TotalElementCount(*shape);
925 if (!optResultElement) {
926 context_.messages().Say(
927 "'shape=' argument (%s) specifies an array with too many elements"_err_en_US,
928 DEREF(args[1]->UnwrapExpr()).AsFortran());
933 dimOrder = ValidateDimensionOrder(GetRank(*shape), *order);
935 context_.messages().Say(
936 "Invalid 'order=' argument (%s) in RESHAPE"_err_en_US,
937 DEREF(args[3]->UnwrapExpr()).AsFortran());
944 }
else if (!source || !shape || (args[2] && !pad) || (args[3] && !order)) {
945 return Expr<T>{std::move(funcRef)};
947 uint64_t resultElements{*optResultElement};
948 std::vector<int> *dimOrderPtr{dimOrder ? &dimOrder.value() :
nullptr};
949 if (resultElements > source->size() && (!pad || pad->empty())) {
950 context_.messages().Say(
951 "Too few elements in 'source=' argument and 'pad=' "
952 "argument is not present or has null size"_err_en_US);
956 ? source->Reshape(std::move(shape.value()))
957 : pad->Reshape(std::move(shape.value()))};
958 ConstantSubscripts subscripts{result.lbounds()};
959 auto copied{result.CopyFrom(*source,
960 std::min(
static_cast<uint64_t
>(source->size()), resultElements),
961 subscripts, dimOrderPtr)};
962 if (copied < resultElements) {
964 copied += result.CopyFrom(
965 *pad, resultElements - copied, subscripts, dimOrderPtr);
967 CHECK(copied == resultElements);
968 return Expr<T>{std::move(result)};
972 return MakeInvalidIntrinsic(std::move(funcRef));
976 auto args{funcRef.arguments()};
977 CHECK(args.size() == 3);
978 const Constant<T> *source{UnwrapConstantValue<T>(args[0])};
979 auto dim{ToInt64(args[1])};
980 auto ncopies{ToInt64(args[2])};
981 if (!source || !dim) {
982 return Expr<T>{std::move(funcRef)};
984 int sourceRank{source->Rank()};
985 if (sourceRank >= common::maxRank) {
986 context_.messages().Say(
987 "SOURCE= argument to SPREAD has rank %d but must have rank less than %d"_err_en_US,
988 sourceRank, common::maxRank);
989 }
else if (*dim < 1 || *dim > sourceRank + 1) {
990 context_.messages().Say(
991 "DIM=%d argument to SPREAD must be between 1 and %d"_err_en_US, *dim,
993 }
else if (!ncopies) {
994 return Expr<T>{std::move(funcRef)};
1004 ConstantSubscripts shape{source->shape()};
1005 shape.insert(shape.begin() + *dim - 1, *ncopies);
1006 Constant<T> spread{source->Reshape(std::move(shape))};
1007 std::optional<uint64_t> n{TotalElementCount(spread.shape())};
1009 context_.messages().Say(
"Too many elements in SPREAD result"_err_en_US);
1011 std::vector<int> dimOrder;
1012 for (
int j{0}; j < sourceRank; ++j) {
1013 dimOrder.push_back(j < *dim - 1 ? j : j + 1);
1015 dimOrder.push_back(*dim - 1);
1016 ConstantSubscripts at{spread.lbounds()};
1017 spread.CopyFrom(*source, *n, at, &dimOrder);
1018 return Expr<T>{std::move(spread)};
1022 return MakeInvalidIntrinsic(std::move(funcRef));
1026 auto args{funcRef.arguments()};
1027 CHECK(args.size() == 1);
1028 const auto *matrix{UnwrapConstantValue<T>(args[0])};
1030 return Expr<T>{std::move(funcRef)};
1033 std::vector<Scalar<T>> resultElements;
1034 ConstantSubscripts at(2);
1035 for (ConstantSubscript j{0}; j < matrix->shape()[0]; ++j) {
1036 at[0] = matrix->lbounds()[0] + j;
1037 for (ConstantSubscript k{0}; k < matrix->shape()[1]; ++k) {
1038 at[1] = matrix->lbounds()[1] + k;
1039 resultElements.push_back(matrix->At(at));
1042 at = matrix->shape();
1043 std::swap(at[0], at[1]);
1044 return Expr<T>{PackageConstant<T>(std::move(resultElements), *matrix, at)};
1048 auto args{funcRef.arguments()};
1049 CHECK(args.size() == 3);
1050 const auto *vector{UnwrapConstantValue<T>(args[0])};
1051 auto convertedMask{Fold(context_,
1052 ConvertToType<LogicalResult>(
1054 const auto *mask{UnwrapConstantValue<LogicalResult>(convertedMask)};
1055 const auto *field{UnwrapConstantValue<T>(args[2])};
1056 if (!vector || !mask || !field) {
1057 return Expr<T>{std::move(funcRef)};
1060 if (field->Rank() > 0 && field->shape() != mask->shape()) {
1062 return MakeInvalidIntrinsic(std::move(funcRef));
1064 ConstantSubscript maskElements{GetSize(mask->shape())};
1065 ConstantSubscript truths{0};
1066 ConstantSubscripts maskAt{mask->lbounds()};
1067 for (ConstantSubscript j{0}; j < maskElements;
1068 ++j, mask->IncrementSubscripts(maskAt)) {
1069 if (mask->At(maskAt).IsTrue()) {
1073 if (truths > GetSize(vector->shape())) {
1074 context_.messages().Say(
1075 "Invalid 'vector=' argument in UNPACK: the 'mask=' argument has %jd true elements, but the vector has only %jd elements"_err_en_US,
1076 static_cast<std::intmax_t
>(truths),
1077 static_cast<std::intmax_t
>(GetSize(vector->shape())));
1078 return MakeInvalidIntrinsic(std::move(funcRef));
1080 std::vector<Scalar<T>> resultElements;
1081 ConstantSubscripts vectorAt{vector->lbounds()};
1082 ConstantSubscripts fieldAt{field->lbounds()};
1083 for (ConstantSubscript j{0}; j < maskElements; ++j) {
1084 if (mask->At(maskAt).IsTrue()) {
1085 resultElements.push_back(vector->At(vectorAt));
1086 vector->IncrementSubscripts(vectorAt);
1088 resultElements.push_back(field->At(fieldAt));
1090 mask->IncrementSubscripts(maskAt);
1091 field->IncrementSubscripts(fieldAt);
1094 PackageConstant<T>(std::move(resultElements), *vector, mask->shape())};
1097std::optional<Expr<SomeType>> FoldTransfer(
1101 if (
auto folded{FoldTransfer(context_, funcRef.arguments())}) {
1102 return DEREF(UnwrapExpr<
Expr<T>>(*folded));
1104 return Expr<T>{std::move(funcRef)};
1110template <
typename T>
1113 static_assert(T::category == TypeCategory::Integer ||
1114 T::category == TypeCategory::Unsigned ||
1115 T::category == TypeCategory::Real ||
1116 T::category == TypeCategory::Character);
1139 auto &args{funcRef.arguments()};
1140 std::size_t nargs{args.size()};
1141 bool allArgsConstant{
true};
1142 bool extremumAnyway{nargs == 2 && T::category != TypeCategory::Character};
1146 if (!folder.Folding(args[0])) {
1147 allArgsConstant =
false;
1149 if (!folder.Folding(args[1])) {
1150 allArgsConstant =
false;
1156 for (std::size_t i{2}; i < nargs; ++i) {
1158 if (!folder.Folding(args[i])) {
1159 allArgsConstant =
false;
1167 if (allArgsConstant || extremumAnyway) {
1170 if (
const auto *resultp{UnwrapExpr<Expr<T>>(args[0])}) {
1172 for (std::size_t i{1}; i < nargs; ++i) {
1173 if (
const auto *tExpr{UnwrapExpr<Expr<T>>(args[i])}) {
1174 result = FoldOperation(
1175 context,
Extremum<T>{order, std::move(result), *tExpr});
1178 return Expr<T>{std::move(funcRef)};
1186 return Expr<T>{std::move(funcRef)};
1196template <
typename T>
1197Expr<T> RewriteSpecificMINorMAX(
1199 ActualArguments &args{funcRef.arguments()};
1200 auto &intrinsic{DEREF(std::get_if<SpecificIntrinsic>(&funcRef.proc().u))};
1203 std::optional<DynamicType> resultType;
1205 for (
auto j{args.size()}; j-- > 0;) {
1212 (type.category() == resultType->category() &&
1213 type.kind() > resultType->kind()) ||
1214 resultType->category() == TypeCategory::Integer) {
1216 resultTypeArg = &*args[j];
1221 return Expr<T>{std::move(funcRef)};
1224 intrinsic.name.find(
"max") != std::string::npos ?
"max"s :
"min"s;
1225 intrinsic.characteristics.value().functionResult.value().SetType(*resultType);
1226 auto insertConversion{[&](
const auto &x) ->
Expr<T> {
1227 using TR = ResultType<
decltype(x)>;
1230 return Fold(context, ConvertToType<T>(AsCategoryExpr(std::move(maxRef))));
1232 if (
auto *sx{UnwrapExpr<Expr<SomeReal>>(*resultTypeArg)}) {
1233 return common::visit(insertConversion, sx->u);
1234 }
else if (
auto *sx{UnwrapExpr<Expr<SomeInteger>>(*resultTypeArg)}) {
1235 return common::visit(insertConversion, sx->u);
1237 return Expr<T>{std::move(funcRef)};
1265 ActualArguments &args{funcRef.arguments()};
1267 if (args.size() >= 2 && args[1]) {
1270 auto *expr{args.size() >= 1 && args[0]
1271 ? UnwrapExpr<Expr<SomeDerived>>(args[0])
1276 const auto *derived{GetEnumerationTypeSpec(expr->GetType())};
1277 const semantics::Scope *scope{derived ? derived->GetScope() :
nullptr};
1281 auto ordIter{scope->find(
1282 semantics::SourceName{semantics::DerivedTypeDetails::ordinalComponentName,
1283 sizeof(semantics::DerivedTypeDetails::ordinalComponentName) - 1})};
1284 if (ordIter == scope->end()) {
1287 const semantics::Symbol &ordSym{*ordIter->second};
1288 int count{derived->typeSymbol()
1290 .get<semantics::DerivedTypeDetails>()
1291 .enumeratorCount()};
1292 auto *constant{UnwrapConstantValue<SomeDerived>(*expr)};
1305 if (context.inConstantContext()) {
1306 context.messages().Say(isNext
1307 ?
"NEXT() of the last enumerator is out of range"_err_en_US
1308 :
"PREVIOUS() of the first enumerator is out of range"_err_en_US);
1312 context.messages().Say(isNext
1313 ?
"NEXT() at the last enumerator is not yet supported"_err_en_US
1314 :
"PREVIOUS() at the first enumerator is not yet supported"_err_en_US);
1316 return MakeInvalidIntrinsic<SomeDerived>(std::move(funcRef));
1318 if (
auto sc{constant->GetScalarValue()}) {
1319 if (
auto ordExpr{sc->Find(ordSym)}) {
1320 if (
auto ordVal{ToInt64(*ordExpr)}) {
1321 if (isNext ? *ordVal >= count : *ordVal <= 1) {
1322 return handleBoundary();
1324 int newOrd{isNext ?
static_cast<int>(*ordVal + 1)
1325 : static_cast<int>(*ordVal - 1)};
1332 }
else if (constant->Rank() > 0) {
1350 std::vector<StructureConstructor> elements;
1351 elements.reserve(constant->values().size());
1352 for (
const StructureConstructorValues &scv : constant->values()) {
1353 auto ordVal{ToInt64(scv.find(ordSym)->second.value())};
1354 if (isNext ? *ordVal >= count : *ordVal <= 1) {
1355 return handleBoundary();
1357 int newOrd{isNext ?
static_cast<int>(*ordVal + 1)
1358 : static_cast<int>(*ordVal - 1)};
1362 elements.emplace_back(std::move(ctor));
1365 *derived, std::move(elements), ConstantSubscripts{constant->shape()}}};
1370template <
typename T>
1372 ActualArguments &args{funcRef.arguments()};
1373 const auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
1374 if (!intrinsic || intrinsic->name !=
"kind") {
1377 for (std::optional<ActualArgument> &arg : args) {
1378 if (arg && arg->GetConditionalArg()) {
1379 FoldConditionalArg(context, arg);
1380 }
else if (
auto *expr{UnwrapExpr<Expr<SomeType>>(arg)}) {
1381 if (!intrinsic && IsNamedConstantDesignator(*expr)) {
1391 *expr = Fold(context, std::move(*expr));
1431 for (
const std::optional<ActualArgument> &arg : args) {
1432 if (arg && arg->isConditionalArg()) {
1433 return Expr<T>{std::move(funcRef)};
1436 const std::string name{intrinsic->name};
1437 if (name ==
"cshift") {
1438 return Folder<T>{context}.CSHIFT(std::move(funcRef));
1439 }
else if (name ==
"eoshift") {
1440 return Folder<T>{context}.EOSHIFT(std::move(funcRef));
1441 }
else if (name ==
"merge") {
1442 return Folder<T>{context}.MERGE(std::move(funcRef));
1443 }
else if (name ==
"pack") {
1444 return Folder<T>{context}.PACK(std::move(funcRef));
1445 }
else if (name ==
"reshape") {
1446 return Folder<T>{context}.RESHAPE(std::move(funcRef));
1447 }
else if (name ==
"spread") {
1448 return Folder<T>{context}.SPREAD(std::move(funcRef));
1449 }
else if (name ==
"transfer") {
1450 return Folder<T>{context}.TRANSFER(std::move(funcRef));
1451 }
else if (name ==
"transpose") {
1452 return Folder<T>{context}.TRANSPOSE(std::move(funcRef));
1453 }
else if (name ==
"unpack") {
1454 return Folder<T>{context}.UNPACK(std::move(funcRef));
1457 if constexpr (std::is_same_v<T, SomeDerived>) {
1460 if (name ==
"huge") {
1462 if (args.size() >= 1 && args[0]) {
1463 if (
auto *expr{UnwrapExpr<Expr<SomeDerived>>(args[0])}) {
1464 return std::move(*expr);
1467 }
else if (name ==
"next" || name ==
"previous") {
1468 return FoldEnumerationNextOrPrevious(
1469 context, std::move(funcRef), name ==
"next");
1472 return FoldIntrinsicFunction(context, std::move(funcRef));
1475 return Expr<T>{std::move(funcRef)};
1479template <
typename T>
class ArrayConstructorFolder {
1481 explicit ArrayConstructorFolder(
FoldingContext &c) : context_{c} {}
1484 if constexpr (T::category == TypeCategory::Character) {
1485 if (
const auto *len{array.LEN()}) {
1486 charLength_ = ToInt64(Fold(context_, common::Clone(*len)));
1487 knownCharLength_ = charLength_.has_value();
1491 if (FoldArray(array)) {
1492 auto n{
static_cast<ConstantSubscript
>(elements_.size())};
1493 if constexpr (std::is_same_v<T, SomeDerived>) {
1495 std::move(elements_), ConstantSubscripts{n}}};
1496 }
else if constexpr (T::category == TypeCategory::Character) {
1499 *charLength_, std::move(elements_), ConstantSubscripts{n}}};
1503 std::move(elements_), ConstantSubscripts{n}, resultInfo_}};
1506 return Expr<T>{std::move(array)};
1510 bool FoldArray(
const Expr<T> &expr) {
1511 Expr<T> folded{Fold(context_, common::Clone(expr))};
1512 if (
const auto *c{UnwrapConstantValue<T>(folded)}) {
1515 ConstantSubscripts index{c->lbounds()};
1517 elements_.emplace_back(c->At(index));
1518 }
while (c->IncrementSubscripts(index));
1520 if constexpr (T::category == TypeCategory::Character) {
1521 if (!knownCharLength_) {
1522 charLength_ = std::max(c->LEN(), charLength_.value_or(-1));
1524 }
else if constexpr (T::category == TypeCategory::Real ||
1525 T::category == TypeCategory::Complex) {
1526 if (c->result().isFromInexactLiteralConversion()) {
1527 resultInfo_.set_isFromInexactLiteralConversion();
1535 bool FoldArray(
const common::CopyableIndirection<
Expr<T>> &expr) {
1536 return FoldArray(expr.value());
1545 std::optional<ConstantSubscript> start{ToInt64(
lower)}, end{ToInt64(upper)},
1546 step{ToInt64(stride)};
1547 if (start && end && step && *step != 0) {
1549 ConstantSubscript &j{context_.StartImpliedDo(iDo.name(), *start)};
1551 for (; j <= *end; j += *step) {
1552 result &= FoldArray(iDo.values());
1555 for (; j >= *end; j += *step) {
1556 result &= FoldArray(iDo.values());
1559 context_.EndImpliedDo(iDo.name());
1566 return common::visit([&](
const auto &y) {
return FoldArray(y); }, x.u);
1569 for (
const auto &x : xs) {
1570 if (!FoldArray(x)) {
1578 std::vector<Scalar<T>> elements_;
1579 std::optional<ConstantSubscript> charLength_;
1580 bool knownCharLength_{
false};
1581 typename Constant<T>::Result resultInfo_;
1584template <
typename T>
1597template <
typename T>
1598bool ArrayConstructorIsFlat(
const ArrayConstructorValues<T> &values) {
1599 for (
const ArrayConstructorValue<T> &x : values) {
1600 if (!std::holds_alternative<Expr<T>>(x.u)) {
1607template <
typename T>
1608std::optional<Expr<T>> AsFlatArrayConstructor(
const Expr<T> &expr) {
1609 if (
const auto *c{UnwrapConstantValue<T>(expr)}) {
1612 ConstantSubscripts at{c->lbounds()};
1615 }
while (c->IncrementSubscripts(at));
1617 return std::make_optional<Expr<T>>(std::move(result));
1618 }
else if (
const auto *a{UnwrapExpr<ArrayConstructor<T>>(expr)}) {
1619 if (ArrayConstructorIsFlat(*a)) {
1620 return std::make_optional<Expr<T>>(expr);
1622 }
else if (
const auto *p{UnwrapExpr<Parentheses<T>>(expr)}) {
1623 return AsFlatArrayConstructor(
Expr<T>{p->left()});
1625 return std::nullopt;
1628template <TypeCategory CAT>
1629std::enable_if_t<CAT != TypeCategory::Derived,
1630 std::optional<Expr<SomeKind<CAT>>>>
1632 return common::visit(
1634 if (
auto flattened{AsFlatArrayConstructor(kindExpr)}) {
1637 return std::nullopt;
1647template <
typename T>
1648std::optional<Expr<T>> FromArrayConstructor(
1650 if (
auto constShape{AsConstantExtents(context, shape)};
1651 constShape && !HasNegativeExtent(*constShape)) {
1653 if (
auto *constant{UnwrapConstantValue<T>(result)}) {
1655 return Expr<T>{constant->Reshape(std::move(*constShape))};
1657 if (constShape->size() == 1) {
1658 if (
auto elements{GetShape(context, result)}) {
1659 if (
auto constElements{AsConstantExtents(context, *elements)}) {
1660 if (constElements->size() == 1 &&
1661 constElements->at(0) == constShape->at(0)) {
1664 return std::move(result);
1670 return std::nullopt;
1681template <
typename RESULT,
typename OPERAND>
1687 if constexpr (common::HasMember<OPERAND, AllIntrinsicCategoryTypes>) {
1689 [&](
auto &&kindExpr) {
1690 using kindType = ResultType<
decltype(kindExpr)>;
1691 auto &aConst{std::get<ArrayConstructor<kindType>>(kindExpr.u)};
1692 for (
auto &acValue : aConst) {
1693 auto &scalar{std::get<Expr<kindType>>(acValue.u)};
1694 result.Push(Fold(context, f(
Expr<OPERAND>{std::move(scalar)})));
1697 std::move(values.u));
1699 auto &aConst{std::get<ArrayConstructor<OPERAND>>(values.u)};
1700 for (
auto &acValue : aConst) {
1701 auto &scalar{std::get<Expr<OPERAND>>(acValue.u)};
1702 result.Push(Fold(context, f(std::move(scalar))));
1705 if constexpr (RESULT::category == TypeCategory::Character) {
1707 result.set_LEN(std::move(*length));
1710 return FromArrayConstructor(context, std::move(result), shape);
1713template <
typename RESULT,
typename A>
1717 if constexpr (RESULT::category == TypeCategory::Character) {
1719 result.set_LEN(std::move(*length));
1725template <
typename LEFT,
typename RIGHT>
1729 auto rightIter{rightArrConst.begin()};
1730 for (
auto &leftValue : leftArrConst) {
1731 CHECK(rightIter != rightArrConst.end());
1732 auto &leftExpr{std::get<Expr<LEFT>>(leftValue.u)};
1733 auto &rightExpr{std::get<Expr<RIGHT>>(rightIter->u)};
1734 if (leftExpr.Rank() != rightExpr.Rank()) {
1737 std::optional<Shape> leftShape{GetShape(context, leftExpr)};
1738 std::optional<Shape> rightShape{GetShape(context, rightExpr)};
1739 if (!leftShape || !rightShape || *leftShape != *rightShape) {
1748template <
typename RESULT,
typename LEFT,
typename RIGHT>
1753 -> std::optional<Expr<RESULT>> {
1754 auto result{ArrayConstructorFromMold<RESULT>(leftValues, std::move(length))};
1755 auto &leftArrConst{std::get<ArrayConstructor<LEFT>>(leftValues.u)};
1756 if constexpr (common::HasMember<RIGHT, AllIntrinsicCategoryTypes>) {
1757 bool mapped{common::visit(
1758 [&](
auto &&kindExpr) ->
bool {
1759 using kindType = ResultType<
decltype(kindExpr)>;
1761 auto &rightArrConst{std::get<ArrayConstructor<kindType>>(kindExpr.u)};
1762 if (!ShapesMatch(context, leftArrConst, rightArrConst)) {
1765 auto rightIter{rightArrConst.begin()};
1766 for (
auto &leftValue : leftArrConst) {
1767 CHECK(rightIter != rightArrConst.end());
1768 auto &leftScalar{std::get<Expr<LEFT>>(leftValue.u)};
1769 auto &rightScalar{std::get<Expr<kindType>>(rightIter->u)};
1770 result.Push(Fold(context,
1771 f(std::move(leftScalar),
Expr<RIGHT>{std::move(rightScalar)})));
1776 std::move(rightValues.u))};
1778 return std::nullopt;
1781 auto &rightArrConst{std::get<ArrayConstructor<RIGHT>>(rightValues.u)};
1782 if (!ShapesMatch(context, leftArrConst, rightArrConst)) {
1783 return std::nullopt;
1785 auto rightIter{rightArrConst.begin()};
1786 for (
auto &leftValue : leftArrConst) {
1787 CHECK(rightIter != rightArrConst.end());
1788 auto &leftScalar{std::get<Expr<LEFT>>(leftValue.u)};
1789 auto &rightScalar{std::get<Expr<RIGHT>>(rightIter->u)};
1791 Fold(context, f(std::move(leftScalar), std::move(rightScalar))));
1795 return FromArrayConstructor(context, std::move(result), shape);
1799template <
typename RESULT,
typename LEFT,
typename RIGHT>
1804 -> std::optional<Expr<RESULT>> {
1805 auto result{ArrayConstructorFromMold<RESULT>(leftValues, std::move(length))};
1806 auto &leftArrConst{std::get<ArrayConstructor<LEFT>>(leftValues.u)};
1807 for (
auto &leftValue : leftArrConst) {
1808 auto &leftScalar{std::get<Expr<LEFT>>(leftValue.u)};
1810 Fold(context, f(std::move(leftScalar),
Expr<RIGHT>{rightScalar})));
1812 return FromArrayConstructor(context, std::move(result), shape);
1816template <
typename RESULT,
typename LEFT,
typename RIGHT>
1821 -> std::optional<Expr<RESULT>> {
1822 auto result{ArrayConstructorFromMold<RESULT>(leftScalar, std::move(length))};
1823 if constexpr (common::HasMember<RIGHT, AllIntrinsicCategoryTypes>) {
1825 [&](
auto &&kindExpr) {
1826 using kindType = ResultType<
decltype(kindExpr)>;
1827 auto &rightArrConst{std::get<ArrayConstructor<kindType>>(kindExpr.u)};
1828 for (
auto &rightValue : rightArrConst) {
1829 auto &rightScalar{std::get<Expr<kindType>>(rightValue.u)};
1830 result.Push(Fold(context,
1835 std::move(rightValues.u));
1837 auto &rightArrConst{std::get<ArrayConstructor<RIGHT>>(rightValues.u)};
1838 for (
auto &rightValue : rightArrConst) {
1839 auto &rightScalar{std::get<Expr<RIGHT>>(rightValue.u)};
1841 Fold(context, f(
Expr<LEFT>{leftScalar}, std::move(rightScalar))));
1844 return FromArrayConstructor(context, std::move(result), shape);
1847template <
typename DERIVED,
typename RESULT,
typename... OPD>
1848std::optional<Expr<SubscriptInteger>> ComputeResultLength(
1850 if constexpr (RESULT::category == TypeCategory::Character) {
1853 return std::nullopt;
1860template <
typename DERIVED,
typename RESULT,
typename OPERAND>
1864 -> std::optional<Expr<RESULT>> {
1865 auto &expr{operation.left()};
1866 expr = Fold(context, std::move(expr));
1867 if (expr.Rank() > 0) {
1868 if (std::optional<Shape> shape{GetShape(context, expr)}) {
1869 if (
auto values{AsFlatArrayConstructor(expr)}) {
1870 return MapOperation(context, std::move(f), *shape,
1871 ComputeResultLength(operation), std::move(*values));
1875 return std::nullopt;
1878template <
typename DERIVED,
typename RESULT,
typename OPERAND>
1879auto ApplyElementwise(
1881 -> std::optional<Expr<RESULT>> {
1882 return ApplyElementwise(context, operation,
1889template <
typename DERIVED,
typename RESULT,
typename LEFT,
typename RIGHT>
1893 -> std::optional<Expr<RESULT>> {
1894 auto resultLength{ComputeResultLength(operation)};
1895 auto &leftExpr{operation.left()};
1896 auto &rightExpr{operation.right()};
1897 if (leftExpr.Rank() != rightExpr.Rank() && leftExpr.Rank() != 0 &&
1898 rightExpr.Rank() != 0) {
1899 return std::nullopt;
1901 leftExpr = Fold(context, std::move(leftExpr));
1902 rightExpr = Fold(context, std::move(rightExpr));
1903 if (leftExpr.Rank() > 0) {
1904 if (std::optional<Shape> leftShape{GetShape(context, leftExpr)}) {
1905 if (
auto left{AsFlatArrayConstructor(leftExpr)}) {
1906 if (rightExpr.Rank() > 0) {
1907 if (std::optional<Shape> rightShape{GetShape(context, rightExpr)}) {
1908 if (
auto right{AsFlatArrayConstructor(rightExpr)}) {
1909 if (CheckConformance(context.messages(), *leftShape, *rightShape,
1910 CheckConformanceFlags::EitherScalarExpandable)
1911 .value_or(
false )) {
1912 return MapOperation(context, std::move(f), *leftShape,
1913 std::move(resultLength), std::move(*left),
1916 return std::nullopt;
1918 return MapOperation(context, std::move(f), *leftShape,
1919 std::move(resultLength), std::move(*left), std::move(*right));
1922 }
else if (IsExpandableScalar(rightExpr, context, *leftShape)) {
1923 return MapOperation(context, std::move(f), *leftShape,
1924 std::move(resultLength), std::move(*left), rightExpr);
1928 }
else if (rightExpr.Rank() > 0) {
1929 if (std::optional<Shape> rightShape{GetShape(context, rightExpr)}) {
1930 if (IsExpandableScalar(leftExpr, context, *rightShape)) {
1931 if (
auto right{AsFlatArrayConstructor(rightExpr)}) {
1932 return MapOperation(context, std::move(f), *rightShape,
1933 std::move(resultLength), leftExpr, std::move(*right));
1938 return std::nullopt;
1941template <
typename DERIVED,
typename RESULT,
typename LEFT,
typename RIGHT>
1942auto ApplyElementwise(
1944 -> std::optional<Expr<RESULT>> {
1945 return ApplyElementwise(context, operation,
1948 return Expr<RESULT>{DERIVED{std::move(left), std::move(right)}};
1954template <
typename TO,
typename FROM>
1955common::IfNoLvalue<std::optional<TO>, FROM> ConvertString(FROM &&s) {
1956 if constexpr (std::is_same_v<TO, FROM>) {
1957 return std::make_optional<TO>(std::move(s));
1962 for (
auto iter{s.cbegin()}; iter != s.cend(); ++iter) {
1963 if (
static_cast<std::uint64_t
>(*iter) > 127) {
1964 return std::nullopt;
1966 str.push_back(
static_cast<typename TO::value_type
>(*iter));
1968 return std::make_optional<TO>(std::move(str));
1972template <
typename TO, TypeCategory FROMCAT>
1975 if (
auto array{ApplyElementwise(context, convert)}) {
1981 } msvcWorkaround{context, convert};
1982 return common::visit(
1983 [&msvcWorkaround](
auto &kindExpr) ->
Expr<TO> {
1984 using Operand = ResultType<
decltype(kindExpr)>;
1987 TypeCategory
constexpr FromCat{FROMCAT};
1988 static_assert(FromCat == Operand::category);
1989 auto &convert{msvcWorkaround.convert};
1990 if (
auto value{GetScalarConstantValue<Operand>(kindExpr)}) {
1992 if constexpr (TO::category == TypeCategory::Integer) {
1993 if constexpr (FromCat == TypeCategory::Integer) {
1994 auto converted{Scalar<TO>::ConvertSigned(*value)};
1995 if (converted.overflow) {
1996 ctx.Warn(common::UsageWarning::FoldingException,
1997 "conversion of %s_%d to INTEGER(%d) overflowed; result is %s"_warn_en_US,
1998 value->SignedDecimal(), Operand::kind, TO::kind,
1999 converted.value.SignedDecimal());
2001 return ScalarConstantToExpr(std::move(converted.value));
2002 }
else if constexpr (FromCat == TypeCategory::Unsigned) {
2003 auto converted{Scalar<TO>::ConvertUnsigned(*value)};
2004 if ((converted.overflow || converted.value.IsNegative())) {
2005 ctx.Warn(common::UsageWarning::FoldingException,
2006 "conversion of %s_U%d to INTEGER(%d) overflowed; result is %s"_warn_en_US,
2007 value->UnsignedDecimal(), Operand::kind, TO::kind,
2008 converted.value.SignedDecimal());
2010 return ScalarConstantToExpr(std::move(converted.value));
2011 }
else if constexpr (FromCat == TypeCategory::Real) {
2012 auto converted{value->template ToInteger<Scalar<TO>>()};
2013 if (converted.flags.test(RealFlag::InvalidArgument)) {
2014 ctx.Warn(common::UsageWarning::FoldingException,
2015 "REAL(%d) to INTEGER(%d) conversion: invalid argument"_warn_en_US,
2016 Operand::kind, TO::kind);
2017 }
else if (converted.flags.test(RealFlag::Overflow)) {
2018 ctx.Warn(common::UsageWarning::FoldingException,
2019 "REAL(%d) to INTEGER(%d) conversion overflowed"_warn_en_US,
2020 Operand::kind, TO::kind);
2022 return ScalarConstantToExpr(std::move(converted.value));
2024 }
else if constexpr (TO::category == TypeCategory::Unsigned) {
2025 if constexpr (FromCat == TypeCategory::Integer ||
2026 FromCat == TypeCategory::Unsigned) {
2028 Constant<TO>{Scalar<TO>::ConvertUnsigned(*value).value}};
2029 }
else if constexpr (FromCat == TypeCategory::Real) {
2031 Constant<TO>{value->template ToInteger<Scalar<TO>>().value}};
2033 }
else if constexpr (TO::category == TypeCategory::Real) {
2034 if constexpr (FromCat == TypeCategory::Integer ||
2035 FromCat == TypeCategory::Unsigned) {
2036 auto converted{Scalar<TO>::FromInteger(
2037 *value, FromCat == TypeCategory::Unsigned)};
2038 if (!converted.flags.empty()) {
2040 std::snprintf(buffer,
sizeof buffer,
2041 "INTEGER(%d) to REAL(%d) conversion", Operand::kind,
2043 ctx.RealFlagWarnings(converted.flags, buffer);
2045 return ScalarConstantToExpr(std::move(converted.value));
2046 }
else if constexpr (FromCat == TypeCategory::Real) {
2047 auto converted{Scalar<TO>::Convert(*value)};
2049 if (!converted.flags.empty()) {
2050 std::snprintf(buffer,
sizeof buffer,
2051 "REAL(%d) to REAL(%d) conversion", Operand::kind, TO::kind);
2052 ctx.RealFlagWarnings(converted.flags, buffer);
2054 if (ctx.targetCharacteristics().areSubnormalsFlushedToZero()) {
2055 converted.value = converted.value.FlushSubnormalToZero();
2057 return ScalarConstantToExpr(std::move(converted.value));
2059 }
else if constexpr (TO::category == TypeCategory::Complex) {
2060 if constexpr (FromCat == TypeCategory::Complex) {
2061 return FoldOperation(ctx,
2068 }
else if constexpr (TO::category == TypeCategory::Character &&
2069 FromCat == TypeCategory::Character) {
2070 if (
auto converted{ConvertString<Scalar<TO>>(std::move(*value))}) {
2071 return ScalarConstantToExpr(std::move(*converted));
2073 }
else if constexpr (TO::category == TypeCategory::Logical &&
2074 FromCat == TypeCategory::Logical) {
2077 }
else if constexpr (TO::category == FromCat &&
2078 FromCat != TypeCategory::Character) {
2080 if constexpr (std::is_same_v<Operand, TO>) {
2081 return std::move(kindExpr);
2082 }
else if constexpr (TO::category == TypeCategory::Logical ||
2083 TO::category == TypeCategory::Integer) {
2084 if (
auto *innerConv{
2085 std::get_if<Convert<Operand, TO::category>>(&kindExpr.u)}) {
2087 if (
auto *x{std::get_if<Expr<TO>>(&innerConv->left().u)}) {
2088 if constexpr (TO::category == TypeCategory::Logical ||
2089 TO::kind <= Operand::kind) {
2090 return std::move(*x);
2092 }
else if constexpr (std::is_same_v<TO,
2093 DescriptorInquiry::Result>) {
2094 if (std::holds_alternative<DescriptorInquiry>(x->u) ||
2095 std::holds_alternative<TypeParamInquiry>(x->u)) {
2097 return std::move(*x);
2104 return Expr<TO>{std::move(convert)};
2109template <
typename T>
2111 auto &operand{x.left()};
2112 operand = Fold(context, std::move(operand));
2113 if (
auto value{GetScalarConstantValue<T>(operand)}) {
2118 return std::move(operand);
2124template <
typename T>
2126 if (
auto array{ApplyElementwise(context, x)}) {
2129 auto &operand{x.left()};
2130 if (
auto *nn{std::get_if<Negate<T>>(&x.left().u)}) {
2132 if (IsVariable(nn->left())) {
2133 return FoldOperation(context,
Parentheses<T>{std::move(nn->left())});
2135 return std::move(nn->left());
2137 }
else if (
auto value{GetScalarConstantValue<T>(operand)}) {
2138 if constexpr (T::category == TypeCategory::Integer) {
2139 auto negated{value->Negate()};
2140 if (negated.overflow) {
2141 context.Warn(common::UsageWarning::FoldingException,
2142 "INTEGER(%d) negation overflowed"_warn_en_US, T::kind);
2145 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2157template <
typename LEFT,
typename RIGHT>
2158std::optional<std::pair<Scalar<LEFT>, Scalar<RIGHT>>> OperandsAreConstants(
2160 if (
auto xvalue{GetScalarConstantValue<LEFT>(x)}) {
2161 if (
auto yvalue{GetScalarConstantValue<RIGHT>(y)}) {
2162 return {std::make_pair(*xvalue, *yvalue)};
2165 return std::nullopt;
2168template <
typename DERIVED,
typename RESULT,
typename LEFT,
typename RIGHT>
2169std::optional<std::pair<Scalar<LEFT>, Scalar<RIGHT>>> OperandsAreConstants(
2171 return OperandsAreConstants(operation.left(), operation.right());
2174template <
typename T>
2176 if (
auto array{ApplyElementwise(context, x)}) {
2179 if (
auto folded{OperandsAreConstants(x)}) {
2180 if constexpr (T::category == TypeCategory::Integer) {
2181 auto sum{folded->first.AddSigned(folded->second)};
2183 context.Warn(common::UsageWarning::FoldingException,
2184 "INTEGER(%d) addition overflowed"_warn_en_US, T::kind);
2187 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2189 Constant<T>{folded->first.AddUnsigned(folded->second).value}};
2191 auto sum{folded->first.Add(
2192 folded->second, context.targetCharacteristics().roundingMode())};
2193 context.RealFlagWarnings(sum.flags,
"addition");
2194 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2195 sum.value = sum.value.FlushSubnormalToZero();
2199 }
else if constexpr (T::category == TypeCategory::Integer ||
2200 T::category == TypeCategory::Unsigned) {
2201 if (
auto c{GetScalarConstantValue<T>(x.right())}) {
2202 if (c->IsZero() && x.left().Rank() == 0) {
2203 if (IsVariable(x.left())) {
2204 return FoldOperation(context,
Parentheses<T>{std::move(x.left())});
2206 return std::move(x.left());
2209 }
else if (
auto c{GetScalarConstantValue<T>(x.left())}) {
2210 if (c->IsZero() && x.right().Rank() == 0) {
2211 if (IsVariable(x.right())) {
2212 return FoldOperation(context,
Parentheses<T>{std::move(x.right())});
2214 return std::move(x.right());
2222template <
typename T>
2224 if (
auto array{ApplyElementwise(context, x)}) {
2227 if (
auto folded{OperandsAreConstants(x)}) {
2228 if constexpr (T::category == TypeCategory::Integer) {
2229 auto difference{folded->first.SubtractSigned(folded->second)};
2230 if (difference.overflow) {
2231 context.Warn(common::UsageWarning::FoldingException,
2232 "INTEGER(%d) subtraction overflowed"_warn_en_US, T::kind);
2235 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2237 Constant<T>{folded->first.SubtractSigned(folded->second).value}};
2239 auto difference{folded->first.Subtract(
2240 folded->second, context.targetCharacteristics().roundingMode())};
2241 context.RealFlagWarnings(difference.flags,
"subtraction");
2242 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2243 difference.value = difference.value.FlushSubnormalToZero();
2247 }
else if constexpr (T::category == TypeCategory::Integer ||
2248 T::category == TypeCategory::Unsigned) {
2249 if (
auto c{GetScalarConstantValue<T>(x.right())}) {
2250 if (c->IsZero() && x.left().Rank() == 0) {
2251 if (IsVariable(x.left())) {
2252 return FoldOperation(context,
Parentheses<T>{std::move(x.left())});
2254 return std::move(x.left());
2262template <
typename T>
2264 if (
auto array{ApplyElementwise(context, x)}) {
2267 if (
auto folded{OperandsAreConstants(x)}) {
2268 if constexpr (T::category == TypeCategory::Integer) {
2269 auto product{folded->first.MultiplySigned(folded->second)};
2270 if (product.SignedMultiplicationOverflowed()) {
2271 context.Warn(common::UsageWarning::FoldingException,
2272 "INTEGER(%d) multiplication overflowed"_warn_en_US, T::kind);
2275 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2277 Constant<T>{folded->first.MultiplyUnsigned(folded->second).lower}};
2279 auto product{folded->first.Multiply(
2280 folded->second, context.targetCharacteristics().roundingMode())};
2281 context.RealFlagWarnings(product.flags,
"multiplication");
2282 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2283 product.value = product.value.FlushSubnormalToZero();
2287 }
else if constexpr (T::category == TypeCategory::Integer) {
2288 if (
auto c{GetScalarConstantValue<T>(x.right())}) {
2289 x.right() = std::move(x.left());
2290 x.left() =
Expr<T>{std::move(*c)};
2292 if (
auto c{GetScalarConstantValue<T>(x.left())}) {
2293 if (c->IsZero() && x.right().Rank() == 0) {
2294 return std::move(x.left());
2295 }
else if (c->CompareSigned(Scalar<T>{1}) == Ordering::Equal) {
2296 if (IsVariable(x.right())) {
2297 return FoldOperation(context,
Parentheses<T>{std::move(x.right())});
2299 return std::move(x.right());
2301 }
else if (c->CompareSigned(Scalar<T>{-1}) == Ordering::Equal) {
2302 return FoldOperation(context,
Negate<T>{std::move(x.right())});
2309template <
typename T>
2311 if (
auto array{ApplyElementwise(context, x)}) {
2314 if (
auto folded{OperandsAreConstants(x)}) {
2315 if constexpr (T::category == TypeCategory::Integer) {
2316 auto quotAndRem{folded->first.DivideSigned(folded->second)};
2317 if (quotAndRem.divisionByZero) {
2318 context.Warn(common::UsageWarning::FoldingException,
2319 "INTEGER(%d) division by zero"_warn_en_US, T::kind);
2322 if (quotAndRem.overflow) {
2323 context.Warn(common::UsageWarning::FoldingException,
2324 "INTEGER(%d) division overflowed"_warn_en_US, T::kind);
2327 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2328 auto quotAndRem{folded->first.DivideUnsigned(folded->second)};
2329 if (quotAndRem.divisionByZero) {
2330 context.Warn(common::UsageWarning::FoldingException,
2331 "UNSIGNED(%d) division by zero"_warn_en_US, T::kind);
2336 auto quotient{folded->first.Divide(
2337 folded->second, context.targetCharacteristics().roundingMode())};
2341 bool isCanonicalNaNOrInf{
false};
2342 if constexpr (T::category == TypeCategory::Real) {
2343 if (folded->second.IsZero() && context.moduleFileName().has_value()) {
2344 using IntType =
typename T::Scalar::Word;
2345 auto intNumerator{folded->first.template ToInteger<IntType>()};
2346 isCanonicalNaNOrInf = intNumerator.flags == RealFlags{} &&
2347 intNumerator.value >= IntType{-1} &&
2348 intNumerator.value <= IntType{1};
2351 if (!isCanonicalNaNOrInf) {
2352 context.RealFlagWarnings(quotient.flags,
"division");
2354 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2355 quotient.value = quotient.value.FlushSubnormalToZero();
2363template <
typename T>
2365 if (
auto array{ApplyElementwise(context, x)}) {
2368 if (
auto folded{OperandsAreConstants(x)}) {
2369 if constexpr (T::category == TypeCategory::Integer) {
2370 auto power{folded->first.Power(folded->second)};
2371 if (power.divisionByZero) {
2372 context.Warn(common::UsageWarning::FoldingException,
2373 "INTEGER(%d) zero to negative power"_warn_en_US, T::kind);
2374 }
else if (power.overflow) {
2375 context.Warn(common::UsageWarning::FoldingException,
2376 "INTEGER(%d) power overflowed"_warn_en_US, T::kind);
2377 }
else if (power.zeroToZero) {
2378 context.Warn(common::UsageWarning::FoldingException,
2379 "INTEGER(%d) 0**0 is not defined"_warn_en_US, T::kind);
2383 if (folded->first.IsZero()) {
2384 if (folded->second.IsZero()) {
2385 context.Warn(common::UsageWarning::FoldingException,
2386 "REAL/COMPLEX 0**0 is not defined"_warn_en_US);
2390 }
else if (
auto callable{GetHostRuntimeWrapper<T, T, T>(
"pow")}) {
2392 Constant<T>{(*callable)(context, folded->first, folded->second)}};
2394 context.Warn(common::UsageWarning::FoldingFailure,
2395 "Power for %s cannot be folded on host"_warn_en_US,
2403template <
typename T>
2405 if (
auto array{ApplyElementwise(context, x)}) {
2408 return common::visit(
2410 if (
auto folded{OperandsAreConstants(x.left(), y)}) {
2411 auto power{evaluate::IntPower(folded->first, folded->second)};
2412 context.RealFlagWarnings(power.flags,
"power with INTEGER exponent");
2413 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2414 power.value = power.value.FlushSubnormalToZero();
2424template <
typename T>
2426 x.condition() = Fold(context, std::move(x.condition()));
2428 if (
auto cst{GetScalarConstantValue<LogicalResult>(x.condition())}) {
2429 return cst->IsTrue() ? Fold(context, std::move(x.thenValue()))
2430 : Fold(context, std::move(x.elseValue()));
2435template <
typename T>
2437 if (
auto array{ApplyElementwise(context, x,
2444 if (
auto folded{OperandsAreConstants(x)}) {
2445 if constexpr (T::category == TypeCategory::Integer) {
2446 if (folded->first.CompareSigned(folded->second) == x.ordering) {
2449 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2450 if (folded->first.CompareUnsigned(folded->second) == x.ordering) {
2453 }
else if constexpr (T::category == TypeCategory::Real) {
2454 if (folded->first.IsNotANumber() ||
2455 (folded->first.Compare(folded->second) == Relation::Less) ==
2456 (x.ordering == Ordering::Less)) {
2460 static_assert(T::category == TypeCategory::Character);
2463 auto maxLen{std::max(folded->first.length(), folded->second.length())};
2464 bool isFirst{x.ordering == Compare(folded->first, folded->second)};
2465 auto res{isFirst ? std::move(folded->first) : std::move(folded->second)};
2466 res = res.length() == maxLen
2468 : CharacterUtils<T::kind>::Resize(res, maxLen);
2480 std::optional<Expr<Result>> result;
2483 using From = std::decay_t<
decltype(x)>;
2484 if constexpr (std::is_same_v<From, BOZLiteralConstant>) {
2487 result = ConvertToType<Result>(std::move(x));
2488 const auto *constant{UnwrapExpr<Constant<Result>>(*result)};
2490 Scalar<Result> real{constant->GetScalarValue().value()};
2491 From converted{From::ConvertUnsigned(real.RawBits()).value};
2492 if (original != converted) {
2493 context.Warn(common::UsageWarning::FoldingValueChecks,
2494 "Nonzero bits truncated from BOZ literal constant in REAL intrinsic"_warn_en_US);
2496 }
else if constexpr (IsNumericCategoryExpr<From>()) {
2497 result = Fold(context, ConvertToType<Result>(std::move(x)));
2499 common::die(
"ToReal: bad argument expression");
2503 return result.value();
2512 if (
auto array{ApplyElementwise(context, x,
2516 x.isImaginaryPart, std::move(operand)}};
2520 auto &operand{x.left()};
2521 if (
auto value{GetScalarConstantValue<Operand>(operand)}) {
2522 if (x.isImaginaryPart) {
2531template <
typename T>
2533 return common::visit(
2535 if constexpr (IsSpecificIntrinsicType<T>) {
2536 return FoldOperation(context, std::move(x));
2537 }
else if constexpr (std::is_same_v<T, SomeDerived>) {
2538 return FoldOperation(context, std::move(x));
2539 }
else if constexpr (common::HasMember<
decltype(x),
2540 TypelessExpression>) {
2541 return std::move(expr);
2543 return Expr<T>{Fold(context, std::move(x))};
Definition fold-implementation.h:1479
Definition expression.h:478
Definition expression.h:506
Definition variable.h:205
Definition variable.h:243
Definition variable.h:357
Definition expression.h:394
Definition constant.h:147
Definition variable.h:381
Definition expression.h:65
Definition fold-implementation.h:54
Definition expression.h:444
Definition variable.h:101
Definition expression.h:113
Definition variable.h:442
Definition expression.h:784
Definition variable.h:304
Definition variable.h:160
Definition variable.h:136
Definition ParserActions.h:24
Definition expression.h:295
Definition expression.h:472
Definition expression.h:256
Definition expression.h:356
Definition expression.h:210
Definition variable.h:288
Definition expression.h:316
Definition expression.h:339
Definition expression.h:436
Definition expression.h:309
Definition expression.h:246
Definition expression.h:228
Definition expression.h:323
Definition expression.h:331
Definition variable.h:191
Definition expression.h:302