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
use proc_macro::{self, TokenStream};
use proc_macro2 as pm2;
use quote::ToTokens;

enum ConstraintItem {
    Context(syn::Ident),
    Access(Vec<syn::Type>),
}

impl syn::parse::Parse for ConstraintItem {
    fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
        let attr: syn::Ident = input.parse()?;
        match attr.to_string().as_str() {
            "context" => {
                let _: syn::Token![=] = input.parse()?;
                let value = input.parse()?;
                Ok(ConstraintItem::Context(value))
            }
            "access" => {
                let content;
                let _: syn::token::Paren = syn::parenthesized!(content in input);
                let punc =
                    syn::punctuated::Punctuated::<syn::Type, syn::Token![,]>::parse_terminated(
                        &content,
                    )?;
                Ok(ConstraintItem::Access(punc.into_iter().collect()))
            }
            _ => Err(syn::Error::new_spanned(
                attr,
                "unsupported persian-rug constraint",
            )),
        }
    }
}

struct ConstraintArgs {
    pub context: syn::Ident,
    pub used_types: Vec<syn::Type>,
}

impl syn::parse::Parse for ConstraintArgs {
    fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
        let punc =
            syn::punctuated::Punctuated::<ConstraintItem, syn::Token![,]>::parse_terminated(input)?;
        let mut context = None;
        let mut used_types = Vec::new();

        for item in punc.into_iter() {
            match item {
                ConstraintItem::Context(id) => {
                    context = Some(id);
                }
                ConstraintItem::Access(tys) => {
                    used_types.extend(tys);
                }
            }
        }

        context
            .map(|context| Self {
                context,
                used_types,
            })
            .ok_or_else(|| {
                syn::Error::new(
                    pm2::Span::call_site(),
                    "No context provided for constraints.",
                )
            })
    }
}

