Skip to main content

batch_impl/
lib.rs

1#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md"))]
2#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/docs/tutorial.md"))]
3// 库不使用任何 unsafe;缺失文档按错误拒绝(仅作用于 pub 项,内部 pub(crate) 不受限)。
4#![forbid(unsafe_code)]
5#![deny(missing_docs)]
6// MSVC 链接器输出"正在创建库…和对象…"到 stdout,被 rustc 当 linker_messages 告警,
7// 属于无害的 Windows 链接产物提示,全局抑制。
8#![allow(linker_messages)]
9// `delimiter!` 宏定义在 preprocess 顶部,经 `#[macro_use]` 导入 crate 根;
10// 文本作用域要求其声明先于所有使用者(fuzz / parse / 本模块)。
11#[macro_use]
12pub(crate) mod preprocess;
13#[cfg(test)]
14mod fuzz;
15use proc_macro2::{TokenStream, TokenTree};
16use syn::{ItemTrait, parse_macro_input};
17
18mod apply;
19mod ast;
20mod batch_trait_entry;
21mod codegen;
22mod consts;
23mod diagnostic;
24mod empty_generics;
25mod expand;
26mod parse;
27mod path_prefix;
28mod scan;
29mod trait_bounds;
30
31pub(crate) use expand::{expand_attr_macro, expand_batch_trait};
32pub(crate) use trait_bounds::TraitBounds;
33
34use diagnostic::compile_error_str;
35use preprocess::{build_from_item, get_trait_item, parse_names_from_tokens};
36
37/// 为 trait 批量生成 `impl` 块的属性宏。
38///
39/// 在 trait 定义上标注 `#[batch_impl(...)]`,宏参数中的每个 impl-spec 都会
40/// 为该 trait 生成一个对应的 `impl` 块。
41///
42/// ## 语法
43///
44/// ```text
45/// #[batch_impl( impl-spec [, impl-spec]* [{ body }]? )]
46/// ```
47///
48/// impl-spec 由三部分组成(均可省略后半部分):
49/// - `<impl-泛型>` — `impl` 块的泛型参数
50/// - `Trait名<trait-泛型>` — trait 的泛型参数与关联类型绑定
51/// - 目标类型 — 用 `[]` 包裹表示并列,用 `^`/`-` 表示泛型应用
52///
53/// ## 示例
54///
55/// ```
56/// # use batch_impl::batch_impl;
57/// #[batch_impl(usize, isize)]
58/// trait Numeric {}
59///
60/// #[batch_impl(<T> Vec<T>)]
61/// trait Collection {}
62///
63/// #[batch_impl(<T> FromValue<T> [i32 { fn wrap(_: T) -> Self { 0 }}, u32 #wrap{0}] )]
64/// trait FromValue<T> { fn wrap(val: T) -> Self; }
65///
66/// // #name{body} 也支持 const 和 type 项
67/// #[batch_impl(usize #MY_CONST{42})]
68/// trait HasConst { const MY_CONST: usize; }
69///
70/// ```
71#[proc_macro_attribute]
72pub fn batch_impl(
73    attr: proc_macro::TokenStream, item: proc_macro::TokenStream,
74) -> proc_macro::TokenStream {
75    let trait_item = parse_macro_input!(item as ItemTrait);
76    expand_attr_macro(attr, trait_item, true).unwrap_or_else(Into::into)
77}
78
79/// 与 `#[batch_impl]` 相同,但丢弃被标注的 trait 定义,只输出 `impl` 块。
80///
81/// 用于 trait 已在别处定义、只需批量生成 impl 的场景。被标注的 trait 仅作为
82/// 指令系统的"签名真相源":`#name`/`#fill`/`#delegate` 从它读取 item 签名,
83/// 开放扩展 `#name(args){body}` 把(方法名列表, body, 整个 trait)一起交给
84/// 用户的同名函数式宏(见 README「指令系统」)。语法与 `#[batch_impl]` 完全一致。
85///
86/// ## 示例
87///
88/// ```
89/// # use batch_impl::batch_impl_only;
90/// trait Greet { fn hello(&self) -> &str; }
91///
92/// #[batch_impl_only(usize #hello{"hi"})]
93/// trait Greet { fn hello(&self) -> &str; } // 此 trait 定义被丢弃,不影响已有的定义
94/// // 这样写而不用batch_trait是为了使用指令系统,建议按trait定义处按原样写
95/// ```
96#[proc_macro_attribute]
97pub fn batch_impl_only(
98    attr: proc_macro::TokenStream, item: proc_macro::TokenStream,
99) -> proc_macro::TokenStream {
100    let trait_item = parse_macro_input!(item as ItemTrait);
101    expand_attr_macro(attr, trait_item, false).unwrap_or_else(Into::into)
102}
103
104/// 对已声明的 trait 批量生成 `impl` 块的函数式宏。
105///
106/// 语法:`unsafe? Trait路径: impl-specs;`,以 `;` 分隔多个 trait 段。
107/// 每段的 `:` 之后是 DSL 表达式,与 `#[batch_impl]` 接受相同的语法。
108///
109/// ## 示例
110///
111/// ```
112/// # use batch_impl::batch_trait;
113/// trait A {}
114/// trait B<T> {}
115/// unsafe trait UnsafeTrait{}
116///
117/// batch_trait!(
118///     A: usize, isize;
119///     B: <T> B<T> Vec<T>;
120///     unsafe UnsafeTrait: usize
121/// );
122/// ```
123///
124/// 路径 trait(如 `foo::C`)同样支持,见 tests/regression.rs。
125#[proc_macro]
126pub fn batch_trait(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
127    expand_batch_trait(input).unwrap_or_else(Into::into)
128}
129
130/// 测试用开放扩展宏(函数式):`name!{(方法名列表){body} trait T {...}}`。
131///
132/// 从宏输入解析方法名列表、body 与 trait 定义,为每个方法生成
133/// `fn 签名 { body }`(沿用 trait 签名)——等价于把 `#fill` 的实现交给用户。
134///
135/// 用于验证开放指令扩展:`#name(args){body}` 展开为 `{name!{(args){body} trait ...}}`,
136/// 宏调用落在 impl body 中,由用户宏根据 trait 展开为需要的 fn 定义
137/// (见 `tests/dsl.rs` 第 28 节)。
138///
139/// 设计要点:这里必须是**函数式宏调用** `name!{...}`,不能是 `#[name[...]] trait ...`
140/// 属性——trait 不是 impl 块内的合法项(`#[attr] trait` 无法出现在 impl 中),
141/// 而函数式宏在 impl body 位置会被 rustc 展开成关联项。
142#[doc(hidden)]
143#[proc_macro]
144pub fn batch_preprocess_test(
145    input: proc_macro::TokenStream,
146) -> proc_macro::TokenStream {
147    let tokens = TokenStream::from(input).into_iter().collect::<Vec<_>>();
148    let tokens = match preprocess::angle_collect(&tokens) {
149        Ok(v) => v,
150        Err(e) => return e.into(),
151    };
152    // 形如:`(add, inc) {*self+1} trait AddInc {...}`
153    let Some(TokenTree::Group(names_group)) = tokens.first() else {
154        return compile_error_str(
155            "batch-impl: batch_preprocess_test 期望 `(方法名列表){body} trait ...`",
156        )
157        .into();
158    };
159    if names_group.delimiter() != delimiter![()] {
160        return compile_error_str(
161            "batch-impl: batch_preprocess_test 期望 `(方法名列表){body} trait ...`",
162        )
163        .into();
164    }
165    let Some(TokenTree::Group(body_group)) = tokens.get(1) else {
166        return compile_error_str(
167            "batch-impl: batch_preprocess_test 期望 `(方法名列表){body} trait ...`",
168        )
169        .into();
170    };
171    if body_group.delimiter() != delimiter![{}] {
172        return compile_error_str(
173            "batch-impl: batch_preprocess_test 期望 `(方法名列表){body} trait ...`",
174        )
175        .into();
176    }
177    let trait_ts = tokens[2..].iter().cloned().collect();
178    let trait_item = match syn::parse2(trait_ts) {
179        Ok(t) => t,
180        Err(_) => {
181            return compile_error_str(
182                "batch-impl: batch_preprocess_test 无法解析 trait 定义",
183            )
184            .into();
185        }
186    };
187    let names = match parse_names_from_tokens(
188        &names_group.stream().into_iter().collect::<Vec<_>>(),
189        &trait_item,
190    ) {
191        Ok(names) => names,
192        Err(e) => return e.into(),
193    };
194    let body = body_group.stream();
195    let mut methods = TokenStream::new();
196    for name in &names {
197        let item = match get_trait_item(&trait_item, name) {
198            Ok(item) => item,
199            Err(e) => return e.into(),
200        };
201        methods.extend(build_from_item(item, &body));
202    }
203    preprocess::render_angles(methods).into()
204}