forked from colin-kiegel/rust-derive-builder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder_field.rs
182 lines (165 loc) · 5.47 KB
/
builder_field.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
use crate::wrap_expression_in_some;
use proc_macro2::TokenStream;
use quote::{ToTokens, TokenStreamExt};
use syn;
/// Field for the builder struct, implementing `quote::ToTokens`.
///
/// # Examples
///
/// Will expand to something like the following (depending on settings):
///
/// ```rust,ignore
/// # extern crate proc_macro2;
/// # #[macro_use]
/// # extern crate quote;
/// # #[macro_use]
/// # extern crate syn;
/// # #[macro_use]
/// # extern crate derive_builder_core;
/// # use derive_builder_core::{BuilderField, BuilderPattern};
/// # fn main() {
/// # let attrs = vec![parse_quote!(#[some_attr])];
/// # let mut field = default_builder_field!();
/// # field.attrs = attrs.as_slice();
/// #
/// # assert_eq!(quote!(#field).to_string(), quote!(
/// #[some_attr] pub foo: ::derive_builder::export::core::option::Option<String>,
/// # ).to_string());
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct BuilderField<'a> {
/// Name of the target field.
pub field_ident: &'a syn::Ident,
/// Type of the target field.
pub field_type: BuilderFieldType<'a>,
/// Whether the builder implements a setter for this field.
///
/// Note: We will fallback to `PhantomData` if the setter is disabled
/// to hack around issues with unused generic type parameters - at
/// least for now.
pub field_enabled: bool,
/// Visibility of this builder field, e.g. `syn::Visibility::Public`.
pub field_visibility: syn::Visibility,
/// Attributes which will be attached to this builder field.
pub attrs: &'a [syn::Attribute],
}
/// The type of a field in the builder struct
#[derive(Debug, Clone)]
pub enum BuilderFieldType<'a> {
/// The corresonding builder field will be `Option<field_type>`.
Optional(&'a syn::Type),
/// The corresponding builder field will be just this type
Precisely(&'a syn::Type),
}
impl<'a> BuilderFieldType<'a> {
/// Some call sites want the target field type
pub fn target_type(&'a self) -> &'a syn::Type {
match self {
BuilderFieldType::Optional(ty) => ty,
BuilderFieldType::Precisely(ty) => ty,
}
}
/// Returns expression wrapping `bare_value` in Some, if appropriate
pub fn wrap_some(&'a self, bare_value: TokenStream) -> TokenStream {
match self {
BuilderFieldType::Optional(_) => wrap_expression_in_some(bare_value),
BuilderFieldType::Precisely(_) => bare_value,
}
}
}
impl<'a> ToTokens for BuilderFieldType<'a> {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
BuilderFieldType::Optional(ty) => tokens.append_all(quote!(
::derive_builder::export::core::option::Option<#ty>
)),
BuilderFieldType::Precisely(ty) => ty.to_tokens(tokens),
}
}
}
impl<'a> ToTokens for BuilderField<'a> {
fn to_tokens(&self, tokens: &mut TokenStream) {
if self.field_enabled {
let vis = &self.field_visibility;
let ident = self.field_ident;
let ty = &self.field_type;
let attrs = self.attrs;
tokens.append_all(quote!(
#(#attrs)* #vis #ident: #ty,
));
} else {
let ident = self.field_ident;
let ty = self.field_type.target_type();
let attrs = self.attrs;
tokens.append_all(quote!(
#(#attrs)* #ident: ::derive_builder::export::core::marker::PhantomData<#ty>,
));
}
}
}
impl<'a> BuilderField<'a> {
/// Emits a struct field initializer that initializes the field to `Default::default`.
pub fn default_initializer_tokens(&self) -> TokenStream {
let ident = self.field_ident;
quote! { #ident : ::derive_builder::export::core::default::Default::default(), }
}
}
/// Helper macro for unit tests. This is _only_ public in order to be accessible
/// from doc-tests too.
#[doc(hidden)]
#[macro_export]
macro_rules! default_builder_field {
() => {{
BuilderField {
field_ident: &syn::Ident::new("foo", ::proc_macro2::Span::call_site()),
field_type: BuilderFieldType::Optional(Box::leak(Box::new(parse_quote!(String)))),
field_enabled: true,
field_visibility: parse_quote!(pub),
attrs: &[parse_quote!(#[some_attr])],
}
}};
}
#[cfg(test)]
mod tests {
#[allow(unused_imports)]
use super::*;
#[test]
fn setter_enabled() {
let field = default_builder_field!();
assert_eq!(
quote!(#field).to_string(),
quote!(
#[some_attr] pub foo: ::derive_builder::export::core::option::Option<String>,
)
.to_string()
);
}
#[test]
fn setter_disabled() {
let mut field = default_builder_field!();
field.field_enabled = false;
assert_eq!(
quote!(#field).to_string(),
quote!(
#[some_attr]
foo: ::derive_builder::export::core::marker::PhantomData<String>,
)
.to_string()
);
}
#[test]
fn private_field() {
let private = syn::Visibility::Inherited;
let mut field = default_builder_field!();
field.field_visibility = private;
assert_eq!(
quote!(#field).to_string(),
quote!(
#[some_attr]
foo: ::derive_builder::export::core::option::Option<String>,
)
.to_string()
);
}
}