From f5a4cebde2f12eb980de73ea41eb8d9e133ae49a Mon Sep 17 00:00:00 2001 From: 魏曹先生 <1992414357@qq.com> Date: Sat, 18 Jul 2026 01:53:59 +0800 Subject: ix(macros)!: require explicit `.into()` on chain function return values --- CHANGELOG.md | 31 ++++ README.md | 12 +- docs/_zh_CN/pages/11-resource-system.md | 2 +- docs/_zh_CN/pages/3-define-a-chain.md | 6 +- docs/_zh_CN/pages/4-render-result.md | 2 +- docs/_zh_CN/pages/5-multiple-commands.md | 8 +- docs/_zh_CN/pages/6-argument-parse-picker.md | 16 +- .../_zh_CN/pages/advanced/2-structural-renderer.md | 2 +- docs/_zh_CN/pages/other/features.md | 4 +- docs/pages/11-resource-system.md | 2 +- docs/pages/3-define-a-chain.md | 6 +- docs/pages/4-render-result.md | 2 +- docs/pages/5-multiple-commands.md | 8 +- docs/pages/6-argument-parse-picker.md | 14 +- docs/pages/advanced/2-structural-renderer.md | 2 +- docs/pages/other/features.md | 4 +- examples/example-argument-parse/src/main.rs | 2 +- examples/example-async-support/src/main.rs | 2 +- examples/example-basic/src/main.rs | 2 +- .../src/sub/mod.rs | 2 +- examples/example-completion/src/main.rs | 2 +- examples/example-enum-tag/src/main.rs | 2 +- examples/example-hook/src/main.rs | 2 +- examples/example-panic-unwind/src/main.rs | 2 +- examples/example-pathfinder/src/sub/mod.rs | 2 +- examples/example-repl-basic/src/main.rs | 2 +- examples/example-resources/src/main.rs | 2 +- mingling/src/example_docs.rs | 18 +- mingling/src/lib.md | 2 +- mingling_core/src/asset/global_resource.rs | 7 +- mingling_macros/src/chain.rs | 200 ++++++--------------- mingling_macros/src/lib.rs | 3 +- mingling_macros/src/renderer.rs | 1 + mingling_macros/src/res_injection.rs | 25 ++- 34 files changed, 177 insertions(+), 222 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 17c0596..fb0cc85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -160,6 +160,37 @@ None All examples, docs, and test cases across the repository have been updated to use the new pattern: creating a `RenderResult` with `RenderResult::new()` or `RenderResult::default()`, writing with `write!`/`writeln!` from `std::io::Write`, and returning the result. +2. **[`macros:chain`]** The `#[chain]` macro's return type requirement has been relaxed. Previously, chain functions were required to return `Next` or `()` (with `()` auto-converting to `ResultEmpty`). Now, chain functions can also return `ChainProcess` directly, or omit the return type entirely (which defaults to `()` → `ResultEmpty`). + + The return value of chain functions is now wrapped in an explicit `.into()` call inside the generated `proc` function, ensuring consistent conversion to `ChainProcess`. As a result, **all downstream code that previously relied on implicit conversion from packed types to `Next`/`ChainProcess` must now call `.into()` explicitly**. + + ```rust + // Before — implicit conversion worked because the generated proc + // function was `fn proc(...) -> impl Into>` + #[chain] + fn handle_greet(args: EntryGreet) -> Next { + let name = /* ... */; + ResultGreeting::new(name) // implicitly converted + } + + // After — the generated proc function is `fn proc(...) -> ChainProcess<...>`, + // so the body must produce ChainProcess explicitly + #[chain] + fn handle_greet(args: EntryGreet) -> Next { + let name = /* ... */; + ResultGreeting::new(name).into() // explicit conversion required + } + ``` + + The key advantage of this design is that **the original function body and the expanded `proc` function body are now identical** — the macro only adjusts the function signature and inserts an outermost `.into()` wrapper, without rewriting the internal return expressions. This means the semantics of the original code are perfectly preserved: there is no invisible type coercion happening mid-body, and the behavior you write in the source is exactly what executes at runtime. If a bug arises, the expanded code mirrors the source almost one-to-one, making debugging straightforward. + + This change also applies to: + - Chain functions returning `()` (unit), where the body's final expression with `.into()` is replaced by an explicit `ResultEmpty::to_chain()` call. + - Chain functions using `&mut` resource injection with non-unit returns: the inner closure now calls `__modify_res_and_return_route` (which returns `ChainProcess` directly) instead of relying on `.into()` conversion. + - The `__modify_res_and_return_route` method signature changed from accepting `impl Into>` to returning `ChainProcess` directly. + + All examples, docs, and test cases across the repository have been updated to use `.into()` where packed types are returned from chain functions. + --- ## Release 0.2.2 (2026-07-10) diff --git a/README.md b/README.md index 50c66c6..f67e6d4 100644 --- a/README.md +++ b/README.md @@ -166,7 +166,7 @@ fn handle_greet(args: EntryGreet) -> Next { .first() .cloned() .unwrap_or_else(|| "World".to_string()); - ResultGreeting::new(greeting) + ResultGreeting::new(greeting).into() } ``` @@ -234,7 +234,7 @@ fn handle_greet(args: EntryGreet) -> Next { .pick::(()) // positional: first string .pick_or::(["-r", "--repeat"], 1) // optional flag with default .unpack(); - ResultGreeting::new(format!("{} x{}", name, count)) + ResultGreeting::new(format!("{} x{}", name, count)).into() } ``` @@ -252,7 +252,7 @@ fn handle(args: EntryGreet) -> Next { .pick::>(()) .pick_or::(["-r", "--repeat"], 1) .unpack(); - ResultGreeting::new(format!("{} x{}", name.unwrap_or_default(), count)) + ResultGreeting::new(format!("{} x{}", name.unwrap_or_default(), count)).into() } ``` @@ -279,7 +279,7 @@ impl PickableEnum for Language {} #[chain] fn handle(args: EntryLang) -> Next { let lang: Language = args.pick(()).unpack(); - lang + lang.into() } ``` @@ -781,7 +781,7 @@ pack!(ResultDownloaded = String); #[chain] pub async fn handle_download(args: EntryDownload) -> Next { let file = args.pick(()).unpack(); - download_file(file).await + download_file(file).await.into() } async fn download_file(name: String) -> ResultDownloaded { @@ -843,7 +843,7 @@ fn handle_greet(args: EntryGreet) -> Next { .first() .cloned() .unwrap_or_else(|| "World".to_string()); - ResultGreeting::new(greeting) + ResultGreeting::new(greeting).into() } #[renderer] diff --git a/docs/_zh_CN/pages/11-resource-system.md b/docs/_zh_CN/pages/11-resource-system.md index 152e5d6..a8aab4d 100644 --- a/docs/_zh_CN/pages/11-resource-system.md +++ b/docs/_zh_CN/pages/11-resource-system.md @@ -57,7 +57,7 @@ fn render_path(result: ResultPath) -> RenderResult { #[chain] fn handle_visit(_args: EntryVisit, counter: &mut ResVisitCount) -> Next { counter.0 += 1; - ResultDone::default() + ResultDone::default().into() } #[renderer] diff --git a/docs/_zh_CN/pages/3-define-a-chain.md b/docs/_zh_CN/pages/3-define-a-chain.md index 7ac5c60..b2850c5 100644 --- a/docs/_zh_CN/pages/3-define-a-chain.md +++ b/docs/_zh_CN/pages/3-define-a-chain.md @@ -24,7 +24,7 @@ fn handle_greet(args: EntryGreet) -> Next { // args 就是用户输入经过匹配后剩下的参数 let name = args.inner.first().cloned().unwrap_or_else(|| "World".to_string()); // 把结果包装成 Next,告诉调度器下一步去哪 - ResultName::new(name) + ResultName::new(name).into() } ``` @@ -88,7 +88,7 @@ fn handle_greet(args: EntryGreet) -> Next { .cloned() .unwrap_or_else(|| "World".to_string()); - ResultName::new(name) + ResultName::new(name).into() } ``` @@ -112,7 +112,7 @@ fn handle_greet(args: EntryGreet) -> Next { .first() .cloned() .unwrap_or_else(|| "World".to_string()); - ResultName::new(name) + ResultName::new(name).into() } fn main() { diff --git a/docs/_zh_CN/pages/4-render-result.md b/docs/_zh_CN/pages/4-render-result.md index 7cf2d2b..81c5102 100644 --- a/docs/_zh_CN/pages/4-render-result.md +++ b/docs/_zh_CN/pages/4-render-result.md @@ -51,7 +51,7 @@ fn handle_greet(args: EntryGreet) -> Next { .first() .cloned() .unwrap_or_else(|| "World".to_string()); - ResultName::new(name) + ResultName::new(name).into() } // 4. 用 Renderer 输出结果 diff --git a/docs/_zh_CN/pages/5-multiple-commands.md b/docs/_zh_CN/pages/5-multiple-commands.md index 7d2617b..38ce2cf 100644 --- a/docs/_zh_CN/pages/5-multiple-commands.md +++ b/docs/_zh_CN/pages/5-multiple-commands.md @@ -20,13 +20,13 @@ pack!(ResultSum = i32); #[chain] fn handle_greet(args: EntryGreet) -> Next { let name = args.inner.first().cloned().unwrap_or_else(|| "World".to_string()); - ResultGreeting::new(name) + ResultGreeting::new(name).into() } #[chain] fn handle_add(args: EntryAdd) -> Next { let sum: i32 = args.inner.iter().filter_map(|s| s.parse::().ok()).sum(); - ResultSum::new(sum) + ResultSum::new(sum).into() } #[renderer] @@ -70,9 +70,9 @@ Sum: 6 @@@dispatcher!("add", CMDAdd => EntryAdd); @@@pack!(ResultGreeting = String); @@@pack!(ResultSum = i32); -@@@#[chain] fn handle_greet(_args: EntryGreet) -> Next { ResultGreeting::new("ok".into()) } +@@@#[chain] fn handle_greet(_args: EntryGreet) -> Next { ResultGreeting::new("ok".into()).into() } @@@#[renderer] fn render_greet(_greeting: ResultGreeting) -> RenderResult { RenderResult::new() } -@@@#[chain] fn handle_add(_args: EntryAdd) -> Next { ResultSum::new(0) } +@@@#[chain] fn handle_add(_args: EntryAdd) -> Next { ResultSum::new(0).into() } @@@#[renderer] fn render_sum(_sum: ResultSum) -> RenderResult { RenderResult::new() } fn main() { let mut program = ThisProgram::new(); diff --git a/docs/_zh_CN/pages/6-argument-parse-picker.md b/docs/_zh_CN/pages/6-argument-parse-picker.md index b41f839..4bf162c 100644 --- a/docs/_zh_CN/pages/6-argument-parse-picker.md +++ b/docs/_zh_CN/pages/6-argument-parse-picker.md @@ -32,7 +32,7 @@ features = ["parser"] #[chain] fn handle_greet_entry(prev: EntryGreet) -> Next { let name = prev.pick_or((), "World").unpack(); - ResultName::new(name) + ResultName::new(name).into() } ``` @@ -47,7 +47,7 @@ fn handle_greet_entry(prev: EntryGreet) -> Next { @@@#[chain] @@@fn handle_greet_entry(prev: EntryGreet) -> Next { let name = prev.pick_or((), "World").unpack(); -@@@ResultName::new(name) +@@@ResultName::new(name).into() @@@} ``` @@ -82,7 +82,7 @@ let name = prev.pick_or((), "World").unpack(); #[chain] fn handle_greet_entry(prev: EntryGreet) -> Next { let name = prev.pick_or(["--name", "-n"], "World").unpack(); - ResultName::new(name) + ResultName::new(name).into() } ``` @@ -124,7 +124,7 @@ fn handle_test_entry(prev: EntryTest) -> Next { .pick::(["--id", "-I"]) .unpack(); - ResultInfo::new((name, age, id)) + ResultInfo::new((name, age, id)).into() } ``` @@ -199,7 +199,7 @@ let name = match pick_result { 在您使用 `pick` 提取了用户输入后,可以使用 `after` 立刻处理该参数 -```rust +````rust // Features: ["parser"] @@@dispatcher!("greet", CMDGreet => EntryGreet); @@@pack!(ResultName = String); @@ -217,7 +217,7 @@ fn handle_greet_entry(prev: EntryGreet) -> Next { }) .unpack(); - ResultName::new(name) + ResultName::new(name).into() } ``` @@ -338,7 +338,7 @@ impl Pickable for Address { #[chain] fn handle_connect_entry(prev: EntryConnect) -> Next { let address: Address = prev.pick("--addr").unpack(); - ResultConnected::new(address) + ResultConnected::new(address).into() } #[renderer] @@ -379,7 +379,7 @@ impl PickableEnum for Fruits {} #[chain] fn handle_eat_entry(prev: EntryEat) -> Next { let fruit: Fruits = prev.pick("--fruit").unpack(); - ResultFruit::new(fruit) + ResultFruit::new(fruit).into() } #[renderer] diff --git a/docs/_zh_CN/pages/advanced/2-structural-renderer.md b/docs/_zh_CN/pages/advanced/2-structural-renderer.md index 9a4f111..6b6b0f9 100644 --- a/docs/_zh_CN/pages/advanced/2-structural-renderer.md +++ b/docs/_zh_CN/pages/advanced/2-structural-renderer.md @@ -37,7 +37,7 @@ pack_structural!(ResultInfo = (String, i32)); fn handle_render(args: EntryRender) -> Next { let name = args.inner.first().cloned().unwrap_or_default(); let age = args.inner.get(1).and_then(|s| s.parse().ok()).unwrap_or(0); - ResultInfo::new((name, age)) + ResultInfo::new((name, age)).into() } #[renderer] diff --git a/docs/_zh_CN/pages/other/features.md b/docs/_zh_CN/pages/other/features.md index bfd9efc..d92e597 100644 --- a/docs/_zh_CN/pages/other/features.md +++ b/docs/_zh_CN/pages/other/features.md @@ -24,7 +24,7 @@ pack!(StateFoo = ()); #[chain] async fn handle_state_foo(foo: StateFoo) -> Next { - StateFoo::new(()) + StateFoo::new(()).into() } ``` @@ -160,7 +160,7 @@ use mingling::macros::entry; pack!(EntryHello = Vec); fn main() { - let result = handle_hello(entry!("--name", "Bob")).into(); + let result: Next = handle_hello(entry!("--name", "Bob")).into(); // ... 此处为断言逻辑 } diff --git a/docs/pages/11-resource-system.md b/docs/pages/11-resource-system.md index bc2197f..9491212 100644 --- a/docs/pages/11-resource-system.md +++ b/docs/pages/11-resource-system.md @@ -57,7 +57,7 @@ Use `&mut T` to inject a mutable resource: #[chain] fn handle_visit(_args: EntryVisit, counter: &mut ResVisitCount) -> Next { counter.0 += 1; - ResultDone::default() + ResultDone::default().into() } #[renderer] diff --git a/docs/pages/3-define-a-chain.md b/docs/pages/3-define-a-chain.md index c6d3f8e..b2822bc 100644 --- a/docs/pages/3-define-a-chain.md +++ b/docs/pages/3-define-a-chain.md @@ -24,7 +24,7 @@ fn handle_greet(args: EntryGreet) -> Next { // args contains the remaining params after matching user input let name = args.inner.first().cloned().unwrap_or_else(|| "World".to_string()); // Wrap the result into Next, telling the dispatcher where to go next - ResultName::new(name) + ResultName::new(name).into() } ``` @@ -88,7 +88,7 @@ fn handle_greet(args: EntryGreet) -> Next { .cloned() .unwrap_or_else(|| "World".to_string()); - ResultName::new(name) + ResultName::new(name).into() } ``` @@ -112,7 +112,7 @@ fn handle_greet(args: EntryGreet) -> Next { .first() .cloned() .unwrap_or_else(|| "World".to_string()); - ResultName::new(name) + ResultName::new(name).into() } fn main() { diff --git a/docs/pages/4-render-result.md b/docs/pages/4-render-result.md index b1365b8..ca1e563 100644 --- a/docs/pages/4-render-result.md +++ b/docs/pages/4-render-result.md @@ -51,7 +51,7 @@ fn handle_greet(args: EntryGreet) -> Next { .first() .cloned() .unwrap_or_else(|| "World".to_string()); - ResultName::new(name) + ResultName::new(name).into() } // 4. Output results with a Renderer diff --git a/docs/pages/5-multiple-commands.md b/docs/pages/5-multiple-commands.md index a56f7b0..d9a335a 100644 --- a/docs/pages/5-multiple-commands.md +++ b/docs/pages/5-multiple-commands.md @@ -20,13 +20,13 @@ pack!(ResultSum = i32); #[chain] fn handle_greet(args: EntryGreet) -> Next { let name = args.inner.first().cloned().unwrap_or_else(|| "World".to_string()); - ResultGreeting::new(name) + ResultGreeting::new(name).into() } #[chain] fn handle_add(args: EntryAdd) -> Next { let sum: i32 = args.inner.iter().filter_map(|s| s.parse::().ok()).sum(); - ResultSum::new(sum) + ResultSum::new(sum).into() } #[renderer] @@ -70,9 +70,9 @@ Notice `with_dispatchers`? When you need to register multiple dispatchers, just @@@dispatcher!("add", CMDAdd => EntryAdd); @@@pack!(ResultGreeting = String); @@@pack!(ResultSum = i32); -@@@#[chain] fn handle_greet(_args: EntryGreet) -> Next { ResultGreeting::new("ok".into()) } +@@@#[chain] fn handle_greet(_args: EntryGreet) -> Next { ResultGreeting::new("ok".into()).into() } @@@#[renderer] fn render_greet(_greeting: ResultGreeting) -> RenderResult { RenderResult::new() } -@@@#[chain] fn handle_add(_args: EntryAdd) -> Next { ResultSum::new(0) } +@@@#[chain] fn handle_add(_args: EntryAdd) -> Next { ResultSum::new(0).into() } @@@#[renderer] fn render_sum(_sum: ResultSum) -> RenderResult { RenderResult::new() } fn main() { let mut program = ThisProgram::new(); diff --git a/docs/pages/6-argument-parse-picker.md b/docs/pages/6-argument-parse-picker.md index c80c25c..398cd3c 100644 --- a/docs/pages/6-argument-parse-picker.md +++ b/docs/pages/6-argument-parse-picker.md @@ -32,7 +32,7 @@ Now let's look at `Picker` in action: #[chain] fn handle_greet_entry(prev: EntryGreet) -> Next { let name = prev.pick_or((), "World").unpack(); - ResultName::new(name) + ResultName::new(name).into() } ``` @@ -47,7 +47,7 @@ Breaking down the example above: @@@#[chain] @@@fn handle_greet_entry(prev: EntryGreet) -> Next { let name = prev.pick_or((), "World").unpack(); -@@@ResultName::new(name) +@@@ResultName::new(name).into() @@@} ``` @@ -82,7 +82,7 @@ If your program needs to parse flag args (e.g., `greet --name Alice`), do this: #[chain] fn handle_greet_entry(prev: EntryGreet) -> Next { let name = prev.pick_or(["--name", "-n"], "World").unpack(); - ResultName::new(name) + ResultName::new(name).into() } ``` @@ -124,7 +124,7 @@ fn handle_test_entry(prev: EntryTest) -> Next { .pick::(["--id", "-I"]) .unpack(); - ResultInfo::new((name, age, id)) + ResultInfo::new((name, age, id)).into() } ``` @@ -224,7 +224,7 @@ fn handle_greet_entry(prev: EntryGreet) -> Next { }) .unpack(); - ResultName::new(name) + ResultName::new(name).into() } ``` @@ -345,7 +345,7 @@ impl Pickable for Address { #[chain] fn handle_connect_entry(prev: EntryConnect) -> Next { let address: Address = prev.pick("--addr").unpack(); - ResultConnected::new(address) + ResultConnected::new(address).into() } #[renderer] @@ -387,7 +387,7 @@ impl PickableEnum for Fruits {} #[chain] fn handle_eat_entry(prev: EntryEat) -> Next { let fruit: Fruits = prev.pick("--fruit").unpack(); - ResultFruit::new(fruit) + ResultFruit::new(fruit).into() } #[renderer] diff --git a/docs/pages/advanced/2-structural-renderer.md b/docs/pages/advanced/2-structural-renderer.md index f31f758..fab7530 100644 --- a/docs/pages/advanced/2-structural-renderer.md +++ b/docs/pages/advanced/2-structural-renderer.md @@ -37,7 +37,7 @@ pack_structural!(ResultInfo = (String, i32)); fn handle_render(args: EntryRender) -> Next { let name = args.inner.first().cloned().unwrap_or_default(); let age = args.inner.get(1).and_then(|s| s.parse().ok()).unwrap_or(0); - ResultInfo::new((name, age)) + ResultInfo::new((name, age)).into() } #[renderer] diff --git a/docs/pages/other/features.md b/docs/pages/other/features.md index 813ccdd..325bb75 100644 --- a/docs/pages/other/features.md +++ b/docs/pages/other/features.md @@ -24,7 +24,7 @@ pack!(StateFoo = ()); #[chain] async fn handle_state_foo(foo: StateFoo) -> Next { - StateFoo::new(()) + StateFoo::new(()).into() } ``` @@ -160,7 +160,7 @@ use mingling::macros::entry; pack!(EntryHello = Vec); fn main() { - let result = handle_hello(entry!("--name", "Bob")).into(); + let result: Next = handle_hello(entry!("--name", "Bob")).into(); // ... assertion logic here } diff --git a/examples/example-argument-parse/src/main.rs b/examples/example-argument-parse/src/main.rs index 59499a2..eb07672 100644 --- a/examples/example-argument-parse/src/main.rs +++ b/examples/example-argument-parse/src/main.rs @@ -46,7 +46,7 @@ fn handle_transfer_parse(args: EntryTransfer) -> Next { // Convert into ResultFile .into(); // --------- IMPORTANT --------- - result + result.into() } pack!(ErrorNoNameProvided = ()); diff --git a/examples/example-async-support/src/main.rs b/examples/example-async-support/src/main.rs index ac85aaf..af86408 100644 --- a/examples/example-async-support/src/main.rs +++ b/examples/example-async-support/src/main.rs @@ -50,7 +50,7 @@ pack!(ResultDownloaded = String); // vvvvv_ `async` keyword can be used directly here pub async fn handle_download(args: EntryDownload) -> Next { let file_name = args.pick(()).unpack(); - fake_download(file_name).await + fake_download(file_name).await.into() } /// Renders the downloaded file name. diff --git a/examples/example-basic/src/main.rs b/examples/example-basic/src/main.rs index 7fc0bce..17077e2 100644 --- a/examples/example-basic/src/main.rs +++ b/examples/example-basic/src/main.rs @@ -55,7 +55,7 @@ fn handle_greet(args: EntryGreet) -> Next { .cloned() .unwrap_or_else(|| "World".to_string()) .into(); - name + name.into() } // Define renderer `render_name`, used to render `ResultName` diff --git a/examples/example-combine-pathf-dispatch-tree/src/sub/mod.rs b/examples/example-combine-pathf-dispatch-tree/src/sub/mod.rs index 5ab0ece..2b7aba9 100644 --- a/examples/example-combine-pathf-dispatch-tree/src/sub/mod.rs +++ b/examples/example-combine-pathf-dispatch-tree/src/sub/mod.rs @@ -14,7 +14,7 @@ pub fn handle_my(args: EntryHello) -> Next { .cloned() .unwrap_or_else(|| "World".to_string()) .into(); - name + name.into() } #[renderer] diff --git a/examples/example-completion/src/main.rs b/examples/example-completion/src/main.rs index 0159807..45cc8ef 100644 --- a/examples/example-completion/src/main.rs +++ b/examples/example-completion/src/main.rs @@ -114,7 +114,7 @@ fn handle_greet(args: EntryGreet) -> Next { .pick_or((), "World") .unpack() .into(); - result + result.into() } /// Renders the greeting with the result name and repeat count. diff --git a/examples/example-enum-tag/src/main.rs b/examples/example-enum-tag/src/main.rs index 01c7767..91c5358 100644 --- a/examples/example-enum-tag/src/main.rs +++ b/examples/example-enum-tag/src/main.rs @@ -79,7 +79,7 @@ dispatcher!("lang-select", CMDLanguageSelection => EntryLanguageSelection); fn handle_language_selection(args: EntryLanguageSelection) -> Next { // You can use Picker to directly parse ProgrammingLanguages let lang: ProgrammingLanguages = args.pick(()).unpack(); - lang + lang.into() } /// Renders the selected programming language with its name and description. diff --git a/examples/example-hook/src/main.rs b/examples/example-hook/src/main.rs index 41928ca..23b87c7 100644 --- a/examples/example-hook/src/main.rs +++ b/examples/example-hook/src/main.rs @@ -64,7 +64,7 @@ fn handle_greet(args: EntryGreet) -> Next { .cloned() .unwrap_or_else(|| "World".to_string()) .into(); - name + name.into() } /// Renders the greeting message with the provided name. diff --git a/examples/example-panic-unwind/src/main.rs b/examples/example-panic-unwind/src/main.rs index a829158..d5f746f 100644 --- a/examples/example-panic-unwind/src/main.rs +++ b/examples/example-panic-unwind/src/main.rs @@ -47,7 +47,7 @@ fn handle_panic(prev: EntryPanic) -> Next { // Panic happens here, will be caught panic!("{}", s) } - None => NotPanic::default(), + None => NotPanic::default().into(), } } diff --git a/examples/example-pathfinder/src/sub/mod.rs b/examples/example-pathfinder/src/sub/mod.rs index 6d15930..8cbc1c5 100644 --- a/examples/example-pathfinder/src/sub/mod.rs +++ b/examples/example-pathfinder/src/sub/mod.rs @@ -13,7 +13,7 @@ pub fn handle_greet(args: EntryGreet) -> Next { .cloned() .unwrap_or_else(|| "World".to_string()) .into(); - name + name.into() } /// Renders the name. diff --git a/examples/example-repl-basic/src/main.rs b/examples/example-repl-basic/src/main.rs index d15319e..cfd00d1 100644 --- a/examples/example-repl-basic/src/main.rs +++ b/examples/example-repl-basic/src/main.rs @@ -94,7 +94,7 @@ pack!(ResultList = Vec); #[chain] fn parse_cd_args(prev: EntryCd) -> Next { let join = prev.pick(()).unpack(); - StateChangeDirectory::new(join) + StateChangeDirectory::new(join).into() } // Execute directory change diff --git a/examples/example-resources/src/main.rs b/examples/example-resources/src/main.rs index b08ee26..60c5c08 100644 --- a/examples/example-resources/src/main.rs +++ b/examples/example-resources/src/main.rs @@ -51,7 +51,7 @@ fn render_modify_current(args: EntryModifyCurrent, current_dir: &mut ResCurrentD current_dir.current_dir = current_dir .current_dir .join(args.pick::(()).unpack()); - EntryCurrent::default() + EntryCurrent::default().into() } // Define renderer for output current path _____________ Injected resource diff --git a/mingling/src/example_docs.rs b/mingling/src/example_docs.rs index 4699a50..c4f59c9 100644 --- a/mingling/src/example_docs.rs +++ b/mingling/src/example_docs.rs @@ -66,7 +66,7 @@ /// // Convert into ResultFile /// .into(); /// // --------- IMPORTANT --------- -/// result +/// result.into() /// } /// /// pack!(ErrorNoNameProvided = ()); @@ -199,7 +199,7 @@ pub mod example_argument_parse {} /// // vvvvv_ `async` keyword can be used directly here /// pub async fn handle_download(args: EntryDownload) -> Next { /// let file_name = args.pick(()).unpack(); -/// fake_download(file_name).await +/// fake_download(file_name).await.into() /// } /// /// /// Renders the downloaded file name. @@ -292,7 +292,7 @@ pub mod example_async_support {} /// .cloned() /// .unwrap_or_else(|| "World".to_string()) /// .into(); -/// name +/// name.into() /// } /// /// // Define renderer `render_name`, used to render `ResultName` @@ -672,7 +672,7 @@ pub mod example_combine_pathf_dispatch_tree {} /// .pick_or((), "World") /// .unpack() /// .into(); -/// result +/// result.into() /// } /// /// /// Renders the greeting with the result name and repeat count. @@ -1026,7 +1026,7 @@ pub mod example_dispatch_tree {} /// fn handle_language_selection(args: EntryLanguageSelection) -> Next { /// // You can use Picker to directly parse ProgrammingLanguages /// let lang: ProgrammingLanguages = args.pick(()).unpack(); -/// lang +/// lang.into() /// } /// /// /// Renders the selected programming language with its name and description. @@ -1428,7 +1428,7 @@ pub mod example_help {} /// .cloned() /// .unwrap_or_else(|| "World".to_string()) /// .into(); -/// name +/// name.into() /// } /// /// /// Renders the greeting message with the provided name. @@ -1967,7 +1967,7 @@ pub mod example_pack_err {} /// // Panic happens here, will be caught /// panic!("{}", s) /// } -/// None => NotPanic::default(), +/// None => NotPanic::default().into(), /// } /// } /// @@ -2161,7 +2161,7 @@ pub mod example_pathfinder {} /// #[chain] /// fn parse_cd_args(prev: EntryCd) -> Next { /// let join = prev.pick(()).unpack(); -/// StateChangeDirectory::new(join) +/// StateChangeDirectory::new(join).into() /// } /// /// // Execute directory change @@ -2323,7 +2323,7 @@ pub mod example_repl_basic {} /// current_dir.current_dir = current_dir /// .current_dir /// .join(args.pick::(()).unpack()); -/// EntryCurrent::default() +/// EntryCurrent::default().into() /// } /// /// // Define renderer for output current path _____________ Injected resource diff --git a/mingling/src/lib.md b/mingling/src/lib.md index cd89b96..03fa61d 100644 --- a/mingling/src/lib.md +++ b/mingling/src/lib.md @@ -40,7 +40,7 @@ fn handle_greet(args: EntryGreet) -> Next { .cloned() .unwrap_or_else(|| "World".to_string()) .into(); - name + name.into() } #[renderer] diff --git a/mingling_core/src/asset/global_resource.rs b/mingling_core/src/asset/global_resource.rs index 3d0af7b..29e1136 100644 --- a/mingling_core/src/asset/global_resource.rs +++ b/mingling_core/src/asset/global_resource.rs @@ -45,13 +45,12 @@ where /// Internal syntax for the `&mut MyResource` syntax of #[chain], do not use directly #[doc(hidden)] - pub fn __modify_res_and_return_route( + pub fn __modify_res_and_return_route( &self, - f: impl FnOnce(&mut Res) -> Return, - ) -> impl Into> + f: impl FnOnce(&mut Res) -> ChainProcess, + ) -> ChainProcess where Res: 'static + Default + ResourceMarker + Send + Sync, - Return: Into>, { let Ok(mut guard) = self.resources.lock() else { let mut default_res = Res::res_default(); diff --git a/mingling_macros/src/chain.rs b/mingling_macros/src/chain.rs index 5f72422..5044227 100644 --- a/mingling_macros/src/chain.rs +++ b/mingling_macros/src/chain.rs @@ -9,8 +9,7 @@ use quote::{ToTokens, quote}; use syn::spanned::Spanned; use syn::{Ident, ItemFn, Pat, ReturnType, Signature, Type, TypePath, parse_macro_input}; -/// Validates that the return type of the function is `Next`. -/// Checks whether the return type is `()` (unit). +/// Checks whether the return type is `()` fn is_unit_return_type(sig: &Signature) -> bool { match &sig.output { ReturnType::Type(_, ty) => match &**ty { @@ -21,8 +20,9 @@ fn is_unit_return_type(sig: &Signature) -> bool { } } +/// Validates that the return type is `Next`, `ChainProcess`, `()`, or omitted. fn validate_return_type(sig: &Signature) -> Result<(), proc_macro2::TokenStream> { - // If return type is `()`, it's valid (no Next required) + // `()` or omitted is always valid if is_unit_return_type(sig) { return Ok(()); } @@ -31,38 +31,36 @@ fn validate_return_type(sig: &Signature) -> Result<(), proc_macro2::TokenStream> ReturnType::Type(_, ty) => match &**ty { Type::Path(type_path) => { let last_segment = type_path.path.segments.last().unwrap(); - if last_segment.ident != "Next" { - return Err(syn::Error::new( - ty.span(), - "Chain function must return `Next` or `()`", - ) - .to_compile_error()); + let ident_str = last_segment.ident.to_string(); + if ident_str == "Next" || ident_str == "ChainProcess" { + return Ok(()); } - } - _ => { - return Err(syn::Error::new( + Err(syn::Error::new( ty.span(), - "Chain function must return `Next` or `()`", + "Chain function must return `Next`, `ChainProcess`, `()`, or omit the return type", ) - .to_compile_error()); + .to_compile_error()) } + _ => Err(syn::Error::new( + ty.span(), + "Chain function must return `Next`, `ChainProcess`, `()`, or omit the return type", + ) + .to_compile_error()), }, ReturnType::Default => { - return Err(syn::Error::new( + Err(syn::Error::new( sig.span(), - "Chain function must specify a return type (must be `Next` or `()`)", + "Chain function must specify a return type (must be `Next`, `ChainProcess`, or `()`)", ) - .to_compile_error()); + .to_compile_error()) } } - Ok(()) } -/// Builds the `proc` function implementation that serves as the actual chain -/// entry point inside the generated `Chain` impl. +/// Builds the `proc` function implementation inside the generated `Chain` impl. /// -/// * Without resources: delegates directly to the original function. -/// * With resources: inlines the body and prepends resource bindings. +/// The user's function body is inlined directly, and its result is converted +/// via `.into()` to `ChainProcess`. #[allow(unused_variables)] fn generate_proc_fn( has_resources: bool, @@ -70,7 +68,6 @@ fn generate_proc_fn( program_type: &proc_macro2::TokenStream, previous_type: &TypePath, prev_param: &Pat, - fn_name: &Ident, fn_body_stmts: &[syn::Stmt], is_async_fn: bool, is_unit_return: bool, @@ -78,59 +75,42 @@ fn generate_proc_fn( let immut_resource_stmts = generate_immut_resource_bindings(resources.iter(), program_type); let mut_resources: Vec<_> = resources.iter().filter(|r| r.is_mut).collect(); - let body_stmts: &[syn::Stmt] = if is_unit_return && has_resources { - let mut stmts = fn_body_stmts.to_vec(); - stmts.push(syn::Stmt::Expr( - syn::parse_quote! { - > - ::to_chain(crate::ResultEmpty) - }, - None, - )); - // Box::leak to get a &'static [syn::Stmt] - Box::leak(Box::new(stmts)) - } else { - fn_body_stmts - }; - let wrapped_body = if is_async_fn && !mut_resources.is_empty() { - wrap_body_with_mut_resources_async(body_stmts, &mut_resources, program_type) + wrap_body_with_mut_resources_async(fn_body_stmts, &mut_resources, program_type) } else { - wrap_body_with_mut_resources(body_stmts, &mut_resources, program_type) + wrap_body_with_mut_resources(fn_body_stmts, &mut_resources, program_type, is_unit_return) }; - // When the function returns `()`, wrap the result with ResultEmpty - let call_or_wrapped = if is_unit_return { - if has_resources { + let proc_body = if is_unit_return { + let body_with_ending = if has_resources { quote! { #(#immut_resource_stmts)* - #wrapped_body + #wrapped_body; + > + ::to_chain(crate::ResultEmpty) } } else { - let call = if is_async_fn { - quote! { #fn_name(#prev_param).await; } - } else { - quote! { #fn_name(#prev_param); } - }; quote! { - #call + #wrapped_body; > ::to_chain(crate::ResultEmpty) } - } - } else if has_resources { - quote! { - #(#immut_resource_stmts)* - #wrapped_body - } + }; + quote! { #body_with_ending } } else { - let call = if is_async_fn { - quote! { #fn_name(#prev_param).await.into() } + let body = if has_resources { + quote! { + #(#immut_resource_stmts)* + #wrapped_body + } } else { - quote! { #fn_name(#prev_param).into() } + quote! { #wrapped_body } }; + // Use a let-binding with explicit type annotation so that the inner + // body's `.into()` calls resolve correctly (same as the original function). quote! { - #call + let __chain_result: ::mingling::ChainProcess<#program_type> = { #body }; + __chain_result } }; @@ -138,7 +118,7 @@ fn generate_proc_fn( { quote! { async fn proc(#prev_param: #previous_type) -> ::mingling::ChainProcess<#program_type> { - #call_or_wrapped + #proc_body } } } @@ -147,73 +127,14 @@ fn generate_proc_fn( { quote! { fn proc(#prev_param: #previous_type) -> ::mingling::ChainProcess<#program_type> { - #call_or_wrapped - } - } - } -} - -/// Generates the original function signature (kept for backwards compatibility / -/// internal use), with its return type changed to `impl Into>`. -#[allow(unused_variables)] -fn generate_original_fn( - fn_attrs: &[syn::Attribute], - vis: &syn::Visibility, - fn_name: &Ident, - inputs: &syn::punctuated::Punctuated, - fn_body: &syn::Block, - is_async_fn: bool, - program_type: &proc_macro2::TokenStream, - is_unit_return: bool, -) -> proc_macro2::TokenStream { - // Both unit and Next return types need to produce `impl Into>` - let return_type = quote! { impl Into<::mingling::ChainProcess<#program_type>> }; - - let body = if is_unit_return { - quote! { - { - #fn_body - >::to_chain(crate::ResultEmpty) - } - } - } else { - quote! { - { - let _: crate::Next; - let _: Next; - #fn_body - } - } - }; - - #[cfg(feature = "async")] - { - let async_kw = if is_async_fn { - quote! { async } - } else { - quote! {} - }; - quote! { - #(#fn_attrs)* - #vis #async_kw fn #fn_name(#inputs) -> #return_type { - #body - } - } - } - - #[cfg(not(feature = "async"))] - { - quote! { - #(#fn_attrs)* - #vis fn #fn_name(#inputs) -> #return_type { - #body + #proc_body } } } } /// Assembles the final expanded output: hidden struct, `register_chain!` invocation, -/// `Chain` impl with the `proc` method, and the original function. +/// `Chain` impl with the `proc` method, and the preserved original function. fn generate_struct_and_impl( fn_attrs: &[syn::Attribute], vis: &syn::Visibility, @@ -222,7 +143,7 @@ fn generate_struct_and_impl( previous_type_str: &proc_macro2::TokenStream, program_type: &proc_macro2::TokenStream, proc_fn: &proc_macro2::TokenStream, - origin_proc_fn: &proc_macro2::TokenStream, + original_fn: &proc_macro2::TokenStream, ) -> proc_macro2::TokenStream { quote! { #(#fn_attrs)* @@ -238,8 +159,8 @@ fn generate_struct_and_impl( #proc_fn } - // Keep the original function for internal use - #origin_proc_fn + // Keep the original function unchanged + #original_fn } } @@ -296,8 +217,6 @@ pub fn chain_attr(attr: TokenStream, item: TokenStream) -> TokenStream { }; // Prepare building blocks - let sig = &input_fn.sig; - let inputs = &sig.inputs; let fn_body = &input_fn.block; let mut fn_attrs = input_fn.attrs.clone(); fn_attrs.retain(|attr| !attr.path().is_ident("chain")); @@ -315,14 +234,13 @@ pub fn chain_attr(attr: TokenStream, item: TokenStream) -> TokenStream { // Always use the default crate-defined program path let program_type = crate::default_program_path(); - // Generate the `proc` function + // Generate the `proc` function for the Chain impl let proc_fn = generate_proc_fn( has_resources, &resources, &program_type, &previous_type, &prev_param, - fn_name, &fn_body.stmts, #[cfg(feature = "async")] is_async_fn, @@ -331,20 +249,14 @@ pub fn chain_attr(attr: TokenStream, item: TokenStream) -> TokenStream { is_unit_return, ); - // Generate the original function - let origin_proc_fn = generate_original_fn( - &fn_attrs, - vis, - fn_name, - inputs, - fn_body, - #[cfg(feature = "async")] - is_async_fn, - #[cfg(not(feature = "async"))] - false, - &program_type, - is_unit_return, - ); + // Preserve the original function untouched, with dead_code allowed + // since it may only be called through the Chain trait dispatch. + // Note: do NOT add `#vis` here — `input_fn` (ItemFn) already contains its own visibility. + let original_fn = quote! { + #[allow(dead_code)] + #(#fn_attrs)* + #input_fn + }; // Assemble the final output let previous_type_str = quote! { #previous_type }; @@ -356,7 +268,7 @@ pub fn chain_attr(attr: TokenStream, item: TokenStream) -> TokenStream { &previous_type_str, &program_type, &proc_fn, - &origin_proc_fn, + &original_fn, ); expanded.into() diff --git a/mingling_macros/src/lib.rs b/mingling_macros/src/lib.rs index d0f603a..e9fc327 100644 --- a/mingling_macros/src/lib.rs +++ b/mingling_macros/src/lib.rs @@ -867,7 +867,8 @@ pub fn dispatcher(input: TokenStream) -> TokenStream { /// /// - The function must have at least **one** parameter (the previous type in the chain). /// - The first parameter must be taken **by move**. -/// - The function must return `Next` (the type alias generated by `gen_program!`, which equals `ChainProcess`). +/// - The function may return `Next`, `ChainProcess`, `()`, or omit the return type. +/// - The original function signature is preserved unchanged. /// - With the `async` feature, async functions are supported; without it, async functions are rejected. #[proc_macro_attribute] pub fn chain(attr: TokenStream, item: TokenStream) -> TokenStream { diff --git a/mingling_macros/src/renderer.rs b/mingling_macros/src/renderer.rs index 398c025..d124ec9 100644 --- a/mingling_macros/src/renderer.rs +++ b/mingling_macros/src/renderer.rs @@ -119,6 +119,7 @@ pub fn renderer_attr(attr: TokenStream, item: TokenStream) -> TokenStream { } // Keep the original function unchanged + #[allow(dead_code)] #(#fn_attrs)* #vis fn #fn_name(#original_inputs) -> #original_return_type { #(#fn_body_stmts)* diff --git a/mingling_macros/src/res_injection.rs b/mingling_macros/src/res_injection.rs index 09da889..606b9a6 100644 --- a/mingling_macros/src/res_injection.rs +++ b/mingling_macros/src/res_injection.rs @@ -163,8 +163,10 @@ fn mut_res_binding_name(var_name: &Ident) -> Ident { syn::Ident::new(&format!("__{}_binding", var_name), var_name.span()) } -/// Wraps the function body in nested `__modify_res_and_return_route` closures for -/// each mutable resource parameter (sync version). +/// Wraps the function body in mutable resource closures (sync version). +/// +/// For unit return types: uses `modify_res` (closure returns `()`). +/// For non-unit return types: uses `__modify_res_and_return_route` (closure returns `ChainProcess`). /// /// The innermost closure gets the original body, and each mutable parameter wraps /// outward from last to first. @@ -172,6 +174,7 @@ pub(crate) fn wrap_body_with_mut_resources( fn_body_stmts: &[syn::Stmt], mut_resources: &[&ResourceInjection], program_type: &proc_macro2::TokenStream, + is_unit_return: bool, ) -> proc_macro2::TokenStream { let mut wrapped = quote! { #(#fn_body_stmts)* @@ -180,11 +183,19 @@ pub(crate) fn wrap_body_with_mut_resources( for res in mut_resources { let var_name = &res.var_name; let inner_type = &res.inner_type; - wrapped = quote! { - ::mingling::this::<#program_type>().__modify_res_and_return_route(|#var_name: &mut #inner_type| { - #wrapped - }).into() - }; + if is_unit_return { + wrapped = quote! { + ::mingling::this::<#program_type>().modify_res(|#var_name: &mut #inner_type| { + #wrapped + }) + }; + } else { + wrapped = quote! { + ::mingling::this::<#program_type>().__modify_res_and_return_route(|#var_name: &mut #inner_type| { + #wrapped + }) + }; + } } wrapped -- cgit