rgpui_macros/rgpui_macros.rs
1mod bench;
2mod derive_action;
3mod derive_app_context;
4mod derive_into_element;
5mod derive_refineable;
6mod derive_render;
7mod derive_visual_context;
8mod icon_named;
9mod property_test;
10mod register_action;
11mod styles;
12mod test;
13
14#[cfg(any(feature = "inspector", debug_assertions))]
15mod derive_inspector_reflection;
16
17use proc_macro::TokenStream;
18use quote::quote;
19use syn::LitStr;
20use syn::parse_macro_input;
21use syn::{DeriveInput, Ident};
22
23/// `Action` 派生宏 - 用于为结构体自动实现 `rgpui::Action` 特质。
24///
25/// 该宏会为标记的类型生成 `Action` 特质的实现,包括动作名称、JSON 序列化/反序列化、
26/// 克隆等功能。支持以下属性配置:
27///
28/// - `name = "..."` - 指定动作的名称
29/// - `namespace = ...` - 指定动作的命名空间
30/// - `no_json` - 禁用 JSON 构建功能
31/// - `no_register` - 禁用自动注册
32/// - `deprecated_aliases = [...]` - 指定已弃用的别名
33/// - `deprecated = "..."` - 标记为已弃用并提供提示信息
34///
35/// # 示例
36///
37/// ```ignore
38/// #[derive(Action)]
39/// struct MyAction {
40/// value: String,
41/// }
42/// ```
43#[proc_macro_derive(Action, attributes(action))]
44pub fn derive_action(input: TokenStream) -> TokenStream {
45 derive_action::derive_action(input)
46}
47
48/// 用于向 RGPUI 运行时注册动作的过程宏。
49///
50/// 当你想要手动实现 `Action` 特质时,可以使用此宏来注册动作。
51/// 通常情况下,你应该使用 `Action` 派生宏或 `actions!` 宏来代替。
52///
53/// # 示例
54///
55/// ```ignore
56/// impl rgpui::Action for MyAction {
57/// // 手动实现...
58/// }
59///
60/// rgpui::register_action!(MyAction);
61/// ```
62#[proc_macro]
63pub fn register_action(ident: TokenStream) -> TokenStream {
64 register_action::register_action(ident)
65}
66
67/// `IntoElement` 派生宏 - 用于将实现了 `RenderOnce` 特质的类型转换为 UI 组件。
68///
69/// 该宏会为标记的类型生成 `rgpui::IntoElement` 特质的实现,使其可以作为
70/// UI 元素在渲染树中使用。
71///
72/// # 示例
73///
74/// ```ignore
75/// #[derive(IntoElement)]
76/// struct MyComponent {
77/// text: String,
78/// }
79/// ```
80#[proc_macro_derive(IntoElement)]
81pub fn derive_into_element(input: TokenStream) -> TokenStream {
82 derive_into_element::derive_into_element(input)
83}
84
85#[proc_macro_derive(Render)]
86#[doc(hidden)]
87pub fn derive_render(input: TokenStream) -> TokenStream {
88 derive_render::derive_render(input)
89}
90
91/// `AppContext` 派生宏 - 用于为持有 `&mut App` 的结构体生成应用上下文实现。
92///
93/// 该宏会为标记的类型生成 `rgpui::AppContext` 特质的实现,使其能够访问和操作
94/// RGPUI 应用状态,包括创建实体、更新实体、读取全局状态等。
95///
96/// 注意:必须使用 `#[app]` 属性标记持有 `&mut App` 的字段。
97///
98/// 缺少该属性会导致编译错误:
99///
100/// ```compile_fail
101/// # #[macro_use] extern crate rgpui_macros;
102/// # #[macro_use] extern crate rgpui;
103/// #[derive(AppContext)]
104/// struct MyContext<'a> {
105/// app: &'a mut rgpui::App
106/// }
107/// ```
108///
109/// # 示例
110///
111/// ```ignore
112/// #[derive(AppContext)]
113/// struct MyContext<'a> {
114/// #[app]
115/// app: &'a mut rgpui::App,
116/// }
117/// ```
118#[proc_macro_derive(AppContext, attributes(app))]
119pub fn derive_app_context(input: TokenStream) -> TokenStream {
120 derive_app_context::derive_app_context(input)
121}
122
123/// `VisualContext` 派生宏 - 用于为持有 `&mut Window` 并实现了 `AppContext` 的类型生成可视化上下文实现。
124///
125/// 该宏会为标记的类型生成 `rgpui::VisualContext` 特质的实现,使其能够管理窗口级别的
126/// 操作,如创建窗口实体、替换根视图、设置焦点等。
127///
128/// 注意:必须同时使用 `#[app]` 和 `#[window]` 属性分别标记持有 `&mut App` 和 `&mut Window` 的字段。
129///
130/// 缺少任一属性都会导致编译错误:
131///
132/// ```compile_fail
133/// # #[macro_use] extern crate rgpui_macros;
134/// # #[macro_use] extern crate rgpui;
135/// #[derive(VisualContext)]
136/// struct MyContext<'a, 'b> {
137/// #[app]
138/// app: &'a mut rgpui::App,
139/// window: &'b mut rgpui::Window
140/// }
141/// ```
142///
143/// ```compile_fail
144/// # #[macro_use] extern crate rgpui_macros;
145/// # #[macro_use] extern crate rgpui;
146/// #[derive(VisualContext)]
147/// struct MyContext<'a, 'b> {
148/// app: &'a mut rgpui::App,
149/// #[window]
150/// window: &'b mut rgpui::Window
151/// }
152/// ```
153///
154/// # 示例
155///
156/// ```ignore
157/// #[derive(VisualContext)]
158/// struct MyContext<'a, 'b> {
159/// #[app]
160/// app: &'a mut rgpui::App,
161/// #[window]
162/// window: &'b mut rgpui::Window,
163/// }
164/// ```
165#[proc_macro_derive(VisualContext, attributes(window, app))]
166pub fn derive_visual_context(input: TokenStream) -> TokenStream {
167 derive_visual_context::derive_visual_context(input)
168}
169
170/// 用于创建细化类型的派生宏。
171///
172/// 为复杂的结构体生成 `Refinement` 结构体,支持部分初始化。
173#[proc_macro_derive(Refineable, attributes(refineable))]
174pub fn derive_refineable(input: TokenStream) -> TokenStream {
175 derive_refineable::derive_refineable(input)
176}
177
178/// 用于生成样式辅助函数的过程宏。
179///
180/// 该宏由 RGPUI 内部使用,用于生成样式相关的基础辅助函数,
181/// 包括边距、内边距、圆角等样式属性的方法生成器。
182#[proc_macro]
183#[doc(hidden)]
184pub fn style_helpers(input: TokenStream) -> TokenStream {
185 styles::style_helpers(input)
186}
187
188/// 生成可见性样式相关的方法。
189///
190/// 该宏会生成 `visible()` 和 `invisible()` 方法,用于控制元素的可见性。
191/// 参考 [Tailwind CSS 文档](https://tailwindcss.com/docs/visibility)
192#[proc_macro]
193pub fn visibility_style_methods(input: TokenStream) -> TokenStream {
194 styles::visibility_style_methods(input)
195}
196
197/// 生成外边距(margin)样式相关的方法。
198///
199/// 该宏会生成一系列方法,如 `m()`、`mt()`、`mb()`、`mx()`、`my()` 等,
200/// 用于设置元素的外边距。参考 [Tailwind CSS 文档](https://tailwindcss.com/docs/margin)
201#[proc_macro]
202pub fn margin_style_methods(input: TokenStream) -> TokenStream {
203 styles::margin_style_methods(input)
204}
205
206/// 生成内边距(padding)样式相关的方法。
207///
208/// 该宏会生成一系列方法,如 `p()`、`pt()`、`pb()`、`px()`、`py()` 等,
209/// 用于设置元素的内边距。参考 [Tailwind CSS 文档](https://tailwindcss.com/docs/padding)
210#[proc_macro]
211pub fn padding_style_methods(input: TokenStream) -> TokenStream {
212 styles::padding_style_methods(input)
213}
214
215/// 生成定位(position)样式相关的方法。
216///
217/// 该宏会生成 `relative()`、`absolute()` 以及 `inset`、`top`、`bottom`、`left`、`right`
218/// 等方法,用于控制元素的定位行为。参考 [Tailwind CSS 文档](https://tailwindcss.com/docs/position)
219#[proc_macro]
220pub fn position_style_methods(input: TokenStream) -> TokenStream {
221 styles::position_style_methods(input)
222}
223
224/// 生成溢出(overflow)样式相关的方法。
225///
226/// 该宏会生成 `overflow_hidden()`、`overflow_x_hidden()`、`overflow_y_hidden()` 等方法,
227/// 用于控制内容溢出容器时的行为。参考 [Tailwind CSS 文档](https://tailwindcss.com/docs/overflow)
228#[proc_macro]
229pub fn overflow_style_methods(input: TokenStream) -> TokenStream {
230 styles::overflow_style_methods(input)
231}
232
233/// 生成光标(cursor)样式相关的方法。
234///
235/// 该宏会生成一系列方法,如 `cursor_default()`、`cursor_pointer()`、`cursor_text()` 等,
236/// 用于设置鼠标悬停在元素上时的光标样式。参考 [Tailwind CSS 文档](https://tailwindcss.com/docs/cursor)
237#[proc_macro]
238pub fn cursor_style_methods(input: TokenStream) -> TokenStream {
239 styles::cursor_style_methods(input)
240}
241
242/// 生成边框(border)样式相关的方法。
243///
244/// 该宏会生成 `border_color()` 以及 `border()`、`border_t()`、`border_b()` 等方法,
245/// 用于设置元素的边框颜色和宽度。参考 [Tailwind CSS 文档](https://tailwindcss.com/docs/border-width)
246#[proc_macro]
247pub fn border_style_methods(input: TokenStream) -> TokenStream {
248 styles::border_style_methods(input)
249}
250
251/// 生成盒子阴影(box shadow)样式相关的方法。
252///
253/// 该宏会生成 `shadow()`、`shadow_none()` 以及 `shadow_sm()`、`shadow_md()`、`shadow_lg()` 等方法,
254/// 用于为元素添加预定义的盒子阴影效果。参考 [Tailwind CSS 文档](https://tailwindcss.com/docs/box-shadow)
255#[proc_macro]
256pub fn box_shadow_style_methods(input: TokenStream) -> TokenStream {
257 styles::box_shadow_style_methods(input)
258}
259
260/// `icon_named!` 宏 - 通过扫描 SVG 目录生成图标枚举及其 `IconNamed` 实现。
261///
262/// 生成的枚举提供 `path()`(资源路径字符串)与 `bytes()`(编译期嵌入字节)。
263#[proc_macro]
264pub fn icon_named(input: TokenStream) -> TokenStream {
265 icon_named::icon_named_impl(input)
266}
267
268/// `#[rgpui::bench]` 标注一个使用 RGPUI 支持的 Criterion 基准测试。
269#[proc_macro_attribute]
270pub fn bench(args: TokenStream, function: TokenStream) -> TokenStream {
271 bench::bench(args, function)
272}
273
274/// `#[rgpui::test]` 测试属性宏 - 用于注解需要 RGPUI 支持的测试函数。
275///
276/// 该宏支持同步和异步测试,并可以提供任意数量的 `TestAppContext` 实例。
277/// 生成的代码包含 `#[test]` 注解,因此可以与任何现有测试框架配合使用
278/// (`cargo test` 或 `cargo-nextest`)。
279///
280/// ```ignore
281/// #[rgpui::test]
282/// async fn test_foo(mut cx: &TestAppContext) { }
283/// ```
284///
285/// 除了 `TestAppContext`,你还可以请求 `StdRng` 实例。
286/// 该实例将通过 `SEED` 环境变量进行种子设定,GPUI 内部的 ForegroundExecutor 和
287/// BackgroundExecutor 会使用它在测试中确定性地运行任务。
288/// 使用相同的 `StdRng` 可以通过仅改变种子来复现各种场景和执行交错。
289///
290/// # 参数
291///
292/// - `#[rgpui::test]` - 无参数时使用种子 `0` 或 `SEED` 环境变量(如果已设置)运行一次。
293/// - `#[rgpui::test(seed = 10)]` - 使用种子 `10` 运行一次。
294/// - `#[rgpui::test(seeds(10, 20, 30))]` - 使用种子 `10`、`20` 和 `30` 分别运行三次。
295/// - `#[rgpui::test(iterations = 5)]` - 运行五次,种子值为 `0..5` 范围。
296/// - `#[rgpui::test(retries = 3)]` - 如果测试失败,最多重试四次以尝试使其通过。
297/// - `#[rgpui::test(on_failure = "crate::test::report_failure")]` - 测试失败时调用指定函数,
298/// 以便输出更详细的失败信息。
299///
300/// 可以组合 `iterations = ...` 和 `seeds(...)`:
301/// - `#[rgpui::test(iterations = 5, seed = 10)]` 等价于 `#[rgpui::test(seeds(0, 1, 2, 3, 4, 10))]`。
302/// - `#[rgpui::test(iterations = 5, seeds(10, 20, 30)]` 等价于 `#[rgpui::test(seeds(0, 1, 2, 3, 4, 10, 20, 30))]`。
303/// - `#[rgpui::test(seeds(10, 20, 30), iterations = 5]` 等价于 `#[rgpui::test(seeds(0, 1, 2, 3, 4, 10, 20, 30))]`。
304///
305/// # 环境变量
306///
307/// - `SEED` - 设置首次运行的种子值
308/// - `ITERATIONS` - 强制设置 `iterations` 参数的值
309#[proc_macro_attribute]
310pub fn test(args: TokenStream, function: TokenStream) -> TokenStream {
311 test::test(args, function)
312}
313
314/// `#[rgpui::property_test]` 属性测试宏 - 支持基于属性的测试(property-based testing)。
315///
316/// 属性测试类似于 RGPUI 随机测试,但允许测试形如"对于任何可能的 X,Y 应该成立"的断言。
317/// 例如:
318/// ```ignore
319/// #[rgpui::property_test]
320/// fn test_arithmetic(x: i32, y: i32) {
321/// assert!(x == y || x < y || x > y);
322/// }
323/// ```
324///
325/// 标准 RGPUI 随机测试提供 `StdRng` 实例以受控方式生成随机数据。
326/// 属性测试具有以下额外优势:
327/// - **收缩(Shrinking)** - 测试框架理解值的"复杂度"概念,能够找到导致测试失败的"最简单值"。
328/// - **易用性/清晰度** - 测试框架会自动生成值,无需在测试体中编写生成逻辑。
329/// - **失败持久化** - 如果找到失败的种子,会存储在文件中,后续运行会优先检查这些已知失败的情况。
330///
331/// 当所有输入都可以预先生成并保存在简单数据结构中时,属性测试效果最佳。
332/// 某些情况下这可能不可行——例如,测试需要根据当前结构状态做出随机决策。
333/// 在这种情况下,标准 RGPUI 随机测试可能更合适。
334///
335/// ## 自定义随机值
336///
337/// 该宏基于 [`#[proptest::property_test]`] 宏,但处理了一些 RGPUI 特有的参数。
338/// 具体来说,`&{mut,} TestAppContext` 和 `BackgroundExecutor` 正常工作。
339/// `StdRng` 参数被**明确禁止**,因为它们会破坏收缩机制,是常见的陷阱。
340///
341/// 所有其他参数都会转发到底层的 proptest 宏。
342///
343/// 类型为 `T` 的随机值由 `Strategy<Value = T>` 对象生成。
344/// 某些类型有标准的 `Strategy`——这些类型也实现了 `Arbitrary`。
345/// `#[rgpui::property_test]` 的参数默认使用类型的 `Arbitrary` 实现。
346/// 如果想要提供自定义策略,可以在参数上使用 `#[strategy = ...]`:
347/// ```ignore
348/// #[rgpui::property_test]
349/// fn int_test(#[strategy = 1..10] x: i32, #[strategy = "[a-zA-Z0-9]{20}"] s: String) {
350/// assert!(s.len() > (x as usize));
351/// }
352/// ```
353///
354/// ## 调度器
355///
356/// 与 `#[rgpui::test]` 类似,该宏会为测试调度器选择随机种子。
357/// 它使用 `.no_shrink()` 告诉 proptest 所有种子在"复杂度"方面大致等价。
358/// 如果设置了 `$SEED`,它只会影响传递给调度器的种子。要控制其他值,请使用自定义 `Strategy`。
359///
360/// [`#[proptest::property_test]`]: https://docs.rs/proptest/latest/proptest/attr.property_test.html
361/// [book]: https://proptest-rs.github.io/proptest/intro.html
362/// [`Strategy`]: https://docs.rs/proptest/latest/proptest/strategy/trait.Strategy.html
363#[proc_macro_attribute]
364pub fn property_test(args: TokenStream, function: TokenStream) -> TokenStream {
365 property_test::test(args.into(), function.into()).into()
366}
367
368/// `#[derive_inspector_reflection]` 属性宏 - 为特质生成检查器反射模块。
369///
370/// 当添加到特质上时,该宏会生成一个模块,提供对所有形如 `fn method(self) -> Self`
371/// 的方法的枚举和按名称查找功能。检查器(inspector)使用此功能来调用 `Styled` 和
372/// `StyledExt` 中的构建器方法。
373///
374/// 生成的模块名称为 `<snake_case_trait_name>_reflection`,包含以下函数:
375///
376/// ```ignore
377/// pub fn methods::<T: TheTrait + 'static>() -> Vec<rgpui::inspector_reflection::FunctionReflection<T>>;
378///
379/// pub fn find_method::<T: TheTrait + 'static>() -> Option<rgpui::inspector_reflection::FunctionReflection<T>>;
380/// ```
381///
382/// `FunctionReflection` 的 `invoke` 方法会运行对应的方法。`FunctionReflection` 还提供方法的文档说明。
383#[cfg(any(feature = "inspector", debug_assertions))]
384#[proc_macro_attribute]
385pub fn derive_inspector_reflection(_args: TokenStream, input: TokenStream) -> TokenStream {
386 derive_inspector_reflection::derive_inspector_reflection(_args, input)
387}
388
389/// 辅助函数:从派生输入中查找带有指定简单属性的字段。
390///
391/// 该函数用于查找结构体中标记了特定属性(如 `#[app]`、`#[window]`)的字段,
392/// 并返回该字段的标识符。仅支持结构体,对枚举和联合体返回 `None`。
393///
394/// # 参数
395///
396/// * `ast` - 派生输入的语法树
397/// * `name` - 要查找的属性名称
398pub(crate) fn get_simple_attribute_field(ast: &DeriveInput, name: &'static str) -> Option<Ident> {
399 match &ast.data {
400 syn::Data::Struct(data_struct) => data_struct
401 .fields
402 .iter()
403 .find(|field| field.attrs.iter().any(|attr| attr.path().is_ident(name)))
404 .map(|field| field.ident.clone().unwrap()),
405 syn::Data::Enum(_) => None,
406 syn::Data::Union(_) => None,
407 }
408}
409
410/// 用于测试中跨平台路径字符串字面量的宏。在 Windows 上将 `/` 替换为 `\\` 并在绝对路径开头添加 `C:`。
411/// 在其他平台上,路径保持不变。
412///
413/// # 示例
414/// ```rust
415/// use rgpui_macros::path;
416///
417/// let path = path!("/Users/user/file.txt");
418/// #[cfg(target_os = "windows")]
419/// assert_eq!(path, "C:\\Users\\user\\file.txt");
420/// #[cfg(not(target_os = "windows"))]
421/// assert_eq!(path, "/Users/user/file.txt");
422/// ```
423#[proc_macro]
424pub fn path(input: TokenStream) -> TokenStream {
425 let path = parse_macro_input!(input as LitStr);
426 let path = path.value();
427
428 #[cfg(target_os = "windows")]
429 let path = {
430 let path = path.replace("/", "\\");
431 if path.starts_with("\\") {
432 format!("C:{}", path)
433 } else {
434 path
435 }
436 };
437
438 TokenStream::from(quote! {
439 #path
440 })
441}
442
443/// 此宏将路径前缀 `file:///` 替换为 `file:///C:/`(仅适用于 Windows)。
444/// 如果目标操作系统不是 Windows,则 URI 保持不变。
445///
446/// # 示例
447/// ```rust
448/// use rgpui_macros::uri;
449///
450/// let uri = uri!("file:///path/to/file");
451/// #[cfg(target_os = "windows")]
452/// assert_eq!(uri, "file:///C:/path/to/file");
453/// #[cfg(not(target_os = "windows"))]
454/// assert_eq!(uri, "file:///path/to/file");
455/// ```
456#[proc_macro]
457pub fn uri(input: TokenStream) -> TokenStream {
458 let uri = parse_macro_input!(input as LitStr);
459 let uri = uri.value();
460
461 #[cfg(target_os = "windows")]
462 let uri = uri.replace("file:///", "file:///C:/");
463
464 TokenStream::from(quote! {
465 #uri
466 })
467}
468
469/// 空的性能标记属性宏,用作 no-op 标记。
470/// 在 Zed 上游中用于性能记录,此处保持兼容性。
471#[proc_macro_attribute]
472pub fn perf(_args: TokenStream, function: TokenStream) -> TokenStream {
473 function
474}
475
476/// 此宏将行尾 `\n` 替换为 `\r\n`(仅适用于 Windows)。
477/// 如果目标操作系统不是 Windows,则行尾保持不变。
478///
479/// # 示例
480/// ```rust
481/// use rgpui_macros::line_endings;
482///
483/// let text = line_endings!("Hello\nWorld");
484/// #[cfg(target_os = "windows")]
485/// assert_eq!(text, "Hello\r\nWorld");
486/// #[cfg(not(target_os = "windows"))]
487/// assert_eq!(text, "Hello\nWorld");
488/// ```
489#[proc_macro]
490pub fn line_endings(input: TokenStream) -> TokenStream {
491 let text = parse_macro_input!(input as LitStr);
492 let text = text.value();
493
494 #[cfg(target_os = "windows")]
495 let text = text.replace("\n", "\r\n");
496
497 TokenStream::from(quote! {
498 #text
499 })
500}