Skip to main content

shep_macros/
lib.rs

1//! The `dog_config` attribute, and nothing else.
2//!
3//! A dog publishes a JSON Schema for its config so shep can render a
4//! settings pane. A credential field needs marking, shown as `<set>` rather
5//! than its value, and a field with one value per dog needs marking as
6//! dog-wide. `schemars` can mark either by hand with an `extend("x-shep-...")`
7//! key, a string an author can misspell silently. This attribute writes it,
8//! and turns a misspelled option into a compile error.
9//!
10//! Depend on `shep-client`, not this crate: it re-exports the attribute.
11
12#![forbid(unsafe_code)]
13
14use proc_macro::TokenStream;
15use proc_macro2::TokenStream as TokenStream2;
16use quote::quote;
17use syn::{Attribute, Data, DeriveInput, Field, Meta, Token, parse_macro_input, parse_quote};
18
19/// The attribute this macro claims on a field.
20const ATTR: &str = "shep";
21
22/// The option that marks a credential.
23const SECRET: &str = "secret";
24
25/// The option that marks a field set only in the dog's own section.
26const DOG_WIDE: &str = "dog_wide";
27
28/// The derive a marked field's extension rides on, checked by name because a
29/// macro cannot resolve a path.
30const JSON_SCHEMA: &str = "JsonSchema";
31
32/// Marks which of a dog's config fields are credentials, or hold one value
33/// per dog, so the author never types the `schemars` extension key.
34///
35/// Put it above the derives on the type a dog deserializes its config into.
36/// Mark a credential `#[shep(secret)]` and a per-dog field `#[shep(dog_wide)]`.
37/// A marked field with no `JsonSchema` derive below it is refused.
38///
39/// # Example
40///
41/// ```rust
42/// use shep_client::dogs::dog_config;
43///
44/// #[dog_config]
45/// #[derive(serde::Deserialize, schemars::JsonSchema)]
46/// #[serde(tag = "kind", rename_all = "snake_case")]
47/// enum Sink {
48///     Discord {
49///         #[shep(secret)]
50///         url: String,
51///     },
52///     Slack {
53///         #[shep(secret)]
54///         url: String,
55///     },
56/// }
57/// ```
58///
59/// The mark rides the field rather than naming it, so it reaches a property
60/// `schemars` renamed and one nested inside another type's subschema. A type
61/// with no marked field is unaffected: it takes no new attribute and needs no
62/// derive, which is what keeps `shep-client`'s `schema` feature optional.
63/// Every deliberate refusal is a compile error with its own message.
64///
65/// The expansion, with each mark replaced by its `schemars` extension and an `impl shep_client::dogs::DogConfig` added:
66///
67/// ```rust,ignore
68/// #[derive(serde::Deserialize, schemars::JsonSchema)]
69/// #[serde(tag = "kind", rename_all = "snake_case")]
70/// enum Sink {
71///     Discord {
72///         #[schemars(extend("x-shep-secret" = true))]
73///         url: String,
74///     },
75///     // ...
76/// }
77///
78/// impl ::shep_client::dogs::DogConfig for Sink {}
79/// ```
80#[proc_macro_attribute]
81pub fn dog_config(args: TokenStream, input: TokenStream) -> TokenStream {
82    let args = TokenStream2::from(args);
83    let mut input = parse_macro_input!(input as DeriveInput);
84    match expand(&args, &mut input) {
85        Ok(tokens) => tokens.into(),
86        Err(err) => {
87            // The type is emitted even on the error path, stripped of
88            // attributes only this macro knows. Dropping it leaves the derives
89            // above holding an impl for a type that no longer exists. One
90            // error, not a cascade.
91            strip_shep_attributes(&mut input);
92            let refusal = err.into_compile_error();
93            let carry_on = dog_config_impl(&input);
94            quote! {
95                #input
96                #carry_on
97                #refusal
98            }
99            .into()
100        }
101    }
102}
103
104/// The macro's whole body, in a form that can return an error instead of
105/// a token stream.
106///
107/// Mutates `input`: a marked field loses its `#[shep(secret)]` and gains the
108/// `schemars` extension. The attribute has to go, since nothing downstream
109/// registers it and rustc refuses an attribute no macro claims.
110fn expand(args: &TokenStream2, input: &mut DeriveInput) -> syn::Result<TokenStream2> {
111    if !args.is_empty() {
112        return Err(syn::Error::new_spanned(
113            args,
114            "`#[dog_config]` takes no arguments: the marking goes on the \
115             fields, as `#[shep(secret)]`",
116        ));
117    }
118
119    if let Some(attr) = find_shep_attribute(&input.attrs) {
120        return Err(syn::Error::new_spanned(
121            attr,
122            "`#[shep(secret)]` marks a field, not the type: move it onto the \
123             field that holds the credential",
124        ));
125    }
126
127    // Every refusal is decided before a single extension goes on, because
128    // the error path emits the type: a half-marked one would carry a
129    // `schemars` attribute with no derive left to claim it, and rustc would
130    // report that ahead of the refusal that explains it.
131    let derives_json_schema = derives_json_schema(&input.attrs);
132    let mut marked: Vec<(&mut Field, Marks)> = Vec::new();
133    for field in fields_of_mut(input)? {
134        let marks = take_marks(field)?;
135        if marks == Marks::default() {
136            continue;
137        }
138        if field.ident.is_none() {
139            return Err(syn::Error::new_spanned(
140                field,
141                "`#[shep(...)]` cannot mark an unnamed field: `schemars` \
142                 puts it in `prefixItems`, where a settings pane reading \
143                 properties by name has nothing to find. Name the field.",
144            ));
145        }
146        marked.push((field, marks));
147    }
148
149    if !marked.is_empty() && !derives_json_schema {
150        return Err(syn::Error::new_spanned(
151            &input.ident,
152            "a `#[shep(secret)]` or `#[shep(dog_wide)]` field needs \
153             `#[derive(schemars::JsonSchema)]` BELOW `#[dog_config]` on this \
154             type. The mark is written as a `schemars` attribute, so a derive \
155             listed above this one has already expanded without it and the \
156             field would go out unmarked. Move `#[dog_config]` above the \
157             derives, or add the derive.",
158        ));
159    }
160
161    for (field, marks) in marked {
162        if marks.secret {
163            field.attrs.push(secret_extension());
164        }
165        if marks.dog_wide {
166            field.attrs.push(dog_wide_extension());
167        }
168    }
169
170    let carry_on = dog_config_impl(input);
171    Ok(quote! {
172        #input
173
174        #carry_on
175    })
176}
177
178/// The impl the attribute exists to write.
179///
180/// Emitted on the error path too, so a refusal does not also break every
181/// `probe::<T>` and `config_schema::<T>` the dog calls. The build still
182/// fails on the refusal; what this buys is that it fails once, naming the
183/// real problem.
184fn dog_config_impl(input: &DeriveInput) -> TokenStream2 {
185    let name = &input.ident;
186    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
187    quote! {
188        impl #impl_generics ::shep_client::dogs::DogConfig
189            for #name #ty_generics #where_clause {}
190    }
191}
192
193/// Removes every `#[shep(...)]` from the type, its variants and its fields.
194///
195/// Nothing downstream registers the attribute, so one left behind is an
196/// error of its own on top of whatever refusal is being reported.
197fn strip_shep_attributes(input: &mut DeriveInput) {
198    let is_shep = |attr: &Attribute| attr.path().is_ident(ATTR);
199    input.attrs.retain(|attr| !is_shep(attr));
200    let fields: Vec<&mut Field> = match &mut input.data {
201        Data::Struct(data) => data.fields.iter_mut().collect(),
202        Data::Enum(data) => data
203            .variants
204            .iter_mut()
205            .flat_map(|variant| {
206                variant.attrs.retain(|attr| !is_shep(attr));
207                variant.fields.iter_mut()
208            })
209            .collect(),
210        Data::Union(data) => data.fields.named.iter_mut().collect(),
211    };
212    for field in fields {
213        field.attrs.retain(|attr| !is_shep(attr));
214    }
215}
216
217/// Whether the type still has a `derive` naming `JsonSchema` for the
218/// extension on a marked field to reach.
219///
220/// False for a type that derives it ABOVE `#[dog_config]` as well as for one
221/// that does not derive it at all: rustc expands the attributes above this
222/// one first and leaves none of them in the input, so the two are the same
223/// picture from here and have the same fix.
224fn derives_json_schema(attrs: &[Attribute]) -> bool {
225    attrs
226        .iter()
227        .filter(|attr| attr.path().is_ident("derive"))
228        .any(|attr| {
229            let mut found = false;
230            // A `derive` that will not parse as a path list is rustc's error to
231            // report, not this macro's, so a failure here says only "not found".
232            let _ = attr.parse_nested_meta(|meta| {
233                if meta
234                    .path
235                    .segments
236                    .last()
237                    .is_some_and(|last| last.ident == JSON_SCHEMA)
238                {
239                    found = true;
240                }
241                Ok(())
242            });
243            found
244        })
245}
246
247/// The `schemars` extension a marked field carries.
248///
249/// The key is a literal because `schemars` accepts only a literal in that
250/// position, which is the whole reason this crate exists. It must stay equal
251/// to `shep_core::dogs::SECRET_KEY`, and
252/// `the_extension_key_is_the_one_shep_core_publishes` in `shep-client` is
253/// what fails when it does not.
254fn secret_extension() -> Attribute {
255    parse_quote!(#[schemars(extend("x-shep-secret" = true))])
256}
257
258/// The `schemars` extension a dog-wide field carries.
259///
260/// A literal for the same reason as [`secret_extension`]. It must stay equal
261/// to `shep_core::dogs::DOG_WIDE_KEY`, and
262/// `the_marker_key_is_the_one_shep_core_publishes` in `shep-client` fails when
263/// it does not.
264fn dog_wide_extension() -> Attribute {
265    parse_quote!(#[schemars(extend("x-shep-dog-wide" = true))])
266}
267
268/// Every field the type has, a struct's directly and an enum's
269/// gathered from its variants.
270///
271/// Unit variants and unmarked tuples have no fields to collect, so they
272/// come back empty. A union is refused outright: it has no serde
273/// representation for a mark to land on. [`expand`] checks each
274/// collected field once it knows which carry a mark.
275fn fields_of_mut(input: &mut DeriveInput) -> syn::Result<Vec<&mut Field>> {
276    match &mut input.data {
277        Data::Struct(data) => Ok(data.fields.iter_mut().collect()),
278        Data::Enum(data) => {
279            let mut fields = Vec::new();
280            for variant in &mut data.variants {
281                if let Some(attr) = find_shep_attribute(&variant.attrs) {
282                    return Err(syn::Error::new_spanned(
283                        attr,
284                        "`#[shep(secret)]` marks a field, not a variant: move \
285                         it onto the field inside that holds the credential",
286                    ));
287                }
288                fields.extend(variant.fields.iter_mut());
289            }
290            Ok(fields)
291        }
292        Data::Union(_) => Err(syn::Error::new_spanned(
293            &input.ident,
294            "`#[dog_config]` cannot be used on a union: a union has no serde \
295             representation, so there is no schema for a mark to go into",
296        )),
297    }
298}
299
300/// The marks a field carries.
301#[derive(Debug, Default, PartialEq, Eq)]
302struct Marks {
303    secret: bool,
304    dog_wide: bool,
305}
306
307/// The marks a field carries, removing every `#[shep(...)]` it finds.
308///
309/// Repeating an option on one field is accepted and marks it once. It is
310/// redundant rather than wrong. A second error message would be noise next
311/// to the one that matters: a misspelled option.
312fn take_marks(field: &mut Field) -> syn::Result<Marks> {
313    let mut marks = Marks::default();
314    for attr in &field.attrs {
315        if !attr.path().is_ident(ATTR) {
316            continue;
317        }
318        if !matches!(&attr.meta, Meta::List(list) if !list.tokens.is_empty()) {
319            return Err(syn::Error::new_spanned(
320                attr,
321                "`#[shep]` needs an option in parentheses: `secret` or \
322                 `dog_wide`, as in `#[shep(secret)]`",
323            ));
324        }
325        attr.parse_nested_meta(|meta| {
326            let mark = if meta.path.is_ident(SECRET) {
327                &mut marks.secret
328            } else if meta.path.is_ident(DOG_WIDE) {
329                &mut marks.dog_wide
330            } else {
331                return Err(meta.error(
332                    "unknown `shep` option: the options are `secret` and \
333                     `dog_wide`, as in `#[shep(secret)]`",
334                ));
335            };
336            if meta.input.peek(Token![=]) {
337                return Err(meta.error(
338                    "`secret` and `dog_wide` are flags and take no value: \
339                     write `#[shep(secret)]`",
340                ));
341            }
342            *mark = true;
343            Ok(())
344        })?;
345    }
346    field.attrs.retain(|attr| !attr.path().is_ident(ATTR));
347    Ok(marks)
348}
349
350/// The first `#[shep(...)]` in a list, for the places one does not belong.
351fn find_shep_attribute(attrs: &[Attribute]) -> Option<&Attribute> {
352    attrs.iter().find(|attr| attr.path().is_ident(ATTR))
353}