mod activation;
mod client;
mod method_enum;
use crate::parse::{
extract_doc_description, find_and_validate_list_search_method, has_child_attr,
has_method_attr, parse_deprecation_attrs, ChildMethodInfo, ChildMethodKind, HubMethodAttrs,
HubMethodsAttrs, ListSearchKind, ListSearchMethodInfo, MethodInfo, ParsedDeprecation,
};
use proc_macro2::{Span, TokenStream};
use proc_macro_crate::{crate_name, FoundCrate};
use quote::{format_ident, quote};
use syn::{spanned::Spanned, FnArg, ImplItem, ItemImpl, Meta, Type};
pub(crate) fn umbrella_crate(err_span: Span) -> Option<syn::Ident> {
match crate_name("plexus-rpc") {
Ok(FoundCrate::Name(name)) => Some(syn::Ident::new(&name, err_span)),
_ => None,
}
}
pub(crate) fn deps_shim(shim_ident: &syn::Ident, err_span: Span) -> TokenStream {
match umbrella_crate(err_span) {
Some(umbrella) => quote! {
#[doc(hidden)]
#[allow(unused_imports, non_snake_case)]
mod #shim_ident {
pub use ::#umbrella::__deps::{
async_trait, futures, jsonrpsee, schemars, serde, serde_json, tokio, uuid,
};
}
},
None => quote! {
#[doc(hidden)]
#[allow(unused_imports, non_snake_case)]
mod #shim_ident {
pub use ::async_trait;
pub use ::futures;
pub use ::jsonrpsee;
pub use ::schemars;
pub use ::serde;
pub use ::serde_json;
pub use ::tokio;
pub use ::uuid;
}
},
}
}
pub(crate) fn derive_core_path(err_span: Span) -> syn::Path {
match crate_name("plexus-core") {
Ok(FoundCrate::Name(name)) => {
let ident = syn::Ident::new(&name, err_span);
syn::parse_quote!(::#ident)
}
Ok(FoundCrate::Itself) => syn::parse_quote!(::plexus_core),
Err(_) => match umbrella_crate(err_span) {
Some(umbrella) => syn::parse_quote!(::#umbrella::core),
None => syn::parse_quote!(::plexus_core),
},
}
}
pub(crate) fn derive_serde_json_path(err_span: Span) -> syn::Path {
match crate_name("serde_json") {
Ok(FoundCrate::Name(name)) => {
let ident = syn::Ident::new(&name, err_span);
syn::parse_quote!(::#ident)
}
Ok(FoundCrate::Itself) => syn::parse_quote!(::serde_json),
Err(_) => match umbrella_crate(err_span) {
Some(umbrella) => syn::parse_quote!(::#umbrella::__deps::serde_json),
None => syn::parse_quote!(::serde_json),
},
}
}
fn resolve_crate_path(explicit: Option<&str>, err_span: Span) -> syn::Result<syn::Path> {
if let Some(s) = explicit {
return syn::parse_str(s);
}
match crate_name("plexus-core") {
Ok(FoundCrate::Itself) => syn::parse_str("crate"),
Ok(FoundCrate::Name(name)) => {
let ident = syn::Ident::new(&name, err_span);
Ok(syn::parse_quote!(::#ident))
}
Err(e) => match umbrella_crate(err_span) {
Some(umbrella) => Ok(syn::parse_quote!(::#umbrella::core)),
None => Err(syn::Error::new(
err_span,
format!(
"#[plexus_macros::activation] could not locate the `plexus-core` \
dependency in Cargo.toml ({e}). Add `plexus-core` (or the \
`plexus-rpc` umbrella) as a dependency, or pass \
`crate_path = \"...\"` explicitly to override."
),
)),
},
}
}
pub(crate) fn resolve_auth_core_path(err_span: Span) -> Option<syn::Path> {
match crate_name("plexus-auth-core") {
Ok(FoundCrate::Itself) => syn::parse_str("crate").ok(),
Ok(FoundCrate::Name(name)) => {
let ident = syn::Ident::new(&name, err_span);
Some(syn::parse_quote!(::#ident))
}
Err(_) => umbrella_crate(err_span)
.map(|umbrella| syn::parse_quote!(::#umbrella::auth_core)),
}
}
pub fn generate_all(args: HubMethodsAttrs, mut input_impl: ItemImpl) -> syn::Result<TokenStream> {
let crate_path: syn::Path =
resolve_crate_path(args.crate_path.as_deref(), Span::call_site())?;
let struct_name = match &*input_impl.self_ty {
Type::Path(type_path) => type_path
.path
.segments
.last()
.map(|s| s.ident.clone())
.ok_or_else(|| syn::Error::new_spanned(&input_impl.self_ty, "Expected struct name"))?,
_ => return Err(syn::Error::new_spanned(&input_impl.self_ty, "Expected struct type")),
};
let self_ty = &input_impl.self_ty;
let (impl_generics, _, where_clause) = input_impl.generics.split_for_impl();
let mut methods: Vec<MethodInfo> = Vec::new();
let mut child_methods: Vec<ChildMethodInfo> = Vec::new();
for item in &mut input_impl.items {
if let ImplItem::Fn(method) = item {
if has_child_attr(method) && has_method_attr(method) {
return Err(syn::Error::new_spanned(
&method.sig,
"#[plexus_macros::child] and #[plexus_macros::method] are mutually exclusive \
on the same function: a function is either an RPC method or a child router \
entry, not both",
));
}
if has_child_attr(method) {
child_methods.push(ChildMethodInfo::from_fn(method)?);
method.attrs.retain(|a| {
let last = a.path().segments.last().map(|s| s.ident.to_string());
!matches!(last.as_deref(), Some("child") | Some("removed_in"))
});
continue;
}
let hub_method_idx = method.attrs.iter().position(|attr| {
let path = attr.path();
let last = path.segments.last().map(|s| s.ident.to_string());
matches!(last.as_deref(), Some("method") | Some("hub_method"))
});
if let Some(idx) = hub_method_idx {
let attr = method.attrs.remove(idx);
let hub_method_attrs = match &attr.meta {
Meta::Path(_) => None, Meta::List(list) => {
Some(syn::parse2::<HubMethodAttrs>(list.tokens.clone())?)
}
Meta::NameValue(_) => None,
};
methods.push(MethodInfo::from_fn(method, hub_method_attrs.as_ref())?);
method.attrs.retain(|a| {
let last = a.path().segments.last().map(|s| s.ident.to_string());
!matches!(last.as_deref(), Some("removed_in"))
});
for arg in &mut method.sig.inputs {
if let FnArg::Typed(pat_type) = arg {
pat_type.attrs.retain(|attr| {
let last =
attr.path().segments.last().map(|s| s.ident.to_string());
!attr.path().is_ident("from_auth")
&& !attr.path().is_ident("activation_param")
&& !attr.path().is_ident("doc")
&& !matches!(
last.as_deref(),
Some("deprecated") | Some("removed_in")
)
});
}
}
}
}
}
if args.request_type.is_none() {
if let Some(m) = methods.iter().find(|m| !m.auth_resolvers.is_empty()) {
return Err(syn::Error::new(
m.fn_name.span(),
format!(
"RED-3: method `{}` uses `#[from_auth(...)]` but the activation \
declares no `request = SomeType`. Auth extraction requires a \
PlexusRequest struct to wire AuthContext through. Add \
`request = MyRequest` to `#[plexus::activation(...)]`, or remove \
the `#[from_auth]` annotation.",
m.method_name
),
));
}
}
let declared_roles = resolve_roles(&args.roles, &methods, &args.namespace)?;
if !args.required_fields.is_empty() {
for m in &methods {
if matches!(m.request_override, Some(crate::parse::MethodRequestOverride::Skip)) {
let required_names: Vec<String> = args.required_fields
.iter()
.map(|i| i.to_string())
.collect();
return Err(syn::Error::new(
m.fn_name.span(),
format!(
"REQ-10: method `{}` uses `request = ()` but activation's `required = [{}]` \
locks these fields. Either remove the method-level `request = ()` override \
or remove the activation's `required` list (or move the method to a \
different activation).",
m.method_name,
required_names.join(", ")
),
));
}
}
}
let activation_deprecation: Option<ParsedDeprecation> =
parse_deprecation_attrs(&input_impl.attrs, input_impl.span())?;
input_impl.attrs.retain(|a| {
let last = a.path().segments.last().map(|s| s.ident.to_string());
if matches!(last.as_deref(), Some("removed_in")) {
return false;
}
if a.path().is_ident("doc") {
if let syn::Meta::NameValue(syn::MetaNameValue { value, .. }) = &a.meta {
if let syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(s),
..
}) = value
{
if s.value().starts_with("__plexus_removed_in:") {
return false;
}
}
}
}
true
});
for item in &mut input_impl.items {
if let ImplItem::Fn(f) = item {
f.attrs.retain(|a| {
let last = a.path().segments.last().map(|s| s.ident.to_string());
!matches!(last.as_deref(), Some("removed_in"))
});
}
}
let dynamic_children: Vec<&ChildMethodInfo> = child_methods
.iter()
.filter(|c| matches!(c.kind, ChildMethodKind::Dynamic))
.collect();
if dynamic_children.len() > 1 {
let names: Vec<String> = dynamic_children
.iter()
.map(|c| c.fn_name.to_string())
.collect();
return Err(syn::Error::new_spanned(
&input_impl,
format!(
"at most one dynamic #[child] method is allowed per activation impl; \
found {}: {}",
dynamic_children.len(),
names.join(", ")
),
));
}
if !child_methods.is_empty() && !args.children.is_empty() {
return Err(syn::Error::new_spanned(
&input_impl,
"#[plexus_macros::child] methods cannot be combined with the legacy \
`children = [...]` activation attribute on the same impl; choose one. \
Remove `children = [...]` to migrate to the method-based syntax.",
));
}
let mut list_method: Option<ListSearchMethodInfo> = None;
let mut search_method: Option<ListSearchMethodInfo> = None;
for child in &child_methods {
if let Some(name) = &child.list_fn {
let info = find_and_validate_list_search_method(
&input_impl.items,
name,
ListSearchKind::List,
&child.fn_name,
)?;
if list_method.is_some() {
return Err(syn::Error::new(
name.span(),
format!(
"duplicate `list = \"{}\"` across #[plexus_macros::child] methods; \
at most one list method per activation impl",
name
),
));
}
list_method = Some(info);
}
if let Some(name) = &child.search_fn {
let info = find_and_validate_list_search_method(
&input_impl.items,
name,
ListSearchKind::Search,
&child.fn_name,
)?;
if search_method.is_some() {
return Err(syn::Error::new(
name.span(),
format!(
"duplicate `search = \"{}\"` across #[plexus_macros::child] methods; \
at most one search method per activation impl",
name
),
));
}
search_method = Some(info);
}
}
if methods.is_empty() {
return Err(syn::Error::new_spanned(
&input_impl,
"No #[plexus::method] functions found",
));
}
if args.hub && !child_methods.is_empty() {
return Err(syn::Error::new_spanned(
&input_impl,
"#[plexus_macros::activation(hub, ...)] cannot be combined with #[plexus_macros::child] \
methods — the macro infers hub-mode from the presence of #[child] methods. Remove the \
'hub' flag or remove the #[child] methods.",
));
}
let effective_hub = args.hub || !child_methods.is_empty();
let hub_explicit = args.hub;
let impl_defines_plugin_children = input_impl.items.iter().any(|item| {
if let ImplItem::Fn(f) = item {
if f.sig.ident == "plugin_children" {
return matches!(f.sig.inputs.first(), Some(FnArg::Receiver(_)));
}
}
false
});
let synthesize_plugin_children =
!child_methods.is_empty() && !impl_defines_plugin_children;
let resolved_description: String = args
.description
.clone()
.or_else(|| extract_doc_description(&input_impl.attrs))
.unwrap_or_default();
let schema_child_methods: Vec<ChildMethodInfo> = child_methods.clone();
input_impl.attrs.retain(|a| !a.path().is_ident("deprecated"));
let hub_deprecation_warning =
hub_flag_deprecation_warning(args.hub, args.hub_span, &struct_name);
let children_deprecation_warning = children_arg_deprecation_warning(
!args.children.is_empty(),
args.children_span,
&struct_name,
);
let effective_auth_posture = args.auth_posture.unwrap_or_default();
let mut required_posture_optional_auth_methods: Vec<&crate::parse::MethodInfo> = Vec::new();
match effective_auth_posture {
crate::parse::AuthPosture::Required => {
for m in &methods {
if m.auth_resolvers.is_empty() && !m.public {
if m.auth_optional {
required_posture_optional_auth_methods.push(m);
continue;
}
return Err(syn::Error::new(
m.fn_name.span(),
format!(
"RED-6: activation `{}` is `auth = \"required\"` but method \
`{}` has no #[from_auth(...)] and no \
#[plexus_macros::method(public)] acknowledgment. \
Either gate the method with #[from_auth(resolver)] \
or explicitly mark it public with \
#[plexus_macros::method(public)].",
struct_name, m.method_name,
),
));
}
}
}
crate::parse::AuthPosture::None => {
for m in &methods {
if !m.auth_resolvers.is_empty() {
return Err(syn::Error::new(
m.fn_name.span(),
format!(
"RED-6: activation `{}` is `auth = \"none\"` (affirmative public) \
but method `{}` uses #[from_auth(...)]. Remove the \
annotation or change the activation's auth posture.",
struct_name, m.method_name,
),
));
}
}
}
crate::parse::AuthPosture::Mixed | crate::parse::AuthPosture::Optional => {}
}
let required_posture_optional_auth_warning = required_posture_optional_auth_warning(
&required_posture_optional_auth_methods,
&struct_name,
);
let suppress_mixed_warning =
!matches!(effective_auth_posture, crate::parse::AuthPosture::Optional);
let mixed_auth_warning = mixed_auth_warning(&methods, suppress_mixed_warning, &struct_name);
let auth_core_path = resolve_auth_core_path(Span::call_site());
let deps = format_ident!("__plexus_deps_{}", struct_name);
let deps_shim_mod = deps_shim(&deps, Span::call_site());
let method_enum = method_enum::generate(
&struct_name,
&methods,
&schema_child_methods,
&crate_path,
auth_core_path.as_ref(),
args.request_type.as_ref(), &deps,
args.auth_posture, &args.namespace, );
let activation_impl = activation::generate(
&struct_name,
self_ty,
&impl_generics,
where_clause,
&args.namespace,
args.version.as_deref(),
&resolved_description,
args.long_description.as_deref(),
&methods,
&crate_path,
args.resolve_handle,
effective_hub,
hub_explicit,
synthesize_plugin_children,
args.plugin_id.as_deref(),
args.namespace_fn.as_deref(),
args.request_type.as_ref(),
&args.children,
&child_methods,
list_method.as_ref(),
search_method.as_ref(),
activation_deprecation.as_ref(),
&deps,
&declared_roles,
);
let client_impl = if args.client {
let span = args.client_span.unwrap_or_else(Span::call_site);
let client_path = client::resolve_client_path(span)?;
client::generate(&struct_name, &args.namespace, &methods, &client_path)?
} else {
TokenStream::new()
};
let server_half = quote! {
#deps_shim_mod
#input_impl
#method_enum
#activation_impl
#hub_deprecation_warning
#children_deprecation_warning
#mixed_auth_warning
#required_posture_optional_auth_warning
};
let server_half = match &args.server_cfg {
None => server_half,
Some(pred) => {
let span = args.server_cfg_span.unwrap_or_else(Span::call_site);
if !args.client {
return Err(syn::Error::new(
span,
"#[plexus_macros::activation]: `server_cfg = \"...\"` suppresses the \
server half of the expansion, which only makes sense alongside the \
`client` flag — otherwise the attribute emits nothing at all under \
the negated predicate. Add `client`, or put your own `#[cfg]` on the \
module instead.",
));
}
cfg_gate(server_half, pred, span)?
}
};
Ok(quote! {
#server_half
#client_impl
})
}
fn resolve_roles(
decls: &[crate::parse::RoleDecl],
methods: &[MethodInfo],
namespace: &str,
) -> syn::Result<Vec<(String, Vec<String>)>> {
use crate::parse::RoleEntry;
let mut out: Vec<(String, Vec<String>)> = Vec::new();
for decl in decls {
let name = decl.name.to_string();
if name == "admin" {
return Err(syn::Error::new(
decl.name.span(),
"`admin` is built in and holds every grant; it needs no list",
));
}
if out.iter().any(|(n, _)| *n == name) {
return Err(syn::Error::new(decl.name.span(), format!("role `{name}` is declared twice")));
}
let mut grants: Vec<String> = Vec::new();
let mut push = |g: String, grants: &mut Vec<String>| {
if !grants.contains(&g) {
grants.push(g);
}
};
for entry in &decl.entries {
match entry {
RoleEntry::Method(lit) => {
let m = lit.value();
if !methods.iter().any(|mi| mi.method_name == m) {
let known: Vec<&str> = methods.iter().map(|mi| mi.method_name.as_str()).collect();
return Err(syn::Error::new(
lit.span(),
format!(
"role `{name}` lists \"{m}\", which is not a method of this activation; \
its methods are: {}",
known.join(", ")
),
));
}
push(format!("{namespace}.{m}"), &mut grants);
}
RoleEntry::Role(ident) => {
let inc = ident.to_string();
let Some((_, included)) = out.iter().find(|(n, _)| *n == inc) else {
return Err(syn::Error::new(
ident.span(),
if inc == "admin" {
format!("role `{name}` cannot include `admin`, which holds every grant")
} else {
format!(
"role `{name}` includes `{inc}`, which is not declared before it \
(a role may include only roles listed earlier in `roles(...)`)"
)
},
));
};
for g in included.clone() {
push(g, &mut grants);
}
}
}
}
out.push((name, grants));
}
Ok(out)
}
fn cfg_gate(items: TokenStream, predicate: &str, span: Span) -> syn::Result<TokenStream> {
let meta: syn::Meta = syn::parse_str(predicate).map_err(|e| {
syn::Error::new(
span,
format!(
"server_cfg = \"...\" must be a `cfg` predicate, e.g. \
`feature = \"server\"` or `not(target_arch = \"wasm32\")` ({e})"
),
)
})?;
let file: syn::File = syn::parse2(items).map_err(|e| {
syn::Error::new(
span,
format!("plexus-macros could not re-parse its own expansion to apply server_cfg ({e})"),
)
})?;
let gated = file.items.into_iter().map(|item| {
quote! {
#[cfg(#meta)]
#item
}
});
Ok(quote! { #(#gated)* })
}
fn required_posture_optional_auth_warning(
methods: &[&crate::parse::MethodInfo],
struct_name: &syn::Ident,
) -> TokenStream {
if methods.is_empty() {
return TokenStream::new();
}
let names = methods
.iter()
.map(|m| m.method_name.as_str())
.collect::<Vec<_>>()
.join(", ");
let note = format!(
"plexus-macros (AUTHZ-MACRO-OPTIONAL-AUTH-1): activation `{}` declares \
`auth = \"required\"` but the following method(s) accept anonymous \
callers via `auth: Option<&AuthContext>`: {}. The handlers will see \
`None` when no auth context is attached. If this is intentional, \
consider `auth = \"mixed\"` to silence this warning; otherwise \
change the handler signature to `auth: &AuthContext` (or use \
`#[from_auth(...)]`).",
struct_name, names,
);
let span = methods
.first()
.map(|m| m.fn_name.span())
.unwrap_or_else(|| struct_name.span());
let const_name = format_ident!(
"_PLEXUS_MACROS_REQUIRED_POSTURE_OPTIONAL_AUTH_WARNING_{}",
struct_name,
span = span,
);
let touch_fn_name = format_ident!(
"_plexus_macros_touch_required_posture_optional_auth_warning_{}",
struct_name,
span = span,
);
quote::quote_spanned! { span =>
#[doc(hidden)]
#[allow(non_upper_case_globals, non_snake_case, dead_code)]
#[deprecated(since = "0.5", note = #note)]
const #const_name: () = ();
#[doc(hidden)]
#[allow(non_snake_case, dead_code)]
fn #touch_fn_name() {
let _ = #const_name;
}
}
}
fn hub_flag_deprecation_warning(
hub_is_set: bool,
hub_span: Option<Span>,
struct_name: &syn::Ident,
) -> TokenStream {
if !hub_is_set {
return TokenStream::new();
}
let span = hub_span.unwrap_or_else(|| struct_name.span());
let const_name = format_ident!(
"_PLEXUS_MACROS_DEPRECATED_HUB_FLAG_{}",
struct_name,
span = span
);
let touch_fn_name = format_ident!(
"_plexus_macros_touch_deprecated_hub_flag_{}",
struct_name,
span = span
);
quote::quote_spanned! { span =>
#[doc(hidden)]
#[allow(non_upper_case_globals, non_snake_case, dead_code)]
#[deprecated(
since = "0.5",
note = "plexus-macros: the 'hub' argument is deprecated; hub mode is inferred automatically from #[child]-tagged methods. This argument will be removed in plexus-macros 0.6."
)]
const #const_name: () = ();
#[doc(hidden)]
#[allow(non_snake_case, dead_code)]
fn #touch_fn_name() {
let _ = #const_name;
}
}
}
fn children_arg_deprecation_warning(
children_is_set: bool,
children_span: Option<Span>,
struct_name: &syn::Ident,
) -> TokenStream {
if !children_is_set {
return TokenStream::new();
}
let span = children_span.unwrap_or_else(|| struct_name.span());
let const_name = format_ident!(
"_PLEXUS_MACROS_DEPRECATED_CHILDREN_ARG_{}",
struct_name,
span = span
);
let touch_fn_name = format_ident!(
"_plexus_macros_touch_deprecated_children_arg_{}",
struct_name,
span = span
);
quote::quote_spanned! { span =>
#[doc(hidden)]
#[allow(non_upper_case_globals, non_snake_case, dead_code)]
#[deprecated(
since = "0.5",
note = "plexus-macros: the 'children' attribute argument is deprecated; use #[plexus_macros::child] on the accessor method(s) instead. This argument will be removed in plexus-macros 0.6."
)]
const #const_name: () = ();
#[doc(hidden)]
#[allow(non_snake_case, dead_code)]
fn #touch_fn_name() {
let _ = #const_name;
}
}
}
fn mixed_auth_warning(
methods: &[crate::parse::MethodInfo],
auth_posture_mixed: bool,
struct_name: &syn::Ident,
) -> TokenStream {
if auth_posture_mixed {
return TokenStream::new();
}
let any_auth = methods.iter().any(|m| !m.auth_resolvers.is_empty());
if !any_auth {
return TokenStream::new();
}
let unauthed: Vec<&crate::parse::MethodInfo> = methods
.iter()
.filter(|m| m.auth_resolvers.is_empty() && !m.public)
.collect();
if unauthed.is_empty() {
return TokenStream::new();
}
let names = unauthed
.iter()
.map(|m| m.method_name.as_str())
.collect::<Vec<_>>()
.join(", ");
let note = format!(
"plexus-macros (RED-2): activation `{}` mixes auth and non-auth \
methods. The following methods do NOT have `#[from_auth(...)]`: {}. \
If this is intentional, add `auth_posture = \"mixed\"` to the \
activation attribute, or `#[plexus_macros::method(public)]` to each \
intentionally-public method. Otherwise, the missing methods will \
dispatch unauthenticated.",
struct_name,
names,
);
let span = unauthed
.first()
.map(|m| m.fn_name.span())
.unwrap_or_else(|| struct_name.span());
let const_name = format_ident!(
"_PLEXUS_MACROS_MIXED_AUTH_WARNING_{}",
struct_name,
span = span,
);
let touch_fn_name = format_ident!(
"_plexus_macros_touch_mixed_auth_warning_{}",
struct_name,
span = span,
);
quote::quote_spanned! { span =>
#[doc(hidden)]
#[allow(non_upper_case_globals, non_snake_case, dead_code)]
#[deprecated(since = "0.5", note = #note)]
const #const_name: () = ();
#[doc(hidden)]
#[allow(non_snake_case, dead_code)]
fn #touch_fn_name() {
let _ = #const_name;
}
}
}