/// Add the type constraints necessary for an impl using persian-rug.
///
/// Rust currently requires all relevant constraints to be written out
/// for every impl using a given type. For persian-rug in particular,
/// there are typically many constraints of a simple kind: for every
/// type owned by the given `Context`, there must be an `Owner`
/// implementation for the context and there must be a matching
/// `Contextual` implementation for the type. This macro simply
/// generates these constraints for you.
///
/// The attribute takes two types of argument:
/// - `context` specifies the name of the type of the context.
/// - `access(...)` specifies the types that this impl requires to
///   exist within that context. Typically each type requires some
///   other types to also exist in its context for it to be
///   well-formed.  This argument needs to be given the transitive
///   closure of all such types, both direct and indirect dependencies
///   of the impl itself. It is unfortunately not possible at present
///   to find the indirect dependencies automatically.
///
/// Example:
/// ```rust
/// use persian_rug::{contextual, Context, Mutator, Proxy};
///
/// #[contextual(C)]
/// struct Foo<C: Context> {
///    _marker: core::marker::PhantomData<C>,
///    a: i32
/// }
///
/// struct Bar<C: Context> {
///    foo: Proxy<Foo<C>>
/// }
///
/// #[persian_rug::constraints(context = C, access(Foo<C>))]
/// impl<C> Bar<C> {
///    pub fn new<M: Mutator<Context=C>>(foo: Foo<C>, mut mutator: M) -> Self {
///        Self { foo: mutator.add(foo) }
///    }
/// }
/// ```
#[proc_macro_attribute]
pub fn constraints(args: TokenStream, input: TokenStream) -> TokenStream {
    let mut target: syn::Item = syn::parse_macro_input!(input);

    let generics = match &mut target {
        syn::Item::Enum(e) => &mut e.generics,
        syn::Item::Fn(f) => &mut f.sig.generics,
        syn::Item::Impl(i) => &mut i.generics,
        syn::Item::Struct(s) => &mut s.generics,
        syn::Item::Trait(t) => &mut t.generics,
        syn::Item::TraitAlias(t) => &mut t.generics,
        syn::Item::Type(t) => &mut t.generics,
        syn::Item::Union(u) => &mut u.generics,
        _ => {
            return syn::Error::new(
                pm2::Span::call_site(),
                "This attribute extends a where clause, or generic constraints. It cannot be used here."
            )
                .to_compile_error()
                .into();
        }
    };

    let ConstraintArgs {
        context,
        used_types,
    } = syn::parse_macro_input!(args);

    let wc = generics.make_where_clause();

    let mut getters = syn::punctuated::Punctuated::<syn::TypeParamBound, syn::token::Add>::new();
    getters.push(syn::parse_quote! { ::persian_rug::Context });
    for ty in &used_types {
        getters.push(syn::parse_quote! { ::persian_rug::Owner<#ty> });
    }

    wc.predicates.push(syn::parse_quote! {
        #context: #getters
    });

    for ty in &used_types {
        wc.predicates.push(syn::parse_quote! {
            #ty: ::persian_rug::Contextual<Context = #context>
        });
    }

    target.into_token_stream().into()
}

/// Convert an annotated struct into a `Context`
///
/// Each field marked with `#[table]` will be converted to be a
/// `Table` of values of the same type. An implementation of `Context`
/// will be provided. In addition, an implementation of `Owner` for
/// each field type will be derived for the overall struct.
///
/// Note that a `Context` can only contain one table of each type.
///
/// Example:
/// ```rust
/// use persian_rug::{contextual, persian_rug, Proxy};
///
/// #[contextual(MyRug)]
/// struct Foo {
///    a: i32
/// }
///
/// #[contextual(MyRug)]
/// struct Bar {
///    a: i32,
///    b: Proxy<Foo>
/// };
///
/// #[persian_rug]
/// struct MyRug(#[table] Foo, #[table] Bar);
/// ```
#[proc_macro_attribute]
pub fn persian_rug(_args: TokenStream, input: TokenStream) -> TokenStream {
    let syn::DeriveInput {
        attrs,
        vis,
        ident: ty_ident,
        data,
        generics
    } = syn::parse_macro_input!(input);

    let (generics, ty_generics, wc) = generics.split_for_impl();

    let mut impls = pm2::TokenStream::new();

    let body = if let syn::Data::Struct(s) = data {
        let mut fields = syn::punctuated::Punctuated::<syn::Field, syn::Token![,]>::new();

        let mut process_field = |field: &syn::Field| {
            let is_table = field.attrs.iter().any(|attr| attr.path.is_ident("table"));

            let field_type = &field.ty;
            let ident = field
                .ident
                .as_ref()
                .map(|id| syn::Member::Named(id.clone()))
                .unwrap_or_else(|| {
                    syn::Member::Unnamed(syn::Index {
                        index: fields.len() as u32,
                        span: pm2::Span::call_site(),
                    })
                });

            let vis = &field.vis;

            let attrs = field
                .attrs
                .iter()
                .cloned()
                .filter(|a| !a.path.is_ident("table"))
                .collect::<Vec<_>>();

            if !is_table {
                fields.push(field.clone());
            } else {
                fields.push(syn::Field {
                    attrs,
                    vis: vis.clone(),
                    ident: if let syn::Member::Named(id) = &ident {
                        Some(id.clone())
                    } else {
                        None
                    },
                    colon_token: field.colon_token,
                    ty: syn::parse_quote! {
                        ::persian_rug::Table<#field_type>
                    },
                });

                impls.extend(quote::quote! {
                    impl ::persian_rug::Owner<#field_type> for #ty_ident #ty_generics #wc {
                        fn add(&mut self, what: #field_type) -> ::persian_rug::Proxy<#field_type> {
                            self.#ident.push(what)
                        }
                        fn get(&self, what: &::persian_rug::Proxy<#field_type>) -> &#field_type {
                            self.#ident.get(what).unwrap()
                        }
                        fn get_mut(&mut self, what: &::persian_rug::Proxy<#field_type>) -> &mut #field_type {
                            self.#ident.get_mut(what).unwrap()
                        }
                        fn get_iter(&self) -> ::persian_rug::TableIterator<'_, #field_type> {
                            self.#ident.iter()
                        }
                        fn get_iter_mut(&mut self) -> ::persian_rug::TableMutIterator<'_, #field_type> {
                            self.#ident.iter_mut()
                        }
                        fn get_proxy_iter(&self) -> ::persian_rug::TableProxyIterator<'_, #field_type> {
                            self.#ident.iter_proxies()
                        }
                    }
                });
            }
        };

        match s.fields {
            syn::Fields::Named(syn::FieldsNamed { named, .. }) => {
                for field in named.iter() {
                    (process_field)(field);
                }
                quote::quote! {
                    #vis struct #ty_ident #generics #wc {
                        #fields
                    }
                }
            }
            syn::Fields::Unnamed(syn::FieldsUnnamed { unnamed, .. }) => {
                for field in unnamed.iter() {
                    (process_field)(field);
                }
                quote::quote! {
                    #vis struct #ty_ident #generics #wc(
                        #fields
                    );
                }
            }
            syn::Fields::Unit => {
                quote::quote! {
                    #vis struct #ty_ident #generics #wc;
                }
            }
        }
    } else {
        return syn::Error::new(
            pm2::Span::call_site(),
            "Only structs can be annotated as persian-rugs.",
        )
        .to_compile_error()
        .into();
    };

    let attrs = {
        let mut res = pm2::TokenStream::new();
        for attr in attrs {
            attr.to_tokens(&mut res);
        }
        res
    };

    let res = quote::quote! {
        #attrs
        #body

        impl #generics ::persian_rug::Context for #ty_ident #ty_generics #wc {
            fn add<T>(&mut self, what: T) -> ::persian_rug::Proxy<T>
            where
                #ty_ident #ty_generics: ::persian_rug::Owner<T>,
                T: ::persian_rug::Contextual<Context=Self>
            {
                <Self as ::persian_rug::Owner<T>>::add(self, what)
            }

            fn get<T>(&self, what: &::persian_rug::Proxy<T>) -> &T
            where
                #ty_ident #ty_generics: ::persian_rug::Owner<T>,
                T: ::persian_rug::Contextual<Context=Self>
            {
                <Self as ::persian_rug::Owner<T>>::get(self, what)
            }

            fn get_mut<T>(&mut self, what: &::persian_rug::Proxy<T>) -> &mut T
            where
                #ty_ident #ty_generics: ::persian_rug::Owner<T>,
                T: ::persian_rug::Contextual<Context=Self>
            {
                <Self as ::persian_rug::Owner<T>>::get_mut(self, what)
            }

            fn get_iter<T>(&self) -> ::persian_rug::TableIterator<'_, T>
            where
                #ty_ident #ty_generics: ::persian_rug::Owner<T>,
                T: ::persian_rug::Contextual<Context=Self>
            {
                <Self as ::persian_rug::Owner<T>>::get_iter(self)
            }

            fn get_iter_mut<T>(&mut self) -> ::persian_rug::TableMutIterator<'_, T>
            where
                #ty_ident #ty_generics: ::persian_rug::Owner<T>,
                T: ::persian_rug::Contextual<Context=Self>
            {
                <Self as ::persian_rug::Owner<T>>::get_iter_mut(self)
            }

            fn get_proxy_iter<T>(&self) -> ::persian_rug::TableProxyIterator<'_, T>
            where
                #ty_ident #ty_generics: ::persian_rug::Owner<T>,
                T: ::persian_rug::Contextual<Context=Self>
            {
                <Self as ::persian_rug::Owner<T>>::get_proxy_iter(self)
            }
        }

        #impls
    };

    res.into()
}

