mod activation;
pub(crate) mod client;
mod contract;
mod method_enum;
mod parent;
pub(crate) mod peer;
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 trait_impl: Option<syn::Path> = match &input_impl.trait_ {
None => None,
Some((Some(bang), _, _)) => {
return Err(syn::Error::new_spanned(bang, "a negative impl cannot be an activation"))
}
Some((None, path, _)) => Some(path.clone()),
};
let bodiless = contract::take_bodiless(&mut input_impl);
if let (Some(path), Some(f)) = (&trait_impl, bodiless.first()) {
return Err(syn::Error::new(
f.span(),
format!(
"`{f}` has no body, in `impl {} for {struct_name}`: a trait impl has every body; \
the contract is the trait itself",
quote!(#path).to_string().replace(' ', "")
),
));
}
let names = contract::Names::resolve(&args, &struct_name, trait_impl.as_ref(), !bodiless.is_empty())?;
let namespace = names.namespace.clone();
let all_public_methods = names.new_form && !args.methods_marked;
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) {
if let Some(path) = &trait_impl {
return Err(syn::Error::new_spanned(
&method.sig.ident,
format!(
"#[plexus_macros::child] in `impl {} for {struct_name}`: a trait impl's children \
are not served yet (GRAFT-1); declare the child in an inherent \
`#[plexus_macros::activation] impl` instead",
quote!(#path).to_string().replace(' ', "")
),
));
}
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("peer") | Some("removed_in"))
});
continue;
}
let verifier_idx = method.attrs.iter().position(|a| {
a.path().segments.last().is_some_and(|s| s.ident == "from_auth")
});
let verifier: Option<syn::Expr> = match verifier_idx {
None => None,
Some(idx) => {
let attr = method.attrs.remove(idx);
if trait_impl.is_none() {
return Err(syn::Error::new_spanned(
&attr,
"#[from_auth(…)] on a method is the form for `impl Trait for Type`, whose \
signatures cannot carry it; on an inherent method, put it on the parameter \
(`#[from_auth(self.access.verify)] user: User`)",
));
}
Some(attr.parse_args::<syn::Expr>()?)
}
};
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"))
});
parent::rewrite_sig(&mut method.sig, &crate_path);
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())?);
} else if all_public_methods
&& (if trait_impl.is_some() {
contract::is_trait_wire_shape(method)
} else {
contract::is_wire_shape(method)?
})
{
methods.push(MethodInfo::from_fn(method, None)?);
} else {
if let Some(v) = &verifier {
return Err(syn::Error::new_spanned(
v,
"#[from_auth(…)] on a method that is not on the wire: only a wire method has a caller to verify",
));
}
continue;
}
if let Some(m) = methods.last_mut() {
m.verifier = verifier;
parent::infer(m, &method.block)?;
}
{
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")
)
});
}
}
}
}
}
let contract_mode = !bodiless.is_empty();
if contract_mode {
if let Some(f) = bodiless.iter().find(|b| !methods.iter().any(|m| &m.fn_name == *b)) {
return Err(syn::Error::new(
f.span(),
format!(
"`{f}` has no body, and is not a wire method; only a wire method may be \
bodiless (a bodiless activation is a contract its implementor fills)"
),
));
}
if methods.iter().any(|m| !bodiless.contains(&m.fn_name)) {
let first = &bodiless[0];
return Err(syn::Error::new(
first.span(),
format!(
"`{first}` has no body, but other wire methods of this activation do: a \
contract has no bodies and a server has all of them. Give `{first}` a body, \
or remove the bodies of the others."
),
));
}
}
if contract_mode && names.trait_ident.is_none() {
return Err(syn::Error::new(
struct_name.span(),
format!(
"`{struct_name}` is bodiless, so it is a contract, and a contract is its trait; \
name it with `trait = \"…\"` in the attribute (or name the type \
`{struct_name}Activation`, whose trait is `{struct_name}`)."
),
));
}
let trait_ident: Option<syn::Ident> = if names.trait_default && !input_impl.generics.params.is_empty() {
None
} else {
names.trait_ident.clone()
};
let self_callable = contract::self_callable(&methods);
if contract_mode && !self_callable {
let m = methods.iter().find(|m| contract::injected(m).is_some()).unwrap();
return Err(syn::Error::new(
m.fn_name.span(),
format!(
"`{}` takes {}, which the server injects; a contract's methods are what its \
implementor is called with, so they take only what a caller passes.",
m.fn_name,
contract::injected(m).unwrap()
),
));
}
if contract_mode {
contract::rewrite_contract_impl(
&mut input_impl,
&struct_name,
trait_ident.as_ref().unwrap(),
&methods,
)?;
}
let self_ty = &input_impl.self_ty;
let (impl_generics, _, where_clause) = input_impl.generics.split_for_impl();
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 slot_names: Vec<String> = child_methods
.iter()
.filter(|c| matches!(c.kind, crate::parse::ChildMethodKind::Dynamic))
.map(|c| c.fn_name.to_string())
.collect();
let declared_roles = resolve_roles(&args.roles, &methods, &namespace, &slot_names)?;
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"))
});
}
}
if args.typed_params {
let mut errors: Option<syn::Error> = None;
for m in &methods {
for p in &m.params {
if is_bare_string_type(&p.ty) {
let e = syn::Error::new_spanned(
&p.ty,
format!(
"`{}.{}`: a bare string parameter; give it a type (typed_params)",
m.method_name, p.name
),
);
match &mut errors {
Some(all) => all.combine(e),
None => errors = Some(e),
}
}
}
}
if let Some(e) = errors {
return Err(e);
}
}
let dynamic_children: Vec<&ChildMethodInfo> = child_methods
.iter()
.filter(|c| matches!(c.kind, ChildMethodKind::Dynamic) && c.peer.is_none())
.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.iter_mut().filter(|c| c.peer.is_some()) {
if let Some(list) = &child.list_fn {
child.list_is_async = input_impl.items.iter().any(|i| matches!(i, ImplItem::Fn(f) if &f.sig.ident == list && f.sig.asyncness.is_some()));
}
}
for child in child_methods.iter().filter(|c| c.peer.is_none()) {
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();
if trait_impl.is_some() {
let required = matches!(effective_auth_posture, crate::parse::AuthPosture::Required);
for m in methods.iter_mut() {
m.caller_required = m.verifier.is_some() || (required && !m.public);
}
}
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 && trait_impl.is_none() {
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, &namespace, );
let activation_impl = activation::generate(
&struct_name,
self_ty,
&impl_generics,
where_clause,
&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,
args.typed_params, trait_impl.as_ref(), args.parent.is_some(), );
let client_path: Option<syn::Path> = if names.new_form {
client::resolve_client_path(Span::call_site()).ok()
} else if args.client {
let span = args.client_span.unwrap_or_else(Span::call_site);
Some(client::resolve_client_path(span)?)
} else {
None
};
let client_flag_warning = if names.new_form && args.client {
contract::client_flag_warning(args.client_span.unwrap_or_else(Span::call_site), &struct_name)
} else if !names.new_form {
contract::legacy_name_warning(&struct_name)
} else {
TokenStream::new()
};
let parent_needs_impl = parent::needs_impl(
args.parent.as_ref(),
&methods,
self_ty,
&impl_generics,
where_clause,
&crate_path,
client_path.as_ref(),
)?;
let (client_impl, client_server_checks) = match &client_path {
Some(path) => {
let (mut client, checks) = client::generate(&names.client_ident, &namespace, &methods, &child_methods, path, &crate_path)?;
let type_name = struct_name.to_string();
let by_type = format_ident!("{}Client", contract::stem_of(&type_name).unwrap_or(&type_name));
if by_type != names.client_ident {
let client_ident = &names.client_ident;
let doc = format!("`{client_ident}`, by the name of the type it is the client of (`{struct_name}`): how a parent's `#[child]` names it.");
client.extend(quote! {
#[doc = #doc]
pub type #by_type<T, L = #path::Root> = #client_ident<T, L>;
});
}
let has_client = quote! {
impl #impl_generics #path::HasClient for #self_ty #where_clause {}
};
let shape_check = if contract_mode || input_impl.generics.params.is_empty() {
let client_ident = &names.client_ident;
let enum_name = format_ident!("{}Method", struct_name);
let version_expr = match &args.version {
Some(v) => quote! { #v },
None => quote! { env!("CARGO_PKG_VERSION") },
};
let peer = quote! { #crate_path::plexus::peer };
let desc = &resolved_description;
quote! {
impl<__T, __L> #path::ParentHash for #client_ident<__T, __L> {
fn method_hash(method: &str) -> ::core::option::Option<::std::string::String> {
static __HASHES: ::std::sync::OnceLock<::std::collections::BTreeMap<::std::string::String, ::std::string::String>> = ::std::sync::OnceLock::new();
__HASHES
.get_or_init(|| {
#enum_name::method_schemas()
.iter()
.map(|m| (::core::clone::Clone::clone(&m.name), #peer::Interface::method_hash(m)))
.collect()
})
.get(method)
.cloned()
}
}
impl<__T, __L> #path::ShapeCheck for #client_ident<__T, __L> {
fn shape_check(path: &str, schema: &#deps::serde_json::Value) -> ::core::result::Result<(), #path::ClientError> {
static __WANT: ::std::sync::OnceLock<#peer::Interface> = ::std::sync::OnceLock::new();
let __want = __WANT.get_or_init(|| {
let __schema = #crate_path::plexus::PluginSchema::leaf(#namespace, #version_expr, #desc, #enum_name::method_schemas());
#peer::Interface::named(#namespace, &__schema)
});
let __served: #crate_path::plexus::PluginSchema = #deps::serde_json::from_value(::core::clone::Clone::clone(schema))
.map_err(|e| #path::ClientError::Decode {
content_type: ::core::option::Option::Some(::std::format!("{path}.schema")),
message: ::std::string::ToString::to_string(&e),
})?;
match #peer::Interface::named(#namespace, &__served).satisfies(__want) {
::core::result::Result::Ok(()) => ::core::result::Result::Ok(()),
::core::result::Result::Err(#peer::PeerError::ShapeMismatch { wanted, got, methods }) => {
::core::result::Result::Err(#path::ClientError::ShapeMismatch { path: ::std::string::ToString::to_string(path), wanted, got, methods })
}
::core::result::Result::Err(__e) => ::core::result::Result::Err(#path::ClientError::ShapeMismatch {
path: ::std::string::ToString::to_string(path),
wanted: ::core::clone::Clone::clone(&__want.hash),
got: ::std::string::ToString::to_string(&__e),
methods: ::std::vec::Vec::new(),
}),
}
}
}
}
} else {
TokenStream::new()
};
(client, quote! { #has_client #checks #shape_check })
}
None => (TokenStream::new(), TokenStream::new()),
};
let server_gate: Option<syn::Meta> = match &args.server_cfg {
Some(pred) => {
let span = args.server_cfg_span.unwrap_or_else(Span::call_site);
if !names.new_form && !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.",
));
}
Some(contract::parse_gate(pred, span)?)
}
None if names.new_form && contract::manifest_declares_server_feature() => {
Some(syn::parse_quote!(feature = "server"))
}
None => None,
};
let mut trait_server_items = TokenStream::new();
let mut trait_items = TokenStream::new();
let boxes = match &trait_ident {
None => None,
Some(_) => match contract::boxes(
client_path.as_ref(),
&crate_path,
args.trait_span.unwrap_or_else(Span::call_site),
) {
Ok(b) => Some(b),
Err(_) if names.trait_default => None,
Err(e) => return Err(e),
},
};
if let (Some(trait_ident), Some(boxes)) = (&trait_ident, &boxes) {
let boxes = boxes;
trait_items.extend(contract::trait_def(
trait_ident,
&struct_name,
&resolved_description,
&methods,
&boxes,
contract_mode,
server_gate.as_ref(),
));
if contract_mode {
trait_server_items.extend(contract::contract_items(
trait_ident,
&struct_name,
&methods,
&boxes,
));
if let (Some(cp), true) = (client_path.as_ref(), peer::peerable(&methods)) {
let version_expr = match &args.version {
Some(v) => quote! { #v },
None => quote! { env!("CARGO_PKG_VERSION") },
};
trait_server_items.extend(peer::contract_peer_items(
trait_ident,
&struct_name,
&namespace,
&resolved_description,
&version_expr,
&methods,
&boxes.future,
&names.client_ident,
cp,
&crate_path,
&deps,
));
}
} else {
let generic = !input_impl.generics.params.is_empty();
let strict = !names.trait_default && self_callable;
if strict || contract::self_implementable(&methods, generic) {
let guarded = (!strict).then_some((&crate_path, namespace.as_str()));
trait_server_items.extend(contract::activation_trait_impl(
trait_ident,
&struct_name,
self_ty,
&impl_generics,
where_clause,
&methods,
boxes,
&deps,
guarded,
));
}
if let (Some(cp), true, false) = (client_path.as_ref(), peer::peerable(&methods), generic) {
trait_server_items.extend(contract::client_trait_impl(
trait_ident,
&names.client_ident,
&methods,
&boxes.future,
cp,
&crate_path,
));
}
}
}
let server_half = quote! {
#deps_shim_mod
#trait_server_items
#input_impl
#method_enum
#activation_impl
#hub_deprecation_warning
#children_deprecation_warning
#mixed_auth_warning
#required_posture_optional_auth_warning
#client_server_checks
#parent_needs_impl
};
let server_half = match &server_gate {
None => server_half,
Some(meta) => cfg_gate(server_half, meta, Span::call_site())?,
};
let mut streaming_warnings = contract::streaming_warnings(&methods, &struct_name);
streaming_warnings.extend(contract::string_arg_warnings(&child_methods, &struct_name));
Ok(quote! {
#server_half
#trait_items
#client_impl
#client_flag_warning
#streaming_warnings
})
}
fn resolve_roles(
decls: &[crate::parse::RoleDecl],
methods: &[MethodInfo],
namespace: &str,
slots: &[String],
) -> 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) if lit.value().contains('{') => {
let v = lit.value();
let rel = v.strip_prefix(&format!("{namespace}.")).unwrap_or(&v).to_string();
let slot = rel
.strip_prefix('{')
.and_then(|r| r.split_once('}'))
.map(|(s, _)| s.to_string());
match slot {
Some(slot) if slots.contains(&slot) => push(format!("{namespace}.{rel}"), &mut grants),
_ => {
return Err(syn::Error::new(
lit.span(),
format!(
"role `{name}` lists \"{v}\", a slot grant whose slot is not a dynamic \
#[child] of this activation; its slots are: {}",
if slots.is_empty() { "(none)".to_string() } else { slots.join(", ") }
),
))
}
}
}
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, meta: &syn::Meta, span: Span) -> syn::Result<TokenStream> {
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;
}
}
}
fn is_bare_string_type(ty: &syn::Type) -> bool {
fn is_string(ty: &syn::Type) -> bool {
let syn::Type::Path(tp) = ty else { return false };
if tp.qself.is_some() {
return false;
}
let segs: Vec<String> = tp.path.segments.iter().map(|s| s.ident.to_string()).collect();
let bare_last = tp.path.segments.last().is_some_and(|s| s.arguments.is_empty());
bare_last
&& matches!(
segs.iter().map(String::as_str).collect::<Vec<_>>().as_slice(),
["String"] | ["std", "string", "String"] | ["alloc", "string", "String"]
)
}
fn is_str_ref(ty: &syn::Type) -> bool {
match ty {
syn::Type::Reference(r) => matches!(&*r.elem, syn::Type::Path(p) if p.qself.is_none() && p.path.is_ident("str")),
_ => false,
}
}
fn wrapped<'a>(ty: &'a syn::Type, wrapper: &str) -> Option<&'a syn::Type> {
let syn::Type::Path(tp) = ty else { return None };
let last = tp.path.segments.last()?;
if tp.qself.is_some() || last.ident != wrapper {
return None;
}
let syn::PathArguments::AngleBracketed(args) = &last.arguments else { return None };
match args.args.first() {
Some(syn::GenericArgument::Type(inner)) if args.args.len() == 1 => Some(inner),
_ => None,
}
}
if is_string(ty) || is_str_ref(ty) {
return true;
}
if let Some(inner) = wrapped(ty, "Option") {
return is_string(inner) || is_str_ref(inner);
}
if let Some(inner) = wrapped(ty, "Vec") {
return is_string(inner);
}
false
}