Compile-time function execution: Difference between revisions

Content deleted Content added
added immediate functions in c++
No edit summary
 
(5 intermediate revisions by 4 users not shown)
Line 1:
{{Short description|A compiler's ability to execute a function at compile time rather than runtime}}
'''Compile-time function execution''' (or '''compile time function evaluation''', or '''general constant expressions''') is the ability of a [[compiler]], that would normally compile a function to machine code and execute it at [[run time (program lifecycle phase)|run time]], to execute the function at [[compile time]]. This is possible if the arguments to the function are known at compile time, and the function does not make any reference to or attempt to modify any global state (is a [[pure function]]).
 
In [[computing]], '''Compilecompile-time function execution''' (or '''compile -time function evaluation''', or '''general constant expressions''') is the ability of a [[compiler]], that would normally compile a [[Subroutine|function]] to [[machine code]] and [[Execution (computing)|execute]] it at [[run time (program lifecycle phase)|run time]], to execute the function at [[compile time]]. This is possible if the arguments to the function are known at compile time, and the function does not make any reference to or attempt to modify any global state (i.e. it is a [[pure function]]).
 
If the value of only some of the arguments are known, the compiler may still be able to perform some level of compile-time function execution ([[partial evaluation]]), possibly producing more optimized code than if no arguments were known.
Line 5 ⟶ 7:
==Examples==
===Lisp===
The [[Lisp Macro_(programming languagecomputer_science)#Syntactic_macros|Lisp]] macro system]] is an early example of the use of compile-time evaluation of user-defined functions in the same language.
 
===C++===
Line 12 ⟶ 14:
In earlier versions of [[C++]], [[template metaprogramming]] is often used to compute values at compile time, such as:
 
<syntaxhighlight lang="CPPcpp">
template <int N>
struct Factorial {
Line 33 ⟶ 35:
Using compile-time function evaluation, code used to compute the factorial would be similar to what one would write for run-time evaluation e.g. using C++11 constexpr.
 
<syntaxhighlight lang="CPPcpp">
#include <cstdio>
 
Line 48 ⟶ 50:
In [[C++11]], this technique is known as [[C++11#constexpr – Generalized constant expressions|generalized constant expressions]] (<code>constexpr</code>).<ref>{{cite web|url=http://www.stroustrup.com/sac10-constexpr.pdf|author=Gabriel Dos Reis and Bjarne Stroustrup | title=General Constant Expressions for System Programming Languages. SAC-2010. The 25th ACM Symposium On Applied Computing. | date=March 2010}}</ref> [[C++14]] [[C++14#Relaxed constexpr restrictions|relaxes the constraints]] on constexpr – allowing local declarations and use of conditionals and loops (the general restriction that all data required for the execution be available at compile-time remains).
 
Here's an example of compile -time function evaluation in C++14:
 
<syntaxhighlight lang="CPPcpp">
// Iterative factorial at compile time.
constexpr int Factorial(int n) {
Line 68 ⟶ 70:
In [[C++20]], immediate functions were introduced, and compile-time function execution was made more accessible and flexible with relaxed <code>constexpr</code> restrictions.
 
<syntaxhighlight lang="CPPcpp">
// Iterative factorial at compile time.
consteval int Factorial(int n) {
Line 86 ⟶ 88:
 
Here's an example of using immediate functions in compile-time function execution:
<syntaxhighlight lang="CPPcpp">
void you_see_this_error_because_assertion_fails() {}
 
Line 109 ⟶ 111:
 
The typical compilation error message would display:
<syntaxhighlight lang="CPPcpp">
In function 'int main()':
in 'constexpr' expansion of 'test()'
Line 120 ⟶ 122:
 
Here's another example of using immediate functions as constructors which enables compile-time argument checking:
<syntaxhighlight lang="CPPcpp">
#include <string_view>
#include <iostream>
Line 147 ⟶ 149:
 
The compilation fails here with the message:
<syntaxhighlight lang="CPPcpp">
In function 'int main()':
in 'constexpr' expansion of 'checked_message(((const char*)"Hello, world!"))'
Line 157 ⟶ 159:
 
===D===
Here's an example of compile -time function evaluation in the [[D programming language]]:<ref>[http://d-programming-language.org/function.html#interpretation D 2.0 language specification: Functions]</ref>
 
<syntaxhighlight lang="Dd">
int factorial(int n) {
if (n == 0)
Line 175 ⟶ 177:
CTFE can be used to populate data structures at compile-time in a simple way (D version 2):
 
<syntaxhighlight lang="Dd">
int[] genFactorials(int n) {
auto result = new int[n];
result[0] = 1;
Line 193 ⟶ 196:
 
CTFE can be used to generate strings which are then parsed and compiled as D code in D.
 
===Zig===
Here's an example of compile-time function evaluation in the [[Zig programming language]]:<ref>[https://ziglang.org/documentation/0.11.0/#Compile-Time-Expressions Zig 0.11.0 Language Reference: Compile-Time Expressions]</ref>
 
<syntaxhighlight lang="zig">
pub fn factorial(n: usize) usize {
var result = 1;
for (1..(n + 1)) |i| {
result *= i;
}
return result;
}
 
pub fn main() void {
const x = comptime factorial(0); // == 0
const y = comptime factorial(4); // == 24
}
</syntaxhighlight>
 
This example specifies a valid Zig function called "factorial" which would typically be evaluated at run time. The use of <code>comptime</code> tells the compiler that the initializer for the variables must be computed at compile time. Note that the arguments to the function must be able to be resolved at compile time as well.
 
Zig also support Compile-Time Parameters.<ref>[https://ziglang.org/documentation/0.11.0/#Compile-Time-Parameters Zig 0.11.0 Language Reference: Compile-Time Parameters]</ref>
 
<syntaxhighlight lang="zig">
pub fn factorial(comptime n: usize) usize {
var result: usize = 1;
for (1..(n + 1)) |i| {
result *= i;
}
return result;
}
 
pub fn main() void {
const x = factorial(0); // == 0
const y = factorial(4); // == 24
}
</syntaxhighlight>
 
CTFE can be used to create generic data structures at compile-time:
 
<syntaxhighlight lang="zig">
fn List(comptime T: type) type {
return struct {
items: []T,
len: usize,
};
}
 
// The generic List data structure can be instantiated by passing in a type:
var buffer: [10]i32 = undefined;
var list = List(i32){
.items = &buffer,
.len = 0,
};
</syntaxhighlight>
 
==References==
Line 199 ⟶ 257:
==External links==
* [http://rosettacode.org/wiki/Compile-time_calculation Rosettacode examples of compile-time function evaluation in various languages]
 
{{Compiler optimizations}}
 
[[Category:Compiler construction]]
[[Category:Articles with example C++ code]]
[[Category:Articles with example D code]]
[[Category:Compiler optimizations]]