Give better error if generics are used with #[derive(FromRef)] (#1874)

This commit is contained in:
David Pedersen 2023-03-22 14:48:27 +01:00 committed by GitHub
parent 3fb67bf79d
commit cfb5df7050
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 29 additions and 4 deletions

View file

@ -8,8 +8,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
# Unreleased # Unreleased
- **change:** Update to syn 2.0 ([#1862]) - **change:** Update to syn 2.0 ([#1862])
- **fixed:** Give better error if generics are used with `#[derive(FromRef)]` ([#1874])
[#1862]: https://github.com/tokio-rs/axum/pull/1862 [#1862]: https://github.com/tokio-rs/axum/pull/1862
[#1874]: https://github.com/tokio-rs/axum/pull/1874
# 0.3.6 (13. March, 2023) # 0.3.6 (13. March, 2023)

View file

@ -8,12 +8,22 @@ use syn::{
use crate::attr_parsing::{combine_unary_attribute, parse_attrs, Combine}; use crate::attr_parsing::{combine_unary_attribute, parse_attrs, Combine};
pub(crate) fn expand(item: ItemStruct) -> TokenStream { pub(crate) fn expand(item: ItemStruct) -> syn::Result<TokenStream> {
item.fields if !item.generics.params.is_empty() {
return Err(syn::Error::new_spanned(
item.generics,
"`#[derive(FromRef)]` doesn't support generics",
));
}
let tokens = item
.fields
.iter() .iter()
.enumerate() .enumerate()
.map(|(idx, field)| expand_field(&item.ident, idx, field)) .map(|(idx, field)| expand_field(&item.ident, idx, field))
.collect() .collect();
Ok(tokens)
} }
fn expand_field(state: &Ident, idx: usize, field: &Field) -> TokenStream { fn expand_field(state: &Ident, idx: usize, field: &Field) -> TokenStream {

View file

@ -655,7 +655,7 @@ pub fn derive_typed_path(input: TokenStream) -> TokenStream {
/// [`FromRef`]: https://docs.rs/axum/latest/axum/extract/trait.FromRef.html /// [`FromRef`]: https://docs.rs/axum/latest/axum/extract/trait.FromRef.html
#[proc_macro_derive(FromRef, attributes(from_ref))] #[proc_macro_derive(FromRef, attributes(from_ref))]
pub fn derive_from_ref(item: TokenStream) -> TokenStream { pub fn derive_from_ref(item: TokenStream) -> TokenStream {
expand_with(item, |item| Ok(from_ref::expand(item))) expand_with(item, from_ref::expand)
} }
fn expand_with<F, I, K>(input: TokenStream, f: F) -> TokenStream fn expand_with<F, I, K>(input: TokenStream, f: F) -> TokenStream

View file

@ -0,0 +1,8 @@
use axum::extract::FromRef;
#[derive(Clone, FromRef)]
struct AppState<T> {
foo: T,
}
fn main() {}

View file

@ -0,0 +1,5 @@
error: `#[derive(FromRef)]` doesn't support generics
--> tests/from_ref/fail/generics.rs:4:16
|
4 | struct AppState<T> {
| ^^^