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:
Michael Sloan 2025-06-23 22:34:51 -06:00 committed by GitHub
parent 21f985a018
commit 24c94d474e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
44 changed files with 878 additions and 789 deletions

View 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
}
}
})
}

View file

@ -1,3 +1,4 @@
mod derive_action;
mod derive_app_context;
mod derive_into_element;
mod derive_render;
@ -12,12 +13,18 @@ mod derive_inspector_reflection;
use proc_macro::TokenStream;
use syn::{DeriveInput, Ident};
/// register_action! can be used to register an action with the GPUI runtime.
/// You should typically use `gpui::actions!` or `gpui::impl_actions!` instead,
/// but this can be used for fine grained customization.
/// `Action` derive macro - see the trait documentation for details.
#[proc_macro_derive(Action, attributes(action))]
pub fn derive_action(input: TokenStream) -> TokenStream {
derive_action::derive_action(input)
}
/// This can be used to register an action with the GPUI runtime when you want to manually implement
/// the `Action` trait. Typically you should use the `Action` derive macro or `actions!` macro
/// instead.
#[proc_macro]
pub fn register_action(ident: TokenStream) -> TokenStream {
register_action::register_action_macro(ident)
register_action::register_action(ident)
}
/// #[derive(IntoElement)] is used to create a Component out of anything that implements

View file

@ -1,18 +1,18 @@
use proc_macro::TokenStream;
use proc_macro2::Ident;
use proc_macro2::{Ident, TokenStream as TokenStream2};
use quote::{format_ident, quote};
use syn::parse_macro_input;
pub fn register_action_macro(ident: TokenStream) -> TokenStream {
pub(crate) fn register_action(ident: TokenStream) -> TokenStream {
let name = parse_macro_input!(ident as Ident);
let registration = register_action(&name);
let registration = generate_register_action(&name);
TokenStream::from(quote! {
#registration
})
}
pub(crate) fn register_action(type_name: &Ident) -> proc_macro2::TokenStream {
pub(crate) fn generate_register_action(type_name: &Ident) -> TokenStream2 {
let action_builder_fn_name = format_ident!(
"__gpui_actions_builder_{}",
type_name.to_string().to_lowercase()
@ -28,11 +28,12 @@ pub(crate) fn register_action(type_name: &Ident) -> proc_macro2::TokenStream {
#[doc(hidden)]
fn #action_builder_fn_name() -> gpui::MacroActionData {
gpui::MacroActionData {
name: <#type_name as gpui::Action>::debug_name(),
aliases: <#type_name as gpui::Action>::deprecated_aliases(),
name: <#type_name as gpui::Action>::name_for_type(),
type_id: ::std::any::TypeId::of::<#type_name>(),
build: <#type_name as gpui::Action>::build,
json_schema: <#type_name as gpui::Action>::action_json_schema,
deprecated_aliases: <#type_name as gpui::Action>::deprecated_aliases(),
deprecation_message: <#type_name as gpui::Action>::deprecation_message(),
}
}
@ -41,7 +42,5 @@ pub(crate) fn register_action(type_name: &Ident) -> proc_macro2::TokenStream {
}
}
}
}
}