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
#[macro_export]
macro_rules! Build {
    {
        $(#[$($attr:tt)*])*
        $vis:vis struct $name:ident {$(
            $fvis:vis $field:ident: $type:ty
        ),* $(,)?}
    } => {
        #[allow(non_upper_case_globals, non_snake_case, non_camel_case_types)]
        const _: () = {
            // add a module here to seal fields.
            impl<'ctx, M: 'ctx, E: effectful::environment::Environment> $crate::Build<'ctx, M, E> for $name 
            where
                $name: effectful::environment::DynBind<E> + effectful::bound::IsSync<E::NeedSend>
            {
                type Builder = $crate::builders::core::r#struct::StructBuilder<'ctx, __Info, M, E>;
            }

            $vis struct Builders<'ctx, M: 'ctx, E: effectful::environment::Environment> {
                $($field: <$type as $crate::Build<'ctx, M, E>>::Builder),*
            }

            unsafe impl<'ctx, M: 'ctx, E: effectful::environment::Environment> effectful::bound::IsSend<E::NeedSend> for Builders<'ctx, M, E> {}
            unsafe impl<'ctx, M: 'ctx, E: effectful::environment::Environment> effectful::bound::IsSync<E::NeedSync> for Builders<'ctx, M, E> {}

            #[derive(Copy, Clone, Debug)]
            $vis enum Field {
                $($field),*
            }

            effectful::is_send_sync!(Field);

            mod field_index {
                enum __Fields {
                    $($field),*
                }

                $(pub const $field: usize = __Fields::$field as usize;)*
            }

            $vis enum Error<'ctx, M: 'ctx, E: effectful::environment::Environment> {
                $($field(<<$type as $crate::Build<'ctx, M, E>>::Builder as $crate::BuilderTypes<E>>::Error)),*
            }

            unsafe impl<'ctx, M: 'ctx, E: effectful::environment::Environment> effectful::bound::IsSend<E::NeedSend> for Error<'ctx, M, E> {}
            unsafe impl<'ctx, M: 'ctx, E: effectful::environment::Environment> effectful::bound::IsSync<E::NeedSync> for Error<'ctx, M, E> {}

            impl ::core::fmt::Display for Field {
                fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    f.write_str(match self {
                        $(Field::$field => stringify!($field)),*
                    })
                }
            }

            impl<'ctx, M: 'ctx, E: effectful::environment::Environment> ::core::fmt::Debug for Error<'ctx, M, E> {
                fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    f.write_str(match self {
                        $(Error::$field(_) => stringify!($field)),*
                    })
                }
            }

            impl<'ctx, M: 'ctx, E: effectful::environment::Environment> ::core::fmt::Display for Error<'ctx, M, E> {
                fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    f.write_str(match self {
                        $(Error::$field(_) => stringify!($field)),*
                    })
                }
            }

            $vis struct __Info;

            impl<'ctx, M: 'ctx, E: effectful::environment::Environment> $crate::builders::core::r#struct::StructTypeInfo<'ctx, M, E> for __Info 
            where
                $name: effectful::environment::DynBind<E>
            {
                type Builders = Builders<'ctx, M, E>;
                type FieldMarker = Field;
                type T = $name;
                type Error = Error<'ctx, M, E>;
                type Seed = ($(<<$type as $crate::Build<'ctx, M, E>>::Builder as $crate::BuilderTypes<E>>::Seed),*);
                type ValueT = $crate::any::OwnedStatic<$name>;

                const FIELD_COUNT: usize = {
                    [$(stringify!($field)),*].len()
                };

                #[inline(always)]
                fn new_builders<'a>(seed: Self::Seed) -> effectful::environment::NativeForm<'a, Self::Builders, E> {
                    let ($($field),*) = seed;

                    todo!()

                    // $crate::effect::join(
                    //     ($(<<$type as $crate::Build<'ctx, M, E>>::Builder as $crate::Builder::<E>>::from_seed($field),)*)
                    // ).map(|($($field,)*)| {
                    //     Builders {
                    //         $($field),*
                    //     }
                    // })
                }

                fn from_builders<'a>(builders: Self::Builders) -> effectful::environment::NativeForm<'a, Result<Self::T, Self::Error>, E> {
                    use $crate::Builder;

                    todo!()

                    // $crate::effect::try_join(
                    //     (
                    //         $(|| builders.$field.build().map(|x| x.map_err(Error::$field)),)*
                    //     )
                    // ).map(|result| match result {
                    //     Ok(($($field,)*)) => Ok($name {
                    //         $($field),*
                    //     }),
                    //     Err(err) => Err(err)
                    // })
                }

                fn as_visitor<'a>(
                    marker: Self::FieldMarker,
                    builders: &'a mut Self::Builders,
                ) -> $crate::protocol::DynVisitor<'a, 'ctx, E> {
                    use $crate::protocol::AsVisitor;

                    match marker {
                        $(Field::$field => builders.$field.as_visitor()),*
                    }
                }

                fn marker_from_index(index: usize) -> Option<Self::FieldMarker> {
                    match index {
                        $(field_index::$field => Some(Field::$field),)*
                        _ => None
                    }
                }

                fn marker_from_name(name: &str) -> Option<Self::FieldMarker> {
                    match name {
                        $(stringify!($field) => Some(Field::$field),)*
                        _ => None
                    }
                }

                fn from_value(value: Self::ValueT) -> Self::T {
                    value.0
                }
            }
        };
    };
    {
        $(#[$($attr:tt)*])*
        $vis:vis enum $name:ident {$(
            $variant:ident($value:ty)
        ),* $(,)?}
    } => {
        #[allow(non_upper_case_globals, non_snake_case, non_camel_case_types)]
        const _: () = {
            // add a module here to seal fields.
            impl<'ctx, M: 'ctx, E: $crate::effect::Effect> $crate::Build<'ctx, M, E> for $name {
                type Builder = $crate::builders::core::r#enum::EnumBuilder<'ctx, __Info, M, E>;
            }

            $vis struct __Info;

            $vis enum __Builders<'ctx, M, E: Effect> {
                $($variant(<$value as $crate::Build<'ctx, M, E>>::Builder)),*
            }

            #[derive(Copy, Clone)]
            $vis enum __Marker {
                $($variant),*
            }

            impl ::core::fmt::Display for __Marker {
                fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    f.write_str(match self {
                        $(Self::$variant => stringify!($variant)),*
                    })
                }
            }

            mod variant_index {
                enum __Variants {
                    $($variant),*
                }

                $(pub const $variant: u32 = __Variants::$variant as u32;)*
            }

            $vis struct __ErrorBuilder<'ctx, M, E: Effect> {
                $($variant: Option<<<$value as $crate::Build<'ctx, M, E>>::Builder as BuilderTypes>::Error>),*
            }

            $vis enum __Error<'ctx, M, E: Effect> {
                __Guess {
                    $($variant: <<$value as $crate::Build<'ctx, M, E>>::Builder as BuilderTypes>::Error),*
                },
                $($variant(<<$value as $crate::Build<'ctx, M, E>>::Builder as BuilderTypes>::Error)),*
            }

            impl<'ctx, M, E: Effect> ::core::fmt::Display for __Error<'ctx, M, E> {
                fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    match self {
                        Self::__Guess {
                            $($variant),*
                        } => {
                            $(writeln!(f, "{}: {}", stringify!($variant), $variant)?;)*

                            Ok(())
                        }
                        $(Self::$variant(value) => write!(f, "{}: {}", stringify!($variant), value)),*
                    }
                }
            }

            impl<'ctx, M, E: Effect> ::core::fmt::Debug for __Error<'ctx, M, E> {
                fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    match self {
                        Self::__Guess {
                            $($variant),*
                        } => {
                            $(writeln!(f, "{}: {:?}", stringify!($variant), $variant)?;)*

                            Ok(())
                        }
                        $(Self::$variant(value) => write!(f, "{}: {:?}", stringify!($variant), value)),*
                    }
                }
            }

            impl<'ctx, M: 'ctx, E: $crate::effect::Effect> $crate::builders::core::r#enum::EnumBuildInfo<'ctx, M, E> for __Info {
                type Builders = __Builders<'ctx, M, E>;

                type Seed = ();

                type Error = __Error<'ctx, M, E>;

                type ValueT = $crate::any::OwnedStatic<$name>;

                type T = $name;

                type VariantMarker = __Marker;

                fn new_builder<'a>(
                    seed: Self::Seed,
                    variant: Self::VariantMarker,
                ) -> ErasedEffective<'a, Self::Builders, E> {
                    match variant {
                        $(__Marker::$variant => {
                            Builder::<E>::from_seed(Default::default()).map(|builder| __Builders::$variant(builder))
                        })*
                    }
                }

                fn finish_builder<'a>(
                    builder: Self::Builders,
                ) -> ErasedEffective<'a, Result<Self::T, Self::Error>, E> {
                    match builder {
                        $(__Builders::$variant(builder) => builder.build().map(|value| value.map($name::$variant).map_err(__Error::$variant))),*
                    }
                }

                fn from_value<'a>(value: TypeName::T<'a, 'ctx, Self::ValueT>) -> Self::T {
                    value.0
                }

                fn as_visitor<'a>(builder: &'a mut Self::Builders) -> DynVisitor<'a, 'ctx> {
                    match builder {
                        $(__Builders::$variant(builder) => builder.as_visitor()),*
                    }
                }

                fn marker_from_name(name: &str) -> Option<Self::VariantMarker> {
                    match name {
                        $(stringify!($variant) => Some(__Marker::$variant),)*
                        _ => None
                    }
                }

                fn marker_from_discriminant(discriminant: u32) -> Option<Self::VariantMarker> {
                    match discriminant {
                        $(variant_index::$variant => Some(__Marker::$variant),)*
                        _ => None
                    }
                }

                fn guess_variant<'a>(
                    seed: Self::Seed,
                    scope: DynRecoverableScope<'a, 'ctx, E>,
                ) -> ErasedEffective<'a, Result<Self::T, Self::Error>, E> {
                    E::ready((scope, Err(__ErrorBuilder::<M, E> { A: None, B: None })))
                        $(.or_else_update(|scope, result| {
                            let mut error = result.into_error();

                            <<$value as Build<M, E>>::Builder as Builder<_>>::from_seed(Default::default())
                                .map(|builder| (scope, builder))
                                .as_ctx(|(scope, builder)| scope.new_walk(builder.as_visitor()).cast())
                                .then(|((_, builder), _)| builder.build())
                                .map(|result| {
                                    result.map(X::$variant).map_err(|err| {
                                        error.$variant = Some(err);
                                        error
                                    })
                                })
                                .cast()
                        }))*
                        .map(|(_, result)| match result {
                            Ok(value) => Ok(value),
                            Err(err) => Err(__Error::__Guess {
                                $($variant: err.$variant.unwrap()),*
                            }),
                        })
                }
            }
        };
    };
}