gluer 0.9.2

A wrapper for Rust frameworks that eliminates redundant type and function definitions between the frontend and backend
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
use quote::ToTokens;
use std::{fmt::Debug, vec};
use syn::{spanned::Spanned, Lit};

use crate::{
    framework::Framework,
    parsing::{
        metadata::{parse_field_attr, MetaAttr, MetadataAttr},
        s_err,
    },
};

/// Function information.
#[derive(Clone, Debug)]
pub struct FnInfo {
    pub name: String,
    pub params: Vec<Field>,
    pub response: RustType,
    pub types: Vec<String>,
    pub docs: Vec<String>,
}

impl FnInfo {
    /// Generates function info from token input.
    pub fn from_tokens(item_fn: syn::ItemFn, metadata_attr: MetadataAttr) -> syn::Result<FnInfo> {
        let fn_name_ident = item_fn.sig.ident.clone();
        let name = fn_name_ident.to_string();
        let docs = get_docs(&item_fn.attrs);

        let mut dependencies = Vec::new();

        let params = item_fn
            .sig
            .inputs
            .iter()
            .filter_map(|param| match param {
                syn::FnArg::Typed(syn::PatType { pat, ty, .. }) => {
                    let pat = pat.to_token_stream().to_string();
                    if let Some(rust_type) = RustType::from_tokens(ty, &metadata_attr.custom) {
                        process_rust_type(&rust_type, &mut dependencies, &[]);
                        Some(Ok((pat, rust_type)))
                    } else {
                        None
                    }
                }
                syn::FnArg::Receiver(_) => Some(Err(s_err(
                    param.span(),
                    format!("Receiver parameter in function '{}' not allowed", name),
                ))),
            })
            .collect::<syn::Result<Vec<_>>>()?;

        let response = match &item_fn.sig.output {
            syn::ReturnType::Type(_, ty) => {
                if let Some(rust_type) = RustType::from_tokens(ty, &metadata_attr.custom) {
                    process_rust_type(&rust_type, &mut dependencies, &[]);
                    rust_type
                } else {
                    return Err(s_err(
                        ty.span(),
                        format!("Unsupported return type in function '{}'", name),
                    ));
                }
            }
            syn::ReturnType::Default => RustType::BuiltIn("()".to_string()),
        };

        let params_info: Vec<Field> = params
            .iter()
            .map(|(pat, ty)| Field {
                name: pat.clone(),
                ty: ty.clone(),
                docs: vec![],
                optional: false,
            })
            .collect();

        Ok(FnInfo {
            name,
            params: params_info,
            response,
            types: dependencies,
            docs,
        })
    }
}

/// Information type.
#[derive(Clone, Debug)]
pub enum TypeCategory {
    Struct(TypeInfo),
    Enum(TypeInfo),
    Type(TypeInfo),
}

/// Type information.
#[derive(Clone, Debug)]
pub struct TypeInfo {
    pub name: String,
    pub generics: Vec<String>,
    pub fields: Vec<Field>,
    pub dependencies: Vec<String>,
    pub docs: Vec<String>,
}

impl TypeInfo {
    /// Generates type info of structs from token input
    pub fn from_struct_tokens(
        item_struct: syn::ItemStruct,
        metadata_attr: MetadataAttr,
    ) -> syn::Result<Self> {
        let struct_name_ident = item_struct.ident.clone();
        let struct_name = struct_name_ident.to_string();
        let generics: Vec<String> = item_struct
            .generics
            .type_params()
            .map(|type_param| type_param.ident.to_string())
            .collect();
        let docs = get_docs(&item_struct.attrs);

        let mut dependencies: Vec<String> = Vec::new();

        let item_struct_fields = item_struct.fields.clone();

        let fields = item_struct_fields
            .iter()
            .filter_map(|field| {
                let ident = match field.ident.clone() {
                    Some(ident) => ident.to_string(),
                    None => {
                        return Some(Err(s_err(
                            field.span(),
                            "Unnamed fields like `self` are not supported",
                        )))
                    }
                };

                let docs = get_docs(&field.attrs);

                let meta_attr = match parse_field_attr(&field.attrs) {
                    Ok(meta_attr) => meta_attr,
                    Err(_) => {
                        return Some(Err(s_err(
                            field.span(),
                            format!(
                                "An error occurred when parsing field attributes on struct '{}'",
                                struct_name
                            ),
                        )))
                    }
                };

                let MetaAttr {
                    into,
                    skip,
                    optional,
                } = meta_attr;

                let field_ty = if let Some(conv_fn) = into.clone() {
                    conv_fn
                } else {
                    field.ty.clone()
                };

                if skip {
                    return None;
                }

                if let Some(ty) = RustType::from_tokens(&field_ty, &metadata_attr.custom) {
                    process_rust_type(&ty, &mut dependencies, &generics);
                    Some(Ok(Field {
                        name: ident,
                        ty,
                        docs,
                        optional,
                    }))
                } else {
                    Some(Err(s_err(field.span(), "Unsupported Rust Type")))
                }
            })
            .collect::<syn::Result<Vec<_>>>()?;

        Ok(Self {
            name: struct_name,
            generics,
            fields,
            dependencies,
            docs,
        })
    }

