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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
//! Module with operations for [`Nat`]s.
//!
//! This module defines many common mathematical type-level operations on natural numbers.
//!
//! # Laziness
//! Operations are implemented by implementing [`NatExpr`] on a generic struct.
//! This makes them lazy in the sense that they will only be evaluated to a [`Nat`]
//! once their associated [`NatExpr::Eval`] is accessed.
//!
//! Most importantly, [`If`] is implemented such that only the necessary branch is evaluated,
//! which means it is possible to do recursion with it.
//!
//! All operations in this module are lazy. In order to get a [`Nat`] from them, e.g. for use
//! with [arrays](crate::array), use [`crate::Eval`] or [`crate::eval!`] to evaluate them.
//!
//! # Primitive operations
//! Operations that are implemented through an (internal) associated type on [`Nat`] are called primitive.
//!
//! All operations in this module are implemented on top of the following primitive operations:
//! - [`PopBit<N>`] removes the last bit of [`N::Eval`](NatExpr).
//! - Evaluates like `N.eval() / 2`
//! - [`LastBit<N>`] gets the last bit of [`N::Eval`](NatExpr).
//! - Evaluates like `N.eval() % 2`
//! - [`PushBit<N, B>`] pushes [`B::Eval`](NatExpr) as a bit to the end of [`N::Eval`](NatExpr)
//! - Evaluates like `2 * N.eval() + (B.eval() != 0) as _`
//! - [`If<C, T, F>`] evaluates to [`T::Eval`](NatExpr) if `C` is nonzero, otherwise
//! to [`F::Eval`](NatExpr). Only the necessary [`NatExpr::Eval`] projection is performed.
//! - Evaluates like `if C != 0 { T.eval() } else { F.eval() }`
//!
//! These primitives, together with recursive [`NatExpr`] implementations,
//! form a [Turing-complete](https://en.wikipedia.org/wiki/Turing_completeness) system.
//! Any computable function on the natural numbers can be implemented.
//!
//! # Recursion
//! The way to implement an operation where the output requires looking at the entire number is to
//! do it recursively. Regular type aliases do not support recursion since they are eagerly
//! expanded (see error E0391 "cycle detected when expanding type alias").
//!
//! Instead, one has to go through [`NatExpr`] to make the operation lazy and use [`If`] to exit the
//! recursion. For example, consider this implementation of [`BitAnd`]:
//! ```
//! use gnat::{NatExpr, expr::*};
//!
//! #[gnat::nat_expr]
//! type MyBitAnd<L: NatExpr, R: NatExpr> = gnat::expr! {
//! if L {
//! PushBit(
//! // recurse on the tails and append the head
//! MyBitAnd(
//! gnat::Eval(PopBit(R)),
//! gnat::Eval(PopBit(L)),
//! ),
//! if LastBit(L) { LastBit(R) } else { 0 }, // logical AND
//! )
//! } else {
//! 0 // base case, 0 & R = 0
//! }
//! };
//! ```
//! Because `MyBitAnd` and [`PushBit`] are lazy and [`If`] only accesses
//! [`NatExpr::Eval`] in the required branch, this will exit when `L = 0`,
//! without getting stuck in an infinite loop.
//!
//! Note the application of [`crate::Eval`] to [`PopBit`]. This is not strictly
//! necessary, but without it, the input to `MyBitAnd` becomes more deeply nested
//! on each recursive evaluation (`PopBit<PopBit<...>>`), which causes `MyBitAnd`
//! to take longer to compute (longer compile times). Evaluating in each step causes
//! the level of nesting to decrease, since the number becomes smaller.
//! Similarly, switching the order of `R` and `L` on each recursion also terminates
//! faster (for `R` much larger than `L`), at no extra cost.
//!
//! <details>
//! <summary>Advanced technique: Tail recursion and helper traits</summary>
//!
//! This example defines an ad-hoc helper trait to implement division using tail recursion.
//! Note that this is slower than the implementation without tail recursion that [`Div`]
//! uses internally.
//! ```
//! use gnat::{
//! Nat, NatExpr,
//! expr::{LastBit, PopBit, PushBit},
//! };
//! pub struct Cons<H, T>(H, T);
//! pub struct Nil;
//! pub trait RNat {
//! type Tail: RNat;
//! type Head: Nat;
//! type End: Nat;
//! }
//! impl RNat for Nil {
//! type Tail = Self;
//! type Head = gnat::lit!(0);
//! type End = gnat::lit!(1);
//! }
//! impl<H: Nat, T: RNat> RNat for Cons<H, T> {
//! type Tail = T;
//! type Head = H;
//! type End = gnat::lit!(0);
//! }
//! #[gnat::nat_expr]
//! pub type _DivAux<L: RNat, R: Nat, AccMod: NatExpr, AccQuot: NatExpr> = gnat::expr! {
//! if L::End {
//! AccQuot
//! } else {
//! _DivAuxRec(
//! L::Tail,
//! R,
//! gnat::Eval(PushBit(AccMod, L::Head)),
//! gnat::Eval(AccQuot),
//! )
//! }
//! };
//! #[gnat::nat_expr]
//! pub type _DivAuxRec<L: RNat, R: Nat, NaiveMod: NatExpr, AccQuot: NatExpr> = gnat::expr! {
//! if NaiveMod < R {
//! _DivAux(
//! L,
//! R,
//! NaiveMod,
//! PushBit(AccQuot, 0),
//! )
//! } else {
//! _DivAux(
//! L,
//! R,
//! NaiveMod - R,
//! PushBit(AccQuot, 1),
//! )
//! }
//! };
//! #[gnat::nat_expr]
//! pub type _DivAuxEnter<L: Nat, R: Nat, AccL: RNat> = gnat::expr! {
//! if L {
//! _DivAuxEnter(
//! gnat::Eval(PopBit(L)),
//! R,
//! Cons(
//! gnat::Eval(LastBit(L)),
//! AccL,
//! ),
//! )
//! } else {
//! _DivAux(AccL, R, 0, 0)
//! }
//! };
//! #[gnat::nat_expr]
//! pub type MyDiv<L: NatExpr, R: NatExpr> = gnat::expr! { _DivAuxEnter(L::Eval, R::Eval, Nil) };
//! assert_eq!(
//! gnat::to_u128::<gnat::expr! { MyDiv(420, 69) }>(),
//! Some(420 / 69)
//! )
//! ```
//! </details>
//!
//! # Opaqueness
//! There is another primitive operation, [`Opaque<P, Out>`].
//! It is implemented to always return `Out::Eval`, but it still goes through a projection on `P::Eval`.
//!
//! This means that something like `Eval<Opaque<A, Opaque<B, Func<A, B>>>>` will always be the same
//! as `Eval<Func<A, B>>`, except that the compiler won't know this until it actually knows the
//! value of both `A` and `B`. The benefits of this are:
//! - If `Func` is recursive over only one of its arguments, then if we do something like
//! `Eval<Func<UsizeMax, B>>`, where `B` is a generic parameter, then the compiler will try to
//! normalize all the recursions away, since it knows how to evaluate `If<A, ...>`, since `A` is
//! known. This can cause unexpected "overflow while evaluating" errors.
//!
//! Wrapping `Func` in `Opaque` causes the evaluation to be deferred until both arguments are
//! known, which prevents this.
//! - Making `Func` public API risks exposing implementation details due to type inferrence.
//! Wrapping a hidden [`NatExpr`] implementor in `Opaque` minimizes the amount of information
//! about the [`Nat`] that is returned, which means that the implementation can be changed after
//! the fact.
//!
//! In the example from before, the following is an almost exact reimplementation of [`BitAnd`]:
//! ```
//! # use gnat::expr::BitAnd as MyBitAnd;
//! use gnat::expr::Opaque;
//! #[gnat::nat_expr]
//! type MyBitAndFinal<L: gnat::NatExpr, R: gnat::NatExpr> = Opaque<
//! L,
//! Opaque<
//! R,
//! MyBitAnd<L, R>,
//! >,
//! >;
//! ```
use crate::;
use crate::;
/// Input format:
/// ```compile_fail
/// #[apply(nat_expr)]
/// pub type A<P1: NatExpr, P2: NatExpr, ...> = $Val;
/// ```
///
/// Output format:
/// ```compile_fail
/// pub struct A<P1, P2, ...>(P1, P2, ...);
/// impl<P1: NatExpr, P2: NatExpr, ...> NatExpr for A<P1, P2, ...> {
/// type Eval = gnat::Eval<$Val>;
/// }
/// ```
};
}
pub use nat_expr;
/// Variadic [`Opaque`]
pub use VarOpaque;
/// Like [`nat_expr`], but wraps the result in [`VarOpaque`].
/// For this, another [`nat_expr`] type `$LazyBase` is declared in the
/// module to holds the implementation to be wrapped by [`VarOpaque`].
///
/// Recursive implementations should use that name when recursing,
/// not the opaque wrapper.
///
/// Additionally, when an additional `pub(...)` visibility is passed
/// to the attribute, the non-opaque base type is exported at that
/// visibility, for internal use elsewhere.
;
$*
$v $Name<$($P $(= $Def)?),*>($($P),*);
,*>
};
}
$*
$v $kw $TypeName<$,*> $*
};
}
\n",
$(
core::concat!(
"assert_nat_eq!;\n",
),
)*
"```",
)
};
}
mod primitives;
pub use primitives::{If, LastBit, Opaque, PopBit, PushBit};
mod helper;
pub(crate) use helper::*;
mod trivial;
pub use trivial::{IsNonzero, IsZero};
mod testing;
mod bitmath;
pub use bitmath::{BitAnd, BitOr, BitXor};
mod log;
pub use log::{BaseLen, Log};
mod add;
pub use add::Add;
pub(crate) use add::*;
mod mul;
pub use mul::Mul;
pub(crate) use mul::*;
mod cmp;
pub(crate) use cmp::*;
pub use cmp::{Eq, Ge, Gt, Le, Lt, Max, Min, Ne};
mod sub;
pub(crate) use sub::*;
pub use sub::{AbsDiff, SatSub};
mod divrem;
pub(crate) use divrem::*;
pub use divrem::{Div, Rem};
mod shift;
pub(crate) use shift::*;
pub use shift::{Shl, Shr};
mod pow;
pub use pow::Pow;