1
use crate::marker::Tuple;
2

            
3
/// The version of the call operator that takes an immutable receiver.
4
///
5
/// Instances of `Fn` can be called repeatedly without mutating state.
6
///
7
/// *This trait (`Fn`) is not to be confused with [function pointers]
8
/// (`fn`).*
9
///
10
/// `Fn` is implemented automatically by closures which only take immutable
11
/// references to captured variables or don't capture anything at all, as well
12
/// as (safe) [function pointers] (with some caveats, see their documentation
13
/// for more details). Additionally, for any type `F` that implements `Fn`, `&F`
14
/// implements `Fn`, too.
15
///
16
/// Since both [`FnMut`] and [`FnOnce`] are supertraits of `Fn`, any
17
/// instance of `Fn` can be used as a parameter where a [`FnMut`] or [`FnOnce`]
18
/// is expected.
19
///
20
/// Use `Fn` as a bound when you want to accept a parameter of function-like
21
/// type and need to call it repeatedly and without mutating state (e.g., when
22
/// calling it concurrently). If you do not need such strict requirements, use
23
/// [`FnMut`] or [`FnOnce`] as bounds.
24
///
25
/// See the [chapter on closures in *The Rust Programming Language*][book] for
26
/// some more information on this topic.
27
///
28
/// Also of note is the special syntax for `Fn` traits (e.g.
29
/// `Fn(usize, bool) -> usize`). Those interested in the technical details of
30
/// this can refer to [the relevant section in the *Rustonomicon*][nomicon].
31
///
32
/// [book]: ../../book/ch13-01-closures.html
33
/// [function pointers]: fn
34
/// [nomicon]: ../../nomicon/hrtb.html
35
///
36
/// # Examples
37
///
38
/// ## Calling a closure
39
///
40
/// ```
41
/// let square = |x| x * x;
42
/// assert_eq!(square(5), 25);
43
/// ```
44
///
45
/// ## Using a `Fn` parameter
46
///
47
/// ```
48
/// fn call_with_one<F>(func: F) -> usize
49
///     where F: Fn(usize) -> usize {
50
///     func(1)
51
/// }
52
///
53
/// let double = |x| x * 2;
54
/// assert_eq!(call_with_one(double), 2);
55
/// ```
56
#[lang = "fn"]
57
#[stable(feature = "rust1", since = "1.0.0")]
58
#[rustc_paren_sugar]
59
#[rustc_on_unimplemented(
60
    on(
61
        Args = "()",
62
        note = "wrap the `{Self}` in a closure with no arguments: `|| {{ /* code */ }}`"
63
    ),
64
    on(
65
        Self = "unsafe fn",
66
        note = "unsafe function cannot be called generically without an unsafe block",
67
        // SAFETY: tidy is not smart enough to tell that the below unsafe block is a string
68
        label = "call the function in a closure: `|| unsafe {{ /* code */ }}`"
69
    ),
70
    message = "expected a `{Trait}` closure, found `{Self}`",
71
    label = "expected an `{Trait}` closure, found `{Self}`"
