aboutsummaryrefslogtreecommitdiff
path: root/azalea-buf/azalea-buf-macros/src/read.rs
blob: 7c8f1c9e3fe92727ce26a83d9be350d29dd9ff54 (plain)
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
use quote::{ToTokens, quote};
use syn::{Data, Field, FieldsNamed, Ident, punctuated::Punctuated, token::Comma};

pub fn create_fn_azalea_read(data: &Data) -> proc_macro2::TokenStream {
    match data {
        syn::Data::Struct(syn::DataStruct { fields, .. }) => match fields {
            syn::Fields::Named(FieldsNamed { named, .. }) => {
                let (read_fields, read_field_names) = read_named_fields(named);

                quote! {
                    fn azalea_read(buf: &mut std::io::Cursor<&[u8]>) -> std::result::Result<Self, azalea_buf::BufReadError> {
                        #(#read_fields)*
                        Ok(Self {
                            #(#read_field_names: #read_field_names),*
                        })
                    }
                }
            }
            syn::Fields::Unit => {
                quote! {
                    fn azalea_read(buf: &mut std::io::Cursor<&[u8]>) -> std::result::Result<Self, azalea_buf::BufReadError> {
                        Ok(Self)
                    }
                }
            }
            syn::Fields::Unnamed(fields) => {
                let read_fields = read_unnamed_fields(&fields.unnamed);

                quote! {
                    fn azalea_read(buf: &mut std::io::Cursor<&[u8]>) -> std::result::Result<Self, azalea_buf::BufReadError> {
                        Ok(Self(
                            #(#read_fields),*
                        ))
                    }
                }
            }
        },
        syn::Data::Enum(syn::DataEnum { variants, .. }) => {
            let mut match_contents = quote!();
            let mut variant_discrim: u32 = 0;
            let mut first = true;
            let mut first_reader = None;
            for variant in variants {
                let variant_name = &variant.ident;
                match &variant.discriminant.as_ref() {
                    Some(d) => {
                        variant_discrim = match &d.1 {
                            syn::Expr::Lit(e) => match &e.lit {
                                syn::Lit::Int(i) => i.base10_parse().unwrap(),
                                _ => panic!("Error parsing enum discriminant as int (is {e:?})"),
                            },
                            syn::Expr::Unary(_) => {
                                panic!("Negative enum discriminants are not supported")
                            }
                            _ => {
                                panic!("Error parsing enum discriminant as literal (is {:?})", d.1)
                            }
                        }
                    }
                    None => {
                        if !first {
                            variant_discrim += 1;
                        }
                    }
                }
                let reader = match &variant.fields {
                    syn::Fields::Named(f) => {
                        let (read_fields, read_field_names) = read_named_fields(&f.named);

                        quote! {
                            #(#read_fields)*
                            Ok(Self::#variant_name {
                                #(#read_field_names: #read_field_names),*
                            })
                        }
                    }
                    syn::Fields::Unnamed(fields) => {
                        let mut reader_code = quote! {};
                        for f in &fields.unnamed {
                            let is_variable_length =
                                f.attrs.iter().any(|a| a.path().is_ident("var"));
                            let limit =
                                f.attrs
                                    .iter()
                                    .find(|a| a.path().is_ident("limit"))
                                    .map(|a| {
                                        a.parse_args::<syn::LitInt>()
                                            .unwrap()
                                            .base10_parse::<u32>()
                                            .unwrap()
                                    });

                            if is_variable_length && limit.is_some() {
                                panic!("Fields cannot have both var and limit attributes");
                            }

                            if is_variable_length {
                                reader_code.extend(quote! {
                                    Self::#variant_name(azalea_buf::AzBufVar::azalea_read_var(buf)?),
                                });
                            } else if let Some(limit) = limit {
                                reader_code.extend(quote! {
                                    Self::#variant_name(azalea_buf::AzBufLimited::azalea_read_limited(buf, #limit)?),
                                });
                            } else {
                                reader_code.extend(quote! {
                                    Self::#variant_name(azalea_buf::AzBuf::azalea_read(buf)?),
                                });
                            }
                        }
                        quote! { Ok(#reader_code) }
                    }
                    syn::Fields::Unit => quote! {
                        Ok(Self::#variant_name)
                    },
                };
                if first {
                    first_reader = Some(reader.clone());
                    first = false;
                };

                match_contents.extend(quote! {
                    #variant_discrim => {
                        #reader
                    },
                });
            }

            let first_reader = first_reader.expect("There should be at least one variant");

            quote! {
                fn azalea_read(buf: &mut std::io::Cursor<&[u8]>) -> std::result::Result<Self, azalea_buf::BufReadError> {
                    let id = azalea_buf::AzBufVar::azalea_read_var(buf)?;

                    match id {
                        #match_contents
                        // you'd THINK this throws an error, but mojang decided to make it default for some reason
                        _ => {#first_reader}
                    }
                }
            }
        }
        _ => panic!("#[derive(AzBuf)] can only be used on structs"),
    }
}

fn read_named_fields(
    named: &Punctuated<Field, Comma>,
) -> (Vec<proc_macro2::TokenStream>, Vec<&Option<Ident>>) {
    let read_fields = named
        .iter()
        .map(|f| {
            let field_name = &f.ident;

            let reader_call = get_reader_call(f);
            quote! { let #field_name = #reader_call; }
        })
        .collect::<Vec<_>>();
    let read_field_names = named.iter().map(|f| &f.ident).collect::<Vec<_>>();

    (read_fields, read_field_names)
}

fn read_unnamed_fields(unnamed: &Punctuated<Field, Comma>) -> Vec<proc_macro2::TokenStream> {
    unnamed
        .iter()
        .map(|f| {
            let reader_call = get_reader_call(f);
            quote! { #reader_call }
        })
        .collect::<Vec<_>>()
}

fn get_reader_call(f: &Field) -> proc_macro2::TokenStream {
    let is_variable_length = f
        .attrs
        .iter()
        .any(|a: &syn::Attribute| a.path().is_ident("var"));
    let limit = f
        .attrs
        .iter()
        .find(|a| a.path().is_ident("limit"))
        .map(|a| {
            a.parse_args::<syn::LitInt>()
                .unwrap()
                .base10_parse::<u32>()
                .unwrap()
        });

    if is_variable_length && limit.is_some() {
        panic!("Fields cannot have both var and limit attributes");
    }

    let field_type = &f.ty;

    // do a different buf.write_* for each field depending on the type
    // if it's a string, use buf.write_string
    match field_type {
        syn::Type::Path(_) | syn::Type::Array(_) => {
            if is_variable_length {
                quote! {
                    azalea_buf::AzBufVar::azalea_read_var(buf)?
                }
            } else if let Some(limit) = limit {
                quote! {
                    azalea_buf::AzBufLimited::azalea_read_limited(buf, #limit)?
                }
            } else {
                quote! {
                    azalea_buf::AzBuf::azalea_read(buf)?
                }
            }
        }
        _ => panic!(
            "Error reading field {:?}: {}",
            f.ident.clone(),
            field_type.to_token_stream()
        ),
    }
}