robotech-macros 1.15.1

Backend service implementation for the RoboTech platform, providing RESTful APIs and business logic for web applications.
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
430
431
432
433
434
435
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{Attribute, Data, DeriveInput, Field, Fields, parse::{Parse, ParseStream}, Token, LitStr};
use wheel_rs::str_utils::{split_camel_case, CamelFormat};

/// vo宏参数
pub struct VoArgs {
    pub mo_crate: Option<String>,
}

impl Parse for VoArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut mo_crate = None;
        while !input.is_empty() {
            let key: syn::Ident = input.parse()?;
            let _: Token![=] = input.parse()?;
            if key == "mo_crate" {
                let value: LitStr = input.parse()?;
                mo_crate = Some(value.value());
            }
            if !input.is_empty() {
                let _: Token![,] = input.parse()?;
            }
        }
        Ok(VoArgs { mo_crate })
    }
}

/// 检查字段是否已经有某个属性
fn has_attribute(attrs: &[Attribute], name: &str) -> bool {
    attrs.iter().any(|attr| attr.path().is_ident(name))
}

/// 分析字段类型,生成对应的属性宏
fn generate_field_attrs(field: &Field) -> TokenStream {
    let ty = &field.ty;

    // 检查是否已经有 serde_as、from 或 builder 属性
    let has_from = has_attribute(&field.attrs, "from");
    let has_builder = has_attribute(&field.attrs, "builder");

    let mut attrs = TokenStream::new();

    if !has_from {
        // 添加 o2o 的 from 属性
        if let Some(from_attr) = generate_from_attr(ty) {
            attrs.extend(from_attr);
        }
    }

    if !has_builder {
        // 添加 builder 属性(仅针对 Option<T> 类型)
        if let Some(builder_attr) = generate_builder_attr(field) {
            attrs.extend(builder_attr);
        }
    }

    attrs
}