72
)]
73
#[fundamental] // so that regex can rely that `&str: !FnMut`
74
#[must_use = "closures are lazy and do nothing unless called"]
75
#[const_trait]
76
#[rustc_const_unstable(feature = "const_trait_impl", issue = "143874")]
77
pub trait Fn<Args: Tuple>: FnMut<Args> {
78
    /// Performs the call operation.
79
    #[unstable(feature = "fn_traits", issue = "29625")]
80
    extern "rust-call" fn call(&self, args: Args) -> Self::Output;
81
}
82

            
83
/// The version of the call operator that takes a mutable receiver.
84
///
85
/// Instances of `FnMut` can be called repeatedly and may mutate state.
86
///
87
/// `FnMut` is implemented automatically by closures which take mutable
88
/// references to captured variables, as well as all types that implement
89
/// [`Fn`], e.g., (safe) [function pointers] (since `FnMut` is a supertrait of
90
/// [`Fn`]). Additionally, for any type `F` that implements `FnMut`, `&mut F`
91
/// implements `FnMut`, too.
92
///
93
/// Since [`FnOnce`] is a supertrait of `FnMut`, any instance of `FnMut` can be
94
/// used where a [`FnOnce`] is expected, and since [`Fn`] is a subtrait of
95
/// `FnMut`, any instance of [`Fn`] can be used where `FnMut` is expected.
96
///
97
/// Use `FnMut` as a bound when you want to accept a parameter of function-like
98
/// type and need to call it repeatedly, while allowing it to mutate state.
99
/// If you don't want the parameter to mutate state, use [`Fn`] as a
100
/// bound; if you don't need to call it repeatedly, use [`FnOnce`].
101
///
102
/// See the [chapter on closures in *The Rust Programming Language*][book] for
103
/// some more information on this topic.
104
///
105
/// Also of note is the special syntax for `Fn` traits (e.g.
106
/// `Fn(usize, bool) -> usize`). Those interested in the technical details of
107
/// this can refer to [the relevant section in the *Rustonomicon*][nomicon].
108
///
109
/// [book]: ../../book/ch13-01-closures.html
110
/// [function pointers]: fn
111
/// [nomicon]: ../../nomicon/hrtb.html
112
///
113
/// # Examples
114
///
115
/// ## Calling a mutably capturing closure
116
///
117
/// ```
118
/// let mut x = 5;
119
/// {
120
///     let mut square_x = || x *= x;
121
///     square_x();
122
/// }
123
/// assert_eq!(x, 25);
124
/// ```
125
///
126
/// ## Using a `FnMut` parameter
127
///
128
/// ```
129
/// fn do_twice<F>(mut func: F)
130
///     where F: FnMut()
131
/// {
132
///     func();
133
///     func();
134
/// }
135
///
136
/// let mut x: usize = 1;
137
/// {
138
///     let add_two_to_x = || x += 2;
139
///     do_twice(add_two_to_x);
140
/// }
141
///
142
/// assert_eq!(x, 5);
143
/// ```
144
#[lang = "fn_mut"]
145
#[stable(feature = "rust1", since = "1.0.0")]
146
#[rustc_paren_sugar]
147
#[rustc_on_unimplemented(
148
    on(
149
        Args = "()",
150
        note = "wrap the `{Self}` in a closure with no arguments: `|| {{ /* code */ }}`"
151
    ),
152
    on(
153
        Self = "unsafe fn",
154
        note = "unsafe function cannot be called generically without an unsafe block",
155
        // SAFETY: tidy is not smart enough to tell that the below unsafe block is a string
156
        label = "call the function in a closure: `|| unsafe {{ /* code */ }}`"
157
    ),
158
    message = "expected a `{Trait}` closure, found `{Self}`",
159
    label = "expected an `{Trait}` closure, found `{Self}`"
160
)]
161
#[fundamental] // so that regex can rely that `&str: !FnMut`
162
#[must_use = "closures are lazy and do nothing unless called"]
163
#[const_trait]
164
#[rustc_const_unstable(feature = "const_trait_impl", issue = "143874")]
165
pub trait FnMut<Args: Tuple>: FnOnce<Args> {
166
    /// Performs the call operation.
167
    #[unstable(feature = "fn_traits", issue = "29625")]
168
    extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
169
}
170

            
171
/// The version of the call operator that takes a by-value receiver.
172
///
173
/// Instances of `FnOnce` can be called, but might not be callable multiple
174
/// times. Because of this, if the only thing known about a type is that it
175
/// implements `FnOnce`, it can only be called once.
176
///
177
/// `FnOnce` is implemented automatically by closures that might consume captured
178
/// variables, as well as all types that implement [`FnMut`], e.g., (safe)
179
/// [function pointers] (since `FnOnce` is a supertrait of [`FnMut`]).
180
///
181
/// Since both [`Fn`] and [`FnMut`] are subtraits of `FnOnce`, any instance of
182
/// [`Fn`] or [`FnMut`] can be used where a `FnOnce` is expected.
183
///
184
/// Use `FnOnce` as a bound when you want to accept a parameter of function-like
185
/// type and only need to call it once. If you need to call the parameter
186
/// repeatedly, use [`FnMut`] as a bound; if you also need it to not mutate
187
/// state, use [`Fn`].
188
///
189
/// See the [chapter on closures in *The Rust Programming Language*][book] for
190
/// some more information on this topic.
191
///
192
/// Also of note is the special syntax for `Fn` traits (e.g.
193
/// `Fn(usize, bool) -> usize`). Those interested in the technical details of
194
/// this can refer to [the relevant section in the *Rustonomicon*][nomicon].
195
///
196
/// [book]: ../../book/ch13-01-closures.html
197
/// [function pointers]: fn
198
/// [nomicon]: ../../nomicon/hrtb.html
199
///
200
/// # Examples
201
///
202
/// ## Using a `FnOnce` parameter
203
///
204
/// ```
205
/// fn consume_with_relish<F>(func: F)
206
///     where F: FnOnce() -> String
207
/// {
208
///     // `func` consumes its captured variables, so it cannot be run more
209
///     // than once.
210
///     println!("Consumed: {}", func());
211
///
212
///     println!("Delicious!");
213
///
214
///     // Attempting to invoke `func()` again will throw a `use of moved
215
///     // value` error for `func`.
216
/// }
217
///
218
/// let x = String::from("x");
219
/// let consume_and_return_x = move || x;
220
/// consume_with_relish(consume_and_return_x);
221
///
222
/// // `consume_and_return_x` can no longer be invoked at this point
223
/// ```
224
#[lang = "fn_once"]
225
#[stable(feature = "rust1", since = "1.0.0")]
226
#[rustc_paren_sugar]
227
#[rustc_on_unimplemented(
228
    on(
229
        Args = "()",
230
        note = "wrap the `{Self}` in a closure with no arguments: `|| {{ /* code */ }}`"
231
    ),
