aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--CHANGELOG.md45
-rw-r--r--GETTING_STARTED.md2
-rw-r--r--docs/_zh_CN/pages/13-hook.md2
-rw-r--r--docs/pages/13-hook.md2
-rw-r--r--examples/example-hook/src/main.rs2
-rw-r--r--mingling/src/example_docs.rs2
-rw-r--r--mingling_cli/about_mling_lint.md35
-rw-r--r--mingling_cli/expand.rs1121
-rw-r--r--mingling_cli/src/linter.rs54
-rw-r--r--mingling_cli/src/linter/mlint_report.rs12
-rw-r--r--mingling_cli/src/lints/non_mingling_naming_style.rs5
-rw-r--r--mingling_cli/src/lints/template_linter.rs2
-rw-r--r--mingling_cli/src/lints/unnecessary_render_result_creation.rs221
-rw-r--r--mingling_core/src/any.rs122
-rw-r--r--mingling_core/src/any/group.rs12
-rw-r--r--mingling_core/src/program/collection/mock.rs7
-rw-r--r--mingling_core/src/program/hook.rs12
-rw-r--r--mingling_macros/src/derive/grouped.rs12
-rw-r--r--mingling_macros/src/func/gen_program.rs22
-rw-r--r--mingling_macros/src/func/group.rs6
-rw-r--r--mingling_macros/src/func/pack.rs6
-rw-r--r--mingling_macros/src/systems/structural_data.rs12
22 files changed, 511 insertions, 1205 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5ed528c..86584cc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -52,6 +52,16 @@ None
### Release 0.3.0 (Unreleased)
+> In detail, the changes in Mingling 0.3.0 are as follows:
+
+1. **Added `arg-picker`** — Mingling has never had a comfortable argument parsing solution. You either suffered with `parser` or went all-in on `clap`. So I wrote a smarter `arg-picker`. The API style is close to the original `parser`, but it's more type-safe, more robust, and more extensible. See the main text for details.
+
+2. **Made implicit behavior explicit**. For a long time, Mingling's attribute macros have been making **implicit** modifications to the original function — I have to admit, that's dirty. In the new version, I've removed **all** implicit modifications to the original function by attribute macros. In other words, `#[chain]`, `#[renderer]`, `#[help]`, and `#[completion]` will no longer modify your original function in any way unless you explicitly specify it. Use the Extension Attribute (`#[chain(/* ... */)]`) mechanism to explicitly inject implicit behavior into your functions.
+
+3. I was originally planning to remove `r_println!` because I couldn't stand that `__renderer_inner_result` thing implicitly injected by the `#[renderer]` macro. But now I've rewritten it: `#[buffer]` injects an implicit `__render_result_buffer` value into the function, and then `r_println!` calls it. It's an extra step, but it also means: the dirt is your choice, not something I'm forcing on you :)
+
+4. **Finally**, a philosophical point. Mingling will move forward with a preference for **"selectively dirty"** over **"invisibly, forcibly dirty"** — this is the biggest direction going forward, building a more comfortable API on this foundation.
+
#### Fixes:
1. **[`pathf:patterns`]** Fixed pattern detection logic in `mingling_pathf` for multiple patterns to correctly detect opening bracket forms (e.g., `[chain`, `[renderer`, `[help`, `[completion`) in addition to the previously supported closing bracket forms (e.g., `chain]`, `renderer]`, `help]`, `completion]`). This ensures that attribute macro usages like `#[chain]`, `#[renderer]`, `#[help]`, and `#[completion]` are properly detected regardless of which side of the attribute the pattern matcher examines.
@@ -556,6 +566,41 @@ None
All examples and internal usages have been updated across the codebase to reflect these changes (e.g., `repl_basic_setup` now calls `println!("{}", r.result)` instead of `println!("{}", r.result.trim())`, since `Display` no longer adds a trailing newline).
+7. **[`any`]** **[`macros`]** Made `AnyOutput`'s `type_id` and `member_id` fields private (`pub(crate)`) and added public accessor methods `type_id()` and `member_id()`. Added the `unsafe fn new_bare<T>(value: T, member_id: G) -> Self` constructor that bypasses the `Grouped` trait, allowing manual specification of `member_id` without requiring the concrete type to implement `Grouped`.
+
+ - **`type_id`** field changed from `pub` to `pub(crate)` — accessible via `type_id()` accessor.
+ - **`member_id`** field changed from `pub` to `pub(crate)` — accessible via `member_id()` accessor (requires `G: Copy`).
+ - **`new_bare`** — Unsafe constructor that takes a raw `member_id` value without invoking `Grouped::member_id()`. The caller must ensure the provided `member_id` correctly corresponds to the concrete type `T`.
+ - Updated all internal `match any.member_id { ... }` patterns in `gen_program.rs` to use `match any.member_id() { ... }` instead.
+ - Updated the panic message in `do_chain` (both sync and async) from `any.type_id` to `any.type_id()`.
+ - Updated the example-hook `main.rs` to call `info.output.member_id()` instead of accessing `info.output.member_id` directly.
+ - Added `Copy` derive to the generated enum to enable `member_id()`'s `Copy` requirement on the enum type.
+
+ _No behavioral changes for existing code — the accessor methods provide the same values as the previously-public fields._
+
+8. **[`any`]** **[`macros`]** **[BREAKING]** Marked `Grouped` trait as `unsafe trait`. The `Grouped` trait has always been inherently unsafe — the `member_id()` return value must exactly correspond to the variant registered by `register_type!` for the concrete type, otherwise dispatching on that type will result in **undefined behavior**. This unsoundness has existed since the trait's inception but was previously unenforced at the type system level.
+
+ By making `Grouped` an `unsafe trait`, implementors must now explicitly acknowledge this safety contract with `unsafe impl Grouped<...> for ...`. This change makes the existing safety invariant visible to developers and enables soundness warnings at compile time.
+
+ **Changes made:**
+
+ - **`Grouped` trait** in `mingling_core/src/any/group.rs` changed from `pub trait Grouped<Group>` to `pub unsafe trait Grouped<Group>`, with a safety doc comment explaining that manually implementing the trait with an incorrect `member_id` leads to undefined behavior.
+
+ - **Derive macros** (`#[derive(Grouped)]`, `#[derive(GroupedSerialize)]`) now generate `unsafe impl` instead of `impl`, with a SAFETY comment stating that the derive macro guarantees correctness because the `Ident` used in `register_type!` matches the `Ident` returned by `member_id()`.
+
+ - **`pack!`, `pack_structural!`, `group!`, `group_structural!`** macros now generate `unsafe impl` instead of `impl`, with analogous SAFETY comments.
+
+ - **All manual test implementations** of `Grouped` across the codebase (in `any.rs` tests, `hook.rs` tests, `mock.rs`) updated to `unsafe impl` with SAFETY comments explaining why they are safe in their test contexts.
+
+ - **`MockProgramCollect::member_id()`** changed from `MockProgramCollect::Foo` to `panic!("Attempting to read an unsafe enum type")` to prevent accidental execution in production paths.
+
+ **Migration guide:**
+
+ - Existing code that uses `Grouped` only through the derive macro or `pack!`/`group!` macros is automatically migrated — no changes needed.
+ - Code with **manual** `impl Grouped<...> for ...` blocks must add `unsafe` before `impl` and verify that the `member_id()` return value correctly corresponds to the type's registered variant. Only proceed if the correspondence is guaranteed.
+
+ _This is a breaking change only for code with manual `Grouped` implementations._
+
---
## Release 0.2.2 (2026-07-10)
diff --git a/GETTING_STARTED.md b/GETTING_STARTED.md
index 1aad8d5..621471e 100644
--- a/GETTING_STARTED.md
+++ b/GETTING_STARTED.md
@@ -551,7 +551,7 @@ fn main() {
.on_pre_chain(|info| {
println!("[DEBUG] Pre chain: {}", info.input);
})
- .on_post_chain(|info| println!("[DEBUG] Post chain: {}", info.output.member_id))
+ .on_post_chain(|info| println!("[DEBUG] Post chain: {}", info.output.member_id()))
.on_finish(|_| {
println!("[DEBUG] Loop end");
ProgramControlUnit::OverrideExitCode(0) // Override exit code
diff --git a/docs/_zh_CN/pages/13-hook.md b/docs/_zh_CN/pages/13-hook.md
index 6d6018a..ad3008a 100644
--- a/docs/_zh_CN/pages/13-hook.md
+++ b/docs/_zh_CN/pages/13-hook.md
@@ -71,7 +71,7 @@ fn main() {
eprintln!("[hook] executing chain for: {}", info.input);
})
.on_post_chain(|info| {
- eprintln!("[hook] chain output: {}", info.output.member_id);
+ eprintln!("[hook] chain output: {}", info.output.member_id());
}),
);
diff --git a/docs/pages/13-hook.md b/docs/pages/13-hook.md
index 26f8712..d927a9c 100644
--- a/docs/pages/13-hook.md
+++ b/docs/pages/13-hook.md
@@ -71,7 +71,7 @@ fn main() {
eprintln!("[hook] executing chain for: {}", info.input);
})
.on_post_chain(|info| {
- eprintln!("[hook] chain output: {}", info.output.member_id);
+ eprintln!("[hook] chain output: {}", info.output.member_id());
}),
);
diff --git a/examples/example-hook/src/main.rs b/examples/example-hook/src/main.rs
index 23b87c7..da92045 100644
--- a/examples/example-hook/src/main.rs
+++ b/examples/example-hook/src/main.rs
@@ -40,7 +40,7 @@ fn main() {
.on_pre_chain(|info| {
println!("[DEBUG] Pre chain: {}", info.input);
})
- .on_post_chain(|info| println!("[DEBUG] Post chain: {}", info.output.member_id))
+ .on_post_chain(|info| println!("[DEBUG] Post chain: {}", info.output.member_id()))
.on_finish(|_| {
println!("[DEBUG] Loop end");
ProgramControlUnit::OverrideExitCode(0) // Override exit code
diff --git a/mingling/src/example_docs.rs b/mingling/src/example_docs.rs
index 3b36f00..89d5af1 100644
--- a/mingling/src/example_docs.rs
+++ b/mingling/src/example_docs.rs
@@ -1649,7 +1649,7 @@ pub mod example_help {}
/// .on_pre_chain(|info| {
/// println!("[DEBUG] Pre chain: {}", info.input);
/// })
-/// .on_post_chain(|info| println!("[DEBUG] Post chain: {}", info.output.member_id))
+/// .on_post_chain(|info| println!("[DEBUG] Post chain: {}", info.output.member_id()))
/// .on_finish(|_| {
/// println!("[DEBUG] Loop end");
/// ProgramControlUnit::OverrideExitCode(0) // Override exit code
diff --git a/mingling_cli/about_mling_lint.md b/mingling_cli/about_mling_lint.md
deleted file mode 100644
index 87fedc8..0000000
--- a/mingling_cli/about_mling_lint.md
+++ /dev/null
@@ -1,35 +0,0 @@
-# 关于 Mingling Linter 设计
-
-Mingling Linter 是独立于 `clippy` 和 `check` 之外的检查器,用于检查 Mingling 项目的代码质量
-
-## 关于 Linter 定义
-
-已完成!所有的定义都被输出到 registry.json 中,可以读取
-
-## 忽略规则
-
-Linter 在检查时,会检查开头的 mlint 标识,用局部读写直到没有#![.*]这样的结构为止,判断当前文件需要参与的 Linter
-
-默认来讲,一个文件所有默认为 deny、warn 的 linter 都会参与,直到被显式 allow 覆盖。
-
-```rust
-#![mlint(allow(linter))]
-#![mlint(warn(linter))]
-#![mlint(deny(linter))]
-```
-
-## 检查阶段
-
-1. 为每个包的内部 rs 文件(必须被包含)检查,并按照忽略规则,计算每个文件需要哪些 linter 检查(仅 file 级别的)
-2. 使用 tokio 并行检查
-3. 同时,在检查过程中,计算更细粒度的哪些 Linter 需要在哪些行(或 AST 层级,待定)检查,检查的程度是什么 (warn还是deny)
-4. 使用 tokio 并行检查 所有 细粒度的 Linter
-5. 输出检查结果
-
-## 性能
-
-请使用 tokio 并行化执行 linter,但是结果放在缓冲区,计算完成后按照文件层级(主:文件深度,次:名字 a-Z,辅:名字 0-9)排序,后输出
-
-## 关于架构层面
-
-第一版可以直接使用 tokio 并行化,这不会很难
diff --git a/mingling_cli/expand.rs b/mingling_cli/expand.rs
deleted file mode 100644
index 2e8bc4f..0000000
--- a/mingling_cli/expand.rs
+++ /dev/null
@@ -1,1121 +0,0 @@
-#![feature(prelude_import)]
-extern crate std;
-#[prelude_import]
-use std::prelude::rust_2024::*;
-use crate::{linter::MinglingLinterSetup, metadata::MinglingMetadataSetup};
-use mingling::{
- macros::gen_program,
- setup::{ExitCodeSetup, picker::{HelpFlagSetup, StructuralRendererSetup}},
-};
-pub mod errors {
- pub mod serde_json {
- use mingling::macros::{buffer, group, r_println, renderer};
- pub type ErrorSerdeJson = serde_json::Error;
- #[allow(non_camel_case_types)]
- mod internal_group_serde_json_error {
- use crate::ThisProgram as __MinglingProgram;
- #[allow(unused_imports)]
- use serde_json::Error;
- use super::ErrorSerdeJson;
- impl ::mingling::Grouped<__MinglingProgram> for ErrorSerdeJson {
- fn member_id() -> __MinglingProgram {
- __MinglingProgram::ErrorSerdeJson
- }
- }
- }
- #[doc(hidden)]
- #[allow(non_camel_case_types)]
- pub struct __internal_renderer_render_error_serde_json;
- impl ::mingling::Renderer for __internal_renderer_render_error_serde_json {
- type Previous = ErrorSerdeJson;
- fn render(prev: Self::Previous) -> ::mingling::RenderResult {
- let __renderer_result = { render_error_serde_json(prev) };
- ::std::convert::Into::into(__renderer_result)
- }
- }
- pub fn render_error_serde_json(
- _err: ErrorSerdeJson,
- ) -> ::mingling::RenderResult {
- let mut __render_result_buffer = ::mingling::RenderResult::new();
- {
- __render_result_buffer
- .println(
- ::alloc::__export::must_use({
- ::alloc::fmt::format(format_args!("serde"))
- }),
- );
- }
- __render_result_buffer
- }
- }
-}
-pub mod linter {
- use mingling::{Program, macros::program_setup};
- use crate::linter::cmd_mlint::CMDMinglingLinter;
- pub mod cmd_mlint {
- use mingling::macros::{chain, dispatcher};
- pub struct CMDMinglingLinter;
- #[automatically_derived]
- impl ::core::fmt::Debug for CMDMinglingLinter {
- #[inline]
- fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
- ::core::fmt::Formatter::write_str(f, "CMDMinglingLinter")
- }
- }
- #[automatically_derived]
- impl ::core::default::Default for CMDMinglingLinter {
- #[inline]
- fn default() -> CMDMinglingLinter {
- CMDMinglingLinter {}
- }
- }
- pub struct EntryMinglingLinter {
- pub(crate) inner: Vec<String>,
- }
- impl EntryMinglingLinter {
- /// Creates a new instance of the wrapper type
- pub fn new(inner: Vec<String>) -> Self {
- Self { inner }
- }
- }
- impl From<Vec<String>> for EntryMinglingLinter {
- fn from(inner: Vec<String>) -> Self {
- Self::new(inner)
- }
- }
- impl From<EntryMinglingLinter> for Vec<String> {
- fn from(wrapper: EntryMinglingLinter) -> Vec<String> {
- wrapper.inner
- }
- }
- impl ::std::convert::AsRef<Vec<String>> for EntryMinglingLinter {
- fn as_ref(&self) -> &Vec<String> {
- &self.inner
- }
- }
- impl ::std::convert::AsMut<Vec<String>> for EntryMinglingLinter {
- fn as_mut(&mut self) -> &mut Vec<String> {
- &mut self.inner
- }
- }
- impl ::std::ops::Deref for EntryMinglingLinter {
- type Target = Vec<String>;
- fn deref(&self) -> &Self::Target {
- &self.inner
- }
- }
- impl ::std::ops::DerefMut for EntryMinglingLinter {
- fn deref_mut(&mut self) -> &mut Self::Target {
- &mut self.inner
- }
- }
- impl ::std::default::Default for EntryMinglingLinter
- where
- Vec<String>: ::std::default::Default,
- {
- fn default() -> Self {
- Self::new(::std::default::Default::default())
- }
- }
- impl Into<mingling::AnyOutput<crate::ThisProgram>> for EntryMinglingLinter {
- fn into(self) -> mingling::AnyOutput<crate::ThisProgram> {
- mingling::AnyOutput::new(self)
- }
- }
- impl Into<mingling::ChainProcess<crate::ThisProgram>> for EntryMinglingLinter {
- fn into(self) -> mingling::ChainProcess<crate::ThisProgram> {
- mingling::AnyOutput::new(self).route_chain()
- }
- }
- impl ::mingling::Grouped<crate::ThisProgram> for EntryMinglingLinter {
- fn member_id() -> crate::ThisProgram {
- crate::ThisProgram::EntryMinglingLinter
- }
- }
- impl ::mingling::Dispatcher<crate::ThisProgram> for CMDMinglingLinter {
- fn node(&self) -> ::mingling::Node {
- mingling::Node::default().join("mlint")
- }
- fn begin(
- &self,
- args: Vec<String>,
- ) -> ::mingling::ChainProcess<crate::ThisProgram> {
- use ::mingling::Grouped;
- ::mingling::Routable::to_chain(EntryMinglingLinter::new(args))
- }
- fn clone_dispatcher(
- &self,
- ) -> Box<dyn ::mingling::Dispatcher<crate::ThisProgram>> {
- Box::new(CMDMinglingLinter)
- }
- }
- #[doc(hidden)]
- #[allow(non_camel_case_types)]
- pub struct __internal_chain_handle_mlint;
- impl ::mingling::Chain<crate::ThisProgram> for __internal_chain_handle_mlint {
- type Previous = EntryMinglingLinter;
- fn proc(
- prev: EntryMinglingLinter,
- ) -> ::mingling::ChainProcess<crate::ThisProgram> {
- handle_mlint(prev);
- <crate::ResultEmpty as ::mingling::Routable<
- crate::ThisProgram,
- >>::to_chain(crate::ResultEmpty)
- }
- }
- pub fn handle_mlint(_args: EntryMinglingLinter) {}
- }
- #[doc(hidden)]
- pub struct MinglingLinterSetup;
- impl ::mingling::setup::ProgramSetup<crate::ThisProgram> for MinglingLinterSetup {
- fn setup(self, program: &mut ::mingling::Program<crate::ThisProgram>) {
- mingling_linter_setup(program);
- }
- }
- pub fn mingling_linter_setup(program: &mut Program<crate::ThisProgram>) {
- {
- program.with_setup(MinglingLinterCommandSetup);
- }
- }
- #[doc(hidden)]
- pub struct MinglingLinterCommandSetup;
- impl ::mingling::setup::ProgramSetup<crate::ThisProgram>
- for MinglingLinterCommandSetup {
- fn setup(self, program: &mut ::mingling::Program<crate::ThisProgram>) {
- mingling_linter_command_setup(program);
- }
- }
- pub fn mingling_linter_command_setup(program: &mut Program<crate::ThisProgram>) {
- {
- program.with_dispatcher(CMDMinglingLinter);
- }
- }
-}
-pub mod metadata {
- use cargo_metadata::Metadata;
- use mingling::{
- AnyOutput, Program, ProgramCollect, RenderResult,
- macros::{buffer, group_structural, program_setup, r_println, renderer, routeify},
- };
- use crate::metadata::{cmd_metadata::CMDMetadata, setup::CargoMetadataSetup};
- pub mod cmd_metadata {
- use cargo_metadata::Metadata;
- use mingling::{LazyRes, macros::{chain, dispatcher, pack_structural}};
- use crate::metadata::setup::ResMetadata;
- pub struct CMDMetadata;
- #[automatically_derived]
- impl ::core::fmt::Debug for CMDMetadata {
- #[inline]
- fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
- ::core::fmt::Formatter::write_str(f, "CMDMetadata")
- }
- }
- #[automatically_derived]
- impl ::core::default::Default for CMDMetadata {
- #[inline]
- fn default() -> CMDMetadata {
- CMDMetadata {}
- }
- }
- pub struct EntryMetadata {
- pub(crate) inner: Vec<String>,
- }
- impl EntryMetadata {
- /// Creates a new instance of the wrapper type
- pub fn new(inner: Vec<String>) -> Self {
- Self { inner }
- }
- }
- impl From<Vec<String>> for EntryMetadata {
- fn from(inner: Vec<String>) -> Self {
- Self::new(inner)
- }
- }
- impl From<EntryMetadata> for Vec<String> {
- fn from(wrapper: EntryMetadata) -> Vec<String> {
- wrapper.inner
- }
- }
- impl ::std::convert::AsRef<Vec<String>> for EntryMetadata {
- fn as_ref(&self) -> &Vec<String> {
- &self.inner
- }
- }
- impl ::std::convert::AsMut<Vec<String>> for EntryMetadata {
- fn as_mut(&mut self) -> &mut Vec<String> {
- &mut self.inner
- }
- }
- impl ::std::ops::Deref for EntryMetadata {
- type Target = Vec<String>;
- fn deref(&self) -> &Self::Target {
- &self.inner
- }
- }
- impl ::std::ops::DerefMut for EntryMetadata {
- fn deref_mut(&mut self) -> &mut Self::Target {
- &mut self.inner
- }
- }
- impl ::std::default::Default for EntryMetadata
- where
- Vec<String>: ::std::default::Default,
- {
- fn default() -> Self {
- Self::new(::std::default::Default::default())
- }
- }
- impl Into<mingling::AnyOutput<crate::ThisProgram>> for EntryMetadata {
- fn into(self) -> mingling::AnyOutput<crate::ThisProgram> {
- mingling::AnyOutput::new(self)
- }
- }
- impl Into<mingling::ChainProcess<crate::ThisProgram>> for EntryMetadata {
- fn into(self) -> mingling::ChainProcess<crate::ThisProgram> {
- mingling::AnyOutput::new(self).route_chain()
- }
- }
- impl ::mingling::Grouped<crate::ThisProgram> for EntryMetadata {
- fn member_id() -> crate::ThisProgram {
- crate::ThisProgram::EntryMetadata
- }
- }
- impl ::mingling::Dispatcher<crate::ThisProgram> for CMDMetadata {
- fn node(&self) -> ::mingling::Node {
- mingling::Node::default().join("metadata")
- }
- fn begin(
- &self,
- args: Vec<String>,
- ) -> ::mingling::ChainProcess<crate::ThisProgram> {
- use ::mingling::Grouped;
- ::mingling::Routable::to_chain(EntryMetadata::new(args))
- }
- fn clone_dispatcher(
- &self,
- ) -> Box<dyn ::mingling::Dispatcher<crate::ThisProgram>> {
- Box::new(CMDMetadata)
- }
- }
- pub struct ResultMetadata {
- pub inner: ResMetadata,
- }
- #[doc(hidden)]
- #[allow(
- non_upper_case_globals,
- unused_attributes,
- unused_qualifications,
- clippy::absolute_paths,
- )]
- const _: () = {
- #[allow(unused_extern_crates, clippy::useless_attribute)]
- extern crate serde as _serde;
- #[automatically_derived]
- impl _serde::Serialize for ResultMetadata {
- fn serialize<__S>(
- &self,
- __serializer: __S,
- ) -> _serde::__private229::Result<__S::Ok, __S::Error>
- where
- __S: _serde::Serializer,
- {
- let mut __serde_state = _serde::Serializer::serialize_struct(
- __serializer,
- "ResultMetadata",
- false as usize + 1,
- )?;
- _serde::ser::SerializeStruct::serialize_field(
- &mut __serde_state,
- "inner",
- &self.inner,
- )?;
- _serde::ser::SerializeStruct::end(__serde_state)
- }
- }
- };
- impl ResultMetadata {
- pub fn new(inner: ResMetadata) -> Self {
- Self { inner }
- }
- }
- impl From<ResMetadata> for ResultMetadata {
- fn from(inner: ResMetadata) -> Self {
- Self::new(inner)
- }
- }
- impl From<ResultMetadata> for ResMetadata {
- fn from(wrapper: ResultMetadata) -> ResMetadata {
- wrapper.inner
- }
- }
- impl ::std::convert::AsRef<ResMetadata> for ResultMetadata {
- fn as_ref(&self) -> &ResMetadata {
- &self.inner
- }
- }
- impl ::std::convert::AsMut<ResMetadata> for ResultMetadata {
- fn as_mut(&mut self) -> &mut ResMetadata {
- &mut self.inner
- }
- }
- impl ::std::ops::Deref for ResultMetadata {
- type Target = ResMetadata;
- fn deref(&self) -> &Self::Target {
- &self.inner
- }
- }
- impl ::std::ops::DerefMut for ResultMetadata {
- fn deref_mut(&mut self) -> &mut Self::Target {
- &mut self.inner
- }
- }
- impl ::std::default::Default for ResultMetadata
- where
- ResMetadata: ::std::default::Default,
- {
- fn default() -> Self {
- Self::new(::std::default::Default::default())
- }
- }
- impl ::mingling::__private::StructuralDataSealed<crate::ThisProgram>
- for ResultMetadata {}
- impl ::mingling::__private::StructuralData<crate::ThisProgram>
- for ResultMetadata {}
- impl Into<::mingling::AnyOutput<crate::ThisProgram>> for ResultMetadata {
- fn into(self) -> ::mingling::AnyOutput<crate::ThisProgram> {
- ::mingling::AnyOutput::new(self)
- }
- }
- impl Into<::mingling::ChainProcess<crate::ThisProgram>> for ResultMetadata {
- fn into(self) -> ::mingling::ChainProcess<crate::ThisProgram> {
- ::mingling::AnyOutput::new(self).route_chain()
- }
- }
- impl ::mingling::Grouped<crate::ThisProgram> for ResultMetadata {
- fn member_id() -> crate::ThisProgram {
- crate::ThisProgram::ResultMetadata
- }
- }
- #[doc(hidden)]
- #[allow(non_camel_case_types)]
- pub struct __internal_chain_handle_metadata;
- impl ::mingling::Chain<crate::ThisProgram> for __internal_chain_handle_metadata {
- type Previous = EntryMetadata;
- fn proc(
- prev: EntryMetadata,
- ) -> ::mingling::ChainProcess<crate::ThisProgram> {
- let __chain_result = {
- ::mingling::this::<crate::ThisProgram>()
- .__modify_res_and_return_route(|
- metadata: &mut LazyRes<ResMetadata>|
- {
- ::mingling::Routable::<
- crate::ThisProgram,
- >::to_chain(handle_metadata(prev, metadata))
- })
- };
- ::mingling::Routable::<crate::ThisProgram>::to_chain(__chain_result)
- }
- }
- pub fn handle_metadata(
- _: EntryMetadata,
- metadata: &mut LazyRes<ResMetadata>,
- ) -> Metadata {
- let metadata = metadata.get_ref().clone();
- metadata.data().clone()
- }
- }
- pub mod setup {
- use std::{env::current_dir, path::PathBuf};
- use cargo_metadata::{CargoOpt, MetadataCommand};
- use mingling::{
- LazyInit, Program, consts::REMAINS, macros::program_setup,
- picker::{IntoPicker, value::Flag},
- prelude::*, res::ResCurrentDir,
- };
- /// Name of Cargo manifest file
- pub const CARGO_TOML: &str = "Cargo.toml";
- use cargo_metadata::Metadata;
- use serde::Serialize;
- pub struct ResMetadata {
- data: Option<Metadata>,
- }
- #[automatically_derived]
- impl ::core::default::Default for ResMetadata {
- #[inline]
- fn default() -> ResMetadata {
- ResMetadata {
- data: ::core::default::Default::default(),
- }
- }
- }
- #[automatically_derived]
- impl ::core::clone::Clone for ResMetadata {
- #[inline]
- fn clone(&self) -> ResMetadata {
- ResMetadata {
- data: ::core::clone::Clone::clone(&self.data),
- }
- }
- }
- #[doc(hidden)]
- #[allow(
- non_upper_case_globals,
- unused_attributes,
- unused_qualifications,
- clippy::absolute_paths,
- )]
- const _: () = {
- #[allow(unused_extern_crates, clippy::useless_attribute)]
- extern crate serde as _serde;
- #[automatically_derived]
- impl _serde::Serialize for ResMetadata {
- fn serialize<__S>(
- &self,
- __serializer: __S,
- ) -> _serde::__private229::Result<__S::Ok, __S::Error>
- where
- __S: _serde::Serializer,
- {
- let mut __serde_state = _serde::Serializer::serialize_struct(
- __serializer,
- "ResMetadata",
- false as usize + 1,
- )?;
- _serde::ser::SerializeStruct::serialize_field(
- &mut __serde_state,
- "data",
- &self.data,
- )?;
- _serde::ser::SerializeStruct::end(__serde_state)
- }
- }
- };
- impl ResMetadata {
- /// Returns a reference to the parsed `cargo metadata`.
- ///
- /// # Panics
- ///
- /// This function does **not** panic in practice, because `ResMetadata` is
- /// always initialized via [`LazyInit`] inside the program setup, and the
- /// initialization either succeeds (setting `data` to `Some(...)`) or fails
- /// by propagating the error from `cmd.exec().unwrap()`. Therefore, by the
- /// time this getter is called, `self.data` is guaranteed to be `Some`.
- pub fn data(&self) -> &Metadata {
- self.data.as_ref().unwrap()
- }
- }
- #[doc(hidden)]
- pub struct CargoMetadataSetup;
- impl ::mingling::setup::ProgramSetup<crate::ThisProgram> for CargoMetadataSetup {
- fn setup(self, program: &mut ::mingling::Program<crate::ThisProgram>) {
- cargo_metadata_setup(program);
- }
- }
- pub fn cargo_metadata_setup(program: &mut Program<crate::ThisProgram>) {
- {
- let args = program.take_args();
- let (
- feature_args,
- manifest_path,
- message_format,
- enable_all_features,
- no_default_features,
- no_deps,
- args,
- ) = args
- .pick(
- &::mingling::picker::PickerArg::<Vec<String>> {
- full: &["features"],
- short: ::std::option::Option::None,
- positional: false,
- internal_type: ::std::marker::PhantomData,
- },
- )
- .pick(
- &::mingling::picker::PickerArg::<Option<String>> {
- full: &["manifest_path"],
- short: ::std::option::Option::None,
- positional: false,
- internal_type: ::std::marker::PhantomData,
- },
- )
- .pick_or(
- &::mingling::picker::PickerArg::<String> {
- full: &["message_format"],
- short: ::std::option::Option::None,
- positional: false,
- internal_type: ::std::marker::PhantomData,
- },
- || "disable".to_string(),
- )
- .pick(
- &::mingling::picker::PickerArg::<Flag> {
- full: &["all_features"],
- short: ::std::option::Option::None,
- positional: false,
- internal_type: ::std::marker::PhantomData,
- },
- )
- .pick(
- &::mingling::picker::PickerArg::<Flag> {
- full: &["no_default_features"],
- short: ::std::option::Option::None,
- positional: false,
- internal_type: ::std::marker::PhantomData,
- },
- )
- .pick(
- &::mingling::picker::PickerArg::<Flag> {
- full: &["no_deps"],
- short: ::std::option::Option::None,
- positional: false,
- internal_type: ::std::marker::PhantomData,
- },
- )
- .pick(&REMAINS)
- .unwrap();
- program.replace_args(args.into());
- program.structural_renderer_name = message_format.into();
- let current_dir = current_dir().unwrap();
- let feature_args_leaked: &[String] = Box::leak(
- feature_args.into_boxed_slice(),
- );
- let manifest_path_clone = manifest_path.clone();
- let current_dir_clone = current_dir.clone();
- program
- .with_resource(
- ResMetadata::lazy_init(move || {
- let metadata_path = match manifest_path_clone {
- Some(ref path_str) => PathBuf::from(path_str),
- None => find_manifest().unwrap(),
- };
- let mut cmd = MetadataCommand::new();
- cmd.manifest_path(metadata_path)
- .current_dir(&current_dir_clone);
- if *enable_all_features {
- cmd.features(CargoOpt::AllFeatures);
- }
- if *no_default_features {
- cmd.features(CargoOpt::NoDefaultFeatures);
- }
- if *no_deps {
- cmd.no_deps();
- }
- cmd.features(
- CargoOpt::SomeFeatures(feature_args_leaked.to_vec()),
- );
- ResMetadata {
- data: Some(cmd.exec().unwrap()),
- }
- }),
- );
- program.with_resource(ResCurrentDir::from(current_dir));
- }
- }
- /// Find `Cargo.toml` by searching upward from `current_dir`.
- fn find_manifest() -> Option<PathBuf> {
- let mut dir = current_dir().ok()?;
- loop {
- let candidate = dir.join(CARGO_TOML);
- if candidate.is_file() {
- return Some(candidate);
- }
- if !dir.pop() {
- return None;
- }
- }
- }
- }
- #[doc(hidden)]
- pub struct MinglingMetadataSetup;
- impl ::mingling::setup::ProgramSetup<crate::ThisProgram> for MinglingMetadataSetup {
- fn setup(self, program: &mut ::mingling::Program<crate::ThisProgram>) {
- mingling_metadata_setup(program);
- }
- }
- pub fn mingling_metadata_setup(program: &mut Program<crate::ThisProgram>) {
- {
- program.with_setup(CargoMetadataSetup);
- program.with_dispatcher(CMDMetadata);
- }
- }
- #[allow(non_camel_case_types)]
- mod internal_group_metadata {
- use crate::ThisProgram as __MinglingProgram;
- #[allow(unused_imports)]
- use super::Metadata;
- impl ::mingling::Grouped<__MinglingProgram> for Metadata {
- fn member_id() -> __MinglingProgram {
- __MinglingProgram::Metadata
- }
- }
- impl ::mingling::__private::StructuralDataSealed<crate::ThisProgram>
- for Metadata {}
- impl ::mingling::__private::StructuralData<crate::ThisProgram> for Metadata {}
- }
- #[doc(hidden)]
- #[allow(non_camel_case_types)]
- pub struct __internal_renderer_render_metadata;
- impl ::mingling::Renderer for __internal_renderer_render_metadata {
- type Previous = Metadata;
- fn render(prev: Self::Previous) -> ::mingling::RenderResult {
- let __renderer_result = { render_metadata(prev) };
- ::std::convert::Into::into(__renderer_result)
- }
- }
- pub fn render_metadata(metadata: Metadata) -> RenderResult {
- let mut r = RenderResult::new();
- r.println(
- ::alloc::__export::must_use({
- ::alloc::fmt::format(
- format_args!("{0}", serde_json::to_string(&metadata)?),
- )
- }),
- );
- r
- }
-}
-fn main() {
- let mut program = ThisProgram::new();
- program.with_setup(HelpFlagSetup::default());
- program.with_setup(ExitCodeSetup::default());
- program.with_setup(StructuralRendererSetup);
- program.with_setup(MinglingMetadataSetup);
- program.with_setup(MinglingLinterSetup);
- program.exec_and_exit();
-}
-/// Alias for the current program type `crate::ThisProgram`
-pub type Next = ::mingling::ChainProcess<crate::ThisProgram>;
-impl ::mingling::Routable<crate::ThisProgram>
-for ::mingling::ChainProcess<crate::ThisProgram> {
- fn to_chain(self) -> ::mingling::ChainProcess<crate::ThisProgram> {
- match self {
- ::mingling::ChainProcess::Ok((any, _)) => {
- ::mingling::ChainProcess::Ok((any, mingling::NextProcess::Chain))
- }
- other => other,
- }
- }
- fn to_render(self) -> ::mingling::ChainProcess<crate::ThisProgram> {
- match self {
- ::mingling::ChainProcess::Ok((any, _)) => {
- ::mingling::ChainProcess::Ok((any, mingling::NextProcess::Renderer))
- }
- other => other,
- }
- }
-}
-pub struct ErrorRendererNotFound {
- pub(crate) inner: String,
-}
-impl ErrorRendererNotFound {
- /// Creates a new instance of the wrapper type
- pub fn new(inner: String) -> Self {
- Self { inner }
- }
-}
-impl From<String> for ErrorRendererNotFound {
- fn from(inner: String) -> Self {
- Self::new(inner)
- }
-}
-impl From<ErrorRendererNotFound> for String {
- fn from(wrapper: ErrorRendererNotFound) -> String {
- wrapper.inner
- }
-}
-impl ::std::convert::AsRef<String> for ErrorRendererNotFound {
- fn as_ref(&self) -> &String {
- &self.inner
- }
-}
-impl ::std::convert::AsMut<String> for ErrorRendererNotFound {
- fn as_mut(&mut self) -> &mut String {
- &mut self.inner
- }
-}
-impl ::std::ops::Deref for ErrorRendererNotFound {
- type Target = String;
- fn deref(&self) -> &Self::Target {
- &self.inner
- }
-}
-impl ::std::ops::DerefMut for ErrorRendererNotFound {
- fn deref_mut(&mut self) -> &mut Self::Target {
- &mut self.inner
- }
-}
-impl ::std::default::Default for ErrorRendererNotFound
-where
- String: ::std::default::Default,
-{
- fn default() -> Self {
- Self::new(::std::default::Default::default())
- }
-}
-impl Into<mingling::AnyOutput<crate::ThisProgram>> for ErrorRendererNotFound {
- fn into(self) -> mingling::AnyOutput<crate::ThisProgram> {
- mingling::AnyOutput::new(self)
- }
-}
-impl Into<mingling::ChainProcess<crate::ThisProgram>> for ErrorRendererNotFound {
- fn into(self) -> mingling::ChainProcess<crate::ThisProgram> {
- mingling::AnyOutput::new(self).route_chain()
- }
-}
-impl ::mingling::Grouped<crate::ThisProgram> for ErrorRendererNotFound {
- fn member_id() -> crate::ThisProgram {
- crate::ThisProgram::ErrorRendererNotFound
- }
-}
-pub struct ErrorDispatcherNotFound {
- pub(crate) inner: Vec<String>,
-}
-impl ErrorDispatcherNotFound {
- /// Creates a new instance of the wrapper type
- pub fn new(inner: Vec<String>) -> Self {
- Self { inner }
- }
-}
-impl From<Vec<String>> for ErrorDispatcherNotFound {
- fn from(inner: Vec<String>) -> Self {
- Self::new(inner)
- }
-}
-impl From<ErrorDispatcherNotFound> for Vec<String> {
- fn from(wrapper: ErrorDispatcherNotFound) -> Vec<String> {
- wrapper.inner
- }
-}
-impl ::std::convert::AsRef<Vec<String>> for ErrorDispatcherNotFound {
- fn as_ref(&self) -> &Vec<String> {
- &self.inner
- }
-}
-impl ::std::convert::AsMut<Vec<String>> for ErrorDispatcherNotFound {
- fn as_mut(&mut self) -> &mut Vec<String> {
- &mut self.inner
- }
-}
-impl ::std::ops::Deref for ErrorDispatcherNotFound {
- type Target = Vec<String>;
- fn deref(&self) -> &Self::Target {
- &self.inner
- }
-}
-impl ::std::ops::DerefMut for ErrorDispatcherNotFound {
- fn deref_mut(&mut self) -> &mut Self::Target {
- &mut self.inner
- }
-}
-impl ::std::default::Default for ErrorDispatcherNotFound
-where
- Vec<String>: ::std::default::Default,
-{
- fn default() -> Self {
- Self::new(::std::default::Default::default())
- }
-}
-impl Into<mingling::AnyOutput<crate::ThisProgram>> for ErrorDispatcherNotFound {
- fn into(self) -> mingling::AnyOutput<crate::ThisProgram> {
- mingling::AnyOutput::new(self)
- }
-}
-impl Into<mingling::ChainProcess<crate::ThisProgram>> for ErrorDispatcherNotFound {
- fn into(self) -> mingling::ChainProcess<crate::ThisProgram> {
- mingling::AnyOutput::new(self).route_chain()
- }
-}
-impl ::mingling::Grouped<crate::ThisProgram> for ErrorDispatcherNotFound {
- fn member_id() -> crate::ThisProgram {
- crate::ThisProgram::ErrorDispatcherNotFound
- }
-}
-pub struct ResultEmpty;
-#[doc(hidden)]
-#[allow(
- non_upper_case_globals,
- unused_attributes,
- unused_qualifications,
- clippy::absolute_paths,
-)]
-const _: () = {
- #[allow(unused_extern_crates, clippy::useless_attribute)]
- extern crate serde as _serde;
- #[automatically_derived]
- impl _serde::Serialize for ResultEmpty {
- fn serialize<__S>(
- &self,
- __serializer: __S,
- ) -> _serde::__private229::Result<__S::Ok, __S::Error>
- where
- __S: _serde::Serializer,
- {
- _serde::Serializer::serialize_unit_struct(__serializer, "ResultEmpty")
- }
- }
-};
-impl ::mingling::__private::StructuralDataSealed<crate::ThisProgram> for ResultEmpty {}
-impl ::mingling::__private::StructuralData<crate::ThisProgram> for ResultEmpty {}
-impl ::mingling::Grouped<crate::ThisProgram> for ResultEmpty {
- fn member_id() -> crate::ThisProgram {
- crate::ThisProgram::ResultEmpty
- }
-}
-impl ::std::convert::Into<::mingling::AnyOutput<crate::ThisProgram>> for ResultEmpty {
- fn into(self) -> ::mingling::AnyOutput<crate::ThisProgram> {
- ::mingling::AnyOutput::new(self)
- }
-}
-impl ::std::convert::Into<::mingling::ChainProcess<crate::ThisProgram>> for ResultEmpty {
- fn into(self) -> ::mingling::ChainProcess<crate::ThisProgram> {
- ::mingling::AnyOutput::new(self).route_chain()
- }
-}
-#[automatically_derived]
-impl ::core::default::Default for ResultEmpty {
- #[inline]
- fn default() -> ResultEmpty {
- ResultEmpty {}
- }
-}
-#[repr(u8)]
-#[allow(nonstandard_style)]
-pub enum ThisProgram {
- EntryMetadata,
- EntryMinglingLinter,
- ErrorDispatcherNotFound,
- ErrorRendererNotFound,
- ErrorSerdeJson,
- Metadata,
- ResultEmpty,
- ResultMetadata,
-}
-#[automatically_derived]
-#[allow(nonstandard_style)]
-impl ::core::fmt::Debug for ThisProgram {
- #[inline]
- fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
- ::core::fmt::Formatter::write_str(
- f,
- match self {
- ThisProgram::EntryMetadata => "EntryMetadata",
- ThisProgram::EntryMinglingLinter => "EntryMinglingLinter",
- ThisProgram::ErrorDispatcherNotFound => "ErrorDispatcherNotFound",
- ThisProgram::ErrorRendererNotFound => "ErrorRendererNotFound",
- ThisProgram::ErrorSerdeJson => "ErrorSerdeJson",
- ThisProgram::Metadata => "Metadata",
- ThisProgram::ResultEmpty => "ResultEmpty",
- ThisProgram::ResultMetadata => "ResultMetadata",
- },
- )
- }
-}
-#[automatically_derived]
-#[allow(nonstandard_style)]
-impl ::core::marker::StructuralPartialEq for ThisProgram {}
-#[automatically_derived]
-#[allow(nonstandard_style)]
-impl ::core::cmp::PartialEq for ThisProgram {
- #[inline]
- fn eq(&self, other: &ThisProgram) -> bool {
- let __self_discr = ::core::intrinsics::discriminant_value(self);
- let __arg1_discr = ::core::intrinsics::discriminant_value(other);
- __self_discr == __arg1_discr
- }
-}
-#[automatically_derived]
-#[allow(nonstandard_style)]
-impl ::core::cmp::Eq for ThisProgram {
- #[doc(hidden)]
- #[coverage(off)]
- fn assert_fields_are_eq(&self) {}
-}
-#[automatically_derived]
-#[allow(nonstandard_style)]
-impl ::core::clone::Clone for ThisProgram {
- #[inline]
- fn clone(&self) -> ThisProgram {
- match self {
- ThisProgram::EntryMetadata => ThisProgram::EntryMetadata,
- ThisProgram::EntryMinglingLinter => ThisProgram::EntryMinglingLinter,
- ThisProgram::ErrorDispatcherNotFound => ThisProgram::ErrorDispatcherNotFound,
- ThisProgram::ErrorRendererNotFound => ThisProgram::ErrorRendererNotFound,
- ThisProgram::ErrorSerdeJson => ThisProgram::ErrorSerdeJson,
- ThisProgram::Metadata => ThisProgram::Metadata,
- ThisProgram::ResultEmpty => ThisProgram::ResultEmpty,
- ThisProgram::ResultMetadata => ThisProgram::ResultMetadata,
- }
- }
-}
-impl ::std::fmt::Display for ThisProgram {
- fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
- match self {
- ThisProgram::EntryMetadata => f.write_fmt(format_args!("EntryMetadata")),
- ThisProgram::EntryMinglingLinter => {
- f.write_fmt(format_args!("EntryMinglingLinter"))
- }
- ThisProgram::ErrorDispatcherNotFound => {
- f.write_fmt(format_args!("ErrorDispatcherNotFound"))
- }
- ThisProgram::ErrorRendererNotFound => {
- f.write_fmt(format_args!("ErrorRendererNotFound"))
- }
- ThisProgram::ErrorSerdeJson => f.write_fmt(format_args!("ErrorSerdeJson")),
- ThisProgram::Metadata => f.write_fmt(format_args!("Metadata")),
- ThisProgram::ResultEmpty => f.write_fmt(format_args!("ResultEmpty")),
- ThisProgram::ResultMetadata => f.write_fmt(format_args!("ResultMetadata")),
- }
- }
-}
-impl ::mingling::ProgramCollect for ThisProgram {
- type Enum = ThisProgram;
- type ErrorDispatcherNotFound = ErrorDispatcherNotFound;
- type ErrorRendererNotFound = ErrorRendererNotFound;
- type ResultEmpty = ResultEmpty;
- fn build_renderer_not_found(
- member_id: Self::Enum,
- ) -> ::mingling::AnyOutput<Self::Enum> {
- ::mingling::AnyOutput::new(ErrorRendererNotFound::new(member_id.to_string()))
- }
- fn build_dispatcher_not_found(
- args: Vec<String>,
- ) -> ::mingling::AnyOutput<Self::Enum> {
- ::mingling::AnyOutput::new(ErrorDispatcherNotFound::new(args))
- }
- fn build_empty_result() -> ::mingling::AnyOutput<Self::Enum> {
- ::mingling::AnyOutput::new(ResultEmpty)
- }
- fn render(any: ::mingling::AnyOutput<Self::Enum>) -> ::mingling::RenderResult {
- match any.member_id {
- Self::ErrorSerdeJson => {
- let value = unsafe {
- any.downcast::<crate::errors::serde_json::ErrorSerdeJson>()
- .unwrap_unchecked()
- };
- <crate::errors::serde_json::__internal_renderer_render_error_serde_json as ::mingling::Renderer>::render(
- value,
- )
- }
- Self::Metadata => {
- let value = unsafe {
- any.downcast::<cargo_metadata::Metadata>().unwrap_unchecked()
- };
- <crate::metadata::__internal_renderer_render_metadata as ::mingling::Renderer>::render(
- value,
- )
- }
- _ => ::mingling::RenderResult::default(),
- }
- }
- fn do_chain(
- any: ::mingling::AnyOutput<Self::Enum>,
- ) -> ::mingling::ChainProcess<Self::Enum> {
- match any.member_id {
- Self::EntryMetadata => {
- let value = unsafe {
- any.downcast::<crate::metadata::cmd_metadata::EntryMetadata>()
- .unwrap_unchecked()
- };
- <crate::metadata::cmd_metadata::__internal_chain_handle_metadata as ::mingling::Chain<
- Self::Enum,
- >>::proc(value)
- }
- Self::EntryMinglingLinter => {
- let value = unsafe {
- any.downcast::<crate::linter::cmd_mlint::EntryMinglingLinter>()
- .unwrap_unchecked()
- };
- <crate::linter::cmd_mlint::__internal_chain_handle_mlint as ::mingling::Chain<
- Self::Enum,
- >>::proc(value)
- }
- _ => {
- ::core::panicking::panic_fmt(
- format_args!("No chain found for type id: {0:?}", any.type_id),
- );
- }
- }
- }
- fn render_help(any: ::mingling::AnyOutput<Self::Enum>) -> ::mingling::RenderResult {
- #[allow(unused_imports)]
- use crate::metadata::cmd_metadata::__internal_chain_handle_metadata;
- use crate::metadata::cmd_metadata::ResultMetadata;
- use crate::linter::cmd_mlint::__internal_chain_handle_mlint;
- use crate::metadata::__internal_renderer_render_metadata;
- use crate::metadata::cmd_metadata::CMDMetadata;
- use crate::metadata::setup::ResMetadata;
- use crate::metadata::cmd_metadata::EntryMetadata;
- use crate::linter::cmd_mlint::CMDMinglingLinter;
- use crate::errors::serde_json::ErrorSerdeJson;
- use cargo_metadata::Metadata;
- use crate::errors::serde_json::__internal_renderer_render_error_serde_json;
- use crate::linter::cmd_mlint::EntryMinglingLinter;
- match any.member_id {
- _ => ::mingling::RenderResult::default(),
- }
- }
- fn has_renderer(any: &::mingling::AnyOutput<Self::Enum>) -> bool {
- match any.member_id {
- Self::ErrorSerdeJson => true,
- Self::Metadata => true,
- _ => false,
- }
- }
- fn has_chain(any: &::mingling::AnyOutput<Self::Enum>) -> bool {
- match any.member_id {
- Self::EntryMetadata => true,
- Self::EntryMinglingLinter => true,
- _ => false,
- }
- }
- fn structural_render(
- any: ::mingling::AnyOutput<Self::Enum>,
- setting: &::mingling::StructuralRendererSetting,
- ) -> Result<
- ::mingling::RenderResult,
- ::mingling::error::StructuralRendererSerializeError,
- > {
- #[allow(unused_imports)]
- use crate::metadata::cmd_metadata::__internal_chain_handle_metadata;
- use crate::metadata::cmd_metadata::ResultMetadata;
- use crate::linter::cmd_mlint::__internal_chain_handle_mlint;
- use crate::metadata::__internal_renderer_render_metadata;
- use crate::metadata::cmd_metadata::CMDMetadata;
- use crate::metadata::setup::ResMetadata;
- use crate::metadata::cmd_metadata::EntryMetadata;
- use crate::linter::cmd_mlint::CMDMinglingLinter;
- use crate::errors::serde_json::ErrorSerdeJson;
- use cargo_metadata::Metadata;
- use crate::errors::serde_json::__internal_renderer_render_error_serde_json;
- use crate::linter::cmd_mlint::EntryMinglingLinter;
- match any.member_id {
- Self::Metadata => {
- let raw = unsafe { any.restore::<Metadata>().unwrap_unchecked() };
- let mut __renderer_inner_result = ::mingling::RenderResult::default();
- ::mingling::StructuralRenderer::render(
- &raw,
- setting,
- &mut __renderer_inner_result,
- )?;
- Ok(__renderer_inner_result)
- }
- _ => {
- let mut r = ::mingling::RenderResult::default();
- ::mingling::StructuralRenderer::render(&ResultEmpty, setting, &mut r)?;
- Ok(r)
- }
- }
- }
-}
-impl ThisProgram {
- /// Creates a new `Program<#name>` instance with default configuration.
- pub fn new() -> ::mingling::Program<ThisProgram> {
- ::mingling::Program::new()
- }
- /// Returns a static reference to the global `Program<#name>` singleton.
- pub fn this() -> &'static ::mingling::Program<ThisProgram> {
- &::mingling::this::<ThisProgram>()
- }
-}
diff --git a/mingling_cli/src/linter.rs b/mingling_cli/src/linter.rs
index b3b2e7b..c85afc1 100644
--- a/mingling_cli/src/linter.rs
+++ b/mingling_cli/src/linter.rs
@@ -1,6 +1,12 @@
-use mingling::{Program, macros::program_setup};
+use mingling::{
+ Program,
+ macros::{chain, dispatcher, entry, program_setup},
+};
-use crate::linter::cmd_mlint::CMDMinglingLinter;
+use crate::{
+ linter::cmd_mlint::{CMDMinglingLinter, EntryMinglingLinter},
+ metadata::setup::ResUsingJson,
+};
pub mod cmd_mlint;
pub mod mlint_attr;
@@ -14,4 +20,48 @@ pub fn mingling_linter_setup(program: &mut Program<crate::ThisProgram>) {
#[program_setup]
pub fn mingling_linter_command_setup(program: &mut Program<crate::ThisProgram>) {
program.with_dispatcher(CMDMinglingLinter);
+ program.with_dispatcher(CMDLinterSupportRustAnalyzer);
+ program.with_dispatcher(CMDLinterSupportRustAnalyzerWithClippy);
+ program.with_dispatcher(CMDLinterSupportRustAnalyzerWithCheck);
+}
+
+// Aliases
+
+dispatcher!("ra-lint-clippy",
+ CMDLinterSupportRustAnalyzerWithClippy => EntryLinterSupportRustAnalyzerWithClippy
+);
+
+dispatcher!("ra-lint-check",
+ CMDLinterSupportRustAnalyzerWithCheck => EntryLinterSupportRustAnalyzerWithCheck
+);
+
+dispatcher!("ra-lint",
+ CMDLinterSupportRustAnalyzer => EntryLinterSupportRustAnalyzer
+);
+
+#[chain]
+pub fn handle_ra_lint(
+ _: EntryLinterSupportRustAnalyzer,
+ use_json: &mut ResUsingJson,
+) -> EntryMinglingLinter {
+ use_json.using = true;
+ entry!("--message-format=json")
+}
+
+#[chain]
+pub fn handle_ra_lint_check(
+ _: EntryLinterSupportRustAnalyzerWithCheck,
+ use_json: &mut ResUsingJson,
+) -> EntryMinglingLinter {
+ use_json.using = true;
+ entry!("--message-format=json", "--with-checker=cargo,check")
+}
+
+#[chain]
+pub fn handle_ra_lint_clippy(
+ _: EntryLinterSupportRustAnalyzerWithClippy,
+ use_json: &mut ResUsingJson,
+) -> EntryMinglingLinter {
+ use_json.using = true;
+ entry!("--message-format=json", "--with-checker=cargo,clippy")
}
diff --git a/mingling_cli/src/linter/mlint_report.rs b/mingling_cli/src/linter/mlint_report.rs
index 8195f77..0472056 100644
--- a/mingling_cli/src/linter/mlint_report.rs
+++ b/mingling_cli/src/linter/mlint_report.rs
@@ -51,8 +51,8 @@ pub struct MlintReport {
/// Compilation target source file path that this report belongs to
pub target_src_path: Option<String>,
- /// A suggestion for automatic fix (shown as diff in annotated output)
- pub suggestion: Option<LintSuggestion>,
+ /// Suggestions for automatic fix (shown as diff in annotated output)
+ pub suggestions: Vec<LintSuggestion>,
}
/// Report severity level, indicating the seriousness of the Lint result.
@@ -248,8 +248,8 @@ impl MlintReport {
group = group.element(msg);
}
- // Render suggestion as a diff (Element::Suggestion)
- if let Some(sugg) = &self.suggestion {
+ // Render suggestions as diffs
+ for sugg in &self.suggestions {
let patch_snippet = Snippet::source(sugg.source.clone())
.line_start(sugg.line_start)
.path(&self.file_name)
@@ -404,8 +404,8 @@ impl MlintReport {
.collect::<Vec<_>>(),
)
.label(span.label.clone())
- .suggested_replacement(self.suggestion.as_ref().map(|s| s.replacement.clone()))
- .suggestion_applicability(if self.suggestion.is_some() {
+ .suggested_replacement(self.suggestions.first().map(|s| s.replacement.clone()))
+ .suggestion_applicability(if !self.suggestions.is_empty() {
Some(cargo_metadata::diagnostic::Applicability::MachineApplicable)
} else {
None
diff --git a/mingling_cli/src/lints/non_mingling_naming_style.rs b/mingling_cli/src/lints/non_mingling_naming_style.rs
index 3340dd2..83168b7 100644
--- a/mingling_cli/src/lints/non_mingling_naming_style.rs
+++ b/mingling_cli/src/lints/non_mingling_naming_style.rs
@@ -153,12 +153,12 @@ fn check_fn_name(func: &syn::ItemFn, source: &str) -> Vec<MlintReport> {
lint_code: "non_mingling_naming_style".into(),
message: msg,
spans: vec![span],
- suggestion: Some(LintSuggestion {
+ suggestions: vec![LintSuggestion {
source: source_line.to_string(),
line_start: func.sig.span().start().line,
byte_range,
replacement: suggestion_target,
- }),
+ }],
attached_reports: vec![MlintReport {
level: MlintLevel::Help,
message: format!("expected `{expected_fn}` ↔ `{expected_type}`"),
@@ -337,6 +337,7 @@ mod lint_test {
fn handle_greet() {}
});
}
+
#[test]
fn regular_fn_ok() {
assert_not_detected!(super::linter, syn::ItemFn => {
diff --git a/mingling_cli/src/lints/template_linter.rs b/mingling_cli/src/lints/template_linter.rs
index 271aa0c..4836e24 100644
--- a/mingling_cli/src/lints/template_linter.rs
+++ b/mingling_cli/src/lints/template_linter.rs
@@ -13,7 +13,7 @@
//! > This section is the **Metadata** section, which needs to be filled in correctly.
//! > These contents will eventually be compiled as the Linter's behavior.
//!
-//! Author: `Weicao-CatilGrass`
+//! Author: `Your-Name`
//! Default: `allow`
// ^^^^^ Supported parameters: `warn`, `allow`, `deny`
diff --git a/mingling_cli/src/lints/unnecessary_render_result_creation.rs b/mingling_cli/src/lints/unnecessary_render_result_creation.rs
index 03f81d2..1450c1a 100644
--- a/mingling_cli/src/lints/unnecessary_render_result_creation.rs
+++ b/mingling_cli/src/lints/unnecessary_render_result_creation.rs
@@ -14,8 +14,9 @@
//! Author: `Weicao-CatilGrass`
//! Default: `warn`
-use crate::linter::mlint_report::{MlintLevel, MlintReport};
+use crate::linter::mlint_report::{LintSuggestion, MlintLevel, MlintReport};
use quote::ToTokens;
+use syn::spanned::Spanned;
pub fn linter(ast: syn::ItemFn, source: &str) -> Vec<MlintReport> {
if !has_renderer_attr(&ast) {
@@ -45,6 +46,31 @@ pub fn linter(ast: syn::ItemFn, source: &str) -> Vec<MlintReport> {
if only_print_and_return && print_count > 0 {
let span = MlintReport::span_from_syn(&ast.sig, source);
+ let mut suggestions = Vec::new();
+
+ // 1. Attribute change: #[renderer] → #[renderer(buffer)]
+ if let Some(sugg) = make_attr_suggestion(&ast, source) {
+ suggestions.push(sugg);
+ }
+
+ // 2. Remove -> RenderResult from function signature
+ if let Some(sugg) = make_return_type_suggestion(&ast, source) {
+ suggestions.push(sugg);
+ }
+
+ // 3. Remove let mut r = RenderResult::...
+ if let Some(sugg) = make_let_removal_suggestion(stmts, let_idx, source) {
+ suggestions.push(sugg);
+ }
+
+ // 4. Fix r_println!(r, ...) → r_println!(...) for all r_xxx macros
+ suggestions.extend(make_macro_arg_suggestions(stmts, &r_name, source));
+
+ // 5. Remove return 'r' expression
+ if let Some(sugg) = make_return_removal_suggestion(stmts, &r_name, source) {
+ suggestions.push(sugg);
+ }
+
vec![MlintReport {
source_code: source.to_string(),
level: MlintLevel::Warning,
@@ -54,6 +80,7 @@ pub fn linter(ast: syn::ItemFn, source: &str) -> Vec<MlintReport> {
ast.sig.ident,
),
spans: vec![span],
+ suggestions,
attached_reports: vec![MlintReport {
level: MlintLevel::Help,
message: format!(
@@ -185,6 +212,198 @@ fn check_stmt_usage(stmt: &syn::Stmt, r_name: &str, print_count: &mut usize) ->
true
}
+/// Build suggestion: `#[renderer]` → `#[renderer(buffer)]`
+fn make_attr_suggestion(ast: &syn::ItemFn, source: &str) -> Option<LintSuggestion> {
+ let attr = ast.attrs.iter().find(|a| {
+ let name = a.path().to_token_stream().to_string();
+ name.ends_with("renderer")
+ })?;
+
+ let line_idx = attr.span().start().line.saturating_sub(1);
+ let line = source.lines().nth(line_idx)?;
+
+ // Replace `renderer]` with `renderer(buffer)]`
+ // This handles both `#[renderer]` and `#[::mingling::macros::renderer]`
+ let line_str = line;
+ let replacement = line_str.replacen("renderer]", "renderer(buffer)]", 1);
+
+ if replacement == line_str {
+ return None;
+ }
+
+ Some(LintSuggestion {
+ source: line_str.to_string(),
+ line_start: line_idx + 1,
+ byte_range: 0..line_str.len(),
+ replacement,
+ })
+}
+
+/// Build suggestion: remove ` -> RenderResult` from function signature
+fn make_return_type_suggestion(ast: &syn::ItemFn, source: &str) -> Option<LintSuggestion> {
+ let syn::ReturnType::Type(arrow, ret_type) = &ast.sig.output else {
+ return None;
+ };
+
+ let sig_line_idx = ast.sig.span().start().line.saturating_sub(1);
+ let line = source.lines().nth(sig_line_idx)?;
+
+ // proc-macro2 column is 0-based byte offset from line start
+ let arrow_byte_col = arrow.span().start().column;
+ let ret_end_byte_col = ret_type.span().end().column;
+
+ // Include the space before `->`
+ let range_start = if arrow_byte_col > 0 {
+ arrow_byte_col - 1
+ } else {
+ arrow_byte_col
+ };
+
+ Some(LintSuggestion {
+ source: line.to_string(),
+ line_start: sig_line_idx + 1,
+ byte_range: range_start..ret_end_byte_col,
+ replacement: String::new(),
+ })
+}
+
+/// Build suggestion: remove `let mut r = RenderResult::...` line
+fn make_let_removal_suggestion(
+ stmts: &[syn::Stmt],
+ let_idx: usize,
+ source: &str,
+) -> Option<LintSuggestion> {
+ let stmt = &stmts[let_idx];
+ let line_idx = stmt.span().start().line.saturating_sub(1);
+ let line = source.lines().nth(line_idx)?;
+
+ Some(LintSuggestion {
+ source: line.to_string(),
+ line_start: line_idx + 1,
+ byte_range: 0..line.len(),
+ replacement: String::new(),
+ })
+}
+
+/// Build suggestions: fix `r_println!(r, ...)` → `r_println!(...)` for all r_xxx macros
+fn make_macro_arg_suggestions(
+ stmts: &[syn::Stmt],
+ r_name: &str,
+ source: &str,
+) -> Vec<LintSuggestion> {
+ let r_macros = ["r_println", "r_eprintln", "r_print", "r_eprint"];
+
+ stmts
+ .iter()
+ .filter_map(|stmt| {
+ let syn::Stmt::Macro(stmt_mac) = stmt else {
+ return None;
+ };
+
+ let macro_name = stmt_mac
+ .mac
+ .path
+ .segments
+ .last()
+ .map(|s| s.ident.to_string())
+ .unwrap_or_default();
+
+ if !r_macros.contains(&macro_name.as_str()) {
+ return None;
+ }
+
+ // Check that the first token is the r_name
+ let first_token = stmt_mac.mac.tokens.clone().into_iter().next()?;
+ if first_token.to_string() != *r_name {
+ return None;
+ }
+
+ let line_idx = stmt.span().start().line.saturating_sub(1);
+ let line = source.lines().nth(line_idx)?;
+
+ // Find pattern: macro_name!(r_name, ...
+ let macro_str = format!("{}!(", macro_name);
+ let macro_pos = line.find(&macro_str)?;
+ let after_open = macro_pos + macro_str.len();
+
+ // The first argument is `r_name` followed by `,` and possibly a space
+ // We need to find and remove `r_name, ` or `r_name,`
+ let first_arg = r_name;
+ if line[after_open..].starts_with(first_arg) {
+ // Find the end of the first argument (including `,` and any whitespace)
+ let arg_end = after_open + first_arg.len();
+ if arg_end < line.len() {
+ let rest = &line[arg_end..];
+ // Skip `,` and optional whitespace
+ let skip = if rest.starts_with(", ") {
+ 2
+ } else if rest.starts_with(',') {
+ 1
+ } else {
+ // Not followed by comma — not our pattern
+ return None;
+ };
+ let range_end = arg_end + skip;
+
+ Some(LintSuggestion {
+ source: line.to_string(),
+ line_start: line_idx + 1,
+ byte_range: after_open..range_end,
+ replacement: String::new(),
+ })
+ } else {
+ None
+ }
+ } else {
+ None
+ }
+ })
+ .collect()
+}
+
+/// Build suggestion: remove the return `r` expression
+fn make_return_removal_suggestion(
+ stmts: &[syn::Stmt],
+ r_name: &str,
+ source: &str,
+) -> Option<LintSuggestion> {
+ let last = stmts.last()?;
+
+ let is_r_return = match last {
+ // `r` (bare expression, no semicolon) or `r;` (with semicolon)
+ syn::Stmt::Expr(expr, _) => {
+ if let syn::Expr::Path(p) = expr {
+ p.path.is_ident(r_name)
+ } else if let syn::Expr::Return(ret) = expr {
+ ret.expr.as_ref().is_some_and(|e| {
+ if let syn::Expr::Path(p) = e.as_ref() {
+ p.path.is_ident(r_name)
+ } else {
+ false
+ }
+ })
+ } else {
+ false
+ }
+ }
+ _ => false,
+ };
+
+ if !is_r_return {
+ return None;
+ }
+
+ let line_idx = last.span().start().line.saturating_sub(1);
+ let line = source.lines().nth(line_idx)?;
+
+ Some(LintSuggestion {
+ source: line.to_string(),
+ line_start: line_idx + 1,
+ byte_range: 0..line.len(),
+ replacement: String::new(),
+ })
+}
+
#[cfg(test)]
mod lint_test {
use crate::{assert_detected, assert_not_detected};
diff --git a/mingling_core/src/any.rs b/mingling_core/src/any.rs
index ec29a1b..3e8fdf0 100644
--- a/mingling_core/src/any.rs
+++ b/mingling_core/src/any.rs
@@ -22,14 +22,14 @@ pub struct AnyOutput<G> {
///
/// This is set during construction and used for type-checking
/// in downcast, restore, and is methods.
- pub type_id: std::any::TypeId,
+ pub(crate) type_id: std::any::TypeId,
/// The variant identifier returned by [`Grouped::member_id`] for the
/// concrete type stored in `inner`.
///
/// This is used by the scheduler to dispatch on the correct enum
/// variant when routing the output.
- pub member_id: G,
+ pub(crate) member_id: G,
}
impl<G> AnyOutput<G> {
@@ -45,6 +45,52 @@ impl<G> AnyOutput<G> {
}
}
+ /// Create an `AnyOutput` from a raw value with a manually specified member_id.
+ ///
+ /// This function bypasses the [`Grouped`] trait, meaning the `member_id` you provide
+ /// does **not** have to match the actual concrete type `T`. The scheduler uses
+ /// `member_id` to determine which enum variant the output belongs to, and later
+ /// attempts to restore the value to the concrete type `T` based on that variant.
+ ///
+ /// # Safety
+ ///
+ /// - The caller must ensure that `member_id` correctly corresponds to the concrete
+ /// type `T` according to the scheduling logic. If `member_id` does not match,
+ /// calling [`restore`](Self::restore) or [`downcast`](Self::downcast) with the
+ /// type associated with `member_id` will cause **undefined behavior**.
+ /// - This safety contract is the caller's responsibility; the compiler cannot
+ /// enforce the correspondence between `member_id` and the stored type.
+ pub unsafe fn new_bare<T>(value: T, member_id: G) -> Self
+ where
+ T: Send + 'static,
+ {
+ Self {
+ inner: Box::new(value),
+ type_id: std::any::TypeId::of::<T>(),
+ member_id,
+ }
+ }
+
+ /// Get the [`TypeId`] of the concrete type stored in `inner`.
+ ///
+ /// The `TypeId` is set during construction (via [`AnyOutput::new`] or [`AnyOutput::new_bare`])
+ /// and is used for subsequent downcasting and type checking.
+ pub fn type_id(&self) -> std::any::TypeId {
+ self.type_id
+ }
+
+ /// Get the [`member_id`] of the concrete type stored in `inner`.
+ ///
+ /// [`member_id`] is set during construction (via [`AnyOutput::new`] or [`AnyOutput::new_bare`])
+ /// and identifies which variant of the output enum this value corresponds to.
+ /// The scheduler uses this value to dispatch the output to the correct next step.
+ pub fn member_id(&self) -> G
+ where
+ G: Copy,
+ {
+ self.member_id
+ }
+
/// Attempt to downcast the `AnyOutput` to a concrete type.
///
/// # Errors
@@ -190,7 +236,17 @@ mod tests {
value: i32,
}
- impl Grouped<MockGroup> for AlphaData {
+ /// # Safety
+ ///
+ /// This implementation is only for testing purposes to satisfy trait bounds.
+ /// Since this code only constructs `AnyOutput` and calls methods like
+ /// `downcast`, `is`, `restore`, `route_chain`, and `route_renderer` —
+ /// none of which involve `ProgramCollect::do_chain` or
+ /// `ProgramCollect::render` — the type/member_id correspondence is
+ /// never exploited in an unsafe way here.
+ /// The caller must ensure that the associated `member_id` correctly
+ /// corresponds to the type's role in the group.
+ unsafe impl Grouped<MockGroup> for AlphaData {
fn member_id() -> MockGroup {
MockGroup::Alpha
}
@@ -202,7 +258,17 @@ mod tests {
name: String,
}
- impl Grouped<MockGroup> for BetaData {
+ /// # Safety
+ ///
+ /// This implementation is only for testing purposes to satisfy trait bounds.
+ /// Since this code only constructs `AnyOutput` and calls methods like
+ /// `downcast`, `is`, `restore`, `route_chain`, and `route_renderer` —
+ /// none of which involve `ProgramCollect::do_chain` or
+ /// `ProgramCollect::render` — the type/member_id correspondence is
+ /// never exploited in an unsafe way here.
+ /// The caller must ensure that the associated `member_id` correctly
+ /// corresponds to the type's role in the group.
+ unsafe impl Grouped<MockGroup> for BetaData {
fn member_id() -> MockGroup {
MockGroup::Beta
}
@@ -213,7 +279,17 @@ mod tests {
#[cfg_attr(feature = "structural_renderer", derive(serde::Serialize))]
struct GammaData;
- impl Grouped<MockGroup> for GammaData {
+ /// # Safety
+ ///
+ /// This implementation is only for testing purposes to satisfy trait bounds.
+ /// Since this code only constructs `AnyOutput` and calls methods like
+ /// `downcast`, `is`, `restore`, `route_chain`, and `route_renderer` —
+ /// none of which involve `ProgramCollect::do_chain` or
+ /// `ProgramCollect::render` — the type/member_id correspondence is
+ /// never exploited in an unsafe way here.
+ /// The caller must ensure that the associated `member_id` correctly
+ /// corresponds to the type's role in the group.
+ unsafe impl Grouped<MockGroup> for GammaData {
fn member_id() -> MockGroup {
MockGroup::Gamma
}
@@ -369,7 +445,17 @@ mod tests {
x: i32,
}
- impl Grouped<MockGroup> for SerData {
+ /// SAFETY:
+ ///
+ /// This implementation is only for testing purposes to satisfy trait bounds.
+ /// Since this code only constructs `AnyOutput` and calls methods like
+ /// `downcast`, `is`, `restore`, `route_chain`, and `route_renderer` —
+ /// none of which involve `ProgramCollect::do_chain` or
+ /// `ProgramCollect::render` — the type/member_id correspondence is
+ /// never exploited in an unsafe way here.
+ /// The caller must ensure that the associated `member_id` correctly
+ /// corresponds to the type's role in the group.
+ unsafe impl Grouped<MockGroup> for SerData {
fn member_id() -> MockGroup {
MockGroup::Gamma
}
@@ -396,13 +482,33 @@ mod tests {
b: String,
}
- impl Grouped<MockGroup> for SerA {
+ /// SAFETY:
+ ///
+ /// This implementation is only for testing purposes to satisfy trait bounds.
+ /// Since this code only constructs `AnyOutput` and calls methods like
+ /// `downcast`, `is`, `restore`, `route_chain`, and `route_renderer` —
+ /// none of which involve `ProgramCollect::do_chain` or
+ /// `ProgramCollect::render` — the type/member_id correspondence is
+ /// never exploited in an unsafe way here.
+ /// The caller must ensure that the associated `member_id` correctly
+ /// corresponds to the type's role in the group.
+ unsafe impl Grouped<MockGroup> for SerA {
fn member_id() -> MockGroup {
MockGroup::Alpha
}
}
- impl Grouped<MockGroup> for SerB {
+ /// SAFETY:
+ ///
+ /// This implementation is only for testing purposes to satisfy trait bounds.
+ /// Since this code only constructs `AnyOutput` and calls methods like
+ /// `downcast`, `is`, `restore`, `route_chain`, and `route_renderer` —
+ /// none of which involve `ProgramCollect::do_chain` or
+ /// `ProgramCollect::render` — the type/member_id correspondence is
+ /// never exploited in an unsafe way here.
+ /// The caller must ensure that the associated `member_id` correctly
+ /// corresponds to the type's role in the group.
+ unsafe impl Grouped<MockGroup> for SerB {
fn member_id() -> MockGroup {
MockGroup::Beta
}
diff --git a/mingling_core/src/any/group.rs b/mingling_core/src/any/group.rs
index 2813ad5..5e5e347 100644
--- a/mingling_core/src/any/group.rs
+++ b/mingling_core/src/any/group.rs
@@ -2,10 +2,14 @@ use crate::{AnyOutput, ChainProcess, ProgramCollect, Routable};
/// Used to mark a type with a unique enum ID, assisting dynamic dispatch
///
-/// **Note:** Unlike earlier versions, `Grouped` no longer requires `Serialize`
-/// even when the `structural_renderer` feature is enabled. Structured output is
-/// controlled separately via the \[`StructuralData`\] trait.
-pub trait Grouped<Group>
+/// # Safety
+///
+/// The returned `Group` value is an enum variant created by `register_type!` when
+/// registering the type's ID. Whether the variant matches correctly is guaranteed
+/// by `Grouped derive` or macros like `pack!`. If implemented manually, and the
+/// type name written in `member_id()` does not match the actually registered type,
+/// dispatching to that type will result in **100% undefined behavior**.
+pub unsafe trait Grouped<Group>
where
Self: Sized + 'static,
{
diff --git a/mingling_core/src/program/collection/mock.rs b/mingling_core/src/program/collection/mock.rs
index 5847f10..dbe4789 100644
--- a/mingling_core/src/program/collection/mock.rs
+++ b/mingling_core/src/program/collection/mock.rs
@@ -23,9 +23,12 @@ pub enum MockProgramCollect {
Bar,
}
-impl Grouped<MockProgramCollect> for MockProgramCollect {
+/// SAFETY: This is a mock type used only for temporary testing.
+/// It will never actually enter the macro system.
+/// The internal `panic!` ensures that `member_id` will never be executed.
+unsafe impl Grouped<MockProgramCollect> for MockProgramCollect {
fn member_id() -> MockProgramCollect {
- MockProgramCollect::Foo
+ panic!("Attempting to read an unsafe enum type");
}
}
diff --git a/mingling_core/src/program/hook.rs b/mingling_core/src/program/hook.rs
index 48f632f..7d94a21 100644
--- a/mingling_core/src/program/hook.rs
+++ b/mingling_core/src/program/hook.rs
@@ -695,7 +695,17 @@ mod tests {
}
}
- impl Grouped<MockHookEnum> for MockHookEnum {
+ /// SAFETY:
+ ///
+ /// This implementation is only for testing purposes to satisfy trait bounds.
+ /// Since this code only constructs `AnyOutput` and calls methods like
+ /// `downcast`, `is`, `restore`, `route_chain`, and `route_renderer` —
+ /// none of which involve `ProgramCollect::do_chain` or
+ /// `ProgramCollect::render` — the type/member_id correspondence is
+ /// never exploited in an unsafe way here.
+ /// The caller must ensure that the associated `member_id` correctly
+ /// corresponds to the type's role in the group.
+ unsafe impl Grouped<MockHookEnum> for MockHookEnum {
fn member_id() -> MockHookEnum {
MockHookEnum::A
}
diff --git a/mingling_macros/src/derive/grouped.rs b/mingling_macros/src/derive/grouped.rs
index 307aab6..a00eea1 100644
--- a/mingling_macros/src/derive/grouped.rs
+++ b/mingling_macros/src/derive/grouped.rs
@@ -16,7 +16,11 @@ pub(crate) fn derive_grouped(input: TokenStream) -> TokenStream {
let expanded = quote! {
::mingling::macros::register_type!(#struct_name);
- impl ::mingling::Grouped<#group_ident> for #struct_name {
+ /// SAFETY: This is an internal implementation of the `Grouped` derive macro,
+ /// guaranteeing that the enum value registered by the `register_type!` macro
+ /// is exactly the same as the actual return value,
+ /// which can be confirmed via the `Ident` in the `quote!` block.
+ unsafe impl ::mingling::Grouped<#group_ident> for #struct_name {
fn member_id() -> #group_ident {
#group_ident::#struct_name
}
@@ -46,7 +50,11 @@ pub fn derive_grouped_serialize(input: TokenStream) -> TokenStream {
::mingling::macros::register_type!(#struct_name);
- impl ::mingling::Grouped<#group_ident> for #struct_name {
+ /// SAFETY: This is an internal implementation of the `Grouped` derive macro,
+ /// guaranteeing that the enum value registered by the `register_type!` macro
+ /// is exactly the same as the actual return value,
+ /// which can be confirmed via the `Ident` in the `quote!` block.
+ unsafe impl ::mingling::Grouped<#group_ident> for #struct_name {
fn member_id() -> #group_ident {
#group_ident::#struct_name
}
diff --git a/mingling_macros/src/func/gen_program.rs b/mingling_macros/src/func/gen_program.rs
index de4da06..db82504 100644
--- a/mingling_macros/src/func/gen_program.rs
+++ b/mingling_macros/src/func/gen_program.rs
@@ -342,7 +342,7 @@ fn main() {
) -> Result<::mingling::RenderResult, ::mingling::error::StructuralRendererSerializeError> {
#[allow(unused_imports)]
#(#pathf_uses)*
- match any.member_id {
+ match any.member_id() {
#(#structural_renderer_tokens)*
_ => {
// Non-structural types: render ResultEmpty (which implements
@@ -408,7 +408,7 @@ fn main() {
fn do_comp(any: &::mingling::AnyOutput<Self::Enum>, ctx: &::mingling::ShellContext) -> ::mingling::Suggest {
#[allow(unused_imports)]
#(#pathf_uses)*
- match any.member_id {
+ match any.member_id() {
#(#completion_tokens)*
_ => ::mingling::Suggest::FileCompletion,
}
@@ -442,7 +442,7 @@ fn main() {
}).collect();
quote! {
fn render(any: ::mingling::AnyOutput<Self::Enum>) -> ::mingling::RenderResult {
- match any.member_id {
+ match any.member_id() {
#(#render_arms)*
_ => ::mingling::RenderResult::default(),
}
@@ -494,9 +494,9 @@ fn main() {
fn do_chain(
any: ::mingling::AnyOutput<Self::Enum>,
) -> ::std::pin::Pin<::std::boxed::Box<dyn ::std::future::Future<Output = ::mingling::ChainProcess<Self::Enum>> + ::std::marker::Send>> {
- match any.member_id {
+ match any.member_id() {
#(#chain_arms_async)*
- _ => ::core::panic!("No chain found for type id: {:?}", any.type_id),
+ _ => ::core::panic!("No chain found for type id: {:?}", any.type_id()),
}
}
}
@@ -505,9 +505,9 @@ fn main() {
fn do_chain(
any: ::mingling::AnyOutput<Self::Enum>,
) -> ::mingling::ChainProcess<Self::Enum> {
- match any.member_id {
+ match any.member_id() {
#(#chain_arms_sync)*
- _ => ::core::panic!("No chain found for type id: {:?}", any.type_id),
+ _ => ::core::panic!("No chain found for type id: {:?}", any.type_id()),
}
}
}
@@ -535,7 +535,7 @@ fn main() {
let expanded = quote! {
#pathf_hint
- #[derive(Debug, PartialEq, Eq, Clone)]
+ #[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[repr(#repr_type)]
#[allow(nonstandard_style)]
pub enum #name {
@@ -569,19 +569,19 @@ fn main() {
fn render_help(any: ::mingling::AnyOutput<Self::Enum>) -> ::mingling::RenderResult {
#[allow(unused_imports)]
#(#pathf_uses)*
- match any.member_id {
+ match any.member_id() {
#(#help_tokens)*
_ => ::mingling::RenderResult::default(),
}
}
fn has_renderer(any: &::mingling::AnyOutput<Self::Enum>) -> bool {
- match any.member_id {
+ match any.member_id() {
#(#renderer_exist_tokens)*
_ => false
}
}
fn has_chain(any: &::mingling::AnyOutput<Self::Enum>) -> bool {
- match any.member_id {
+ match any.member_id() {
#(#chain_exist_tokens)*
_ => false
}
diff --git a/mingling_macros/src/func/group.rs b/mingling_macros/src/func/group.rs
index b865913..edb1fe1 100644
--- a/mingling_macros/src/func/group.rs
+++ b/mingling_macros/src/func/group.rs
@@ -133,7 +133,11 @@ pub(crate) fn group_macro(input: TokenStream) -> TokenStream {
#type_use
#alias_use
- impl ::mingling::Grouped<__MinglingProgram> for #type_name {
+ /// SAFETY: This is an internal implementation of the `group!` macro,
+ /// guaranteeing that the enum value registered by the `register_type!` macro
+ /// is exactly the same as the actual return value,
+ /// which can be confirmed via the `Ident` in the `quote!` block.
+ unsafe impl ::mingling::Grouped<__MinglingProgram> for #type_name {
fn member_id() -> __MinglingProgram {
__MinglingProgram::#type_name
}
diff --git a/mingling_macros/src/func/pack.rs b/mingling_macros/src/func/pack.rs
index a1a7e6b..7206b8e 100644
--- a/mingling_macros/src/func/pack.rs
+++ b/mingling_macros/src/func/pack.rs
@@ -138,7 +138,11 @@ pub(crate) fn pack(input: TokenStream) -> TokenStream {
}
}
- impl ::mingling::Grouped<#group_name> for #type_name {
+ /// SAFETY: This is an internal implementation of the `pack!` macro,
+ /// guaranteeing that the enum value registered by the `register_type!` macro
+ /// is exactly the same as the actual return value,
+ /// which can be confirmed via the `Ident` in the `quote!` block.
+ unsafe impl ::mingling::Grouped<#group_name> for #type_name {
fn member_id() -> #group_name {
#group_name::#type_name
}
diff --git a/mingling_macros/src/systems/structural_data.rs b/mingling_macros/src/systems/structural_data.rs
index 0a783ec..46d7cf8 100644
--- a/mingling_macros/src/systems/structural_data.rs
+++ b/mingling_macros/src/systems/structural_data.rs
@@ -176,7 +176,11 @@ pub(crate) fn pack_structural(input: TokenStream) -> TokenStream {
}
}
- impl ::mingling::Grouped<#program_path> for #type_name {
+ /// SAFETY: This is an internal implementation of the `pack_structural!` macro,
+ /// guaranteeing that the enum value registered by the `register_type!` macro
+ /// is exactly the same as the actual return value,
+ /// which can be confirmed via the `Ident` in the `quote!` block.
+ unsafe impl ::mingling::Grouped<#program_path> for #type_name {
fn member_id() -> #program_path {
#program_path::#type_name
}
@@ -297,7 +301,11 @@ pub(crate) fn group_structural(input: TokenStream) -> TokenStream {
#type_use
#alias_use
- impl ::mingling::Grouped<__MinglingProgram> for #type_name {
+ /// SAFETY: This is an internal implementation of the `pack_structural!` macro,
+ /// guaranteeing that the enum value registered by the `register_type!` macro
+ /// is exactly the same as the actual return value,
+ /// which can be confirmed via the `Ident` in the `quote!` block.
+ unsafe impl ::mingling::Grouped<__MinglingProgram> for #type_name {
fn member_id() -> __MinglingProgram {
__MinglingProgram::#type_name
}