From 69e5fd86b4532d3dfa7c503f74d42a64a845d57e Mon Sep 17 00:00:00 2001 From: 魏曹先生 <1992414357@qq.com> Date: Tue, 30 Jun 2026 04:45:04 +0800 Subject: fix(mingling_pathf): extract CMD, error, and help types from dispatcher_clap --- mingling_pathf/Cargo.toml | 1 + mingling_pathf/src/patterns/dispatcher_clap.rs | 197 +++++++++++++++++++-- mingling_pathf/test/Cargo.lock | 1 + mingling_pathf/test/src/lib.rs | 29 +++ .../test/src/test_files/test_dispatcher_clap.rs | 40 +++++ 5 files changed, 252 insertions(+), 16 deletions(-) (limited to 'mingling_pathf') diff --git a/mingling_pathf/Cargo.toml b/mingling_pathf/Cargo.toml index 9619adc..84bb260 100644 --- a/mingling_pathf/Cargo.toml +++ b/mingling_pathf/Cargo.toml @@ -8,3 +8,4 @@ repository.workspace = true [dependencies] syn.workspace = true proc-macro2.workspace = true +just_fmt.workspace = true diff --git a/mingling_pathf/src/patterns/dispatcher_clap.rs b/mingling_pathf/src/patterns/dispatcher_clap.rs index 398b269..aed96e5 100644 --- a/mingling_pathf/src/patterns/dispatcher_clap.rs +++ b/mingling_pathf/src/patterns/dispatcher_clap.rs @@ -2,11 +2,17 @@ use syn::Item; use crate::pattern_analyzer::{AnalyzeItem, AnalyzePattern}; -/// Match structs annotated with `#[dispatcher_clap]`, extracting the entry type name (i.e., the struct name). +/// Match structs annotated with `#[dispatcher_clap(...)]`, extracting: +/// - The entry type (struct name, always) +/// - The dispatcher struct (`CMD*`, always) +/// - The error type, if `error = ErrorType` is specified +/// - The help internal struct, if `help = true` is specified /// -/// Covers the following forms: -/// - `#[dispatcher_clap] struct EntryGreet { ... }` -/// - `#[dispatcher_clap] #[command(...)] struct EntryGreet { ... }` +/// Covers forms: +/// - `#[dispatcher_clap("greet", CMDGreet)] struct EntryGreet { ... }` +/// - `#[dispatcher_clap("greet", CMDGreet, error = ErrorGreet)] struct EntryGreet { ... }` +/// - `#[dispatcher_clap("greet", CMDGreet, help = true)] struct EntryGreet { ... }` +/// - `#[dispatcher_clap("greet", CMDGreet, error = ErrorGreet, help = true)] struct EntryGreet { ... }` pub struct DispatcherClapPattern; impl AnalyzePattern for DispatcherClapPattern { @@ -24,21 +30,113 @@ impl AnalyzePattern for DispatcherClapPattern { for item in &syntax.items { match item { Item::Struct(s) if has_attr(&s.attrs, "dispatcher_clap") => { + // Entry type (struct name) — always + let entry_name = s.ident.to_string(); items.push(AnalyzeItem { module: String::new(), - item_name: s.ident.to_string(), + item_name: entry_name.clone(), }); + + // Parse the attribute to extract CMD, error, and help info + if let Some(attr) = s.attrs.iter().find(|a| { + a.path() + .segments + .last() + .is_some_and(|seg| seg.ident == "dispatcher_clap") + }) { + let args = attr.meta.require_list().ok(); + let args_str = args.map(|l| l.tokens.to_string()).unwrap_or_default(); + let parsed = parse_dispatcher_clap_args(&args_str); + + // CMD type — always + if let Some(ref cmd) = parsed.cmd_type { + items.push(AnalyzeItem { + module: String::new(), + item_name: cmd.clone(), + }); + } + + // Error type — if error = TypeName + if let Some(ref err) = parsed.error_type { + items.push(AnalyzeItem { + module: String::new(), + item_name: err.clone(), + }); + } + + // Help internal struct — if help = true + // The dispatcher_clap macro generates: + // __{cmd_snake}_help (via `format!("__{}_help", snake_case(dispatcher_struct))`) + // The `#[help]` macro then generates: + // __internal_help_{fn_snake} (via `format!("__internal_help_{}", snake_case(fn_name))`) + // Final name: __internal_help_{snake_case("__{cmd_snake}_help")} + if parsed.help_enabled + && let Some(ref cmd) = parsed.cmd_type + { + let help_fn = format!("__{}_help", just_fmt::snake_case!(cmd)); + let help_struct = + format!("__internal_help_{}", just_fmt::snake_case!(&help_fn)); + items.push(AnalyzeItem { + module: String::new(), + item_name: help_struct, + }); + } + } } Item::Mod(item_mod) => { if let Some((_, nested)) = &item_mod.content { for n in nested { if let Item::Struct(s) = n - && has_attr(&s.attrs, "dispatcher_clap") { - items.push(AnalyzeItem { - module: item_mod.ident.to_string(), - item_name: s.ident.to_string(), - }); + && has_attr(&s.attrs, "dispatcher_clap") + { + let entry_name = s.ident.to_string(); + items.push(AnalyzeItem { + module: item_mod.ident.to_string(), + item_name: entry_name.clone(), + }); + + if let Some(attr) = s.attrs.iter().find(|a| { + a.path() + .segments + .last() + .is_some_and(|seg| seg.ident == "dispatcher_clap") + }) { + let args = attr.meta.require_list().ok(); + let args_str = + args.map(|l| l.tokens.to_string()).unwrap_or_default(); + let parsed = parse_dispatcher_clap_args(&args_str); + + if let Some(ref cmd) = parsed.cmd_type { + items.push(AnalyzeItem { + module: item_mod.ident.to_string(), + item_name: cmd.clone(), + }); + } + + if let Some(ref err) = parsed.error_type { + items.push(AnalyzeItem { + module: item_mod.ident.to_string(), + item_name: err.clone(), + }); + } + + // Help internal struct — same naming rule as root level + if parsed.help_enabled + && let Some(ref cmd) = parsed.cmd_type + { + let help_fn = + format!("__{}_help", just_fmt::snake_case!(cmd)); + let help_struct = format!( + "__internal_help_{}", + just_fmt::snake_case!(&help_fn) + ); + items.push(AnalyzeItem { + module: item_mod.ident.to_string(), + item_name: help_struct, + }); + } } + } } } } @@ -50,11 +148,78 @@ impl AnalyzePattern for DispatcherClapPattern { } } +struct ParsedClapArgs { + cmd_type: Option, + error_type: Option, + help_enabled: bool, +} + +/// Parse `#[dispatcher_clap("cmd", CMDType, error = ErrorType, help = true)]` arguments. +fn parse_dispatcher_clap_args(args: &str) -> ParsedClapArgs { + let mut cmd_type = None; + let mut error_type = None; + let mut help_enabled = false; + + let args = args.trim(); + + // Find the first quoted string (the command name) and skip it + // After that, look for ident-like tokens separated by commas + let after_cmd = if let Some(start) = args.find('"') { + let after_open = &args[start + 1..]; + if let Some(end) = after_open.find('"') { + after_open[end + 1..].trim() + } else { + args + } + } else { + args + }; + + // Split by commas and parse each part + for part in after_cmd.split(',') { + let part = part.trim(); + if part.is_empty() { + continue; + } + + // Skip the command name (first quoted string should already be removed) + if part.starts_with('"') { + continue; + } + + // Check for key = value + if let Some(eq_idx) = part.find('=') { + let key = part[..eq_idx].trim(); + let value = part[eq_idx + 1..].trim(); + let value = value.trim_end_matches([')', ']']).trim(); + + match key { + "error" => { + error_type = Some(value.to_string()); + } + "help" => { + help_enabled = value == "true"; + } + _ => {} + } + } else { + // Bare ident — the CMD type + let clean = part.trim_end_matches([')', ']']).trim(); + if !clean.is_empty() && cmd_type.is_none() { + cmd_type = Some(clean.to_string()); + } + } + } + + ParsedClapArgs { + cmd_type, + error_type, + help_enabled, + } +} + fn has_attr(attrs: &[syn::Attribute], name: &str) -> bool { - attrs.iter().any(|a| { - a.path() - .segments - .last() - .is_some_and(|s| s.ident == name) - }) + attrs + .iter() + .any(|a| a.path().segments.last().is_some_and(|s| s.ident == name)) } diff --git a/mingling_pathf/test/Cargo.lock b/mingling_pathf/test/Cargo.lock index 6c89ae3..e5fd23a 100644 --- a/mingling_pathf/test/Cargo.lock +++ b/mingling_pathf/test/Cargo.lock @@ -12,6 +12,7 @@ checksum = "5454cda0d57db59778608d7a47bff5b16c6705598265869fb052b657f66cf05e" name = "mingling_pathf" version = "0.2.0" dependencies = [ + "just_fmt", "proc-macro2", "syn", ] diff --git a/mingling_pathf/test/src/lib.rs b/mingling_pathf/test/src/lib.rs index 51e19a6..6fce3b2 100644 --- a/mingling_pathf/test/src/lib.rs +++ b/mingling_pathf/test/src/lib.rs @@ -315,12 +315,41 @@ fn test_dispatcher_clap_analyze() { let r = analyzer.analyze_file(file).unwrap(); let required: Vec<&str> = vec![ + // Root: entry types (bare dispatcher_clap, no params) "::EntryClap1", "::EntryClap2", "::EntryClap3", "::EntryClap4", + // Root: with CMD type + "::EntryWithCmd", + "::CMDGreet", + // Root: with CMD + error + "::EntryWithError", + "::CMDDelete", + "::ErrorDelete", + // Root: with CMD + help + "::EntryWithHelp", + "::CMDHelp", + "::__internal_help_cmdhelp_help", + // Root: with CMD + error + help + "::EntryFull", + "::CMDFull", + "::ErrorFull", + "::__internal_help_cmdfull_help", + // Sub: entry types (bare dispatcher_clap) "::sub::EntryClap1", "::sub::EntryClap3", + // Sub: with CMD type + "::sub::EntryWithCmd", + "::sub::CMDGreet", + // Sub: with CMD + error + "::sub::EntryWithError", + "::sub::CMDDelete", + "::sub::ErrorDelete", + // Sub: with CMD + help + "::sub::EntryWithHelp", + "::sub::CMDHelp", + "::sub::__internal_help_cmdhelp_help", ]; assert_eq!(r.len(), required.len()); diff --git a/mingling_pathf/test/src/test_files/test_dispatcher_clap.rs b/mingling_pathf/test/src/test_files/test_dispatcher_clap.rs index 0ba884d..33d86e0 100644 --- a/mingling_pathf/test/src/test_files/test_dispatcher_clap.rs +++ b/mingling_pathf/test/src/test_files/test_dispatcher_clap.rs @@ -1,3 +1,4 @@ +// Basic: entry type only (no CMD type specified) #[mingling::macros::dispatcher_clap] struct EntryClap1 { name: String, @@ -20,6 +21,30 @@ pub struct EntryClap4 { value: i32, } +// With CMD type +#[dispatcher_clap("greet", CMDGreet)] +struct EntryWithCmd { + name: String, +} + +// With CMD + error +#[dispatcher_clap("delete", CMDDelete, error = ErrorDelete)] +struct EntryWithError { + id: u64, +} + +// With CMD + help +#[dispatcher_clap("helpcmd", CMDHelp, help = true)] +struct EntryWithHelp { + verbose: bool, +} + +// With CMD + error + help +#[dispatcher_clap("full", CMDFull, error = ErrorFull, help = true)] +struct EntryFull { + all: bool, +} + pub mod sub { #[mingling::macros::dispatcher_clap] struct EntryClap1 { @@ -30,4 +55,19 @@ pub mod sub { struct EntryClap3 { value: String, } + + #[dispatcher_clap("greet", CMDGreet)] + struct EntryWithCmd { + name: String, + } + + #[dispatcher_clap("delete", CMDDelete, error = ErrorDelete)] + struct EntryWithError { + id: u64, + } + + #[dispatcher_clap("helpcmd", CMDHelp, help = true)] + struct EntryWithHelp { + verbose: bool, + } } -- cgit