gpui: Simplify Action
macros + support doc comments in actions!
(#33263)
Instead of a menagerie of macros for implementing `Action`, now there are just two: * `actions!(editor, [MoveLeft, MoveRight])` * `#[derive(..., Action)]` with `#[action(namespace = editor)]` In both contexts, `///` doc comments can be provided and will be used in `JsonSchema`. In both contexts, parameters can provided in `#[action(...)]`: - `namespace = some_namespace` sets the namespace. In Zed this is required. - `name = "ActionName"` overrides the action's name. This must not contain "::". - `no_json` causes the `build` method to always error and `action_json_schema` to return `None` and allows actions not implement `serde::Serialize` and `schemars::JsonSchema`. - `no_register` skips registering the action. This is useful for implementing the `Action` trait while not supporting invocation by name or JSON deserialization. - `deprecated_aliases = ["editor::SomeAction"]` specifies deprecated old names for the action. These action names should *not* correspond to any actions that are registered. These old names can then still be used to refer to invoke this action. In Zed, the keymap JSON schema will accept these old names and provide warnings. - `deprecated = "Message about why this action is deprecation"` specifies a deprecation message. In Zed, the keymap JSON schema will cause this to be displayed as a warning. This is a new feature. Also makes the following changes since this seems like a good time to make breaking changes: * In `zed.rs` tests adds a test with an explicit list of namespaces. The rationale for this is that there is otherwise no checking of `namespace = ...` attributes. * `Action::debug_name` renamed to `name_for_type`, since its only difference with `name` was that it * `Action::name` now returns `&'static str` instead of `&str` to match the return of `name_for_type`. This makes the action trait more limited, but the code was already assuming that `name_for_type` is the same as `name`, and it requires `&'static`. So really this just makes the trait harder to misuse. * Various action reflection methods now use `&'static str` instead of `SharedString`. Release Notes: - N/A
This commit is contained in:
parent
21f985a018
commit
24c94d474e
44 changed files with 878 additions and 789 deletions
176
crates/gpui_macros/src/derive_action.rs
Normal file
176
crates/gpui_macros/src/derive_action.rs
Normal file
|
@ -0,0 +1,176 @@
|
|||
use crate::register_action::generate_register_action;
|
||||
use proc_macro::TokenStream;
|
||||
use proc_macro2::Ident;
|
||||
use quote::quote;
|
||||
use syn::{Data, DeriveInput, LitStr, Token, parse::ParseStream};
|
||||
|
||||
pub(crate) fn derive_action(input: TokenStream) -> TokenStream {
|
||||
let input = syn::parse_macro_input!(input as DeriveInput);
|
||||
|
||||
let struct_name = &input.ident;
|
||||
let mut name_argument = None;
|
||||
let mut deprecated_aliases = Vec::new();
|
||||
let mut no_json = false;
|
||||
let mut no_register = false;
|
||||
let mut namespace = None;
|
||||
let mut deprecated = None;
|
||||
|
||||
for attr in &input.attrs {
|
||||
if attr.path().is_ident("action") {
|
||||
attr.parse_nested_meta(|meta| {
|
||||
if meta.path.is_ident("name") {
|
||||
if name_argument.is_some() {
|
||||
return Err(meta.error("'name' argument specified multiple times"));
|
||||
}
|
||||
meta.input.parse::<Token![=]>()?;
|
||||
let lit: LitStr = meta.input.parse()?;
|
||||
name_argument = Some(lit.value());
|
||||
} else if meta.path.is_ident("namespace") {
|
||||
if namespace.is_some() {
|
||||
return Err(meta.error("'namespace' argument specified multiple times"));
|
||||
}
|
||||
meta.input.parse::<Token![=]>()?;
|
||||
let ident: Ident = meta.input.parse()?;
|
||||
namespace = Some(ident.to_string());
|
||||
} else if meta.path.is_ident("no_json") {
|
||||
if no_json {
|
||||
return Err(meta.error("'no_json' argument specified multiple times"));
|
||||
}
|
||||
no_json = true;
|
||||
} else if meta.path.is_ident("no_register") {
|
||||
if no_register {
|
||||
return Err(meta.error("'no_register' argument specified multiple times"));
|
||||
}
|
||||
no_register = true;
|
||||
} else if meta.path.is_ident("deprecated_aliases") {
|
||||
if !deprecated_aliases.is_empty() {
|
||||
return Err(
|
||||
meta.error("'deprecated_aliases' argument specified multiple times")
|
||||
);
|
||||
}
|
||||
meta.input.parse::<Token![=]>()?;
|
||||
// Parse array of string literals
|
||||
let content;
|
||||
syn::bracketed!(content in meta.input);
|
||||
let aliases = content.parse_terminated(
|
||||
|input: ParseStream| input.parse::<LitStr>(),
|
||||
Token![,],
|
||||
)?;
|
||||
deprecated_aliases.extend(aliases.into_iter().map(|lit| lit.value()));
|
||||
} else if meta.path.is_ident("deprecated") {
|
||||
if deprecated.is_some() {
|
||||
return Err(meta.error("'deprecated' argument specified multiple times"));
|
||||
}
|
||||
meta.input.parse::<Token![=]>()?;
|
||||
let lit: LitStr = meta.input.parse()?;
|
||||
deprecated = Some(lit.value());
|
||||
} else {
|
||||
return Err(meta.error(format!(
|
||||
"'{:?}' argument not recognized, expected \
|
||||
'namespace', 'no_json', 'no_register, 'deprecated_aliases', or 'deprecated'",
|
||||
meta.path
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap_or_else(|e| panic!("in #[action] attribute: {}", e));
|
||||
}
|
||||
}
|
||||
|
||||
let name = name_argument.unwrap_or_else(|| struct_name.to_string());
|
||||
|
||||
if name.contains("::") {
|
||||
panic!(
|
||||
"in #[action] attribute: `name = \"{name}\"` must not contain `::`, \
|
||||
also specify `namespace` instead"
|
||||
);
|
||||
}
|
||||
|
||||
let full_name = if let Some(namespace) = namespace {
|
||||
format!("{namespace}::{name}")
|
||||
} else {
|
||||
name
|
||||
};
|
||||
|
||||
let is_unit_struct = matches!(&input.data, Data::Struct(data) if data.fields.is_empty());
|
||||
|
||||
let build_fn_body = if no_json {
|
||||
let error_msg = format!("{} cannot be built from JSON", full_name);
|
||||
quote! { Err(gpui::private::anyhow::anyhow!(#error_msg)) }
|
||||
} else if is_unit_struct {
|
||||
quote! { Ok(Box::new(Self)) }
|
||||
} else {
|
||||
quote! { Ok(Box::new(gpui::private::serde_json::from_value::<Self>(_value)?)) }
|
||||
};
|
||||
|
||||
let json_schema_fn_body = if no_json || is_unit_struct {
|
||||
quote! { None }
|
||||
} else {
|
||||
quote! { Some(<Self as gpui::private::schemars::JsonSchema>::json_schema(_generator)) }
|
||||
};
|
||||
|
||||
let deprecated_aliases_fn_body = if deprecated_aliases.is_empty() {
|
||||
quote! { &[] }
|
||||
} else {
|
||||
let aliases = deprecated_aliases.iter();
|
||||
quote! { &[#(#aliases),*] }
|
||||
};
|
||||
|
||||
let deprecation_fn_body = if let Some(message) = deprecated {
|
||||
quote! { Some(#message) }
|
||||
} else {
|
||||
quote! { None }
|
||||
};
|
||||
|
||||
let registration = if no_register {
|
||||
quote! {}
|
||||
} else {
|
||||
generate_register_action(struct_name)
|
||||
};
|
||||
|
||||
TokenStream::from(quote! {
|
||||
#registration
|
||||
|
||||
impl gpui::Action for #struct_name {
|
||||
fn name(&self) -> &'static str {
|
||||
#full_name
|
||||
}
|
||||
|
||||
fn name_for_type() -> &'static str
|
||||
where
|
||||
Self: Sized
|
||||
{
|
||||
#full_name
|
||||
}
|
||||
|
||||
fn partial_eq(&self, action: &dyn gpui::Action) -> bool {
|
||||
action
|
||||
.as_any()
|
||||
.downcast_ref::<Self>()
|
||||
.map_or(false, |a| self == a)
|
||||
}
|
||||
|
||||
fn boxed_clone(&self) -> Box<dyn gpui::Action> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
|
||||
fn build(_value: gpui::private::serde_json::Value) -> gpui::Result<Box<dyn gpui::Action>> {
|
||||
#build_fn_body
|
||||
}
|
||||
|
||||
fn action_json_schema(
|
||||
_generator: &mut gpui::private::schemars::r#gen::SchemaGenerator,
|
||||
) -> Option<gpui::private::schemars::schema::Schema> {
|
||||
#json_schema_fn_body
|
||||
}
|
||||
|
||||
fn deprecated_aliases() -> &'static [&'static str] {
|
||||
#deprecated_aliases_fn_body
|
||||
}
|
||||
|
||||
fn deprecation_message() -> Option<&'static str> {
|
||||
#deprecation_fn_body
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue