1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
//! This crate provides type-level natural numbers, similar to [`typenum`](https://docs.rs/typenum/latest/typenum/).
//!
//! A type-level number is a type that represents a number. The [`Nat`] trait functions as the
//! "meta-type" of type-level numbers, i.e. to accept a type-level number, use a generic
//! parameter `N: Nat`.
//!
//! The use cases are the same as those of generic consts.
//!
//! ## Why this crate?
//! This crate differs from `typenum` in that [`Nat`] is not just a marker trait.
//! To perform arbitrary operations on a generic `N: Nat`, no extra bounds are
//! required.
//!
//! As a result, this crate is more expressive than `typenum` or the
//! `generic_const_exprs` feature.
//!
//! ### Motivating examples
//! <details>
//! <summary>Click to expand</summary>
//!
//! #### Concatenating arrays at compile time
//! Using `generic_const_exprs` or `typenum`/`generic-array`:
//! ```
//! #![feature(generic_const_exprs)]
//! const fn concat_arrays_gcex<T, const M: usize, const N: usize>(
//! a: [T; M],
//! b: [T; N],
//! ) -> [T; M + N]
//! where
//! [T; M + N]:, // Required well-formedness bound
//! {
//! todo!() // Possible with unsafe code
//! }
//!
//! use generic_array::{GenericArray, ArrayLength};
//! const fn concat_arrays_tnum<T, M: ArrayLength, N: ArrayLength>(
//! a: GenericArray<T, M>,
//! b: GenericArray<T, N>,
//! ) -> GenericArray<T, typenum::op!(M + N)>
//! where // ArrayLength is not enough, we also need to add a bound for `+`
//! M: std::ops::Add<N, Output: ArrayLength>,
//! {
//! todo!() // Possible with unsafe code
//! }
//! ```
//! Using this crate:
//! ```
//! use gnat::{Nat, array::Arr};
//! const fn concat_arrays_gnat<T, M: Nat, N: Nat>(
//! a: Arr<T, M>,
//! b: Arr<T, N>,
//! ) -> Arr<T, gnat::eval!(M + N)> { // No extra bounds!
//! a.concat_arr(b).retype() // There is even a method for this :)
//! }
//! ```
//! #### Const Recursion
//! Naively writing a function that recurses over the const parameter is impossible in
//! `generic_const_exprs` and `typenum`, since the recursive argument needs the same
//! bounds as the parameter:
//! ```compile_fail
//! #![feature(generic_const_exprs)]
//! fn recursive_gcex<const N: usize>() -> u32
//! where
//! [(); N / 2]:, // The argument must be well-formed
//! [(); (N / 2) / 2]:, // The argument's argument must be well-formed
//! // ... need infinitely many bounds, even though N converges to 0
//! {
//! if N == 0 {
//! 0
//! } else {
//! // The bounds above for N need to imply the same bounds for N / 2
//! recursive_gcex::<{ N / 2 }>() + 1
//! }
//! }
//!
//! use {std::ops::Div, typenum::{P2, Unsigned}};
//! fn recursive_tnum<N>() -> u32
//! where
//! N: Unsigned + Div<P2>,
//! N::Output: Unsigned + Div<P2>,
//! <N::Output as Div<P2>>::Output: Unsigned + Div<P2>,
//! // ... again, we would need this to repeat infinitely often
//! {
//! if N::USIZE == 0 { // (Pretend this correctly handles overflow)
//! 0
//! } else {
//! recursive_tnum::<typenum::op!(N / 2)>() + 1
//! }
//! }
//! ```
//! While this can be expressed using a helper trait like `trait RecDiv2: Unsigned { type Output: RecDiv2; }`,
//! it is cumbersome and leaks into the bounds of every other calling function.
//!
//! Using this crate, the naive implementation without bounds just works:
//! ```
//! fn recursive_gnat<N: gnat::Nat>() -> u32 {
//! if gnat::is_zero::<N>() {
//! 0
//! } else {
//! recursive_gnat::<gnat::eval!(N / 2)>() + 1
//! }
//! }
//! assert_eq!(recursive_gnat::<gnat::lit!(10)>(), 4); // 10 5 2 1 0
//! ```
//! </details>
extern crate alloc;
// Nat Implementation internals
// Macro implementation details
// internal utils
// Public API
pub use *;
/// Trait for type-level natural numbers.
///
/// See the [crate level documentation](crate).
///
/// It is guaranteed that there is a one-to-one correspondence between
/// the natural numbers including zero and the types that implement this trait.
/// Trait for deferred [`Nat`] expressions.
///
/// This is not only a conversion trait. It is essential to the implementation of most operations.
/// See the [`mod@expr`] module.
///
/// A common pattern is to define operations like this:
/// ```
/// struct Add<L, R>(L, R);
/// impl<L: gnat::NatExpr, R: gnat::NatExpr> gnat::NatExpr for Add<L, R> {
/// type Eval = ...;
/// }
/// ```
/// This can be abbreviated with the [`nat_expr`] macro.
/// Turns an integer literal into a [`Nat`].
///
/// If you need to convert a value stored in a `const` that is small, you
/// can instead convert it using [`consts::Usize`]. Otherwise consider
/// declaring it as a [`Nat`] instead and using [`to_usize`] to get the
/// value.
///
/// # Examples
/// ```
/// #![recursion_limit = "1024"] // `lit!` doesn't recurse, the type is just long
///
/// assert_eq!(gnat::to_u128::<gnat::lit!(1)>(), Some(1));
/// assert_eq!(
/// gnat::to_u128::<gnat::lit!(100000000000000000000000000000)>(),
/// Some(100000000000000000000000000000),
/// )
/// ```
/// Converts expression syntax into [`NatExpr`] type expressions.
///
/// # Examples
/// ```
/// # macro_rules! chk_same_type {
/// # ($l:ty, $r:ty $(,)?) => { let _: $l = panic!() as $r; };
/// # }
/// fn with_exprs<A: gnat::NatExpr, B: gnat::NatExpr>() {
/// // Unsuffixed literals are translated to `Nat`s
/// chk_same_type!(
/// gnat::expr! { 2 },
/// gnat::lit!(2),
/// );
/// // Most operators map to their correspondingly named operation
/// chk_same_type!(
/// gnat::expr! { A + B },
/// gnat::expr::Add<A, B>,
/// );
/// chk_same_type!(
/// gnat::expr! { A == B },
/// gnat::expr::Eq<A, B>,
/// );
/// // Subtraction is saturating
/// chk_same_type!(
/// gnat::expr! { A - B },
/// gnat::expr::SatSub<A, B>,
/// );
/// // `!` uses logical negation
/// chk_same_type!(
/// gnat::expr! { !A },
/// gnat::expr::IsZero<A>,
/// );
/// // Function calls translate to type paths
/// chk_same_type!(
/// gnat::expr! { gnat::expr::AbsDiff(A, B) },
/// gnat::expr::AbsDiff<A, B>,
/// );
/// // Expression paths also translate to type paths
/// chk_same_type!(
/// gnat::expr! { gnat::expr::AbsDiff::<A, B> },
/// gnat::expr::AbsDiff<A, B>,
/// );
/// // Conditionals are also supported
/// chk_same_type!(
/// gnat::expr! { if A { B } else { 2 * B } },
/// gnat::expr::If<
/// A,
/// B,
/// gnat::expr::Mul<gnat::lit!(2), B>,
/// >,
/// );
/// }
/// ```
=> ;
}
/// Same as [`expr!`] wrapped in [`Eval`]. Useful for [`mod@array`] lengths.
///
/// # Examples
/// The [`mod@array`] module only accepts [`Nat`] for lengths, rather than [`NatExpr`] (for better type inference).
/// This macro is more convenient than [`expr!`]+[`Eval`]:
/// ```
/// use gnat::{Nat, array::*};
/// fn concat<T, M: Nat, N: Nat>(
/// a: Arr<T, M>,
/// b: Arr<T, N>,
/// ) -> Arr<T, gnat::eval! { M + N }> { // Alternatively: gnat::Eval<gnat::expr!(M + N)>
/// a.concat_arr(b).retype()
/// }
/// ```
=> ;
}
/// Converts type alias syntax into a [`NatExpr`] impl.
///
/// # Examples
/// ```
/// #[gnat::nat_expr]
/// type Factorial<N: gnat::NatExpr> = gnat::expr! {
/// if N {
/// Factorial(gnat::Eval(N - 1)) * N
/// } else {
/// 1
/// }
/// };
/// assert_eq!(
/// gnat::to_u128::<Factorial<gnat::lit!(5)>>(),
/// Some(120),
/// );
/// ```
/// Equivalent code without this attribute:
/// ```
/// struct Factorial<N>(N);
/// impl<N: gnat::NatExpr> gnat::NatExpr for Factorial<N> {
/// type Eval = gnat::eval! {
/// if N {
/// Factorial(gnat::Eval(N - 1)) * N
/// } else {
/// 1
/// }
/// };
/// }
/// ```
pub use nat_expr;