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
use std::any::Any;
use std::borrow::Borrow;
use std::ops::Deref;

use proc_macro2::{Literal, TokenStream, Span};
use quote::__private::ext::RepToTokensExt;
use quote::{quote, ToTokens};
use syn::*;

#[proc_macro_attribute]
pub fn assign_targets (_input: proc_macro::TokenStream, alt: proc_macro::TokenStream) -> proc_macro::TokenStream {
    alt
}

#[proc_macro_attribute]
pub fn assign_rhs (_input: proc_macro::TokenStream, alt: proc_macro::TokenStream) -> proc_macro::TokenStream {
    alt
}

#[proc_macro_derive(Assign)]
pub fn assign_macro (input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let DeriveInput { 
        generics, 
        attrs, 
        vis: _, 
        ident, 
        data
    } = parse_macro_input!(input as DeriveInput);

    let targets = attrs.iter()
        .filter_map(|x| match x.parse_meta().unwrap() {
            Meta::List(list) => if list.path.is_ident("assign_targets") {
                return Some(list.nested.into_iter()
                    .map(|y| match y {
                        NestedMeta::Meta(meta) => meta.path().get_ident().unwrap().clone(),
                        _ => panic!("Unexpected error")
                    }))
            } else { None },
            _ => None
        })
        .flatten();

    let rhss = attrs.iter()
        .filter_map(|x| match x.parse_meta().unwrap() {
            Meta::List(list) => if list.path.is_ident("assign_rhs") {
                return Some(list.nested.into_iter()
                    .map(|y| match y {
                        NestedMeta::Meta(meta) => meta.path().get_ident().unwrap().clone(),
                        _ => panic!("Unexpected error")
                    }))
            } else { None },
            _ => None
        })
        .flatten()
        .collect::<Vec<Ident>>();

    let mut output = Vec::new();
    for target in targets {
        for rhs in rhss.iter() {
            output.push(assign_macro_impl(ident.clone(), generics.clone(), target.clone(), rhs.clone()));
        }
    }

    let output = quote! { #(#output)* };
    output.into()
}

fn assign_macro_impl (target: Ident, generics: Generics, original: Ident, rhs: Ident) -> proc_macro2::TokenStream {
    let original_name = format!("{original}");
    let original_fun = Ident::new(original_name.to_lowercase().as_str(), original.span());

    let assign_trait = Ident::new(&format!("{}Assign", original_name), original.span());
    let assign_fun = Ident::new(&format!("{}_assign", original_name.to_lowercase()), original.span());

    quote! {
        impl #assign_trait<#rhs> for #target #generics {
            #[inline(always)]
            fn #assign_fun (&mut self, rhs: #rhs) {
                *self = #original::<#rhs>::#original_fun(*self, rhs)
            } 
        } 
    }
}

// ARRAY GENERATOR
use syn::parse::Parse;
use syn::punctuated::Punctuated;
use syn::token::Comma;

struct ArrInput {
    expr: Expr,
    len: Lit
}

impl Parse for ArrInput {
    fn parse(input: parse::ParseStream) -> Result<Self> {
        let expr = input.parse::<Expr>()?;
        input.parse::<Token![;]>()?;
            
        Ok(ArrInput {
            expr,
            len: input.parse::<Lit>()?
        })
    }
}

