rorm 0.10.0

A asynchronous declarative ORM written in pure rust.
Documentation
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//! `const fn` in traits
//!
//! Traits can have 3 kinds of associated objects: `fn`, `const` and `type`.
//! `fn` can't be const yet, so we have to abuse one of the other two to build a workaround.
//! `const` could be used, but their type and therefore their possible implementations have
//! to be defined by the trait author. (See [example](#alternative) below)
//! This module uses the third option (associated types).
//!
//! It provides two central traits:
//! - [`Contains`] which defines values i.e. arguments and returns
//! - [`ConstFn`] which defines functions
//!
//! # Basic Idea
//!
//! The basic idea is to have some type `add` (lower case because it should represent a function)
//! which implements `ConstFn<(i32, i32), i32>`.
//! The trait `ConstFn<(i32, i32), i32>` contains one associated constant
//! which takes a `(i32, i32)` as argument and is of type `i32`:
//! ```compile_fail
//! pub trait IdealConstFn<Args, Ret> {
//!     const RETURN<const ARGS: Args>: Ret;
//! }
//!
//! # #[allow(non_camel_case_types)]
//! pub struct add;
//! impl IdealConstFn<(i32, i32), i32> for add {
//!     const RETURN<const ARGS: (i32, i32)>: i32 = {
//!         let (x, y) = ARGS;
//!
//!         // The actual function body
//!         x + 1
//!     };
//! }
//!
//! const THREE: i32 = <add as IdealConstFn<(i32, i32), i32>>::RETURN::<(1, 2)>;
//! ```
//!
//! # Actual implementation
//!
//! However, this ideal has two problems:
//! 1. associated consts can't be generic
//! 2. const generics can't be tuples
//!
//! Solving 1. is not much of an issue, just introduce another generic as indirection:
//! ```compile_fail
//! pub trait NotSoIdealConstFn<Args, Ret> {
//!     type Call<const ARGS: Args>: Return<Ret>;
//! }
//! pub trait Return<Ret> {
//!     const RETURN: Ret;
//! }
//!
//! pub struct add;
//! impl NotSoIdealConstFn<(i32, i32), i32> for add {
//!     type Call<const ARGS: (i32, i32)> = addBody<ARGS>;
//! }
//! pub struct addBody<const: ARGS: (i32, i32)>;
//! impl<const ARGS: (i32, i32)> Return<i32> for addBody<ARGS> {
//!     const RETURN: i32 = {
//!         let (x, y) = ARGS;
//!
//!         // The actual function body
//!         x + 1
//!     };
//! }
//! ```
//!
//! Solving 2. is doable but makes calling `ConstFn`s really unergonomic.
//! Since we can't have const generics, we have to fall back to normal generics.
//! However, this means, we have to have one type for each value we might want to pass to a function:
//! ```
//! pub trait Contains<T> {
//!     const ITEM: T;
//! }
//! pub struct OneAndOne;
//! impl Contains<(i32, i32)> for OneAndOne {
//!     const ITEM: (i32, i32) = (1, 1);
//! }
//! ```
//!
//! Actually `Contains<T>` and `Returns<Ret>` look the same, so we can just use `Contains` which brings us to the actual implementation:
//! ```
//! pub trait Contains<T> {
//!     const ITEM: T;
//! }
//! pub trait ConstFn<Arg, Ret> {
//!     // Named it `Body` instead of `Call`
//!     // which makes more sense from the implementors perspective.
//!     type Body<T: Contains<Arg>>: Contains<Ret>;
//! }
//!
//! # #[allow(non_camel_case_types)]
//! pub struct add;
//! impl ConstFn<(i32, i32), i32> for add {
//!     type Body<T: Contains<(i32, i32)>> = addBody<T>;
//! }
//! # #[allow(non_camel_case_types)]
//! pub struct addBody<T>([T; 0]);
//! impl<T: Contains<(i32, i32)>> Contains<i32> for addBody<T> {
//!     const ITEM: i32 = {
//!         let (x, y) = T::ITEM;
//!
//!         // actual body
//!         x + y
//!     };
//! }
//!
//! pub struct OneAndTwo;
//! impl Contains<(i32, i32)> for OneAndTwo {
//!     const ITEM: (i32, i32) = (1, 2);
//! }
//! const THREE: i32 = <<add as ConstFn<(i32, i32), i32>>::Body::<OneAndTwo> as Contains<i32>>::ITEM;
//! ```
//!
//! # Alternative
//! As described in the introduction paragraph, you could use associated `const`s.
//!
//! Their huge advantage is readability:
//!     There is no type magic, just basic rust.
//!
//! However, they also have a huge disadvantage:
//!     The trait author has to decide on the fixed set of possible methods an implementor may choose from.
//!
//! ```rust
//! trait SomeTrait {
//!     const SOME_METHOD: SomeMethod;
//! }
//! enum SomeMethod {
//!     ImplemenationA,
//!     ImplemenationB,
//!     // ...
//! }
//! impl SomeMethod {
//!     const fn call(self) {
//!         match self {
//!             Self::ImplemenationA => {},
//!             Self::ImplemenationB => {},
//!             // ...
//!         }
//!     }
//! }
//! ```

