1use heck::{ToSnakeCase as _, ToTitleCase as _};
2use proc_macro2::TokenStream;
3use quote::{ToTokens, quote};
4use syn::{Data, DeriveInput, LitStr, Token, parse_macro_input};
5
6/// Derive macro for the `SettingsUi` marker trait.
7///
8/// This macro automatically implements the `SettingsUi` trait for the annotated type.
9/// The `SettingsUi` trait is a marker trait used to indicate that a type can be
10/// displayed in the settings UI.
11///
12/// # Example
13///
14/// ```
15/// use settings_ui_macros::SettingsUi;
16///
17/// #[derive(SettingsUi)]
18/// #[settings_ui(group = "Standard")]
19/// struct MySettings {
20/// enabled: bool,
21/// count: usize,
22/// }
23/// ```
24#[proc_macro_derive(SettingsUi, attributes(settings_ui))]
25pub fn derive_settings_ui(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
26 let input = parse_macro_input!(input as DeriveInput);
27 let name = &input.ident;
28
29 // Handle generic parameters if present
30 let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
31
32 let mut group_name = Option::<String>::None;
33 let mut path_name = Option::<String>::None;
34
35 for attr in &input.attrs {
36 if attr.path().is_ident("settings_ui") {
37 attr.parse_nested_meta(|meta| {
38 if meta.path.is_ident("group") {
39 if group_name.is_some() {
40 return Err(meta.error("Only one 'group' path can be specified"));
41 }
42 meta.input.parse::<Token![=]>()?;
43 let lit: LitStr = meta.input.parse()?;
44 group_name = Some(lit.value());
45 } else if meta.path.is_ident("path") {
46 // todo(settings_ui) rely entirely on settings_key, remove path attribute
47 if path_name.is_some() {
48 return Err(meta.error("Only one 'path' can be specified, either with `path` in `settings_ui` or with `settings_key`"));
49 }
50 meta.input.parse::<Token![=]>()?;
51 let lit: LitStr = meta.input.parse()?;
52 path_name = Some(lit.value());
53 } else if meta.path.is_ident("render") {
54 // Just consume the tokens even if we don't use them here
55 meta.input.parse::<Token![=]>()?;
56 let _lit: LitStr = meta.input.parse()?;
57 }
58 Ok(())
59 })
60 .unwrap_or_else(|e| panic!("in #[settings_ui] attribute: {}", e));
61 } else if let Some(settings_key) = parse_setting_key_attr(attr) {
62 // todo(settings_ui) either remove fallback key or handle it here
63 if path_name.is_some() && settings_key.key.is_some() {
64 panic!("Both 'path' and 'settings_key' are specified. Must specify only one");
65 }
66 path_name = settings_key.key;
67 }
68 }
69
70 let doc_str = parse_documentation_from_attrs(&input.attrs);
71
72 let ui_item_fn_body = generate_ui_item_body(group_name.as_ref(), &input);
73
74 // todo(settings_ui): make group name optional, repurpose group as tag indicating item is group, and have "title" tag for custom title
75 let title = group_name.unwrap_or(input.ident.to_string().to_title_case());
76
77 let ui_entry_fn_body = map_ui_item_to_entry(
78 path_name.as_deref(),
79 &title,
80 doc_str.as_deref(),
81 quote! { Self },
82 );
83
84 let expanded = quote! {
85 impl #impl_generics settings::SettingsUi for #name #ty_generics #where_clause {
86 fn settings_ui_item() -> settings::SettingsUiItem {
87 #ui_item_fn_body
88 }
89
90 fn settings_ui_entry() -> settings::SettingsUiEntry {
91 #ui_entry_fn_body
92 }
93 }
94 };
95
96 proc_macro::TokenStream::from(expanded)
97}
98
99fn extract_type_from_option(ty: TokenStream) -> TokenStream {
100 match option_inner_type(ty.clone()) {
101 Some(inner_type) => inner_type,
102 None => ty,
103 }
104}
105
106fn option_inner_type(ty: TokenStream) -> Option<TokenStream> {
107 let ty = syn::parse2::<syn::Type>(ty).ok()?;
108 let syn::Type::Path(path) = ty else {
109 return None;
110 };
111 let segment = path.path.segments.last()?;
112 if segment.ident != "Option" {
113 return None;
114 }
115 let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
116 return None;
117 };
118 let arg = args.args.first()?;
119 let syn::GenericArgument::Type(ty) = arg else {
120 return None;
121 };
122 return Some(ty.to_token_stream());
123}
124
125fn map_ui_item_to_entry(
126 path: Option<&str>,
127 title: &str,
128 doc_str: Option<&str>,
129 ty: TokenStream,
130) -> TokenStream {
131 // todo(settings_ui): does quote! just work with options?
132 let path = path.map_or_else(|| quote! {None}, |path| quote! {Some(#path)});
133 let doc_str = doc_str.map_or_else(|| quote! {None}, |doc_str| quote! {Some(#doc_str)});
134 let item = ui_item_from_type(ty);
135 quote! {
136 settings::SettingsUiEntry {
137 title: #title,
138 path: #path,
139 item: #item,
140 documentation: #doc_str,
141 }
142 }
143}
144
145fn ui_item_from_type(ty: TokenStream) -> TokenStream {
146 let ty = extract_type_from_option(ty);
147 return trait_method_call(ty, quote! {settings::SettingsUi}, quote! {settings_ui_item});
148}
149
150fn trait_method_call(
151 ty: TokenStream,
152 trait_name: TokenStream,
153 method_name: TokenStream,
154) -> TokenStream {
155 // doing the <ty as settings::SettingsUi> makes the error message better:
156 // -> "#ty Doesn't implement settings::SettingsUi" instead of "no item "settings_ui_item" for #ty"
157 // and ensures safety against name conflicts
158 //
159 // todo(settings_ui): Turn `Vec<T>` into `Vec::<T>` here as well
160 quote! {
161 <#ty as #trait_name>::#method_name()
162 }
163}
164
165fn generate_ui_item_body(group_name: Option<&String>, input: &syn::DeriveInput) -> TokenStream {
166 match (group_name, &input.data) {
167 (_, Data::Union(_)) => unimplemented!("Derive SettingsUi for Unions"),
168 (None, Data::Struct(_)) => quote! {
169 settings::SettingsUiItem::None
170 },
171 (Some(_), Data::Struct(data_struct)) => {
172 let parent_serde_attrs = parse_serde_attributes(&input.attrs);
173 item_group_from_fields(&data_struct.fields, &parent_serde_attrs)
174 }
175 (None, Data::Enum(data_enum)) => {
176 let serde_attrs = parse_serde_attributes(&input.attrs);
177 let render_as = parse_render_as(&input.attrs);
178 let length = data_enum.variants.len();
179
180 let mut variants = Vec::with_capacity(length);
181 let mut labels = Vec::with_capacity(length);
182
183 for variant in &data_enum.variants {
184 // todo(settings_ui): Can #[serde(rename = )] be on enum variants?
185 let ident = variant.ident.clone().to_string();
186 let variant_name = serde_attrs.rename_all.apply(&ident);
187 let title = variant_name.to_title_case();
188
189 variants.push(variant_name);
190 labels.push(title);
191 }
192
193 let is_not_union = data_enum.variants.iter().all(|v| v.fields.is_empty());
194 if is_not_union {
195 return match render_as {
196 RenderAs::ToggleGroup if length > 6 => {
197 panic!("Can't set toggle group with more than six entries");
198 }
199 RenderAs::ToggleGroup => {
200 quote! {
201 settings::SettingsUiItem::Single(settings::SettingsUiItemSingle::ToggleGroup{ variants: &[#(#variants),*], labels: &[#(#labels),*] })
202 }
203 }
204 RenderAs::Default => {
205 quote! {
206 settings::SettingsUiItem::Single(settings::SettingsUiItemSingle::DropDown{ variants: &[#(#variants),*], labels: &[#(#labels),*] })
207 }
208 }
209 };
210 }
211 // else: Union!
212 let enum_name = &input.ident;
213
214 let options = data_enum.variants.iter().map(|variant| {
215 if variant.fields.is_empty() {
216 return quote! {None};
217 }
218 let name = &variant.ident;
219 let item = item_group_from_fields(&variant.fields, &serde_attrs);
220 // todo(settings_ui): documentation
221 return quote! {
222 Some(settings::SettingsUiEntry {
223 path: None,
224 title: stringify!(#name),
225 documentation: None,
226 item: #item,
227 })
228 };
229 });
230 let defaults = data_enum.variants.iter().map(|variant| {
231 let variant_name = &variant.ident;
232 if variant.fields.is_empty() {
233 quote! {
234 serde_json::to_value(#enum_name::#variant_name).expect("Failed to serialize default value for #enum_name::#variant_name")
235 }
236 } else {
237 let fields = variant.fields.iter().enumerate().map(|(index, field)| {
238 let field_name = field.ident.as_ref().map_or_else(|| syn::Index::from(index).into_token_stream(), |ident| ident.to_token_stream());
239 let field_type_is_option = option_inner_type(field.ty.to_token_stream()).is_some();
240 let field_default = if field_type_is_option {
241 quote! {
242 None
243 }
244 } else {
245 quote! {
246 ::std::default::Default::default()
247 }
248 };
249
250 quote!{
251 #field_name: #field_default
252 }
253 });
254 quote! {
255 serde_json::to_value(#enum_name::#variant_name {
256 #(#fields),*
257 }).expect("Failed to serialize default value for #enum_name::#variant_name")
258 }
259 }
260 });
261 // todo(settings_ui): Identify #[default] attr and use it for index, defaulting to 0
262 let default_variant_index: usize = 0;
263 let determine_option_fn = {
264 let match_arms = data_enum
265 .variants
266 .iter()
267 .enumerate()
268 .map(|(index, variant)| {
269 let variant_name = &variant.ident;
270 quote! {
271 Ok(#variant_name {..}) => #index
272 }
273 });
274 quote! {
275 |value: &serde_json::Value, _cx: &gpui::App| -> usize {
276 use #enum_name::*;
277 match serde_json::from_value::<#enum_name>(value.clone()) {
278 #(#match_arms),*,
279 Err(_) => #default_variant_index,
280 }
281 }
282 }
283 };
284 // todo(settings_ui) should probably always use toggle group for unions, dropdown makes less sense
285 return quote! {
286 settings::SettingsUiItem::Union(settings::SettingsUiItemUnion {
287 defaults: Box::new([#(#defaults),*]),
288 labels: &[#(#labels),*],
289 options: Box::new([#(#options),*]),
290 determine_option: #determine_option_fn,
291 })
292 };
293 // panic!("Unhandled");
294 }
295 // todo(settings_ui) discriminated unions
296 (_, Data::Enum(_)) => quote! {
297 settings::SettingsUiItem::None
298 },
299 }
300}
301
302fn item_group_from_fields(fields: &syn::Fields, parent_serde_attrs: &SerdeOptions) -> TokenStream {
303 let group_items = fields
304 .iter()
305 .filter(|field| {
306 !field.attrs.iter().any(|attr| {
307 let mut has_skip = false;
308 if attr.path().is_ident("settings_ui") {
309 let _ = attr.parse_nested_meta(|meta| {
310 if meta.path.is_ident("skip") {
311 has_skip = true;
312 }
313 Ok(())
314 });
315 }
316
317 has_skip
318 })
319 })
320 .map(|field| {
321 let field_serde_attrs = parse_serde_attributes(&field.attrs);
322 let name = field.ident.as_ref().map(ToString::to_string);
323 let title = name.as_ref().map_or_else(
324 || "todo(settings_ui): Titles for tuple fields".to_string(),
325 |name| name.to_title_case(),
326 );
327 let doc_str = parse_documentation_from_attrs(&field.attrs);
328
329 (
330 title,
331 doc_str,
332 name.filter(|_| !field_serde_attrs.flatten).map(|name| {
333 parent_serde_attrs.apply_rename_to_field(&field_serde_attrs, &name)
334 }),
335 field.ty.to_token_stream(),
336 )
337 })
338 // todo(settings_ui): Re-format field name as nice title, and support setting different title with attr
339 .map(|(title, doc_str, path, ty)| {
340 map_ui_item_to_entry(path.as_deref(), &title, doc_str.as_deref(), ty)
341 });
342
343 quote! {
344 settings::SettingsUiItem::Group(settings::SettingsUiItemGroup{ items: vec![#(#group_items),*] })
345 }
346}
347
348struct SerdeOptions {
349 rename_all: SerdeRenameAll,
350 rename: Option<String>,
351 flatten: bool,
352 untagged: bool,
353 _alias: Option<String>, // todo(settings_ui)
354}
355
356#[derive(PartialEq)]
357enum SerdeRenameAll {
358 Lowercase,
359 SnakeCase,
360 None,
361}
362
363impl SerdeRenameAll {
364 fn apply(&self, name: &str) -> String {
365 match self {
366 SerdeRenameAll::Lowercase => name.to_lowercase(),
367 SerdeRenameAll::SnakeCase => name.to_snake_case(),
368 SerdeRenameAll::None => name.to_string(),
369 }
370 }
371}
372
373impl SerdeOptions {
374 fn apply_rename_to_field(&self, field_options: &Self, name: &str) -> String {
375 // field renames take precedence over struct rename all cases
376 if let Some(rename) = &field_options.rename {
377 return rename.clone();
378 }
379 return self.rename_all.apply(name);
380 }
381}
382
383enum RenderAs {
384 ToggleGroup,
385 Default,
386}
387
388fn parse_render_as(attrs: &[syn::Attribute]) -> RenderAs {
389 let mut render_as = RenderAs::Default;
390
391 for attr in attrs {
392 if !attr.path().is_ident("settings_ui") {
393 continue;
394 }
395
396 attr.parse_nested_meta(|meta| {
397 if meta.path.is_ident("render") {
398 meta.input.parse::<Token![=]>()?;
399 let lit = meta.input.parse::<LitStr>()?.value();
400
401 if lit == "toggle_group" {
402 render_as = RenderAs::ToggleGroup;
403 } else {
404 return Err(meta.error(format!("invalid `render` attribute: {}", lit)));
405 }
406 }
407 Ok(())
408 })
409 .unwrap();
410 }
411
412 render_as
413}
414
415fn parse_serde_attributes(attrs: &[syn::Attribute]) -> SerdeOptions {
416 let mut options = SerdeOptions {
417 rename_all: SerdeRenameAll::None,
418 rename: None,
419 flatten: false,
420 untagged: false,
421 _alias: None,
422 };
423
424 for attr in attrs {
425 if !attr.path().is_ident("serde") {
426 continue;
427 }
428 attr.parse_nested_meta(|meta| {
429 if meta.path.is_ident("rename_all") {
430 meta.input.parse::<Token![=]>()?;
431 let lit = meta.input.parse::<LitStr>()?.value();
432
433 if options.rename_all != SerdeRenameAll::None {
434 return Err(meta.error("duplicate `rename_all` attribute"));
435 } else if lit == "lowercase" {
436 options.rename_all = SerdeRenameAll::Lowercase;
437 } else if lit == "snake_case" {
438 options.rename_all = SerdeRenameAll::SnakeCase;
439 } else {
440 return Err(meta.error(format!("invalid `rename_all` attribute: {}", lit)));
441 }
442 // todo(settings_ui): Other options?
443 } else if meta.path.is_ident("flatten") {
444 options.flatten = true;
445 } else if meta.path.is_ident("rename") {
446 if options.rename.is_some() {
447 return Err(meta.error("Can only have one rename attribute"));
448 }
449
450 meta.input.parse::<Token![=]>()?;
451 let lit = meta.input.parse::<LitStr>()?.value();
452 options.rename = Some(lit);
453 } else if meta.path.is_ident("untagged") {
454 options.untagged = true;
455 }
456 Ok(())
457 })
458 .unwrap();
459 }
460
461 return options;
462}
463
464fn parse_documentation_from_attrs(attrs: &[syn::Attribute]) -> Option<String> {
465 let mut doc_str = Option::<String>::None;
466 for attr in attrs {
467 if attr.path().is_ident("doc") {
468 // /// ...
469 // becomes
470 // #[doc = "..."]
471 use syn::{Expr::Lit, ExprLit, Lit::Str, Meta, MetaNameValue};
472 if let Meta::NameValue(MetaNameValue {
473 value:
474 Lit(ExprLit {
475 lit: Str(ref lit_str),
476 ..
477 }),
478 ..
479 }) = attr.meta
480 {
481 let doc = lit_str.value();
482 let doc_str = doc_str.get_or_insert_default();
483 doc_str.push_str(doc.trim());
484 doc_str.push('\n');
485 }
486 }
487 }
488 return doc_str;
489}
490
491struct SettingsKey {
492 key: Option<String>,
493 fallback_key: Option<String>,
494}
495
496fn parse_setting_key_attr(attr: &syn::Attribute) -> Option<SettingsKey> {
497 if !attr.path().is_ident("settings_key") {
498 return None;
499 }
500
501 let mut settings_key = SettingsKey {
502 key: None,
503 fallback_key: None,
504 };
505
506 let mut found_none = false;
507
508 attr.parse_nested_meta(|meta| {
509 if meta.path.is_ident("None") {
510 found_none = true;
511 } else if meta.path.is_ident("key") {
512 if settings_key.key.is_some() {
513 return Err(meta.error("Only one 'group' path can be specified"));
514 }
515 meta.input.parse::<Token![=]>()?;
516 let lit: LitStr = meta.input.parse()?;
517 settings_key.key = Some(lit.value());
518 } else if meta.path.is_ident("fallback_key") {
519 if found_none {
520 return Err(meta.error("Cannot specify 'fallback_key' and 'None'"));
521 }
522
523 if settings_key.fallback_key.is_some() {
524 return Err(meta.error("Only one 'fallback_key' can be specified"));
525 }
526
527 meta.input.parse::<Token![=]>()?;
528 let lit: LitStr = meta.input.parse()?;
529 settings_key.fallback_key = Some(lit.value());
530 }
531 Ok(())
532 })
533 .unwrap_or_else(|e| panic!("in #[settings_key] attribute: {}", e));
534
535 if found_none && settings_key.fallback_key.is_some() {
536 panic!("in #[settings_key] attribute: Cannot specify 'None' and 'fallback_key'");
537 }
538 if found_none && settings_key.key.is_some() {
539 panic!("in #[settings_key] attribute: Cannot specify 'None' and 'key'");
540 }
541 if !found_none && settings_key.key.is_none() {
542 panic!("in #[settings_key] attribute: 'key' must be specified");
543 }
544
545 return Some(settings_key);
546}
547
548#[proc_macro_derive(SettingsKey, attributes(settings_key))]
549pub fn derive_settings_key(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
550 let input = parse_macro_input!(input as DeriveInput);
551 let name = &input.ident;
552
553 // Handle generic parameters if present
554 let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
555
556 let mut settings_key = Option::<SettingsKey>::None;
557
558 for attr in &input.attrs {
559 let parsed_settings_key = parse_setting_key_attr(attr);
560 if parsed_settings_key.is_some() && settings_key.is_some() {
561 panic!("Duplicate #[settings_key] attribute");
562 }
563 settings_key = settings_key.or(parsed_settings_key);
564 }
565
566 let Some(SettingsKey { key, fallback_key }) = settings_key else {
567 panic!("Missing #[settings_key] attribute");
568 };
569
570 let key = key.map_or_else(|| quote! {None}, |key| quote! {Some(#key)});
571 let fallback_key = fallback_key.map_or_else(
572 || quote! {None},
573 |fallback_key| quote! {Some(#fallback_key)},
574 );
575
576 let expanded = quote! {
577 impl #impl_generics settings::SettingsKey for #name #ty_generics #where_clause {
578 const KEY: Option<&'static str> = #key;
579
580 const FALLBACK_KEY: Option<&'static str> = #fallback_key;
581 };
582 };
583
584 proc_macro::TokenStream::from(expanded)
585}
586
587#[cfg(test)]
588mod tests {
589 use syn::{Attribute, parse_quote};
590
591 use super::*;
592
593 #[test]
594 fn test_extract_key() {
595 let input: Attribute = parse_quote!(
596 #[settings_key(key = "my_key")]
597 );
598 let settings_key = parse_setting_key_attr(&input).unwrap();
599 assert_eq!(settings_key.key, Some("my_key".to_string()));
600 assert_eq!(settings_key.fallback_key, None);
601 }
602
603 #[test]
604 fn test_empty_key() {
605 let input: Attribute = parse_quote!(
606 #[settings_key(None)]
607 );
608 let settings_key = parse_setting_key_attr(&input).unwrap();
609 assert_eq!(settings_key.key, None);
610 assert_eq!(settings_key.fallback_key, None);
611 }
612}