qlexpress_derive/lib.rs
1//! Procedural macros for qlexpress.
2#![warn(missing_docs)]
3//!
4//! Currently exposes:
5//! - `#[derive(QLExpressType)]` — auto-implement
6//! `qlexpress::runtime::member::QLExpressNativeType` and
7//! `qlexpress::runtime::native_object::NativeObject` for a struct.
8//!
9//! See README and the design notes in plan.md Stage 6 for the attribute
10//! grammar and emitted code shape.
11
12use proc_macro::TokenStream;
13use quote::quote;
14
15mod attrs;
16mod convert;
17mod native_object;
18mod native_type;
19
20/// Derive macro for QLExpress-native types.
21///
22/// # Attributes
23///
24/// On the struct itself:
25/// - `#[qlexpress(name = "com.foo.Bar")]` — canonical Java-style type name
26/// (defaults to the Rust struct identifier).
27/// - `#[qlexpress(no_native_object)]` — do not emit `impl NativeObject`.
28/// Useful when the type is only used through registry closures.
29///
30/// On fields:
31/// - `#[qlexpress(skip)]` — do not expose the field.
32/// - `#[qlexpress(readonly)]` — expose only the getter (no setter).
33/// - `#[qlexpress(alias = "X", "Y")]` — add field aliases.
34/// (The first alias is also registered as a getter method matching the
35/// Java `isX/getX` convention.)
36///
37/// # Limitations (v1)
38///
39/// - Generic structs / generic methods are rejected with a clear error.
40/// - Rust derive 宏看不到独立的 `impl` 块,因此不会自动注册方法或构造器;
41/// 宿主必须通过 `NativeRegistry` 显式注册这些成员。
42///
43/// 对应 Java: 无(Rust 原生适配)。
44#[proc_macro_derive(QLExpressType, attributes(qlexpress))]
45pub fn derive_ql_express_type(input: TokenStream) -> TokenStream {
46 let ast = syn::parse_macro_input!(input as syn::DeriveInput);
47 match expand(&ast) {
48 Ok(ts) => ts.into(),
49 Err(e) => e.to_compile_error().into(),
50 }
51}
52
53fn expand(ast: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
54 let qlexpress_path: syn::Path = syn::parse_quote!(::qlexpress);
55
56 let struct_attrs = attrs::ContainerAttrs::from_ast(ast)?;
57 let item = attrs::ItemSpec::from_ast(ast)?;
58
59 let native_type_impl = native_type::generate(ast, &item, &struct_attrs, &qlexpress_path);
60 let native_object_impl = native_object::generate(ast, &item, &struct_attrs, &qlexpress_path);
61
62 // 始终生成两个实现。当前 trait 约束要求 `QLExpressNativeType` 同时实现
63 // `NativeObject`,因此 `no_native_object` 仍作为后续版本保留字段。
64 let _ = struct_attrs.no_native_object;
65 Ok(quote! {
66 #native_type_impl
67 #native_object_impl
68 })
69}