/// Attaches a constant value of type `T`.
///
/// See [module docs](self) for more information about how and why.
pub trait Contains<T> {
    /// The value attached to / represented by `Self`
    const ITEM: T;
}

/// A `const fn(...Arg) -> Ret` which can be used in traits.
///
/// See [`const_fn!`](crate::const_fn) for an easy way to implement this.
///
/// See [module docs](self) for more information about how and why.
pub trait ConstFn<Arg, Ret> {
    /// A type which is generic over `T` and uses `T::ITEM` in its `Contains` implementation
    /// to compute the "return" value.
    type Body<T: Contains<Arg>>: Contains<Ret>;
}

/// Converts a normal function into a [`ConstFn`].
///
/// Only accepts a very simple `fn` syntax!
///
/// ```
/// # use ::rorm::const_fn;
/// const_fn! {
///     fn add(x: i32, y: i32) -> i32 {
///         x + y
///     }
/// }
/// ```
#[macro_export]
macro_rules! const_fn {
    /*
     * Start by parsing until start of generics
     */

    // Parse start non-generic function
    ($(#[$attr:meta])* $vis:vis fn $fn_name:ident($($rest:tt)+) -> $ret_type:ty $body:block) => {
        $crate::const_fn!(
            @parse_args
            ret_type: $ret_type,
            body: $body,
            rest: [$($rest)+],
            {
                attrs: [$(#[$attr])*],
                vis: $vis,
                name: $fn_name,
            }
        );
    };
    // Parse start of generic function
    ($(#[$attr:meta])* $vis:vis fn $fn_name:ident<$($rest:tt)+) => {
        $crate::const_fn!(
            @parse_generic
            [$($rest)+]
            { [] [] [(),] }
            {
                attrs: [$(#[$attr])*],
                vis: $vis,
                name: $fn_name,
            }
        );
    };

    /*
     * Parse the inside of <...>
     */

    // Parse some const generic
    (
        @parse_generic
        [const $N:ident: $Type:ty, $($rest:tt)+ ]
        { [$($type_generics:tt)*] [$($impl_generics:tt)*] [$($phantom_generics:tt)*] }
        { $($passthrough:tt)* }
    ) => {
        $crate::const_fn!(
            @parse_generic
            [$($rest)+]
            {
                [$($type_generics)* $N, ]
                [$($impl_generics)* const $N: $Type, ]
                [$($phantom_generics)*]
            }
            { $($passthrough)* }
        );
    };
    // Parse last const generic
    (
        @parse_generic
        [const $N:ident: $Type:ty >($($rest:tt)+) -> $ret_type:ty $body:block ]
        { [$($type_generics:tt)*] [$($impl_generics:tt)*] [$($phantom_generics:tt)*] }
        { $($passthrough:tt)* }
    ) => {
        $crate::const_fn!(
            @parse_args
            [$($type_generics)* $N, ],
            [$($impl_generics)* const $N: $Type, ],
            [$($phantom_generics)*],
            ret_type: $ret_type,
            body: $body,
            rest: [$($rest)+],
            {$($passthrough)*}
        );
    };
    // Parse some type generic
    (
        @parse_generic
        [$T:ident $(: $bound:path)?, $($rest:tt)+ ]
        { [$($type_generics:tt)*] [$($impl_generics:tt)*] [$($phantom_generics:tt)*] }
        { $($passthrough:tt)* }
    ) => {
        $crate::const_fn!(
            @parse_generic
            [$($rest)+]
            {
                [$($type_generics)* $T, ]
                [$($impl_generics)* $T $(: $bound)?, ]
                [$($phantom_generics)* $T,]
            }
            { $($passthrough)* }
        );
    };
    // Parse last type generic
    (
        @parse_generic
        [$T:ident $(: $bound:path)? >($($rest:tt)+) -> $ret_type:ty $body:block ]
        { [$($type_generics:tt)*] [$($impl_generics:tt)*] [$($phantom_generics:tt)*] }
        { $($passthrough:tt)* }
    ) => {
        $crate::const_fn!(
            @parse_args
            [$($type_generics)* $T, ],
            [$($impl_generics)* $T $(: $bound)?, ],
            [$($phantom_generics)* $T,],
            ret_type: $ret_type,
            body: $body,
            rest: [$($rest)+],
            {$($passthrough)*}
        );
    };
    // Parse end of generic function
    //
    // This arm will trigger if the function used a trailing comma.
    (
        @parse_generic
        [> ($($rest:tt)+) -> $ret_type:ty $body:block]
        { [$($type_generics:tt)*] [$($impl_generics:tt)*] [$($phantom_generics:tt)*] }
        { $($passthrough:tt)* }
    ) => {
        $crate::const_fn!(
            @parse_args
            [$($type_generics)+],
            [$($impl_generics)+],
            [$($phantom_generics)*],
            ret_type: $ret_type,
            body: $body,
            rest: [$($rest)+],
            {$($passthrough)*}
        );
    };

    /*
     * Finish by parsing the arguments
     */

    // Parse normal arguments
    (
        @parse_args
        $(
            [$($type_generics:tt)+],
            [$($impl_generics:tt)+],
            [$($phantom_generics:tt)*],
        )?
        ret_type: $RetType:ty,
        body: $body:block,
        rest: [$( $arg_name:tt : $ArgType:ty ),+ $(,)?],
        {
            attrs: [$($attr:tt)*],
            vis: $vis:vis,
            name: $name:ident,
        }
    ) => {
        $($attr)* $vis const fn $name $(< $($impl_generics)+ >)?($( $arg_name : $ArgType ),+) -> $RetType $body

        $crate::raw_const_fn!(
            attrs: [
                #[doc = concat!("`ConstFn` version of [`", stringify!($name), "`](fn@", stringify!($name), ")")]
                #[allow(non_camel_case_types)]
            ],
            vis: $vis,
            name: $name,
            $(
                type_generics: [$($type_generics)+],
                impl_generics: [$($impl_generics)+],
                phantom_generics: ($($phantom_generics)*),
            )?
            arg_type: ($($ArgType,)+),
            arg_param: Arg,
            ret_type: $RetType,
            body: {
                let ($($arg_name,)+) = Arg::ITEM;
                $name $( ::<$($type_generics)+> )? ($($arg_name,)*)
            },
        );
    };
    // Parse raw arguments
    (
        @parse_args
        $(
            [$($type_generics:tt)+],
            [$($impl_generics:tt)+],
            [$($phantom_generics:tt)*],
        )?
        ret_type: $RetType:ty,
        body: $body:block,
        rest: [#[raw] $arg_name:ident: $ArgType:ty],
        {
            attrs: [$($attr:tt)*],
            vis: $vis:vis,
            name: $name:ident,
        }
    ) => {
        $crate::raw_const_fn!(
            attrs: [
                $($attr)*
                #[allow(non_camel_case_types)]
            ],
            vis: $vis,
            name: $name,
            $(
                type_generics: [$($type_generics)+],
                impl_generics: [$($impl_generics)+],
                phantom_generics: ($($phantom_generics)*),
            )?
            arg_type: $ArgType,
            arg_param: $arg_name,
            ret_type: $RetType,
            body: $body,
        );
    };
}

/// Defines a [`ConstFn`]
///
/// This macros API is very direct and expects a lot of knowledge from its user.
///
/// Normal developer should try [`const_fn!`](crate::const_fn).
/// This macro is its implementation detail.
/// It is exported if `const_fn` is not flexible enough.
#[doc(hidden)]
#[macro_export]
macro_rules! raw_const_fn {
    (
        attrs: [$(#[$attr:meta])*],
        vis: $vis:vis,
        name: $Name:ident,
        $(
            type_generics: [$($TG:tt)+],
            impl_generics: [$($IG:tt)+],
            phantom_generics: $PG:ty,
        )?
        arg_type: $ArgType:ty,
        arg_param: $Arg:ident,
        ret_type: $RetType:ty,
        body: $body:block,
    ) => {
        $(#[$attr])*
        $vis struct $Name $(< $($IG)+ >)? {
            $( phantom: ::core::marker::PhantomData<$PG> )?
        }

        const _: () = {
            impl $( < $($IG)+ > )? $crate::fields::utils::const_fn::ConstFn<$ArgType, $RetType> for $Name $( < $($TG)+ > )? {
                type Body<Arg: $crate::fields::utils::const_fn::Contains<$ArgType>> = Body<(Self, Arg)>;
            }
            $vis struct Body<T>(::std::marker::PhantomData<T>);
            impl<$Arg: $crate::fields::utils::const_fn::Contains<$ArgType> $( , $($IG)+)?>
                $crate::fields::utils::const_fn::Contains<$RetType> for Body<($Name $( < $($TG)+ > )?, $Arg)>
            {
                const ITEM: $RetType = $body;
            }
        };
    };
}

/// Implements `Contains<T>` for `C` where `T` is any tuple and `C` is a tuple
/// whose elements implement `Contains<_>` for their corresponding element in `T`
macro_rules! impl_tuples {
    ($( ($($C:ident : $T:ident),+) ),+$(,)?) => {$(
        impl<$($T, $C: Contains<$T>),+> Contains<($($T,)+)> for ($($C,)+) {
            const ITEM: ($($T,)+) = ($($C::ITEM,)+);
        }
    )+};
}

impl_tuples! [
    (C1: T1),
    (C1: T1, C2: T2),
    (C1: T1, C2: T2, C3: T3),
    (C1: T1, C2: T2, C3: T3, C4: T4),
    (C1: T1, C2: T2, C3: T3, C4: T4, C5: T5),
];

#[cfg(debug_assertions)]
#[allow(dead_code)]
mod compile_tests {
    const_fn! {
        fn non_generic(_arg: ()) -> () {}
    }
    const_fn! {
        fn single_const_generic<const N: usize>(_arg: ()) -> () {}
    }
    const_fn! {
        fn single_type_generic<T>(_arg: ()) -> () {}
    }
    const_fn! {
        fn single_type_generic_with_bound<T: Copy>(_arg: ()) -> () {}
    }
    const_fn! {
        fn mixed_generics<const N: usize, T, U, const O: usize>(_arg: ()) -> () {}
    }

    const_fn! {
        fn raw_arg(#[raw] _Arg: ()) -> () {
            _Arg::ITEM
        }
    }
}