232
    on(
233
        Self = "unsafe fn",
234
        note = "unsafe function cannot be called generically without an unsafe block",
235
        // SAFETY: tidy is not smart enough to tell that the below unsafe block is a string
236
        label = "call the function in a closure: `|| unsafe {{ /* code */ }}`"
237
    ),
238
    message = "expected a `{Trait}` closure, found `{Self}`",
239
    label = "expected an `{Trait}` closure, found `{Self}`"
240
)]
241
#[fundamental] // so that regex can rely that `&str: !FnMut`
242
#[must_use = "closures are lazy and do nothing unless called"]
243
#[const_trait]
244
#[rustc_const_unstable(feature = "const_trait_impl", issue = "143874")]
245
pub trait FnOnce<Args: Tuple> {
246
    /// The returned type after the call operator is used.
247
    #[lang = "fn_once_output"]
248
    #[stable(feature = "fn_once_output", since = "1.12.0")]
249
    type Output;
250

            
251
    /// Performs the call operation.
252
    #[unstable(feature = "fn_traits", issue = "29625")]
253
    extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
254
}
255

            
256
mod impls {
257
    use crate::marker::Tuple;
258

            
259
    #[stable(feature = "rust1", since = "1.0.0")]
260
    #[rustc_const_unstable(feature = "const_trait_impl", issue = "143874")]
261
    impl<A: Tuple, F: ?Sized> const Fn<A> for &F
262
    where
263
        F: [const] Fn<A>,
264
    {
265
        extern "rust-call" fn call(&self, args: A) -> F::Output {
266
            (**self).call(args)
267
        }
268
    }
269

            
270
    #[stable(feature = "rust1", since = "1.0.0")]
271
    #[rustc_const_unstable(feature = "const_trait_impl", issue = "143874")]
272
    impl<A: Tuple, F: ?Sized> const FnMut<A> for &F
273
    where
274
        F: [const] Fn<A>,
275
    {
276
2052556
        extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
277
2052556
            (**self).call(args)
278
2052556
        }
279
    }
280

            
281
    #[stable(feature = "rust1", since = "1.0.0")]
282
    #[rustc_const_unstable(feature = "const_trait_impl", issue = "143874")]
283
    impl<A: Tuple, F: ?Sized> const FnOnce<A> for &F
284
    where
285
        F: [const] Fn<A>,
286
    {
287
        type Output = F::Output;
288

            
289
        extern "rust-call" fn call_once(self, args: A) -> F::Output {
290
            (*self).call(args)
291
        }
292
    }
293

            
294
    #[stable(feature = "rust1", since = "1.0.0")]
295
    #[rustc_const_unstable(feature = "const_trait_impl", issue = "143874")]
296
    impl<A: Tuple, F: ?Sized> const FnMut<A> for &mut F
297
    where
298
        F: [const] FnMut<A>,
299
    {
300
35746196
        extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
301
35746196
            (*self).call_mut(args)
302
35746196
        }
303
    }
304

            
305
    #[stable(feature = "rust1", since = "1.0.0")]
306
    #[rustc_const_unstable(feature = "const_trait_impl", issue = "143874")]
307
    impl<A: Tuple, F: ?Sized> const FnOnce<A> for &mut F
308
    where
309
        F: [const] FnMut<A>,
310
    {
311
        type Output = F::Output;
312
2459646
        extern "rust-call" fn call_once(self, args: A) -> F::Output {
313
2459646
            (*self).call_mut(args)
314
2459646
        }
315
    }
316
}