aboutsummaryrefslogtreecommitdiff
path: root/mingling_macros/src
diff options
context:
space:
mode:
Diffstat (limited to 'mingling_macros/src')
-rw-r--r--mingling_macros/src/attr.rs2
-rw-r--r--mingling_macros/src/attr/command.rs365
-rw-r--r--mingling_macros/src/func/dispatcher.rs26
-rw-r--r--mingling_macros/src/func/gen_program.rs107
-rw-r--r--mingling_macros/src/func/program_comp_gen.rs4
-rw-r--r--mingling_macros/src/func/program_final_gen.rs122
-rw-r--r--mingling_macros/src/lib.rs87
-rw-r--r--mingling_macros/src/systems/dispatch_tree_gen.rs43
8 files changed, 577 insertions, 179 deletions
diff --git a/mingling_macros/src/attr.rs b/mingling_macros/src/attr.rs
index ed7f58b..8c17878 100644
--- a/mingling_macros/src/attr.rs
+++ b/mingling_macros/src/attr.rs
@@ -1,4 +1,6 @@
pub(crate) mod chain;
+#[cfg(feature = "extra_macros")]
+pub(crate) mod command;
#[cfg(feature = "comp")]
pub(crate) mod completion;
#[cfg(feature = "clap")]
diff --git a/mingling_macros/src/attr/command.rs b/mingling_macros/src/attr/command.rs
new file mode 100644
index 0000000..35c5c30
--- /dev/null
+++ b/mingling_macros/src/attr/command.rs
@@ -0,0 +1,365 @@
+use proc_macro::TokenStream;
+use proc_macro2::TokenStream as TokenStream2;
+use quote::quote;
+use syn::parse::{Parse, ParseStream};
+use syn::parse_macro_input;
+use syn::spanned::Spanned;
+use syn::token::Comma;
+use syn::{FnArg, Ident, ItemFn, LitStr, PatType, Token, Type};
+
+/// Parsed arguments for `#[command(...)]`.
+///
+/// Supports:
+/// - `node = "dot.separated.path"` — explicit command path
+/// - `name = CMDName` — explicit CMD struct name
+/// - `entry = EntryName` — explicit Entry struct name
+/// - bare paths like `routeify`, `::mingling::macros::routeify` — extension attrs for the original fn
+struct CommandArgs {
+ node: Option<LitStr>,
+ name: Option<Ident>,
+ entry: Option<Ident>,
+ exts: Vec<syn::Path>,
+}
+
+impl Parse for CommandArgs {
+ fn parse(input: ParseStream) -> syn::Result<Self> {
+ let mut node = None;
+ let mut name = None;
+ let mut entry = None;
+ let mut exts = Vec::new();
+
+ while !input.is_empty() {
+ if input.peek(Ident) && input.peek2(Token![=]) {
+ // key = value pair
+ let key: Ident = input.parse()?;
+ input.parse::<Token![=]>()?;
+
+ if key == "node" {
+ if node.is_some() {
+ return Err(input.error("duplicate `node` argument"));
+ }
+ node = Some(input.parse()?);
+ } else if key == "name" {
+ if name.is_some() {
+ return Err(input.error("duplicate `name` argument"));
+ }
+ name = Some(input.parse()?);
+ } else if key == "entry" {
+ if entry.is_some() {
+ return Err(input.error("duplicate `entry` argument"));
+ }
+ entry = Some(input.parse()?);
+ } else {
+ return Err(input.error(format!(
+ "unknown key `{}`; expected `node`, `name`, or `entry`",
+ key
+ )));
+ }
+ } else {
+ // Extension path (e.g. `routeify` or `::mingling::macros::routeify`)
+ let ext: syn::Path = input.parse()?;
+ exts.push(ext);
+ }
+
+ // Skip optional trailing comma
+ if input.peek(Comma) {
+ let _ = input.parse::<Comma>();
+ }
+ }
+
+ Ok(CommandArgs {
+ node,
+ name,
+ entry,
+ exts,
+ })
+ }
+}
+
+/// Returns the default node path as a dot-separated string, derived from the function name.
+///
+/// Example: `greet_someone` -> `"greet.someone"`, `greet` -> `"greet"`
+fn default_node_from_fn(fn_name: &Ident) -> String {
+ just_fmt::dot_case!(fn_name.to_string())
+}
+
+/// Checks basic function constraints for `#[command]`.
+/// Returns `Err(compile_error token stream)` on failure.
+fn validate_function(f: &ItemFn) -> Result<(), TokenStream2> {
+ if f.sig
+ .inputs
+ .iter()
+ .any(|arg| matches!(arg, FnArg::Receiver(_)))
+ {
+ return Err(syn::Error::new(
+ f.sig.span(),
+ "#[command] function cannot have a `self` parameter",
+ )
+ .to_compile_error());
+ }
+
+ Ok(())
+}
+
+/// Returns `(wrapper_async_token, await_call)` for the chain wrapper.
+///
+/// When the original function is async and the `async` feature is enabled,
+/// the wrapper needs to be `async` and call `.await` on the original function.
+/// Without the feature, async functions are rejected.
+fn handle_async(f: &ItemFn) -> Result<(TokenStream2, TokenStream2), TokenStream2> {
+ let is_async = f.sig.asyncness.is_some();
+
+ #[cfg(not(feature = "async"))]
+ if is_async {
+ return Err(syn::Error::new(
+ f.sig.span(),
+ "#[command] function cannot be async when the `async` feature is disabled",
+ )
+ .to_compile_error());
+ }
+
+ let wrapper_async = is_async.then_some(quote! { async }).unwrap_or_default();
+ let await_call = is_async.then_some(quote! { .await }).unwrap_or_default();
+ Ok((wrapper_async, await_call))
+}
+
+/// All resolved identifiers derived from `#[command]` arguments + function name.
+struct ResolvedNames {
+ /// `node_str` as a string literal token
+ node_lit: LitStr,
+ /// Whether the user supplied any explicit override (node/name/entry)
+ has_overrides: bool,
+ /// CMD struct name (e.g. `CMDGreet`)
+ cmd_name: Ident,
+ /// Entry struct name (e.g. `EntryGreet`)
+ entry_type: Ident,
+ /// Chain wrapper function name (e.g. `__command_chain_greet`)
+ chain_fn_name: Ident,
+}
+
+/// Resolves `node`, `cmd_name`, `entry_type`, and `chain_fn_name` from
+/// the attribute args and the original function name.
+fn resolve_names(fn_name: &Ident, args: &CommandArgs) -> ResolvedNames {
+ let fn_name_str = fn_name.to_string();
+
+ let node_str = match &args.node {
+ Some(lit) => lit.value(),
+ None => default_node_from_fn(fn_name),
+ };
+ let node_lit = syn::LitStr::new(&node_str, fn_name.span());
+
+ let has_overrides = args.node.is_some() || args.name.is_some() || args.entry.is_some();
+
+ let cmd_name = args.name.clone().unwrap_or_else(|| {
+ let pascal = just_fmt::pascal_case!(&node_str);
+ Ident::new(&format!("CMD{pascal}"), fn_name.span())
+ });
+
+ let entry_type = args.entry.clone().unwrap_or_else(|| {
+ let pascal = just_fmt::pascal_case!(&node_str);
+ Ident::new(&format!("Entry{pascal}"), fn_name.span())
+ });
+
+ let chain_fn_name = Ident::new(&format!("__command_chain_{}", fn_name_str), fn_name.span());
+
+ ResolvedNames {
+ node_lit,
+ has_overrides,
+ cmd_name,
+ entry_type,
+ chain_fn_name,
+ }
+}
+
+/// Converts extension paths into `#[ext]` attribute token streams.
+fn build_ext_attrs(exts: &[syn::Path]) -> Vec<TokenStream2> {
+ exts.iter().map(|ext| quote! { #[#ext] }).collect()
+}
+
+/// Returns `true` if the function has a first non-reference (owned) parameter that
+/// serves as the "args" input.
+fn has_args_param(sig: &syn::Signature) -> bool {
+ sig.inputs.first().map_or(false, |arg| {
+ if let FnArg::Typed(pat_type) = arg {
+ !matches!(&*pat_type.ty, Type::Reference(_))
+ } else {
+ false
+ }
+ })
+}
+
+/// Builds the wrapper function's parameter list.
+///
+/// - If the function has an "args" param (first non-reference): replaces its type
+/// with the entry type (e.g. `Vec<String>` → `EntryGreet`).
+/// - If not (no params, or first param is a reference): inserts a new entry param
+/// at the front to satisfy `#[chain]`'s requirement for an owned first parameter.
+fn build_wrapper_params(
+ sig: &syn::Signature,
+ entry_type: &Ident,
+) -> syn::punctuated::Punctuated<FnArg, syn::token::Comma> {
+ if has_args_param(sig) {
+ // First param is owned (args) -> replace its type with entry type
+ let mut params = sig.inputs.clone();
+ if let Some(FnArg::Typed(first)) = params.first_mut() {
+ first.ty = Box::new(Type::Path(syn::TypePath {
+ qself: None,
+ path: syn::Path::from(entry_type.clone()),
+ }));
+ }
+ params
+ } else {
+ // No args param -> insert an entry param at the front, keep rest as-is
+ let mut params = syn::punctuated::Punctuated::new();
+ let entry_param: FnArg = syn::parse_quote! { _args: #entry_type };
+ params.push(entry_param);
+ for arg in sig.inputs.iter() {
+ params.push(arg.clone());
+ }
+ params
+ }
+}
+
+/// Builds call arguments for the original function call inside the wrapper.
+///
+/// - If the function has an "args" param (first non-reference): first arg gets
+/// `.into()` (converts `EntryGreet` → `Vec<String>`), rest pass through as-is.
+/// - If not (no args): all params are resources — pass none, return empty.
+fn build_call_args(sig: &syn::Signature) -> Vec<TokenStream2> {
+ let has_args = has_args_param(sig);
+ sig.inputs
+ .iter()
+ .enumerate()
+ .map(|(i, arg)| {
+ let pat = match arg {
+ FnArg::Typed(PatType { pat, .. }) => quote! { #pat },
+ FnArg::Receiver(_) => unreachable!(),
+ };
+ if has_args && i == 0 {
+ quote! { #pat.into() }
+ } else {
+ pat
+ }
+ })
+ .collect()
+}
+
+/// Generates the `dispatcher!(...)` call.
+///
+/// - No overrides → abbreviated form: `dispatcher!("node")`
+/// - Any override → explicit form: `dispatcher!("node", CMDName => EntryName)`
+fn build_dispatcher_invoke(names: &ResolvedNames) -> TokenStream2 {
+ let node_lit = &names.node_lit;
+ if names.has_overrides {
+ let cmd_name = &names.cmd_name;
+ let entry_type = &names.entry_type;
+ quote! { ::mingling::macros::dispatcher!(#node_lit, #cmd_name => #entry_type); }
+ } else {
+ quote! { ::mingling::macros::dispatcher!(#node_lit); }
+ }
+}
+
+pub(crate) fn command_attr(attr: TokenStream, item: TokenStream) -> TokenStream {
+ let input_fn = parse_macro_input!(item as ItemFn);
+
+ // validation
+ if let Err(err) = validate_function(&input_fn) {
+ return err.into();
+ }
+
+ // parse attribute
+ let args: CommandArgs = if attr.is_empty() {
+ CommandArgs {
+ node: None,
+ name: None,
+ entry: None,
+ exts: Vec::new(),
+ }
+ } else {
+ parse_macro_input!(attr as CommandArgs)
+ };
+
+ // async handling
+ let (wrapper_async, await_call) = match handle_async(&input_fn) {
+ Ok(pair) => pair,
+ Err(err) => return err.into(),
+ };
+
+ // resolve node / name / entry
+ let fn_name = &input_fn.sig.ident;
+ let names = resolve_names(fn_name, &args);
+ let chain_fn_name = &names.chain_fn_name;
+
+ // build extension attributes (applied to the ORIGINAL function)
+ let ext_attrs = build_ext_attrs(&args.exts);
+
+ // build wrapper
+ let wrapper_params = build_wrapper_params(&input_fn.sig, &names.entry_type);
+ let call_args = build_call_args(&input_fn.sig);
+
+ // build dispatcher invocation
+ let dispatcher_invoke = build_dispatcher_invoke(&names);
+
+ // preserve original function
+ let mut fn_attrs = input_fn.attrs.clone();
+ fn_attrs.retain(|attr| !attr.path().is_ident("command"));
+
+ let vis = &input_fn.vis;
+ let asyncness = input_fn.sig.asyncness;
+ let generics = &input_fn.sig.generics;
+ let orig_params = &input_fn.sig.inputs;
+ let orig_return = &input_fn.sig.output;
+ let fn_body = &input_fn.block;
+
+ // compute names for the re‑export module and internal structs
+ let fn_name_s = fn_name.to_string();
+ let mod_name = Ident::new(&format!("__command_{}_module", &fn_name_s), fn_name.span());
+ let wrapper_full = format!("__command_chain_{}", &fn_name_s);
+ let snaked_wrapper = just_fmt::snake_case!(wrapper_full);
+ let chain_internal = Ident::new(
+ &format!("__internal_chain_{}", snaked_wrapper),
+ fn_name.span(),
+ );
+
+ // dispatcher internal static (only exists with dispatch_tree feature)
+ #[cfg(feature = "dispatch_tree")]
+ let snaked_node = just_fmt::snake_case!(names.node_lit.value());
+ #[cfg(feature = "dispatch_tree")]
+ let dispatcher_internal = {
+ let ident = Ident::new(
+ &format!("__internal_dispatcher_{}", snaked_node),
+ fn_name.span(),
+ );
+ quote! { #vis use super::#ident; }
+ };
+ #[cfg(not(feature = "dispatch_tree"))]
+ let dispatcher_internal = quote! {};
+
+ let cmd_name = &names.cmd_name;
+ let entry_type = &names.entry_type;
+
+ // assemble output
+ let expanded = quote! {
+ #dispatcher_invoke
+
+ #[::mingling::macros::chain]
+ #vis #wrapper_async fn #chain_fn_name #generics(#wrapper_params) -> crate::Next {
+ #fn_name(#(#call_args),*)#await_call.into()
+ }
+
+ #(#fn_attrs)*
+ #(#ext_attrs)*
+ #vis #asyncness fn #fn_name #generics(#orig_params) #orig_return #fn_body
+
+ // hidden module gathering all generated types for pathf / external access
+ #[doc(hidden)]
+ #vis mod #mod_name {
+ #vis use super::#cmd_name;
+ #vis use super::#entry_type;
+ #vis use super::#chain_internal;
+ #dispatcher_internal
+ }
+ };
+
+ expanded.into()
+}
diff --git a/mingling_macros/src/func/dispatcher.rs b/mingling_macros/src/func/dispatcher.rs
index 4e7c42f..ef02618 100644
--- a/mingling_macros/src/func/dispatcher.rs
+++ b/mingling_macros/src/func/dispatcher.rs
@@ -99,7 +99,7 @@ pub(crate) fn dispatcher(input: TokenStream) -> TokenStream {
command_name,
} => {
let command_name_str = command_name.value();
- let pascal = dotted_to_pascal_case(&command_name_str);
+ let pascal = just_fmt::pascal_case!(&command_name_str);
let command_struct = Ident::new(&format!("CMD{pascal}"), command_name.span());
let pack = Ident::new(&format!("Entry{pascal}"), command_name.span());
(command_name, command_struct, pack, cmd_attrs, Vec::new())
@@ -121,6 +121,12 @@ pub(crate) fn dispatcher(input: TokenStream) -> TokenStream {
::mingling::macros::pack!(#(#entry_attrs)* #pack = Vec<String>);
+ impl From<#pack> for crate::Entry {
+ fn from(value: #pack) -> Self {
+ crate::Entry::new(value.inner)
+ }
+ }
+
#comp_entry
#dispatch_tree_entry
@@ -178,21 +184,3 @@ fn get_dispatch_tree_entry(
) -> TokenStream2 {
quote! {}
}
-
-/// Converts a dotted command name (e.g. "remote.add") to `PascalCase` (e.g. "`RemoteAdd`").
-///
-/// Each segment is split by `.`, the first character of each segment is uppercased,
-/// and the segments are joined. This is used by the abbreviated `dispatcher!` syntax
-/// (when `Command => Entry` is omitted) to auto-derive struct names.
-#[cfg(feature = "extra_macros")]
-pub(crate) fn dotted_to_pascal_case(s: &str) -> String {
- s.split('.')
- .map(|segment| {
- let mut chars = segment.chars();
- match chars.next() {
- None => String::new(),
- Some(c) => c.to_uppercase().to_string() + chars.as_str(),
- }
- })
- .collect()
-}
diff --git a/mingling_macros/src/func/gen_program.rs b/mingling_macros/src/func/gen_program.rs
index c5358bc..d50041e 100644
--- a/mingling_macros/src/func/gen_program.rs
+++ b/mingling_macros/src/func/gen_program.rs
@@ -15,33 +15,100 @@ pub(crate) fn gen_program_impl(_input: TokenStream) -> TokenStream {
#[cfg(not(feature = "comp"))]
let comp_gen = quote! {};
+ // When pathf is enabled, load the type_using.rs generated by the build script
+ // and emit its use statements so types from submodules are in scope.
+ #[cfg(feature = "pathf")]
+ let pathf_uses: Vec<proc_macro2::TokenStream> = {
+ let uses = load_pathf_uses();
+ if uses.is_empty() {
+ // The file might not exist yet — emit a clear hint
+ let hint: proc_macro2::TokenStream = syn::parse_quote! {
+ compile_error!(
+ "pathf: `{}` not found or empty.\n\
+ Make sure `build.rs` calls `mingling::build::analyze_and_build_type_mapping().unwrap();`\n\
+ with features [\"build\", \"pathf\"] enabled."
+ );
+ };
+ vec![hint]
+ } else {
+ uses
+ }
+ };
+ #[cfg(not(feature = "pathf"))]
+ let pathf_uses: Vec<proc_macro2::TokenStream> = Vec::new();
+
+ #[cfg(feature = "pathf")]
+ let super_use = quote! {};
+
+ #[cfg(not(feature = "pathf"))]
+ let super_use = quote! {
+ use super::*;
+ };
+
TokenStream::from(quote! {
- /// 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))
+ pub use __this_program_impl::*;
+
+ #[doc(hidden)]
+ pub mod __this_program_impl {
+ #super_use
+ #(#pathf_uses)*
+
+ /// Alias for the current program type `ThisProgram`
+ pub type Next = ::mingling::ChainProcess<ThisProgram>;
+
+ ::mingling::macros::pack!(Entry = Vec<String>);
+
+ impl ::mingling::Routable<ThisProgram> for ::mingling::ChainProcess<ThisProgram>
+ {
+ fn to_chain(self) -> ::mingling::ChainProcess<ThisProgram> {
+ match self {
+ ::mingling::ChainProcess::Ok((any, _)) => {
+ ::mingling::ChainProcess::Ok((any, mingling::NextProcess::Chain))
+ }
+ other => other,
}
- other => other,
}
- }
- fn to_render(self) -> ::mingling::ChainProcess<crate::ThisProgram> {
- match self {
- ::mingling::ChainProcess::Ok((any, _)) => {
- ::mingling::ChainProcess::Ok((any, mingling::NextProcess::Renderer))
+ fn to_render(self) -> ::mingling::ChainProcess<ThisProgram> {
+ match self {
+ ::mingling::ChainProcess::Ok((any, _)) => {
+ ::mingling::ChainProcess::Ok((any, mingling::NextProcess::Renderer))
+ }
+ other => other,
}
- other => other,
}
}
- }
- #comp_gen
- ::mingling::macros::program_fallback_gen!();
- ::mingling::macros::program_final_gen!();
+ #comp_gen
+ ::mingling::macros::program_fallback_gen!();
+ ::mingling::macros::program_final_gen!();
+ }
})
}
+
+/// Loads `type_using.rs` generated by the pathf build script and returns each
+/// `use ...;` line as a token stream, ready to be emitted in the generated output.
+#[cfg(feature = "pathf")]
+fn load_pathf_uses() -> Vec<proc_macro2::TokenStream> {
+ let out_dir = match std::env::var("OUT_DIR") {
+ Ok(d) => d,
+ Err(_) => return Vec::new(),
+ };
+ let crate_name = match std::env::var("CARGO_PKG_NAME") {
+ Ok(n) => n,
+ Err(_) => return Vec::new(),
+ };
+ let path = std::path::Path::new(&out_dir)
+ .join(&crate_name)
+ .join("type_using.rs");
+ let content = match std::fs::read_to_string(&path) {
+ Ok(c) => c,
+ Err(_) => return Vec::new(),
+ };
+ content
+ .lines()
+ .map(|line| line.trim().to_string())
+ .filter(|line| !line.is_empty())
+ .filter_map(|line| line.parse::<proc_macro2::TokenStream>().ok())
+ .collect()
+}
diff --git a/mingling_macros/src/func/program_comp_gen.rs b/mingling_macros/src/func/program_comp_gen.rs
index b6b2546..2fbb0e0 100644
--- a/mingling_macros/src/func/program_comp_gen.rs
+++ b/mingling_macros/src/func/program_comp_gen.rs
@@ -14,7 +14,7 @@ pub(crate) fn program_comp_gen_impl(_input: TokenStream) -> TokenStream {
match read_ctx {
Ok(ctx) => {
let suggest = ::mingling::CompletionHelper::exec_completion::<crate::ThisProgram>(&ctx);
- ::mingling::Routable::<crate::ThisProgram>::to_render(crate::CompletionSuggest::new((ctx, suggest)))
+ ::mingling::Routable::<crate::ThisProgram>::to_render(CompletionSuggest::new((ctx, suggest)))
}
Err(_) => std::process::exit(1),
}
@@ -32,7 +32,7 @@ pub(crate) fn program_comp_gen_impl(_input: TokenStream) -> TokenStream {
match read_ctx {
Ok(ctx) => {
let suggest = ::mingling::CompletionHelper::exec_completion::<crate::ThisProgram>(&ctx);
- ::mingling::Routable::<crate::ThisProgram>::to_render(crate::CompletionSuggest::new((ctx, suggest)))
+ ::mingling::Routable::<crate::ThisProgram>::to_render(CompletionSuggest::new((ctx, suggest)))
}
Err(_) => std::process::exit(1),
}
diff --git a/mingling_macros/src/func/program_final_gen.rs b/mingling_macros/src/func/program_final_gen.rs
index d3af3b3..0eed1db 100644
--- a/mingling_macros/src/func/program_final_gen.rs
+++ b/mingling_macros/src/func/program_final_gen.rs
@@ -1,5 +1,3 @@
-use std::collections::HashMap;
-
use proc_macro::TokenStream;
use quote::quote;
@@ -37,48 +35,12 @@ fn parse_entry_pair(entry: &proc_macro2::TokenStream) -> (proc_macro2::Ident, pr
(struct_ident, variant_ident)
}
-/// Loads the pathf type mapping from `$OUT_DIR/{crate}/type_using.rs`.
-fn load_pathf_map() -> Option<std::collections::HashMap<String, String>> {
- if !cfg!(feature = "pathf") {
- return None;
- }
- let out_dir = std::env::var("OUT_DIR").ok()?;
- let crate_name = std::env::var("CARGO_PKG_NAME").ok()?;
- let path = std::path::Path::new(&out_dir)
- .join(&crate_name)
- .join("type_using.rs");
- let content = std::fs::read_to_string(&path).ok()?;
- Some(
- content
- .lines()
- .filter_map(|line| {
- let line = line.trim();
- if let Some(rest) = line.strip_prefix("use ") {
- let path = rest.strip_suffix(';').unwrap_or(rest);
- if let Some((_mod, type_name)) = path.rsplit_once("::") {
- return Some((type_name.to_string(), path.to_string()));
- }
- }
- None
- })
- .collect(),
- )
-}
-
-/// Resolves a type name to its full path token stream using the pathf mapping.
-pub(crate) fn resolve_type(
- name: &str,
- map: &std::collections::HashMap<String, String>,
-) -> proc_macro2::TokenStream {
- if let Some(full_path) = map.get(name) {
- syn::parse_str::<proc_macro2::TokenStream>(full_path).unwrap_or_else(|_| {
- let ident = proc_macro2::Ident::new(name, proc_macro2::Span::call_site());
- quote! { #ident }
- })
- } else {
- let ident = proc_macro2::Ident::new(name, proc_macro2::Span::call_site());
- quote! { #ident }
- }
+/// Helper: convert a string ident into a token stream for the generated code.
+/// Types are expected to be in scope (e.g. via pathf glob re-exports), so bare
+/// idents suffice.
+fn ident_tokens(name: &str) -> proc_macro2::TokenStream {
+ let ident = proc_macro2::Ident::new(name, proc_macro2::Span::call_site());
+ quote! { #ident }
}
#[allow(clippy::too_many_lines)]
@@ -126,45 +88,6 @@ pub(crate) fn program_final_gen_impl(_input: TokenStream) -> TokenStream {
.map(|s| syn::parse_str::<proc_macro2::TokenStream>(s).unwrap())
.collect();
- let pathf_map: Option<HashMap<String, String>> = load_pathf_map();
-
- #[cfg(feature = "pathf")]
- let pathf_hint: proc_macro2::TokenStream = if pathf_map.is_none() {
- quote! {
- compile_error!(
-"Cannot load type mapping computed by `pathf`.
-If not yet configured, execute `mingling::build::analyze_and_build_type_mapping()` in your `build.rs`.
-
-fn main() {
- // Require features: [\"builds\", \"pathf\"]
- mingling::build::analyze_and_build_type_mapping().unwrap();
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\__ Write to `build.rs`
-
-}
- ");
- }
- } else {
- quote! {}
- };
-
- #[cfg(not(feature = "pathf"))]
- let pathf_hint: proc_macro2::TokenStream = quote! {};
-
- let pathf_map: HashMap<String, String> = if cfg!(feature = "pathf") {
- pathf_map.unwrap_or_default()
- } else {
- HashMap::new()
- };
-
- let pathf_uses: Vec<proc_macro2::TokenStream> = if cfg!(feature = "pathf") {
- pathf_map
- .values()
- .map(|path| format!("use {};", path).parse().unwrap_or_default())
- .collect()
- } else {
- Vec::new()
- };
-
#[cfg(feature = "structural_renderer")]
let structural_renderer_tokens: Vec<proc_macro2::TokenStream> = structural_renderers
.iter()
@@ -177,13 +100,9 @@ fn main() {
any: ::mingling::AnyOutput<Self::Enum>,
setting: &::mingling::StructuralRendererSetting,
) -> Result<::mingling::RenderResult, ::mingling::error::StructuralRendererSerializeError> {
- #[allow(unused_imports)]
- #(#pathf_uses)*
match any.member_id() {
#(#structural_renderer_tokens)*
_ => {
- // Non-structural types: render ResultEmpty (which implements
- // StructuralData + Serialize) instead of producing nothing.
let mut r = ::mingling::RenderResult::default();
::mingling::StructuralRenderer::render(&ResultEmpty, setting, &mut r)?;
Ok(r)
@@ -222,8 +141,8 @@ fn main() {
})
.collect();
- let get_nodes_fn = dispatch_tree_gen::gen_get_nodes(&entries, &pathf_map);
- let dispatch_trie_fn = dispatch_tree_gen::gen_dispatch_args_trie(&entries, &pathf_map);
+ let get_nodes_fn = dispatch_tree_gen::gen_get_nodes(&entries);
+ let dispatch_trie_fn = dispatch_tree_gen::gen_dispatch_args_trie(&entries);
quote! {
#get_nodes_fn
@@ -243,8 +162,6 @@ fn main() {
#[cfg(feature = "comp")]
let comp = quote! {
fn do_comp(any: &::mingling::AnyOutput<Self::Enum>, ctx: &::mingling::ShellContext) -> ::mingling::Suggest {
- #[allow(unused_imports)]
- #(#pathf_uses)*
match any.member_id() {
#(#completion_tokens)*
_ => ::mingling::Suggest::FileCompletion,
@@ -266,12 +183,10 @@ fn main() {
} else {
let render_arms: Vec<_> = renderer_tokens.iter().map(|entry| {
let (struct_ident, variant_ident) = parse_entry_pair(entry);
- let downcast_ty = resolve_type(&variant_ident.to_string(), &pathf_map);
- let resolved_struct = resolve_type(&struct_ident.to_string(), &pathf_map);
+ let downcast_ty = ident_tokens(&variant_ident.to_string());
+ let resolved_struct = ident_tokens(&struct_ident.to_string());
quote! {
Self::#variant_ident => {
- // SAFETY: The `type_id` check ensures that `any` contains a value of type `#variant_ident`,
- // so downcasting to `#variant_ident` is safe.
let value = unsafe { any.downcast::<#downcast_ty>().unwrap_unchecked() };
<#resolved_struct as ::mingling::Renderer>::render(value)
}
@@ -290,12 +205,10 @@ fn main() {
// Build do_chain function (async and sync versions)
let chain_arms_async: Vec<_> = chain_tokens.iter().map(|entry| {
let (struct_ident, variant_ident) = parse_entry_pair(entry);
- let downcast_ty = resolve_type(&variant_ident.to_string(), &pathf_map);
- let resolved_struct = resolve_type(&struct_ident.to_string(), &pathf_map);
+ let downcast_ty = ident_tokens(&variant_ident.to_string());
+ let resolved_struct = ident_tokens(&struct_ident.to_string());
quote! {
Self::#variant_ident => {
- // SAFETY: The `type_id` check ensures that `any` contains a value of type `#variant_ident`,
- // so downcasting to `#variant_ident` is safe.
let value = unsafe { any.downcast::<#downcast_ty>().unwrap_unchecked() };
let fut = async { <#resolved_struct as ::mingling::Chain<Self::Enum>>::proc(value).await };
::std::boxed::Box::pin(fut)
@@ -307,12 +220,10 @@ fn main() {
.iter()
.map(|entry| {
let (struct_ident, variant_ident) = parse_entry_pair(entry);
- let downcast_ty = resolve_type(&variant_ident.to_string(), &pathf_map);
- let resolved_struct = resolve_type(&struct_ident.to_string(), &pathf_map);
+ let downcast_ty = ident_tokens(&variant_ident.to_string());
+ let resolved_struct = ident_tokens(&struct_ident.to_string());
quote! {
Self::#variant_ident => {
- // SAFETY: The `type_id` check ensures that `any` contains a value of type `#variant_ident`,
- // so downcasting to `#variant_ident` is safe.
let value = unsafe { any.downcast::<#downcast_ty>().unwrap_unchecked() };
<#resolved_struct as ::mingling::Chain<Self::Enum>>::proc(value)
}
@@ -370,8 +281,6 @@ fn main() {
};
let expanded = quote! {
- #pathf_hint
-
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[repr(#repr_type)]
#[allow(nonstandard_style)]
@@ -392,6 +301,7 @@ fn main() {
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()))
}
@@ -404,8 +314,6 @@ fn main() {
#render_fn
#do_chain_fn
fn render_help(any: ::mingling::AnyOutput<Self::Enum>) -> ::mingling::RenderResult {
- #[allow(unused_imports)]
- #(#pathf_uses)*
match any.member_id() {
#(#help_tokens)*
_ => ::mingling::RenderResult::default(),
diff --git a/mingling_macros/src/lib.rs b/mingling_macros/src/lib.rs
index 27563a4..ae874af 100644
--- a/mingling_macros/src/lib.rs
+++ b/mingling_macros/src/lib.rs
@@ -1100,6 +1100,93 @@ pub fn program_setup(attr: TokenStream, item: TokenStream) -> TokenStream {
program_setup::setup_attr(attr, item)
}
+/// Declares a command from a plain function.
+///
+/// **This macro is only available with the `extra_macros` feature.**
+///
+/// The `#[command]` attribute converts a function taking `Vec<String>` into a
+/// Mingling command by:
+/// 1. Calling `dispatcher!("command_name")` to register the dispatcher entry.
+/// 2. Generating a `#[chain]` wrapper that bridges the entry type (`Entry{Pascal}`)
+/// to the original function.
+/// 3. Preserving the original function unchanged (including attributes, extensions,
+/// visibility, and asyncness).
+///
+/// # Syntax
+///
+/// ## Simple form (auto-derives names from function name)
+///
+/// ```rust,ignore
+/// #[command]
+/// fn greet(args: Vec<String>) -> Next {
+/// // ...
+/// }
+/// ```
+///
+/// This deduces:
+/// - Command path: `"greet"` (via `dot_case` of function name)
+/// - Dispatcher struct: `CMDGreet`
+/// - Entry struct: `EntryGreet`
+/// - Dispatches via `dispatcher!("greet")`
+///
+/// ## Explicit attributes
+///
+/// ```rust,ignore
+/// #[command(node = "hello.world")]
+/// fn greet(args: Vec<String>) -> Next {
+/// // ...
+/// }
+/// // → dispatcher!("hello.world", CMDGreet => EntryGreet)
+/// ```
+///
+/// ```rust,ignore
+/// #[command(name = MyDispatcher, entry = MyEntry)]
+/// fn greet(args: Vec<String>) -> Next {
+/// // ...
+/// }
+/// // → dispatcher!("greet", MyDispatcher => MyEntry)
+/// ```
+///
+/// ## Extension attributes
+///
+/// Extra bare paths (e.g. `buffer`, `routeify`, `::mingling::macros::routeify`)
+/// are emitted as `#[ext]` attributes **on the original function**, not on the
+/// chain wrapper. The chain wrapper always uses bare `#[::mingling::macros::chain]`.
+///
+/// ```rust,ignore
+/// #[command(buffer)]
+/// fn greet(args: Vec<String>) {
+/// r_println!("Hello!");
+/// }
+/// ```
+///
+/// # Resource injection
+///
+/// Parameters after the first are treated as resource injections and passed
+/// through to the generated `#[chain]` wrapper unchanged (as reference params):
+///
+/// ```rust,ignore
+/// #[command]
+/// fn greet(args: Vec<String>, ec: &mut ResExitCode) -> Next {
+/// ec.exit_code = 0;
+/// // ...
+/// }
+/// ```
+///
+/// The generated chain wrapper calls the original function with `entry.into()`
+/// for the first argument and passes all subsequent arguments directly.
+///
+/// # Requirements
+///
+/// - The function must have at least one parameter (the `Vec<String>` entry argument).
+/// - The function must not have a `self` parameter.
+/// - Visibility (`pub` etc.) and `async` are preserved on the original function.
+#[cfg(feature = "extra_macros")]
+#[proc_macro_attribute]
+pub fn command(attr: TokenStream, item: TokenStream) -> TokenStream {
+ attr::command::command_attr(attr, item)
+}
+
/// Declares a `Dispatcher` that uses `clap::Parser` for argument parsing.
///
/// **This macro is only available with the `clap` feature.**
diff --git a/mingling_macros/src/systems/dispatch_tree_gen.rs b/mingling_macros/src/systems/dispatch_tree_gen.rs
index 9eeb637..fe44a49 100644
--- a/mingling_macros/src/systems/dispatch_tree_gen.rs
+++ b/mingling_macros/src/systems/dispatch_tree_gen.rs
@@ -1,27 +1,22 @@
-use std::collections::{BTreeMap, HashMap};
+use std::collections::BTreeMap;
use just_fmt::snake_case;
use proc_macro2::TokenStream;
use quote::quote;
-use crate::func::program_final_gen::resolve_type;
-
/// Generate the `get_nodes()` function body for a ProgramCollect impl.
-/// If `pathf_map` is non-empty, resolves internal dispatcher statics using full paths.
-pub(crate) fn gen_get_nodes(
- entries: &[(String, String, String)],
- pathf_map: &HashMap<String, String>,
-) -> TokenStream {
+pub(crate) fn gen_get_nodes(entries: &[(String, String, String)]) -> TokenStream {
let mut node_entries = Vec::new();
for (node_name, _disp_type, _entry_name) in entries {
let static_name_str = format!("__internal_dispatcher_{}", snake_case!(node_name));
- let resolved = resolve_type(&static_name_str, pathf_map);
+ let static_ident =
+ proc_macro2::Ident::new(&static_name_str, proc_macro2::Span::call_site());
let node_display_name = node_name.replace('.', " ");
let node_display_lit = syn::LitStr::new(&node_display_name, proc_macro2::Span::call_site());
node_entries.push(quote! {
- (#node_display_lit.to_string(), & #resolved)
+ (#node_display_lit.to_string(), &#static_ident)
});
}
@@ -38,20 +33,13 @@ pub(crate) fn gen_get_nodes(
///
/// Builds a hardcoded match tree: at each depth, group nodes by character.
/// Single-node groups use `starts_with`; multi-node groups recurse with `nth()` match.
-///
-/// If `pathf_map` is non-empty, resolves dispatcher types using full paths.
-pub(crate) fn gen_dispatch_args_trie(
- entries: &[(String, String, String)],
- pathf_map: &HashMap<String, String>,
-) -> TokenStream {
- // Prepare (display_name, disp_type) pairs.
- // display_name = node_name.replace('.', " ")
+pub(crate) fn gen_dispatch_args_trie(entries: &[(String, String, String)]) -> TokenStream {
let nodes: Vec<(String, String)> = entries
.iter()
.map(|(name, disp, _)| (name.replace('.', " "), disp.clone()))
.collect();
- let dispatch_body = build_dispatch_body(&nodes, 0, pathf_map);
+ let dispatch_body = build_dispatch_body(&nodes, 0);
quote! {
fn dispatch_args_trie(
@@ -70,19 +58,13 @@ pub(crate) fn gen_dispatch_args_trie(
///
/// `nodes`: slice of (display_name, disp_type) for commands that share the same prefix so far.
/// `depth`: The character index currently being matched.
-/// `pathf_map`: optional mapping from type name to full path for resolving dispatchers.
-fn build_dispatch_body(
- nodes: &[(String, String)],
- depth: usize,
- pathf_map: &HashMap<String, String>,
-) -> TokenStream {
+fn build_dispatch_body(nodes: &[(String, String)], depth: usize) -> TokenStream {
if nodes.is_empty() {
return quote! {
return Ok(Self::build_dispatcher_not_found(raw.to_vec()));
};
}
- // Group by character at `depth`
let mut groups: BTreeMap<char, Vec<(String, String)>> = BTreeMap::new();
let mut exact_nodes: Vec<(String, String)> = Vec::new();
@@ -97,18 +79,17 @@ fn build_dispatch_body(
}
}
- // Build a dispatch arm for a single node via `starts_with`
let make_starts_with_arm = |name: &str, disp_type: &str| -> TokenStream {
let name_space = format!("{} ", name);
let name_lit = syn::LitStr::new(&name_space, proc_macro2::Span::call_site());
- let disp_resolved = resolve_type(disp_type, pathf_map);
+ let disp_ident = proc_macro2::Ident::new(disp_type, proc_macro2::Span::call_site());
let prefix_word_count = name.split_whitespace().count();
quote! {
if raw_str.starts_with(#name_lit) {
let prefix_len = #prefix_word_count;
let trimmed_args: Vec<String> = raw.iter().skip(prefix_len).cloned().collect();
- let __cp = <#disp_resolved as ::mingling::Dispatcher<Self::Enum>>::begin(
- &#disp_resolved::default(),
+ let __cp = <#disp_ident as ::mingling::Dispatcher<Self::Enum>>::begin(
+ &#disp_ident::default(),
trimmed_args,
);
return match __cp {
@@ -136,7 +117,7 @@ fn build_dispatch_body(
}
});
} else {
- let sub_body = build_dispatch_body(sub_nodes, depth + 1, pathf_map);
+ let sub_body = build_dispatch_body(sub_nodes, depth + 1);
arms.push(quote! {
Some(#ch_char) => {
#sub_body