j3-fortran / fortran_proposals

Proposals for the Fortran Standard Committee
178 stars 15 forks source link

Add CONSTEXPR procedures in Fortran #214

Open FortranFan opened 3 years ago

FortranFan commented 3 years ago

"Constexpr as much as possible" or in other words, utilize as much compile-time computing as viable is a mantra that's increasingly becoming important in many modern codes based on C++17 (and later revisions) toward scientific and technical computing in industry, especially in process simulations and modeling.

Improved constexpr in C++17 is particularly valuable when one needs to construct large named constants arrays for use in simulations based on other constants (e.g., coefficients in engineering correlations, results from prior simulation runs, results from first-principles models to be applied in reduced-order models, etc.). These are all use cases that are rather similar to some threads that have come up at Fortran-lang.org:

An option can be to introduce a CONSTEXPR attribute to functions in Fortran combined with appropriate semantics and constraints which can allow such a nonintrinsic i.e., user-defined functions to be used in constant expressions.

Such an option appears consistent, in my view , with the evolution path of Fortran with PURE/ELEMENTAL procedures in Fortran 95 to SIMPLE procedures in Fortran 202X.

The introduction of such a CONSTEXPR function in a future Fortran standard, say 202Y, will greatly enhance compile-time computing facilities in Fortran and it holds the promise of great benefit in scientific and technical computing.

Some further reading here

klausler commented 3 years ago

C++'s constexpr is useful for computing values that are needed at compilation time. Large named constant arrays that must be present before execution begins are not the same use case; they can be computed once at build time and written to an unformatted file, for example, but their contents do not determine types. I think you should concentrate your use case justification for a Fortran constexpr upon the calculation of things that are needed for compilation and are typically implemented today via preprocessor macros or via INCLUDE of precalculated values.

certik commented 3 years ago

Another approach worth investigating is Zig's comptime feature:

tkoenig1 commented 1 year ago

This would be a subset of issue #293, where it would be trivial to do so.