/// 生成 from 属性
fn generate_from_attr(ty: &syn::Type) -> Option<TokenStream> {
    Some(match ty {
        syn::Type::Path(type_path) => {
            let path_str = type_path.path.segments.last().unwrap().ident.to_string();

            // 检查是否是 Vo 后缀,如果是,说明是BelongsTo关系的字段
            if path_str.ends_with("Vo") {
                return Some(quote! { #[from(belongs_to_owned(~))] });
            }

            // 检查是否是 Option<T> 类型
            if is_option_type(ty) {
                if let Some(inner_ty) = extract_option_inner_type(type_path) {
                    // 处理 Option<VoType>:关联关系字段,用户可能手动写了 Option
                    if inner_ty.ends_with("Vo") {
                        return Some(quote! { #[from(belongs_to_owned(~))] });
                    }
                    return Some(match inner_ty.as_str() {
                        "u8" | "u16" | "u32" | "u64" | "u128" => {
                            quote! { #[from(~.map(|v|v.into()))] }
                        }
                        _ => return None,
                    });
                }
            }

            // 处理普通类型
            Some(match path_str.as_str() {
                "u8" | "u16" | "u32" | "u64" | "u128" => quote! { #[from(~.into())] },
                _ => return None,
            })?
        }
        _ => return None,
    })
}

/// 提取 Option 类型的内部类型
fn extract_option_inner_type(type_path: &syn::TypePath) -> Option<String> {
    if let syn::PathArguments::AngleBracketed(args) = &type_path.path.segments.last()?.arguments {
        if let Some(syn::GenericArgument::Type(inner_ty)) = args.args.first() {
            if let syn::Type::Path(inner_path) = inner_ty {
                return Some(inner_path.path.segments.last()?.ident.to_string());
            }
        }
    }
    None
}

/// 生成 builder 属性(仅针对 Option<T> 类型)
fn generate_builder_attr(field: &Field) -> Option<TokenStream> {
    let ty = &field.ty;

    if is_option_type(ty) {
        return Some(quote! {
            #[builder(default, setter(into))]
        });
    }

    None
}

/// 将无符号整型映射为对应的U*类型,非无符号整型则保持原样
/// 支持 Option<T> 类型,例如 Option<u64> -> Option<U64>
/// Vo 类型(关联关系)自动改为 ExVo,外键约束保证数据存在
fn map_unsigned_type(ty: &syn::Type) -> TokenStream {
    match ty {
        syn::Type::Path(type_path) => {
            if let Some(segment) = type_path.path.segments.last() {
                let ident_str = segment.ident.to_string();
                // Vo 类型(关联关系)自动改为 ExVo
                if ident_str.ends_with("Vo") {
                    let ex_vo_type = format_ident!("{}", &ident_str.replace("Vo", "ExVo"));
                    return quote! { #ex_vo_type };
                }

                // 处理 Option<T> 类型
                if ident_str == "Option" {
                    if let Some(inner) = extract_option_inner_type(type_path) {
                        return match inner.as_str() {
                            "u8" => quote! { Option<U8> },
                            "u16" => quote! { Option<U16> },
                            "u32" => quote! { Option<U32> },
                            "u64" => quote! { Option<U64> },
                            "u128" => quote! { Option<U128> },
                            _ => quote! { #ty },
                        };
                    }
                    return quote! { #ty };
                }

                // 处理普通类型
                match ident_str.as_str() {
                    "u8" => return quote! { U8 },
                    "u16" => return quote! { U16 },
                    "u32" => return quote! { U32 },
                    "u64" => return quote! { U64 },
                    "u128" => return quote! { U128 },
                    _ => {}
                }
            }
        }
        _ => {}
    }
    quote! { #ty }
}

/// 检查类型是否是 Option<T>
fn is_option_type(ty: &syn::Type) -> bool {
    match ty {
        syn::Type::Path(type_path) => {
            if let Some(segment) = type_path.path.segments.last() {
                segment.ident == "Option"
            } else {
                false
            }
        }
        _ => false,
    }
}

/// 获取类型的简单名称(不含路径前缀和泛型参数)
fn get_type_name(ty: &syn::Type) -> Option<String> {
    match ty {
        syn::Type::Path(type_path) => type_path.path.segments.last().map(|s| s.ident.to_string()),
        _ => None,
    }
}

fn handle_fields(input: &DeriveInput, is_ex: bool) -> Result<TokenStream, TokenStream> {
    Ok(match &input.data {
        Data::Struct(data_struct) => match &data_struct.fields {
            Fields::Named(fields_named) => {
                let processed_fields: Vec<_> = fields_named
                    .named
                    .iter()
                    .filter_map(|field| {
                        let field_name = &field.ident;

                        // 获取类型名称,判断后缀是不是Vo
                        let is_vo_field =
                            get_type_name(&field.ty).map_or(false, |name| name.ends_with("Vo"));

                        // 如果是Vo类型字段且不是ExVo,则跳过(Model不包含关联关系字段)
                        if is_vo_field && !is_ex {
                            return None;
                        }

                        let field_ty = map_unsigned_type(&field.ty);
                        let attrs = generate_field_attrs(field);

                        // 保留原有的注释和其他属性(除了 from/builder/serde)
                        let original_attrs: Vec<_> = field
                            .attrs
                            .iter()
                            .filter(|attr| {
                                !attr.path().is_ident("from")
                                    && !attr.path().is_ident("builder")
                                    && !attr.path().is_ident("serde")
                            })
                            .collect();

                        Some(quote! {
                            #(#original_attrs)*
                            #attrs
                            pub #field_name: #field_ty,
                        })
                    })
                    .collect();

                quote! {
                    { #(#processed_fields)* }
                }
            }
            Fields::Unnamed(_) | Fields::Unit => {
                return Err(quote! {
                    compile_error!("VO macro only supports named fields");
                });
            }
        },
        _ => {
            return Err(quote! {
                compile_error!("VO macro can only be used on structs");
            });
        }
    })
}

/// 为客户端模式处理字段(不包含 o2o/sea_orm 相关属性)
fn handle_fields_client(input: &DeriveInput, is_ex: bool) -> Result<TokenStream, TokenStream> {
    Ok(match &input.data {
        Data::Struct(data_struct) => match &data_struct.fields {
            Fields::Named(fields_named) => {
                let processed_fields: Vec<_> = fields_named
                    .named
                    .iter()
                    .filter_map(|field| {
                        let field_name = &field.ident;
                        let field_ty = &field.ty;

                        // 获取类型名称,判断后缀是不是Vo
                        let is_vo_field =
                            get_type_name(field_ty).map_or(false, |name| name.ends_with("Vo"));

                        // 如果是Vo类型字段且不是ExVo,则跳过
                        if is_vo_field && !is_ex {
                            return None;
                        }

                        // Vo 类型字段自动转为 ExVo
                        let field_ty = if is_vo_field {
                            if let syn::Type::Path(type_path) = field_ty {
                                if let Some(segment) = type_path.path.segments.last() {
                                    let ident_str = segment.ident.to_string();
                                    if ident_str.ends_with("Vo") {
                                        let ex_vo_type = format_ident!("{}", &ident_str.replace("Vo", "ExVo"));
                                        return Some(quote! {
                                            #field_name: #ex_vo_type,
                                        });
                                    }
                                }
                            }
                            quote! { #field_ty }
                        } else {
                            quote! { #field_ty }
                        };

                        let original_attrs: Vec<_> = field
                            .attrs
                            .iter()
                            .filter(|attr| {
                                !attr.path().is_ident("from")
                                    && !attr.path().is_ident("builder")
                                    && !attr.path().is_ident("serde")
                            })
                            .collect();

                        Some(quote! {
                            #(#original_attrs)*
                            #[builder(default, setter(into))]
                            pub #field_name: #field_ty,
                        })
                    })
                    .collect();

                quote! {
                    { #(#processed_fields)* }
                }
            }
            Fields::Unnamed(_) | Fields::Unit => {
                return Err(quote! {
                    compile_error!("VO macro only supports named fields");
                });
            }
        },
        _ => {
            return Err(quote! {
                compile_error!("VO macro can only be used on structs");
            });
        }
    })
}

pub fn vo_macro(args: VoArgs, input: DeriveInput) -> TokenStream {
    let struct_name = &input.ident;
    let vis = &input.vis;
    let struct_name_str = struct_name.to_string();

    // 验证结构体名称必须以Vo结尾
    if !struct_name_str.ends_with("Vo") {
        return syn::Error::new_spanned(struct_name, "Struct name must end with 'Vo'")
            .to_compile_error()
            .into();
    }
    let struct_name_split = split_camel_case(&struct_name_str, CamelFormat::Upper);
    if struct_name_split.is_err() {
        return syn::Error::new_spanned(
            struct_name,
            "Struct name must be a valid upper camel case",
        )
        .to_compile_error()
        .into();
    }
    let mut struct_name_split = struct_name_split.unwrap();
    struct_name_split.pop();
    let module_name = format_ident!("{}", struct_name_split.join("_").to_lowercase());
    let ex_struct_name = format_ident!("{}ExVo", struct_name_split.join(""));

    // 处理字段 - server mode
    let fields = match handle_fields(&input, false) {
        Ok(value) => value,
        Err(value) => return value,
    };
    let ex_fields = match handle_fields(&input, true) {
        Ok(value) => value,
        Err(value) => return value,
    };

    // 处理字段 - client mode (不包含 o2o/sea_orm 相关属性)
    let client_fields = match handle_fields_client(&input, false) {
        Ok(value) => value,
        Err(value) => return value,
    };
    let client_ex_fields = match handle_fields_client(&input, true) {
        Ok(value) => value,
        Err(value) => return value,
    };

    let mo_crate_path = args.mo_crate.as_deref().unwrap_or("crate");
    let mo_crate_token: TokenStream = syn::parse_str(mo_crate_path).unwrap_or_else(|_| quote! { crate });

    // 生成完整的结构体定义,包含所有必要的属性和派生宏
    let expanded = quote! {
        use serde::{Serialize, Deserialize};
        use serde_with::{serde_as, skip_serializing_none};
        use utoipa::ToSchema;
        use derive_setters::Setters;
        use typed_builder::TypedBuilder;
        use wheel_rs::serde::{u64_serde, u64_option_serde};

        // ========== Server mode: full o2o/sea_orm code ==========
        #[cfg(feature = "server")]
        use o2o::o2o;
        #[cfg(feature = "server")]
        use sea_orm::DerivePartialModel;
        #[cfg(feature = "server")]
        use robotech::dao::{belongs_to_owned, U8, U16, U32, U64, U128};
        #[cfg(feature = "server")]
        use #mo_crate_token::mo::#module_name::{Entity, Model, ModelEx};

        // Import other VO types (needed by both server and client for ExVo references)
        use #mo_crate_token::vo::*;

        #[cfg(feature = "server")]
        #[skip_serializing_none]
        #[derive(o2o, ToSchema, DerivePartialModel, Debug, Serialize, Deserialize, Clone, Setters, TypedBuilder)]
        #[from_owned(Model)]
        #[serde(rename_all = "camelCase")]
        #[serde_as]
        #[builder]
        #[sea_orm(entity = "Entity")]
        #vis struct #struct_name #fields

        #[cfg(feature = "server")]
        #[skip_serializing_none]
        #[derive(o2o, ToSchema, Debug, Serialize, Deserialize, Clone, Setters, TypedBuilder)]
        #[from_owned(ModelEx)]
        #[serde(rename_all = "camelCase")]
        #[serde_as]
        #[builder]
        #vis struct #ex_struct_name #ex_fields

        // ========== Client mode: pure data structures ==========
        #[cfg(not(feature = "server"))]
        #[skip_serializing_none]
        #[derive(ToSchema, Debug, Serialize, Deserialize, Clone, Setters, TypedBuilder)]
        #[serde(rename_all = "camelCase")]
        #[serde_as]
        #[builder]
        #vis struct #struct_name #client_fields

        #[cfg(not(feature = "server"))]
        #[skip_serializing_none]
        #[derive(ToSchema, Debug, Serialize, Deserialize, Clone, Setters, TypedBuilder)]
        #[serde(rename_all = "camelCase")]
        #[serde_as]
        #[builder]
        #vis struct #ex_struct_name #client_ex_fields
    };

    // 调试:打印完整展开的代码
    // println!("Full expanded code:\n{expanded}");

    TokenStream::from(expanded)
}