summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
author魏曹先生 <1992414357@qq.com>2026-03-28 00:47:46 +0800
committer魏曹先生 <1992414357@qq.com>2026-03-28 00:47:46 +0800
commit7ce68cd11516bd7cf037ecea99a92aee7c31b2c3 (patch)
treea3923ad41c91aa21fe169fd6b4b1bf8898a82589
Add initial Mingling framework codebase
-rw-r--r--.cargo/config.toml4
-rw-r--r--.gitignore1
-rw-r--r--LICENSE-APACHE202
-rw-r--r--LICENSE-MIT9
-rw-r--r--README.md0
-rw-r--r--mingling/Cargo.lock114
-rw-r--r--mingling/Cargo.toml17
-rw-r--r--mingling/src/any.rs72
-rw-r--r--mingling/src/asset.rs4
-rw-r--r--mingling/src/asset/chain.rs8
-rw-r--r--mingling/src/asset/chain/error.rs13
-rw-r--r--mingling/src/asset/dispatcher.rs19
-rw-r--r--mingling/src/asset/node.rs54
-rw-r--r--mingling/src/asset/renderer.rs6
-rw-r--r--mingling/src/lib.rs33
-rw-r--r--mingling/src/program.rs35
-rw-r--r--mingling/src/program/config.rs33
-rw-r--r--mingling/src/program/flag.rs115
-rw-r--r--mingling/src/program/setup.rs15
-rw-r--r--mingling/src/program/setup/basic.rs25
-rw-r--r--mingling/src/renderer.rs1
-rw-r--r--mingling/src/renderer/render_result.rs38
-rw-r--r--mingling_macros/Cargo.lock54
-rw-r--r--mingling_macros/Cargo.toml18
-rw-r--r--mingling_macros/src/chain.rs164
-rw-r--r--mingling_macros/src/chain_struct.rs185
-rw-r--r--mingling_macros/src/dispatcher.rs72
-rw-r--r--mingling_macros/src/lib.rs182
-rw-r--r--mingling_macros/src/node.rs60
-rw-r--r--mingling_macros/src/render.rs87
-rw-r--r--mingling_macros/src/renderer.rs248
31 files changed, 1888 insertions, 0 deletions
diff --git a/.cargo/config.toml b/.cargo/config.toml
new file mode 100644
index 0000000..e3cd902
--- /dev/null
+++ b/.cargo/config.toml
@@ -0,0 +1,4 @@
+[build]
+target-dir = "./.temp/target"
+
+[env]
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..e0fdece
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+.temp
diff --git a/LICENSE-APACHE b/LICENSE-APACHE
new file mode 100644
index 0000000..506aeb9
--- /dev/null
+++ b/LICENSE-APACHE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2026 MinglingRS Team, Weicao-CatilGrass
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/LICENSE-MIT b/LICENSE-MIT
new file mode 100644
index 0000000..ec48781
--- /dev/null
+++ b/LICENSE-MIT
@@ -0,0 +1,9 @@
+# The MIT License (MIT)
+
+Copyright © 2026 MinglingRS Team, Weicao-CatilGrass
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/README.md
diff --git a/mingling/Cargo.lock b/mingling/Cargo.lock
new file mode 100644
index 0000000..34edcd9
--- /dev/null
+++ b/mingling/Cargo.lock
@@ -0,0 +1,114 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "just_fmt"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5454cda0d57db59778608d7a47bff5b16c6705598265869fb052b657f66cf05e"
+
+[[package]]
+name = "mingling"
+version = "0.1.0"
+dependencies = [
+ "just_fmt",
+ "mingling_macros",
+ "serde",
+ "thiserror",
+]
+
+[[package]]
+name = "mingling_macros"
+version = "0.1.0"
+dependencies = [
+ "just_fmt",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "serde"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.117"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
diff --git a/mingling/Cargo.toml b/mingling/Cargo.toml
new file mode 100644
index 0000000..5cd681a
--- /dev/null
+++ b/mingling/Cargo.toml
@@ -0,0 +1,17 @@
+[package]
+name = "mingling"
+version = "0.1.0"
+edition = "2024"
+authors = ["Weicao-CatilGrass"]
+license-file = "LICENSE-MIT"
+
+[features]
+default = ["macros"]
+macros = ["mingling_macros"]
+serde_renderer = ["dep:serde", "mingling_macros/serde"]
+
+[dependencies]
+mingling_macros = { path = "../mingling_macros", optional = true }
+just_fmt = "0.1.2"
+serde = { version = "1.0", features = ["derive"], optional = true }
+thiserror = "2"
diff --git a/mingling/src/any.rs b/mingling/src/any.rs
new file mode 100644
index 0000000..a74cd54
--- /dev/null
+++ b/mingling/src/any.rs
@@ -0,0 +1,72 @@
+#[cfg(feature = "serde_renderer")]
+use serde::Serialize;
+
+use crate::error::ChainProcessError;
+
+pub type ChainProcess = Result<AnyOutput, ChainProcessError>;
+
+#[derive(Debug)]
+pub struct AnyOutput {
+ inner: Box<dyn std::any::Any + Send + 'static>,
+ type_id: std::any::TypeId,
+}
+
+impl AnyOutput {
+ #[cfg(feature = "serde_renderer")]
+ pub fn new<T>(value: T) -> Self
+ where
+ T: Send + Serialize + 'static,
+ {
+ Self {
+ inner: Box::new(value),
+ type_id: std::any::TypeId::of::<T>(),
+ }
+ }
+
+ #[cfg(not(feature = "serde_renderer"))]
+ pub fn new<T>(value: T) -> Self
+ where
+ T: Send + 'static,
+ {
+ Self {
+ inner: Box::new(value),
+ type_id: std::any::TypeId::of::<T>(),
+ }
+ }
+
+ pub fn downcast<T: 'static>(self) -> Result<T, Self> {
+ if self.type_id == std::any::TypeId::of::<T>() {
+ Ok(*self.inner.downcast::<T>().unwrap())
+ } else {
+ Err(self)
+ }
+ }
+
+ pub fn is<T: 'static>(&self) -> bool {
+ self.type_id == std::any::TypeId::of::<T>()
+ }
+
+ /// Route the output to the next Chain
+ pub fn route_chain(self) -> ChainProcess {
+ Ok(self)
+ }
+
+ /// Route the output to the Renderer, ending execution
+ pub fn route_renderer(self) -> ChainProcess {
+ Err(ChainProcessError::Broken(self))
+ }
+}
+
+impl std::ops::Deref for AnyOutput {
+ type Target = dyn std::any::Any + Send + 'static;
+
+ fn deref(&self) -> &Self::Target {
+ &*self.inner
+ }
+}
+
+impl std::ops::DerefMut for AnyOutput {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut *self.inner
+ }
+}
diff --git a/mingling/src/asset.rs b/mingling/src/asset.rs
new file mode 100644
index 0000000..c2adf4e
--- /dev/null
+++ b/mingling/src/asset.rs
@@ -0,0 +1,4 @@
+pub mod chain;
+pub mod dispatcher;
+pub mod node;
+pub mod renderer;
diff --git a/mingling/src/asset/chain.rs b/mingling/src/asset/chain.rs
new file mode 100644
index 0000000..1ea1125
--- /dev/null
+++ b/mingling/src/asset/chain.rs
@@ -0,0 +1,8 @@
+use crate::ChainProcess;
+
+pub mod error;
+
+pub trait Chain {
+ type Previous;
+ fn proc(p: Self::Previous) -> impl Future<Output = ChainProcess> + Send;
+}
diff --git a/mingling/src/asset/chain/error.rs b/mingling/src/asset/chain/error.rs
new file mode 100644
index 0000000..d4da4ac
--- /dev/null
+++ b/mingling/src/asset/chain/error.rs
@@ -0,0 +1,13 @@
+use crate::AnyOutput;
+
+#[derive(thiserror::Error, Debug)]
+pub enum ChainProcessError {
+ #[error("Other error: {0}")]
+ Other(String),
+
+ #[error("IO error: {0}")]
+ IO(#[from] std::io::Error),
+
+ #[error("Broken chain")]
+ Broken(AnyOutput),
+}
diff --git a/mingling/src/asset/dispatcher.rs b/mingling/src/asset/dispatcher.rs
new file mode 100644
index 0000000..31623d3
--- /dev/null
+++ b/mingling/src/asset/dispatcher.rs
@@ -0,0 +1,19 @@
+use crate::{ChainProcess, Program, asset::node::Node};
+
+pub use mingling_macros::Dispatcher;
+
+pub trait Dispatcher {
+ fn node(&self) -> Node;
+}
+
+pub trait DispatcherChain {
+ fn begin(&self) -> ChainProcess;
+}
+
+impl Program {
+ /// Adds a dispatcher to the program.
+ pub fn with_dispatcher<D: Dispatcher + 'static>(&mut self, dispatcher: D) {
+ let dispatcher = Box::new(dispatcher);
+ self.dispatcher.push(dispatcher);
+ }
+}
diff --git a/mingling/src/asset/node.rs b/mingling/src/asset/node.rs
new file mode 100644
index 0000000..c8b7600
--- /dev/null
+++ b/mingling/src/asset/node.rs
@@ -0,0 +1,54 @@
+use just_fmt::kebab_case;
+
+#[derive(Debug, Default)]
+pub struct Node {
+ node: Vec<String>,
+}
+
+impl Node {
+ pub fn join(self, node: impl Into<String>) -> Node {
+ let mut new_node = self.node;
+ new_node.push(node.into());
+ Node { node: new_node }
+ }
+}
+
+impl From<&str> for Node {
+ fn from(s: &str) -> Self {
+ let node = s.split('.').map(|part| kebab_case!(part)).collect();
+ Node { node }
+ }
+}
+
+impl From<String> for Node {
+ fn from(s: String) -> Self {
+ let node = s.split('.').map(|part| kebab_case!(part)).collect();
+ Node { node }
+ }
+}
+
+impl PartialEq for Node {
+ fn eq(&self, other: &Self) -> bool {
+ self.node == other.node
+ }
+}
+
+impl Eq for Node {}
+
+impl PartialOrd for Node {
+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+ Some(self.cmp(other))
+ }
+}
+
+impl Ord for Node {
+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {
+ self.node.cmp(&other.node)
+ }
+}
+
+impl std::fmt::Display for Node {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.node.join("."))
+ }
+}
diff --git a/mingling/src/asset/renderer.rs b/mingling/src/asset/renderer.rs
new file mode 100644
index 0000000..3852b55
--- /dev/null
+++ b/mingling/src/asset/renderer.rs
@@ -0,0 +1,6 @@
+use crate::RenderResult;
+
+pub trait Renderer {
+ type Previous;
+ fn render(p: Self::Previous, r: &mut RenderResult);
+}
diff --git a/mingling/src/lib.rs b/mingling/src/lib.rs
new file mode 100644
index 0000000..c172559
--- /dev/null
+++ b/mingling/src/lib.rs
@@ -0,0 +1,33 @@
+mod any;
+pub use crate::any::*;
+
+pub mod error {
+ pub use crate::asset::chain::error::*;
+}
+
+mod program;
+pub use crate::program::*;
+pub mod setup {
+ pub use crate::program::setup::*;
+}
+
+#[cfg(feature = "macros")]
+#[allow(unused_imports)]
+pub mod macros {
+ pub use mingling_macros::chain;
+ pub use mingling_macros::chain_struct;
+ pub use mingling_macros::node;
+ pub use mingling_macros::r_print;
+ pub use mingling_macros::r_println;
+ pub use mingling_macros::renderer;
+}
+
+mod renderer;
+
+mod asset;
+pub use crate::asset::chain::*;
+pub use crate::asset::dispatcher::*;
+pub use crate::asset::node::*;
+pub use crate::asset::renderer::*;
+pub use crate::renderer::render_result::*;
+pub use mingling_macros::Dispatcher;
diff --git a/mingling/src/program.rs b/mingling/src/program.rs
new file mode 100644
index 0000000..e4bc3d0
--- /dev/null
+++ b/mingling/src/program.rs
@@ -0,0 +1,35 @@
+use crate::asset::dispatcher::Dispatcher;
+use std::env;
+
+pub mod setup;
+
+mod config;
+pub use config::*;
+
+mod flag;
+pub use flag::*;
+
+#[derive(Default)]
+pub struct Program {
+ pub(crate) args: Vec<String>,
+ pub(crate) dispatcher: Vec<Box<dyn Dispatcher>>,
+
+ pub stdout_setting: ProgramStdoutSetting,
+ pub user_context: ProgramUserContext,
+}
+
+impl Program {
+ /// Creates a new Program instance, initializing args from environment.
+ pub fn new() -> Self {
+ Program {
+ args: env::args().collect(),
+ dispatcher: Vec::new(),
+ ..Default::default()
+ }
+ }
+
+ /// Run the command line program
+ pub async fn exec(self) {
+ todo!()
+ }
+}
diff --git a/mingling/src/program/config.rs b/mingling/src/program/config.rs
new file mode 100644
index 0000000..93507e7
--- /dev/null
+++ b/mingling/src/program/config.rs
@@ -0,0 +1,33 @@
+pub struct ProgramStdoutSetting {
+ /// Output error messages
+ pub error_output: bool,
+
+ /// Render results and output
+ pub render_output: bool,
+}
+
+impl Default for ProgramStdoutSetting {
+ fn default() -> Self {
+ ProgramStdoutSetting {
+ error_output: true,
+ render_output: true,
+ }
+ }
+}
+
+pub struct ProgramUserContext {
+ /// View help information instead of running the command
+ pub help: bool,
+
+ /// Skip user confirmation step
+ pub confirm: bool,
+}
+
+impl Default for ProgramUserContext {
+ fn default() -> Self {
+ ProgramUserContext {
+ help: false,
+ confirm: false,
+ }
+ }
+}
diff --git a/mingling/src/program/flag.rs b/mingling/src/program/flag.rs
new file mode 100644
index 0000000..0178ebe
--- /dev/null
+++ b/mingling/src/program/flag.rs
@@ -0,0 +1,115 @@
+use crate::Program;
+
+pub struct Flag {
+ vec: Vec<&'static str>,
+}
+
+impl From<&'static str> for Flag {
+ fn from(s: &'static str) -> Self {
+ Flag { vec: vec![s] }
+ }
+}
+
+impl From<&'static [&'static str]> for Flag {
+ fn from(slice: &'static [&'static str]) -> Self {
+ Flag {
+ vec: slice.to_vec(),
+ }
+ }
+}
+
+impl<const N: usize> From<[&'static str; N]> for Flag {
+ fn from(slice: [&'static str; N]) -> Self {
+ Flag {
+ vec: slice.to_vec(),
+ }
+ }
+}
+
+impl<const N: usize> From<&'static [&'static str; N]> for Flag {
+ fn from(slice: &'static [&'static str; N]) -> Self {
+ Flag {
+ vec: slice.to_vec(),
+ }
+ }
+}
+
+impl AsRef<[&'static str]> for Flag {
+ fn as_ref(&self) -> &[&'static str] {
+ &self.vec
+ }
+}
+
+impl std::ops::Deref for Flag {
+ type Target = [&'static str];
+
+ fn deref(&self) -> &Self::Target {
+ &self.vec
+ }
+}
+
+macro_rules! special_flag {
+ ($args:expr, $flag:expr) => {{
+ let flag = $flag;
+ let found = $args.iter().any(|arg| arg == flag);
+ $args.retain(|arg| arg != flag);
+ found
+ }};
+}
+
+macro_rules! special_argument {
+ ($args:expr, $flag:expr) => {{
+ let flag = $flag;
+ let mut value: Option<String> = None;
+ let mut i = 0;
+ while i < $args.len() {
+ if &$args[i] == flag {
+ if i + 1 < $args.len() {
+ value = Some($args[i + 1].clone());
+ $args.remove(i + 1);
+ $args.remove(i);
+ } else {
+ value = None;
+ $args.remove(i);
+ }
+ break;
+ }
+ i += 1;
+ }
+ value
+ }};
+}
+
+impl Program {
+ /// Registers a global argument (with value) and its handler.
+ pub fn global_argument<F, A>(&mut self, arguments: A, do_fn: F)
+ where
+ F: Fn(&mut Program, String),
+ A: Into<Flag>,
+ {
+ let flag = arguments.into();
+ for argument in flag.iter() {
+ let value = special_argument!(self.args, argument);
+ if let Some(value) = value {
+ do_fn(self, value);
+ return;
+ }
+ }
+ }
+
+ /// Registers a global flag (boolean) and its handler.
+ pub fn global_flag<F, A>(&mut self, flag: A, do_fn: F)
+ where
+ F: Fn(&mut Program),
+ A: Into<Flag>,
+ {
+ let flag = flag.into();
+ for argument in flag.iter() {
+ let enabled = special_flag!(self.args, argument);
+ if enabled {
+ do_fn(self);
+ return;
+ }
+ }
+ }
+}
diff --git a/mingling/src/program/setup.rs b/mingling/src/program/setup.rs
new file mode 100644
index 0000000..fdf7b04
--- /dev/null
+++ b/mingling/src/program/setup.rs
@@ -0,0 +1,15 @@
+use crate::program::Program;
+
+mod basic;
+pub use basic::*;
+
+pub trait ProgramSetup {
+ fn setup(program: &mut Program);
+}
+
+impl Program {
+ /// Load and execute init logic
+ pub fn with_setup<S: ProgramSetup + 'static>(&mut self, _setup: S) {
+ S::setup(self);
+ }
+}
diff --git a/mingling/src/program/setup/basic.rs b/mingling/src/program/setup/basic.rs
new file mode 100644
index 0000000..0ea72a6
--- /dev/null
+++ b/mingling/src/program/setup/basic.rs
@@ -0,0 +1,25 @@
+use crate::program::{Program, setup::ProgramSetup};
+
+/// Performs basic program initialization:
+///
+/// - Collects `--quiet` flag to control message rendering
+/// - Collects `--help` flag to enable help mode
+/// - Collects `--confirm` flag to skip user confirmation
+pub struct BasicProgramSetup;
+
+impl ProgramSetup for BasicProgramSetup {
+ fn setup(program: &mut Program) {
+ program.global_flag(["--quiet", "-q"], |p| {
+ p.stdout_setting.render_output = false;
+ p.stdout_setting.error_output = false;
+ });
+
+ program.global_flag(["--help", "-h"], |p| {
+ p.user_context.help = true;
+ });
+
+ program.global_flag(["--confirm", "-C"], |p| {
+ p.user_context.confirm = true;
+ });
+ }
+}
diff --git a/mingling/src/renderer.rs b/mingling/src/renderer.rs
new file mode 100644
index 0000000..631092b
--- /dev/null
+++ b/mingling/src/renderer.rs
@@ -0,0 +1 @@
+pub mod render_result;
diff --git a/mingling/src/renderer/render_result.rs b/mingling/src/renderer/render_result.rs
new file mode 100644
index 0000000..73c38e7
--- /dev/null
+++ b/mingling/src/renderer/render_result.rs
@@ -0,0 +1,38 @@
+use std::{
+ fmt::{Display, Formatter},
+ ops::Deref,
+};
+
+#[derive(Default, Debug, PartialEq)]
+pub struct RenderResult {
+ render_text: String,
+}
+
+impl Display for RenderResult {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ writeln!(f, "{}", self.render_text.trim())
+ }
+}
+
+impl Deref for RenderResult {
+ type Target = str;
+
+ fn deref(&self) -> &Self::Target {
+ &self.render_text
+ }
+}
+
+impl RenderResult {
+ pub fn print(&mut self, text: &str) {
+ self.render_text.push_str(text);
+ }
+
+ pub fn println(&mut self, text: &str) {
+ self.render_text.push_str(text);
+ self.render_text.push('\n');
+ }
+
+ pub fn clear(&mut self) {
+ self.render_text.clear();
+ }
+}
diff --git a/mingling_macros/Cargo.lock b/mingling_macros/Cargo.lock
new file mode 100644
index 0000000..b2fef0e
--- /dev/null
+++ b/mingling_macros/Cargo.lock
@@ -0,0 +1,54 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "just_fmt"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5454cda0d57db59778608d7a47bff5b16c6705598265869fb052b657f66cf05e"
+
+[[package]]
+name = "mingling_macros"
+version = "0.1.0"
+dependencies = [
+ "just_fmt",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.117"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
diff --git a/mingling_macros/Cargo.toml b/mingling_macros/Cargo.toml
new file mode 100644
index 0000000..683b5b4
--- /dev/null
+++ b/mingling_macros/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "mingling_macros"
+version = "0.1.0"
+edition = "2024"
+
+[lib]
+proc-macro = true
+
+[features]
+default = []
+serde = []
+
+[dependencies]
+syn = { version = "2.0", features = ["full", "visit-mut"] }
+quote = "1.0"
+proc-macro2 = "1.0"
+
+just_fmt = "0.1.2"
diff --git a/mingling_macros/src/chain.rs b/mingling_macros/src/chain.rs
new file mode 100644
index 0000000..0c21c79
--- /dev/null
+++ b/mingling_macros/src/chain.rs
@@ -0,0 +1,164 @@
+//! Chain Attribute Macro Implementation
+//!
+//! This module provides the `#[chain]` attribute macro for automatically
+//! generating structs that implement the `Chain` trait from async functions.
+
+use proc_macro::TokenStream;
+use quote::quote;
+use syn::parse::{Parse, ParseStream};
+use syn::spanned::Spanned;
+use syn::{
+ FnArg, Ident, ItemFn, Pat, PatType, ReturnType, Signature, Type, TypePath, parse_macro_input,
+};
+
+/// Parses the chain attribute arguments
+struct ChainAttribute {
+ struct_name: Ident,
+}
+
+impl Parse for ChainAttribute {
+ fn parse(input: ParseStream) -> syn::Result<Self> {
+ let struct_name = input.parse()?;
+ Ok(ChainAttribute { struct_name })
+ }
+}
+
+/// Extracts the previous type and parameter name from function arguments
+fn extract_previous_info(sig: &Signature) -> syn::Result<(Pat, TypePath)> {
+ // The function should have exactly one parameter
+ if sig.inputs.len() != 1 {
+ return Err(syn::Error::new(
+ sig.inputs.span(),
+ "Chain function must have exactly one parameter",
+ ));
+ }
+
+ let arg = &sig.inputs[0];
+ match arg {
+ FnArg::Typed(PatType { pat, ty, .. }) => {
+ // Extract the pattern (parameter name)
+ let param_pat = (**pat).clone();
+
+ // Extract the type
+ match &**ty {
+ Type::Path(type_path) => Ok((param_pat, type_path.clone())),
+ _ => Err(syn::Error::new(
+ ty.span(),
+ "Parameter type must be a type path",
+ )),
+ }
+ }
+ FnArg::Receiver(_) => Err(syn::Error::new(
+ arg.span(),
+ "Chain function cannot have self parameter",
+ )),
+ }
+}
+
+/// Extracts the return type from the function signature
+fn extract_return_type(sig: &Signature) -> syn::Result<TypePath> {
+ match &sig.output {
+ ReturnType::Type(_, ty) => match &**ty {
+ Type::Path(type_path) => Ok(type_path.clone()),
+ _ => Err(syn::Error::new(
+ ty.span(),
+ "Return type must be a type path",
+ )),
+ },
+ ReturnType::Default => Err(syn::Error::new(
+ sig.span(),
+ "Chain function must have a return type",
+ )),
+ }
+}
+
+/// Implementation of the `#[chain]` attribute macro
+///
+/// This macro transforms an async function into a struct that implements
+/// the `Chain` trait. The struct name is specified in the attribute.
+///
+/// # Examples
+///
+/// ```ignore
+/// use mingling_macros::chain;
+///
+/// #[chain(InitEntry)]
+/// pub async fn process(data: InitBegin) -> mingling::AnyOutput {
+/// AnyOutput::new::<InitResult>("初始化成功!".to_string().into())
+/// }
+/// ```
+///
+/// This generates:
+/// ```ignore
+/// pub struct InitEntry;
+/// impl Chain for InitEntry {
+/// type Previous = InitBegin;
+/// async fn proc(data: Self::Previous) -> mingling::AnyOutput {
+/// AnyOutput::new::<InitResult>("初始化成功!".to_string().into())
+/// }
+/// }
+/// ```
+pub fn chain_attr(attr: TokenStream, item: TokenStream) -> TokenStream {
+ // Parse the attribute arguments
+ let chain_attr = parse_macro_input!(attr as ChainAttribute);
+ let struct_name = chain_attr.struct_name;
+
+ // Parse the function item
+ let input_fn = parse_macro_input!(item as ItemFn);
+
+ // Validate the function
+ if !input_fn.sig.asyncness.is_some() {
+ return syn::Error::new(input_fn.sig.span(), "Chain function must be async")
+ .to_compile_error()
+ .into();
+ }
+
+ // Extract the previous type and parameter name from function arguments
+ let (prev_param, previous_type) = match extract_previous_info(&input_fn.sig) {
+ Ok(info) => info,
+ Err(e) => return e.to_compile_error().into(),
+ };
+
+ // Extract the return type
+ let return_type = match extract_return_type(&input_fn.sig) {
+ Ok(ty) => ty,
+ Err(e) => return e.to_compile_error().into(),
+ };
+
+ // Get the function body
+ let fn_body = &input_fn.block;
+
+ // Get function attributes (excluding the chain attribute)
+ let mut fn_attrs = input_fn.attrs.clone();
+ // Remove any #[chain(...)] attributes to avoid infinite recursion
+ fn_attrs.retain(|attr| !attr.path().is_ident("chain"));
+
+ // Get function visibility
+ let vis = &input_fn.vis;
+
+ // Get function name
+ let fn_name = &input_fn.sig.ident;
+
+ // Generate the struct and implementation
+ let expanded = quote! {
+ #(#fn_attrs)*
+ #vis struct #struct_name;
+
+ impl ::mingling::Chain for #struct_name {
+ type Previous = #previous_type;
+
+ async fn proc(#prev_param: Self::Previous) -> #return_type {
+ // Call the original function
+ #fn_name(#prev_param).await
+ }
+ }
+
+ // Keep the original function for internal use
+ #(#fn_attrs)*
+ #vis async fn #fn_name(#prev_param: #previous_type) -> #return_type {
+ #fn_body
+ }
+ };
+
+ expanded.into()
+}
diff --git a/mingling_macros/src/chain_struct.rs b/mingling_macros/src/chain_struct.rs
new file mode 100644
index 0000000..82a596d
--- /dev/null
+++ b/mingling_macros/src/chain_struct.rs
@@ -0,0 +1,185 @@
+//! Chain Struct Macro Implementation
+//!
+//! This module provides the `chain_struct!` macro for creating wrapper types
+//! with automatic implementations of common traits.
+
+use proc_macro::TokenStream;
+use quote::quote;
+use syn::parse::{Parse, ParseStream};
+use syn::{Ident, Result as SynResult, Token, Type};
+
+/// Parses input in the format: `TypeName = InnerType`
+struct ChainStructInput {
+ type_name: Ident,
+ inner_type: Type,
+}
+
+impl Parse for ChainStructInput {
+ fn parse(input: ParseStream) -> SynResult<Self> {
+ let type_name = input.parse()?;
+ input.parse::<Token![=]>()?;
+ let inner_type = input.parse()?;
+
+ Ok(ChainStructInput {
+ type_name,
+ inner_type,
+ })
+ }
+}
+
+/// Implementation of the `chain_struct!` macro
+///
+/// This macro creates a wrapper struct with automatic implementations of:
+/// - `From<InnerType>` and `Into<InnerType>`
+/// - `new()` constructor
+/// - `Default` (if the inner type implements Default)
+/// - `AsRef<InnerType>` and `AsMut<InnerType>`
+/// - `Deref` and `DerefMut` to the inner type
+///
+/// # Examples
+///
+/// ```ignore
+/// use mingling_macros::chain_struct;
+///
+/// // Creates a wrapper type around String
+/// chain_struct!(NameString = String);
+///
+/// // Usage:
+/// let name = NameString::new("Hello".to_string());
+/// let inner: String = name.into(); // Into conversion
+/// let name2 = NameString::from("World".to_string()); // From conversion
+/// let ref_str: &String = name2.as_ref(); // AsRef
+/// ```
+pub fn chain_struct(input: TokenStream) -> TokenStream {
+ let ChainStructInput {
+ type_name,
+ inner_type,
+ } = syn::parse_macro_input!(input as ChainStructInput);
+
+ // Generate the struct definition
+ #[cfg(not(feature = "serde"))]
+ let struct_def = quote! {
+ #[derive(Debug)]
+ pub struct #type_name {
+ inner: #inner_type,
+ }
+ };
+
+ #[cfg(feature = "serde")]
+ let struct_def = quote! {
+ #[derive(Debug, serde::Serialize)]
+ pub struct #type_name {
+ inner: #inner_type,
+ }
+ };
+
+ // Generate the new() method
+ let new_impl = quote! {
+ impl #type_name {
+ /// Creates a new instance of the wrapper type
+ pub fn new(inner: #inner_type) -> Self {
+ Self { inner }
+ }
+ }
+ };
+
+ // Generate From and Into implementations
+ let from_into_impl = quote! {
+ impl From<#inner_type> for #type_name {
+ fn from(inner: #inner_type) -> Self {
+ Self::new(inner)
+ }
+ }
+
+ impl From<#type_name> for #inner_type {
+ fn from(wrapper: #type_name) -> #inner_type {
+ wrapper.inner
+ }
+ }
+ };
+
+ // Generate AsRef and AsMut implementations
+ let as_ref_impl = quote! {
+ impl ::std::convert::AsRef<#inner_type> for #type_name {
+ fn as_ref(&self) -> &#inner_type {
+ &self.inner
+ }
+ }
+
+ impl ::std::convert::AsMut<#inner_type> for #type_name {
+ fn as_mut(&mut self) -> &mut #inner_type {
+ &mut self.inner
+ }
+ }
+ };
+
+ // Generate Deref and DerefMut implementations
+ let deref_impl = quote! {
+ impl ::std::ops::Deref for #type_name {
+ type Target = #inner_type;
+
+ fn deref(&self) -> &Self::Target {
+ &self.inner
+ }
+ }
+
+ impl ::std::ops::DerefMut for #type_name {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.inner
+ }
+ }
+ };
+
+ // Check if the inner type implements Default by generating conditional code
+ let default_impl = quote! {
+ impl ::std::default::Default for #type_name
+ where
+ #inner_type: ::std::default::Default,
+ {
+ fn default() -> Self {
+ Self::new(::std::default::Default::default())
+ }
+ }
+ };
+
+ let any_out_impl = quote! {
+ impl Into<mingling::AnyOutput> for #type_name {
+ fn into(self) -> mingling::AnyOutput {
+ mingling::AnyOutput::new(self)
+ }
+ }
+
+ impl Into<mingling::ChainProcess> for #type_name {
+ fn into(self) -> mingling::ChainProcess {
+ mingling::AnyOutput::new(self).route_chain()
+ }
+ }
+
+ impl #type_name {
+ /// Converts the wrapper type into a `ChainProcess` for chaining operations.
+ pub fn to_chain(self) -> mingling::ChainProcess {
+ mingling::AnyOutput::new(self).route_chain()
+ }
+
+ /// Converts the wrapper type into a `ChainProcess` for rendering operations.
+ pub fn to_render(self) -> mingling::ChainProcess {
+ mingling::AnyOutput::new(self).route_renderer()
+ }
+ }
+ };
+
+ // Combine all implementations
+ let expanded = quote! {
+ #struct_def
+
+ #new_impl
+ #from_into_impl
+ #as_ref_impl
+ #deref_impl
+ #default_impl
+
+ #any_out_impl
+ };
+
+ expanded.into()
+}
diff --git a/mingling_macros/src/dispatcher.rs b/mingling_macros/src/dispatcher.rs
new file mode 100644
index 0000000..a411081
--- /dev/null
+++ b/mingling_macros/src/dispatcher.rs
@@ -0,0 +1,72 @@
+//! Dispatcher Derive Macro Implementation
+//!
+//! This module provides the `Dispatcher` derive macro for automatically
+//! implementing the `mingling::Dispatcher` trait for structs.
+
+use just_fmt::dot_case;
+use proc_macro::TokenStream;
+use quote::quote;
+use syn::{Attribute, DeriveInput, Ident, Lit, Meta, MetaNameValue, parse_macro_input};
+
+/// Parses the `#[dispatcher("path")]` attribute if present
+fn parse_dispatcher_attribute(attrs: &[Attribute]) -> Option<String> {
+ for attr in attrs {
+ if attr.path().is_ident("dispatcher") {
+ match attr.parse_args::<Meta>() {
+ Ok(Meta::NameValue(MetaNameValue {
+ value:
+ syn::Expr::Lit(syn::ExprLit {
+ lit: Lit::Str(lit_str),
+ ..
+ }),
+ ..
+ })) => {
+ return Some(lit_str.value());
+ }
+ Ok(_) => {
+ // If it's not a string literal, we'll use a default
+ return None;
+ }
+ Err(_) => {
+ // If parsing fails, we'll use a default
+ return None;
+ }
+ }
+ }
+ }
+ None
+}
+
+/// Generates the command node path from the struct name or attribute
+fn generate_command_path(struct_name: &Ident, attr_path: Option<String>) -> String {
+ if let Some(path) = attr_path {
+ path
+ } else {
+ // Convert struct name to dot_case for default path using the dot_case! macro
+ dot_case!(struct_name.to_string())
+ }
+}
+
+/// Implementation of the `Dispatcher` derive macro
+pub fn dispatcher_derive(input: TokenStream) -> TokenStream {
+ let input = parse_macro_input!(input as DeriveInput);
+
+ let struct_name = &input.ident;
+
+ // Parse the dispatcher attribute if present
+ let attr_path = parse_dispatcher_attribute(&input.attrs);
+
+ // Generate the command path
+ let command_path = generate_command_path(struct_name, attr_path);
+
+ // Generate the implementation
+ let expanded = quote! {
+ impl ::mingling::Dispatcher for #struct_name {
+ fn node(&self) -> ::mingling::Node {
+ ::mingling::macros::node!(#command_path)
+ }
+ }
+ };
+
+ expanded.into()
+}
diff --git a/mingling_macros/src/lib.rs b/mingling_macros/src/lib.rs
new file mode 100644
index 0000000..3fdd130
--- /dev/null
+++ b/mingling_macros/src/lib.rs
@@ -0,0 +1,182 @@
+//! Mingling Macros Crate
+//!
+//! This crate provides procedural macros for the Mingling framework.
+//! Macros are implemented in separate modules and re-exported here.
+
+use proc_macro::TokenStream;
+
+mod chain;
+mod chain_struct;
+mod dispatcher;
+mod node;
+mod render;
+mod renderer;
+
+/// Creates a command node from a dot-separated path string.
+///
+/// # Examples
+///
+/// ```ignore
+/// use mingling_macros::node;
+///
+/// let node = node!("root.subcommand.action");
+/// ```
+#[proc_macro]
+pub fn node(input: TokenStream) -> TokenStream {
+ node::node(input)
+}
+
+/// Derive macro for automatically implementing the `Dispatcher` trait.
+///
+/// This macro generates an implementation of `mingling::Dispatcher` for a struct.
+/// By default, it uses the struct name converted to snake_case as the command path.
+/// You can also specify a custom path using the `#[dispatcher("path")]` attribute.
+///
+/// # Examples
+///
+/// ```ignore
+/// use mingling_macros::Dispatcher;
+///
+/// // Uses default path: "remote.add"
+/// #[derive(Dispatcher)]
+/// pub struct RemoteAdd;
+///
+/// // Uses custom path: "remote.rm"
+/// #[derive(Dispatcher)]
+/// #[dispatcher("remote.rm")]
+/// pub struct MyCommand;
+/// ```
+#[proc_macro_derive(Dispatcher, attributes(dispatcher))]
+pub fn dispatcher_derive(input: TokenStream) -> TokenStream {
+ dispatcher::dispatcher_derive(input)
+}
+
+/// Macro for creating wrapper types with automatic trait implementations.
+///
+/// This macro creates a new struct that wraps an inner type and automatically
+/// implements common traits:
+/// - `From<InnerType>` and `Into<InnerType>`
+/// - `new()` constructor
+/// - `Default` (if inner type implements Default)
+/// - `AsRef<InnerType>` and `AsMut<InnerType>`
+/// - `Deref` and `DerefMut` to inner type
+///
+/// # Examples
+///
+/// ```ignore
+/// use mingling_macros::chain_struct;
+///
+/// // Creates a wrapper type around String
+/// chain_struct!(NameString = String);
+///
+/// // Usage:
+/// let name = NameString::new("Hello".to_string());
+/// let inner: String = name.into(); // Into conversion
+/// let name2 = NameString::from("World".to_string()); // From conversion
+/// let ref_str: &String = name2.as_ref(); // AsRef
+/// ```
+#[proc_macro]
+pub fn chain_struct(input: TokenStream) -> TokenStream {
+ chain_struct::chain_struct(input)
+}
+
+/// Macro for printing to a RenderResult without newline.
+///
+/// This macro expands to a call to `RenderResult::print` with formatted arguments.
+/// It expects a mutable reference to a `RenderResult` named `r` to be in scope.
+///
+/// # Examples
+///
+/// ```ignore
+/// use mingling_macros::r_print;
+///
+/// let mut r = RenderResult::default();
+/// r_print!("Hello, {}!", "world");
+/// ```
+#[proc_macro]
+pub fn r_print(input: TokenStream) -> TokenStream {
+ render::r_print(input)
+}
+
+/// Macro for printing to a RenderResult with newline.
+///
+/// This macro expands to a call to `RenderResult::println` with formatted arguments.
+/// It expects a mutable reference to a `RenderResult` named `r` to be in scope.
+///
+/// # Examples
+///
+/// ```ignore
+/// use mingling_macros::r_println;
+///
+/// let mut r = RenderResult::default();
+/// r_println!("Hello, {}!", "world");
+/// ```
+#[proc_macro]
+pub fn r_println(input: TokenStream) -> TokenStream {
+ render::r_println(input)
+}
+
+/// Attribute macro for automatically generating structs that implement the `Chain` trait.
+///
+/// This macro transforms an async function into a struct that implements
+/// the `Chain` trait. The struct name is specified in the attribute.
+///
+/// # Examples
+///
+/// ```ignore
+/// use mingling_macros::chain;
+///
+/// #[chain(InitEntry)]
+/// pub async fn proc(_: InitBegin) -> mingling::AnyOutput {
+/// AnyOutput::new::<InitResult>("初始化成功!".to_string().into())
+/// }
+/// ```
+///
+/// This generates:
+/// ```ignore
+/// pub struct InitEntry;
+/// impl Chain for InitEntry {
+/// type Previous = InitBegin;
+/// async fn proc(_: Self::Previous) -> mingling::AnyOutput {
+/// AnyOutput::new::<InitResult>("初始化成功!".to_string().into())
+/// }
+/// }
+/// ```
+#[proc_macro_attribute]
+pub fn chain(attr: TokenStream, item: TokenStream) -> TokenStream {
+ chain::chain_attr(attr, item)
+}
+
+/// Attribute macro for automatically generating structs that implement the `Renderer` trait.
+///
+/// This macro transforms a function into a struct that implements
+/// the `Renderer` trait. The struct name is specified in the attribute.
+///
+/// # Examples
+///
+/// ```ignore
+/// use mingling_macros::renderer;
+///
+/// #[renderer(InitResultRenderer)]
+/// fn render(p: InitResult, r: &mut RenderResult) {
+/// let str: String = p.into();
+/// r_println!("{}", str);
+/// }
+/// ```
+///
+/// This generates:
+/// ```ignore
+/// pub struct InitResultRenderer;
+/// impl Renderer for InitResultRenderer {
+/// type Previous = InitResult;
+///
+/// fn render(p: Self::Previous, r: &mut RenderResult) {
+/// let str: String = p.into();
+/// r_println!("{}", str);
+/// }
+/// }
+/// ```
+#[proc_macro_attribute]
+pub fn renderer(attr: TokenStream, item: TokenStream) -> TokenStream {
+ renderer::renderer_attr(attr, item)
+}
diff --git a/mingling_macros/src/node.rs b/mingling_macros/src/node.rs
new file mode 100644
index 0000000..3d9473f
--- /dev/null
+++ b/mingling_macros/src/node.rs
@@ -0,0 +1,60 @@
+//! Command Node Macro Implementation
+//!
+//! This module provides the `node` procedural macro for creating
+//! command nodes from dot-separated path strings.
+
+use just_fmt::kebab_case;
+use proc_macro::TokenStream;
+use proc_macro2::TokenStream as TokenStream2;
+use quote::quote;
+use syn::parse::{Parse, ParseStream};
+use syn::{LitStr, Result as SynResult};
+
+/// Parses a string literal input for the node macro
+struct NodeInput {
+ path: LitStr,
+}
+
+impl Parse for NodeInput {
+ fn parse(input: ParseStream) -> SynResult<Self> {
+ Ok(NodeInput {
+ path: input.parse()?,
+ })
+ }
+}
+
+/// Implementation of the `node` procedural macro
+///
+/// # Examples
+///
+/// ```ignore
+/// use mingling_macros::node;
+///
+/// // Creates: Node::default().join("root").join("subcommand").join("action")
+/// let node = node!("root.subcommand.action");
+/// ```
+pub fn node(input: TokenStream) -> TokenStream {
+ // Parse the input as a string literal
+ let input_parsed = syn::parse_macro_input!(input as NodeInput);
+ let path_str = input_parsed.path.value();
+
+ // Split the path by dots
+ let parts: Vec<String> = path_str
+ .split('.')
+ .map(|s| kebab_case!(s).to_string())
+ .collect();
+
+ // Build the expression starting from Node::default()
+ let mut expr: TokenStream2 = quote! {
+ mingling::Node::default()
+ };
+
+ // Add .join() calls for each part of the path
+ for part in parts {
+ expr = quote! {
+ #expr.join(#part)
+ };
+ }
+
+ expr.into()
+}
diff --git a/mingling_macros/src/render.rs b/mingling_macros/src/render.rs
new file mode 100644
index 0000000..8b75f34
--- /dev/null
+++ b/mingling_macros/src/render.rs
@@ -0,0 +1,87 @@
+//! Render Macros Module
+//!
+//! This module provides procedural macros for rendering operations.
+//! These macros expect a mutable reference to a `RenderResult` named `r` to be in scope.
+
+use proc_macro::TokenStream;
+use quote::quote;
+use syn::parse::Parser;
+use syn::{Expr, Token};
+
+/// Implementation of the `r_print!` procedural macro
+///
+/// This macro expands to a call to `RenderResult::print` with formatted arguments.
+/// It expects a mutable reference to a `RenderResult` named `r` to be in scope.
+///
+/// # Examples
+///
+/// ```ignore
+/// use mingling_macros::r_print;
+///
+/// let mut r = RenderResult::default();
+/// r_print!("Hello, {}!", "world");
+/// ```
+pub fn r_print(input: TokenStream) -> TokenStream {
+ // Parse the input as format arguments
+ let parser = syn::punctuated::Punctuated::<Expr, Token![,]>::parse_terminated;
+ let format_args = match parser.parse(input) {
+ Ok(args) => args,
+ Err(e) => return e.to_compile_error().into(),
+ };
+
+ // Build the format macro call
+ let format_call = if format_args.is_empty() {
+ quote! { ::std::format!("") }
+ } else {
+ let args_iter = format_args.iter();
+ quote! { ::std::format!(#(#args_iter),*) }
+ };
+
+ let expanded = quote! {
+ {
+ let formatted = #format_call;
+ ::mingling::RenderResult::print(r, &formatted)
+ }
+ };
+
+ expanded.into()
+}
+
+/// Implementation of the `r_println!` procedural macro
+///
+/// This macro expands to a call to `RenderResult::println` with formatted arguments.
+/// It expects a mutable reference to a `RenderResult` named `r` to be in scope.
+///
+/// # Examples
+///
+/// ```ignore
+/// use mingling_macros::r_println;
+///
+/// let mut r = RenderResult::default();
+/// r_println!("Hello, {}!", "world");
+/// ```
+pub fn r_println(input: TokenStream) -> TokenStream {
+ // Parse the input as format arguments
+ let parser = syn::punctuated::Punctuated::<Expr, Token![,]>::parse_terminated;
+ let format_args = match parser.parse(input) {
+ Ok(args) => args,
+ Err(e) => return e.to_compile_error().into(),
+ };
+
+ // Build the format macro call
+ let format_call = if format_args.is_empty() {
+ quote! { ::std::format!("") }
+ } else {
+ let args_iter = format_args.iter();
+ quote! { ::std::format!(#(#args_iter),*) }
+ };
+
+ let expanded = quote! {
+ {
+ let formatted = #format_call;
+ ::mingling::RenderResult::println(r, &formatted)
+ }
+ };
+
+ expanded.into()
+}
diff --git a/mingling_macros/src/renderer.rs b/mingling_macros/src/renderer.rs
new file mode 100644
index 0000000..3fd01bd
--- /dev/null
+++ b/mingling_macros/src/renderer.rs
@@ -0,0 +1,248 @@
+//! Renderer Attribute Macro Implementation
+//!
+//! This module provides the `#[renderer]` attribute macro for automatically
+//! generating structs that implement the `Renderer` trait from functions.
+
+use proc_macro::TokenStream;
+use quote::quote;
+use syn::parse::{Parse, ParseStream};
+use syn::spanned::Spanned;
+use syn::{
+ FnArg, Ident, ItemFn, Pat, PatType, ReturnType, Signature, Type, TypePath, parse_macro_input,
+};
+
+/// Parses the renderer attribute arguments
+struct RendererAttribute {
+ struct_name: Ident,
+}
+
+impl Parse for RendererAttribute {
+ fn parse(input: ParseStream) -> syn::Result<Self> {
+ let struct_name = input.parse()?;
+ Ok(RendererAttribute { struct_name })
+ }
+}
+
+/// Extracts the previous type and parameter name from function arguments
+fn extract_previous_info(sig: &Signature) -> syn::Result<(Pat, TypePath)> {
+ // The function should have exactly two parameters
+ if sig.inputs.len() != 2 {
+ return Err(syn::Error::new(
+ sig.inputs.span(),
+ "Renderer function must have exactly two parameters",
+ ));
+ }
+
+ // First parameter is the previous type
+ let arg = &sig.inputs[0];
+ match arg {
+ FnArg::Typed(PatType { pat, ty, .. }) => {
+ // Extract the pattern (parameter name)
+ let param_pat = (**pat).clone();
+
+ // Extract the type
+ match &**ty {
+ Type::Path(type_path) => Ok((param_pat, type_path.clone())),
+ _ => Err(syn::Error::new(
+ ty.span(),
+ "First parameter type must be a type path",
+ )),
+ }
+ }
+ FnArg::Receiver(_) => Err(syn::Error::new(
+ arg.span(),
+ "Renderer function cannot have self parameter",
+ )),
+ }
+}
+
+/// Validates that the second parameter is r: &mut RenderResult
+fn validate_render_result_param(sig: &Signature) -> syn::Result<()> {
+ // Second parameter should be &mut RenderResult
+ let arg = &sig.inputs[1];
+
+ match arg {
+ FnArg::Typed(PatType { pat, ty, .. }) => {
+ // Check parameter name is "r"
+ let param_name = match &**pat {
+ Pat::Ident(pat_ident) => pat_ident.ident.to_string(),
+ _ => {
+ return Err(syn::Error::new(
+ pat.span(),
+ "Second parameter must be named 'r'",
+ ));
+ }
+ };
+
+ if param_name != "r" {
+ return Err(syn::Error::new(
+ pat.span(),
+ "Second parameter must be named 'r'",
+ ));
+ }
+
+ // Check type is &mut RenderResult
+ match &**ty {
+ Type::Reference(type_ref) => {
+ // Check mutability
+ if !type_ref.mutability.is_some() {
+ return Err(syn::Error::new(
+ ty.span(),
+ "Second parameter must be mutable reference: &mut RenderResult",
+ ));
+ }
+
+ // Check inner type is RenderResult
+ match &*type_ref.elem {
+ Type::Path(type_path) => {
+ let type_name =
+ type_path.path.segments.last().unwrap().ident.to_string();
+ if type_name != "RenderResult" {
+ return Err(syn::Error::new(
+ ty.span(),
+ "Second parameter must be &mut RenderResult",
+ ));
+ }
+ }
+ _ => {
+ return Err(syn::Error::new(
+ ty.span(),
+ "Second parameter must be &mut RenderResult",
+ ));
+ }
+ }
+ }
+ _ => {
+ return Err(syn::Error::new(
+ ty.span(),
+ "Second parameter must be &mut RenderResult",
+ ));
+ }
+ }
+ }
+ FnArg::Receiver(_) => {
+ return Err(syn::Error::new(
+ arg.span(),
+ "Renderer function cannot have self parameter",
+ ));
+ }
+ }
+
+ Ok(())
+}
+
+/// Extracts the return type from the function signature
+fn extract_return_type(sig: &Signature) -> syn::Result<()> {
+ // Renderer functions should return () or have no return type
+ match &sig.output {
+ ReturnType::Type(_, ty) => {
+ // Check if it's ()
+ match &**ty {
+ Type::Tuple(tuple) if tuple.elems.is_empty() => Ok(()),
+ _ => Err(syn::Error::new(
+ ty.span(),
+ "Renderer function must return () or have no return type",
+ )),
+ }
+ }
+ ReturnType::Default => Ok(()),
+ }
+}
+
+/// Implementation of the `#[renderer]` attribute macro
+///
+/// This macro transforms a function into a struct that implements
+/// the `Renderer` trait. The struct name is specified in the attribute.
+///
+/// # Examples
+///
+/// ```ignore
+/// use mingling_macros::renderer;
+///
+/// #[renderer(InitResultRenderer)]
+/// fn render(data: InitResult, r: &mut RenderResult) {
+/// let str: String = data.into();
+/// r_println!("{}", str);
+/// }
+/// ```
+///
+/// This generates:
+/// ```ignore
+/// pub struct InitResultRenderer;
+/// impl Renderer for InitResultRenderer {
+/// type Previous = InitResult;
+///
+/// fn render(data: Self::Previous, r: &mut RenderResult) {
+/// let str: String = data.into();
+/// r_println!("{}", str);
+/// }
+/// }
+/// ```
+pub fn renderer_attr(attr: TokenStream, item: TokenStream) -> TokenStream {
+ // Parse the attribute arguments
+ let renderer_attr = parse_macro_input!(attr as RendererAttribute);
+ let struct_name = renderer_attr.struct_name;
+
+ // Parse the function item
+ let input_fn = parse_macro_input!(item as ItemFn);
+
+ // Validate the function is not async
+ if input_fn.sig.asyncness.is_some() {
+ return syn::Error::new(input_fn.sig.span(), "Renderer function cannot be async")
+ .to_compile_error()
+ .into();
+ }
+
+ // Extract the previous type and parameter name from function arguments
+ let (prev_param, previous_type) = match extract_previous_info(&input_fn.sig) {
+ Ok(info) => info,
+ Err(e) => return e.to_compile_error().into(),
+ };
+
+ // Validate second parameter is r: &mut RenderResult
+ if let Err(e) = validate_render_result_param(&input_fn.sig) {
+ return e.to_compile_error().into();
+ }
+
+ // Validate return type
+ if let Err(e) = extract_return_type(&input_fn.sig) {
+ return e.to_compile_error().into();
+ }
+
+ // Get the function body
+ let fn_body = &input_fn.block;
+
+ // Get function attributes (excluding the renderer attribute)
+ let mut fn_attrs = input_fn.attrs.clone();
+ // Remove any #[renderer(...)] attributes to avoid infinite recursion
+ fn_attrs.retain(|attr| !attr.path().is_ident("renderer"));
+
+ // Get function visibility
+ let vis = &input_fn.vis;
+
+ // Get function name
+ let fn_name = &input_fn.sig.ident;
+
+ // Generate the struct and implementation
+ let expanded = quote! {
+ #(#fn_attrs)*
+ #vis struct #struct_name;
+
+ impl ::mingling::Renderer for #struct_name {
+ type Previous = #previous_type;
+
+ fn render(#prev_param: Self::Previous, r: &mut ::mingling::RenderResult) {
+ // Call the original function
+ #fn_name(#prev_param, r)
+ }
+ }
+
+ // Keep the original function for internal use
+ #(#fn_attrs)*
+ #vis fn #fn_name(#prev_param: #previous_type, r: &mut ::mingling::RenderResult) {
+ #fn_body
+ }
+ };
+
+ expanded.into()
+}