/// Provide a implementation of `Contextual` for a type.
///
/// This is a very simple derive-style macro, that creates an
/// impl for `Contextual` for the type it annotates. It takes
/// one argument, which is the `Context` type that this
/// type belongs to.
///
/// Example:
/// ```rust
/// use persian_rug::{contextual, Context};
///
/// #[contextual(C)]
/// struct Foo<C: Context> {
///    _marker: core::marker::PhantomData<C>
/// }
/// ```
/// which is equivalent to the following:
/// ```rust
/// use persian_rug::{Context, Contextual};
///
/// struct Foo<C: Context> {
///    _marker: core::marker::PhantomData<C>
/// }
///
/// impl<C: Context> Contextual for Foo<C> {
///    type Context = C;
/// }
/// ```
#[proc_macro_attribute]
pub fn contextual(args: TokenStream, input: TokenStream) -> TokenStream {
    let body = pm2::TokenStream::from(input.clone());

    let syn::DeriveInput {
        ident, generics, ..
    } = syn::parse_macro_input!(input);

    if args.is_empty() {
        return syn::Error::new(
            pm2::Span::call_site(),
            "You must specify the associated context when using contextual.",
        )
        .to_compile_error()
        .into();
    }

    let context: syn::Type = syn::parse_macro_input!(args);

    let (generics, ty_generics, wc) = generics.split_for_impl();

    let res = quote::quote! {
        #body

        impl #generics ::persian_rug::Contextual for #ident #ty_generics #wc {
            type Context = #context;
        }
    };

    res.into()
}