#[proc_macro]
pub fn arr (input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input = parse_macro_input!(input as ArrInput);

    let len = match input.len {
        Lit::Int(x) => x.base10_parse::<usize>().unwrap(),
        _ => panic!("Only integers are valid as array lengths")
    };

    let expresions = (0..len).into_iter()
        .map(|i| match input.expr.clone() {
            Expr::Lit(lit) => lit.into_token_stream(),
            Expr::Closure(c) => {
                assert!(c.inputs.len() == 1 && matches!(&c.inputs[0], Ident), "Invalid expresion");
                let ident = match &c.inputs[0] {
                    Pat::Ident(ident) => ident.clone().ident,
                    _ => panic!("Input is not an identity")
                };

                replace_ident(*c.body, ident, Lit::Int(Literal::usize_suffixed(i).into())).into_token_stream()
            },
            _ => panic!("Invalid array input")
        }).collect::<Punctuated<TokenStream, Comma>>();

    let output = quote! { [#expresions] };
    output.into()
}

fn replace_ident (expr: impl Into<Expr>, find: Ident, replace: Lit) -> Expr {
    match expr.into() {
        Expr::Array(mut array) => {
            array.elems = array.elems.into_iter()
                .map(|elem| replace_ident(elem, find.clone(), replace.clone()))
                .collect::<Punctuated<Expr, Comma>>();

            Expr::Array(array)
        },

        Expr::Assign(mut assign) => {
            assign.right = Box::new(replace_ident(*assign.right, find.clone(), replace.clone()));
            Expr::Assign(assign)
        },

        Expr::AssignOp(mut assign) => {
            assign.right = Box::new(replace_ident(*assign.right, find.clone(), replace.clone()));
            Expr::AssignOp(assign)
        },

        Expr::Binary(mut bin) => {
            bin.left = Box::new(replace_ident(*bin.left, find.clone(), replace.clone()));
            bin.right = Box::new(replace_ident(*bin.right, find.clone(), replace.clone()));
            Expr::Binary(bin)
        },

        Expr::Path(path) => {
            let true_path = path.clone().path;
            if true_path.segments.len() == 1 && true_path.segments[0].ident == find { return Expr::Lit(ExprLit { attrs: path.attrs, lit: replace }); }
            Expr::Path(path)
        },

        Expr::Unary(mut unary) => {
            unary.expr = Box::new(replace_ident(*unary.expr, find.clone(), replace.clone()));
            Expr::Unary(unary)
        },

        Expr::MethodCall(mut call) => {
            call.receiver = Box::new(replace_ident(*call.receiver, find.clone(), replace.clone()));
            call.args = call.args.into_iter()
                .map(|elem| replace_ident(elem, find.clone(), replace.clone()))
                .collect::<Punctuated<Expr, Comma>>();
            Expr::MethodCall(call)
        },

        Expr::Group(mut group) => {
            group.expr = Box::new(replace_ident(*group.expr, find.clone(), replace.clone()));
            Expr::Group(group)
        },

        Expr::Paren(mut paren) => {
            paren.expr = Box::new(replace_ident(*paren.expr, find.clone(), replace.clone()));
            Expr::Paren(paren)
        },

        Expr::Cast(mut cast) => {
            cast.expr = Box::new(replace_ident(*cast.expr, find.clone(), replace.clone()));
            Expr::Cast(cast)
        },

        Expr::Index(mut idx) => {
            idx.expr = Box::new(replace_ident(*idx.expr, find.clone(), replace.clone()));
            idx.index = Box::new(replace_ident(*idx.index, find.clone(), replace.clone()));
            Expr::Index(idx)
        },

        Expr::Field(mut field) => {
            field.base = Box::new(replace_ident(*field.base, find.clone(), replace.clone()));
            Expr::Field(field)
        },

        Expr::Lit(lit) => Expr::Lit(lit),
        expr => panic!("Unidentified expression: {expr:?}")
    }
}

// GENERIC CONSTANTS
struct ConstsInput {
    pre: Ident,
    len: Lit,
    ty: Ident
}

impl Parse for ConstsInput {
    fn parse(input: parse::ParseStream) -> Result<Self> {
        let pre = input.parse::<Ident>()?;
        input.parse::<Token![;]>()?;
        let len = input.parse::<Lit>()?;
        input.parse::<Token![as]>()?;

        Ok(ConstsInput {
            pre,
            len,
            ty: input.parse::<Ident>()?
        })
    }
}


#[proc_macro]
pub fn consts (input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input = parse_macro_input!(input as ConstsInput);

    let ty = input.ty;
    let len = match input.len {
        Lit::Int(x) => x.base10_parse::<usize>().unwrap(),
        _ => panic!("Only integers are valid as consts lengths")
    };


    let consts : Punctuated<proc_macro2::TokenStream, Comma> = (0..len).into_iter()
        .map(|i| Ident::new(&format!("{:?}{i}", input.pre), Span::call_site()))
        .map(|cst| quote! { const #cst: #ty })
        .collect();

    consts.to_token_stream().into()
}