    /// Generates type info of enums from token input
    pub fn from_enum_tokens(item_enum: syn::ItemEnum, _: MetadataAttr) -> syn::Result<Self> {
        if !item_enum.generics.params.is_empty() {
            return Err(s_err(
                item_enum.generics.span(),
                "Generics and Lifetimes not supported for enums",
            ));
        }

        let enum_name_ident = item_enum.ident.clone();
        let enum_name = enum_name_ident.to_string();
        let docs = get_docs(&item_enum.attrs);

        let fields = item_enum
            .variants
            .iter()
            .map(|variant| {
                if !variant.fields.is_empty() {
                    return Err(s_err(
                        variant.fields.span(),
                        "Enums with values are not supported",
                    ));
                }
                let ident = variant.ident.to_string();
                let docs = get_docs(&variant.attrs);
                Ok(Field {
                    name: ident,
                    ty: RustType::None,
                    docs,
                    optional: false,
                })
            })
            .collect::<syn::Result<Vec<_>>>()?;

        Ok(Self {
            name: enum_name,
            generics: vec![],
            fields,
            dependencies: vec![],
            docs,
        })
    }

    /// Generates type info of types from token input
    pub fn from_type_tokens(
        item_type: syn::ItemType,
        metadata_attr: MetadataAttr,
    ) -> syn::Result<Self> {
        let type_name_ident = item_type.ident.clone();
        let type_name = type_name_ident.to_string();
        let generics: Vec<String> = item_type
            .generics
            .type_params()
            .map(|type_param| type_param.ident.to_string())
            .collect();
        let docs = get_docs(&item_type.attrs);

        let mut dependencies: Vec<String> = Vec::new();

        let ty = RustType::from_tokens(&item_type.ty, &metadata_attr.custom)
            .ok_or_else(|| s_err(item_type.ty.span(), "Unsupported type"))?;

        process_rust_type(&ty, &mut dependencies, &generics);

        Ok(Self {
            name: type_name,
            generics,
            fields: vec![Field {
                name: String::new(),
                ty,
                docs: vec![],
                optional: false,
            }],
            dependencies,
            docs,
        })
    }
}

/// Fills the dependencies for `Custom` and `CustomGeneric` types
fn process_rust_type(rust_type: &RustType, dependencies: &mut Vec<String>, generics: &[String]) {
    match rust_type {
        RustType::Custom(inner_ty)
            if !dependencies.contains(inner_ty) && !generics.contains(inner_ty) =>
        {
            dependencies.push(inner_ty.clone());
        }
        RustType::CustomGeneric(outer_ty, inner_tys) => {
            if !dependencies.contains(outer_ty) && !generics.contains(outer_ty) {
                dependencies.push(outer_ty.clone());
            }
            for inner_ty in inner_tys {
                process_rust_type(inner_ty, dependencies, generics);
            }
        }
        RustType::Tuple(inner_tys) => {
            for inner_ty in inner_tys {
                process_rust_type(inner_ty, dependencies, generics);
            }
        }
        RustType::Generic(_, inner_tys) => {
            for inner_ty in inner_tys {
                process_rust_type(inner_ty, dependencies, generics);
            }
        }
        _ => {}
    }
}

