Skip to content

Commit e12ec62

Browse files
committed
option default_by_default
1 parent b3ff141 commit e12ec62

File tree

3 files changed

+24
-10
lines changed

3 files changed

+24
-10
lines changed

macro/src/lib.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,9 +135,11 @@ pub fn attribute_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStre
135135
}
136136
} else {
137137
quote! {
138-
#ident: __options.#ident.map(|t| ::attribute_derive::ConvertParsed::convert(t)).ok_or_else(||
139-
#syn::Error::new(#pm2::Span::call_site(), #error)
140-
)??
138+
#ident: match __options.#ident.map(|t| ::attribute_derive::ConvertParsed::convert(t)) {
139+
Some(__option) => __option?,
140+
None if <#ty as ::attribute_derive::ConvertParsed>::default_by_default() => <#ty as ::attribute_derive::ConvertParsed>::default(),
141+
_ => #err(#syn::Error::new(#pm2::Span::call_site(), #error))?,
142+
}
141143
}
142144
});
143145

src/lib.rs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ use std::fmt::Display;
88
use proc_macro2::{Literal, Span};
99
pub use r#macro::Attribute;
1010
use syn::{
11-
bracketed, parse::Parse, punctuated::Punctuated, Expr, Lit, LitBool,
12-
LitByteStr, LitChar, LitFloat, LitInt, LitStr, Path, Result, Token, Type, __private::ToTokens,
11+
bracketed, parse::Parse, punctuated::Punctuated, Expr, Lit, LitBool, LitByteStr, LitChar,
12+
LitFloat, LitInt, LitStr, Path, Result, Token, Type, __private::ToTokens,
1313
};
1414

1515
pub mod __private {
@@ -31,6 +31,12 @@ where
3131
{
3232
type Type;
3333
fn convert(value: Self::Type) -> Result<Self>;
34+
fn default_by_default() -> bool {
35+
false
36+
}
37+
fn default() -> Self {
38+
unreachable!("default_by_default should only return true if this is overridden")
39+
}
3440
}
3541

3642
/// Helper trait to generate sensible errors
@@ -104,6 +110,14 @@ where
104110
fn convert(s: Parsed) -> Result<Self> {
105111
Ok(Some(ConvertParsed::convert(s)?))
106112
}
113+
114+
fn default_by_default() -> bool {
115+
true
116+
}
117+
118+
fn default() -> Self {
119+
Default::default()
120+
}
107121
}
108122

109123
impl<Output, Parsed> ConvertParsed for Vec<Output>

tests/derive.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,11 @@ fn test() {
1010
// a: u8,
1111
b: LitStr,
1212
c: String,
13-
#[attribute(default)]
1413
oc: Option<String>,
15-
#[attribute(default)]
1614
od: Option<Type>,
1715
d: Type,
1816
e: Expr,
19-
f: Vec<Type>
17+
f: Vec<Type>,
2018
}
2119

2220
let parsed = Test::from_attributes([
@@ -74,10 +72,10 @@ fn error() {
7472
fn error2() {
7573
#[derive(Attribute, Debug)]
7674
#[attribute(test)]
75+
#[allow(dead_code)]
7776
struct Test {
78-
#[allow(dead_code)]
7977
a: f32,
80-
b: u8
78+
b: u8,
8179
}
8280

8381
assert_eq!(

0 commit comments

Comments
 (0)