/// Gets docs by collecting the `LitStr` of `doc` attributes
fn get_docs(attrs: &[syn::Attribute]) -> Vec<String> {
    attrs
        .iter()
        .filter_map(|attr| {
            if !attr.path().is_ident("doc") {
                return None;
            }

            let name_value = attr.meta.require_name_value().ok()?;
            let syn::Expr::Lit(expr_lit) = &name_value.value else {
                return None;
            };
            let Lit::Str(lit_str) = &expr_lit.lit else {
                return None;
            };

            Some(lit_str.value())
        })
        .map(|s| s.trim().trim_start_matches('/').trim().to_string())
        .collect()
}

/// Field information.
#[derive(Clone, Debug)]
pub struct Field {
    pub name: String,
    pub ty: RustType,
    pub docs: Vec<String>,
    pub optional: bool,
}

/// The parsed Rust Type.
#[derive(Debug, PartialEq, Clone)]
pub enum RustType {
    BuiltIn(String),
    Generic(String, Vec<RustType>),
    Tuple(Vec<RustType>),
    Custom(String),
    CustomGeneric(String, Vec<RustType>),
    None,
}

impl RustType {
    const RUST_TYPES: &'static [&'static str] = &[
        "bool", "char", "str", "u8", "u16", "u32", "u64", "u128", "i8", "i16", "i32", "i64",
        "i128", "usize", "isize", "f16", "f32", "f64", "f128", "String",
    ];

    const BUILTIN_GENERICS: &'static [&'static str] = &["HashMap", "Vec", "Option", "Result"];

    fn is_builtin_type(ident: &syn::Ident) -> bool {
        Self::RUST_TYPES.contains(&ident.to_string().as_str())
    }

    fn is_builtin_generic(ident: &syn::Ident) -> bool {
        Self::BUILTIN_GENERICS.contains(&ident.to_string().as_str())
    }

    fn is_custom(ident: &syn::Ident, custom: &[String]) -> bool {
        custom.contains(&ident.to_string())
    }

    /// Returns an optional Rust Type, if `None` the type needs to be skipped
    fn from_tokens(ty: &syn::Type, custom: &[String]) -> Option<Self> {
        match ty {
            syn::Type::Path(type_path) => {
                let segment = type_path.path.segments.last().unwrap();
                let ident = &segment.ident;

                if Self::is_builtin_type(ident) && !Self::is_custom(ident, custom) {
                    Some(Self::BuiltIn(ident.to_string()))
                } else if Framework::is_skip_type(ident) && !Self::is_custom(ident, custom) {
                    None
                } else if (Framework::is_extractor_type(ident) || Self::is_builtin_generic(ident))
                    && !Self::is_custom(ident, custom)
                {
                    if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
                        let inner_types = Self::extract_inner_types(args, custom);
                        Some(Self::Generic(ident.to_string(), inner_types))
                    } else {
                        Some(Self::Generic(ident.to_string(), vec![]))
                    }
                } else if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
                    let inner_types = Self::extract_inner_types(args, custom);
                    Some(Self::CustomGeneric(ident.to_string(), inner_types))
                } else {
                    Some(Self::Custom(ident.to_string()))
                }
            }
            syn::Type::Reference(syn::TypeReference { elem, .. })
            | syn::Type::Paren(syn::TypeParen { elem, .. })
            | syn::Type::Group(syn::TypeGroup { elem, .. }) => Self::from_tokens(elem, custom),

            syn::Type::Tuple(type_tuple) => {
                if type_tuple.elems.is_empty() {
                    return Some(Self::BuiltIn(String::from("()")));
                }
                let inner_types: Vec<Self> = type_tuple
                    .elems
                    .iter()
                    .filter_map(|t| Self::from_tokens(t, custom))
                    .collect();
                Some(Self::Tuple(inner_types))
            }
            syn::Type::Slice(syn::TypeSlice { elem, .. })
            | syn::Type::Array(syn::TypeArray { elem, .. }) => Self::from_tokens(elem, custom)
                .map(|inner| Self::Generic("Vec".to_string(), vec![inner])),
            _ => None,
        }
    }

    /// Recursively get inner types
    fn extract_inner_types(
        args: &syn::AngleBracketedGenericArguments,
        custom: &[String],
    ) -> Vec<Self> {
        args.args
            .iter()
            .filter_map(|arg| {
                if let syn::GenericArgument::Type(inner_ty) = arg {
                    Self::from_tokens(inner_ty, custom)
                } else {
                    None
                }
            })
            .collect()
    }
}