bon_macros/builder/builder_gen/
getters.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
use super::member::{GetterConfig, GetterKind};
use super::{BuilderGenCtx, NamedMember};
use crate::parsing::SpannedKey;
use crate::util::prelude::*;
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;

pub(crate) struct GettersCtx<'a> {
    base: &'a BuilderGenCtx,
    member: &'a NamedMember,
    config: &'a GetterConfig,
}

impl<'a> GettersCtx<'a> {
    pub(crate) fn new(base: &'a BuilderGenCtx, member: &'a NamedMember) -> Option<Self> {
        Some(Self {
            base,
            member,
            config: member.config.getter.as_ref()?,
        })
    }

    pub(crate) fn getter_methods(self) -> Result<TokenStream> {
        let name = self.config.name.as_deref().cloned().unwrap_or_else(|| {
            syn::Ident::new(
                &format!("get_{}", self.member.name.snake.raw_name()),
                self.member.name.snake.span(),
            )
        });

        let vis = self
            .config
            .vis
            .as_deref()
            .unwrap_or(&self.base.builder_type.vis)
            .clone();

        let docs = self.config.docs.as_deref().cloned().unwrap_or_else(|| {
            let header = format!(
                "_**Getter.**_ Returns `{}`, which must be set before calling this method.\n\n",
                self.member.name.snake,
            );

            std::iter::once(syn::parse_quote!(#[doc = #header]))
                .chain(self.member.docs.iter().cloned())
                .collect()
        });

        let return_ty = self.return_ty()?;
        let body = self.body();

        let state_var = &self.base.state_var;
        let member_pascal = &self.member.name.pascal;
        let state_mod = &self.base.state_mod.ident;

        Ok(quote! {
            #( #docs )*
            #[allow(
                // This is intentional. We want the builder syntax to compile away
                clippy::inline_always,
                clippy::missing_const_for_fn,
            )]
            #[inline(always)]
            #[must_use = "this method has no side effects; it only returns a value"]
            #vis fn #name(&self) -> #return_ty
            where
                #state_var::#member_pascal: #state_mod::IsSet,
            {
                #body
            }
        })
    }

    fn body(&self) -> TokenStream {
        let index = &self.member.index;
        let member = quote! {
            self.__unsafe_private_named.#index
        };

        let bon = &self.base.bon;

        match self.config.kind.as_deref() {
            Some(GetterKind::Copy) => {
                // Use a `_` type hint with the span of the original type
                // to make the compiler point to the original type in case
                // if the type doesn't implement `Copy`.
                let span = self.member.underlying_orig_ty().span();
                let ty = quote_spanned!(span=> _);

                let copy = quote! {
                    #bon::__::better_errors::copy_member::<#ty>(&#member)
                };

                if !self.member.is_required() {
                    return copy;
                }
                quote! {
                    // SAFETY: the method requires S::{Member}: IsSet, so it's Some
                    unsafe {
                        ::core::option::Option::unwrap_unchecked(#copy)
                    }
                }
            }
            Some(GetterKind::Clone) => {
                // Use a `_` type hint with the span of the original type
                // to make the compiler point to the original type in case
                // if the type doesn't implement `Clone`.
                let span = self.member.underlying_orig_ty().span();
                let ty = quote_spanned!(span=> _);

                let clone = quote! {
                    <#ty as ::core::clone::Clone>::clone
                };

                if !self.member.is_required() {
                    return quote! {
                        #clone(&#member)
                    };
                }
                quote! {
                    match &#member {
                        Some(value) => #clone(value),

                        // SAFETY: the method requires S::{Member}: IsSet, so it's Some
                        None => unsafe {
                            ::core::hint::unreachable_unchecked()
                        },
                    }
                }
            }
            Some(GetterKind::Deref(ty)) => {
                // Assign the span of the deref target type to the `value` variable
                // so that compiler points to that type if there is a type mismatch.
                let span = ty.span();
                let value = quote_spanned!(span=> value);

                if !self.member.is_required() {
                    return quote! {
                        // Explicit match is important to trigger an implicit deref coercion
                        // that can potentially do multiple derefs to the reach the target type.
                        match &#member {
                            Some(#value) => Some(#value),
                            None => None,
                        }
                    };
                }
                quote! {
                    // Explicit match is important to trigger an implicit deref coercion
                    // that can potentially do multiple derefs to the reach the target type.
                    match &#member {
                        Some(#value) => #value,

                        // SAFETY: the method requires S::{Member}: IsSet, so it's Some
                        None => unsafe {
                            ::core::hint::unreachable_unchecked()
                        },
                    }
                }
            }
            None => {
                if !self.member.is_required() {
                    return quote! {
                        ::core::option::Option::as_ref(&#member)
                    };
                }
                quote! {
                    match &#member {
                        Some(value) => value,

                        // SAFETY: the method requires S::{Member}: IsSet, so it's Some
                        None => unsafe {
                            ::core::hint::unreachable_unchecked()
                        },
                    }
                }
            }
        }
    }

    fn return_ty(&self) -> Result<TokenStream> {
        let underlying_return_ty = self.underlying_return_ty()?;

        Ok(if self.member.is_required() {
            quote! { #underlying_return_ty }
        } else {
            // We are not using the fully qualified path to `Option` here
            // to make function signature in IDE popus shorter and more
            // readable.
            quote! { Option<#underlying_return_ty> }
        })
    }

    fn underlying_return_ty(&self) -> Result<TokenStream> {
        let ty = self.member.underlying_norm_ty();

        let kind = match &self.config.kind {
            Some(kind) => kind,
            None => return Ok(quote! { &#ty }),
        };

        match &kind.value {
            GetterKind::Copy | GetterKind::Clone => Ok(quote! { #ty }),
            GetterKind::Deref(Some(deref_target)) => Ok(quote! { &#deref_target }),
            GetterKind::Deref(None) => Self::infer_deref_target(ty, kind),
        }
    }

    fn infer_deref_target(
        underlying_member_ty: &syn::Type,
        kind: &SpannedKey<GetterKind>,
    ) -> Result<TokenStream> {
        use quote_spanned as qs;

        let span = underlying_member_ty.span();

        #[allow(clippy::type_complexity)]
        let deref_target_inference_table: &[(_, &dyn Fn(&Punctuated<_, _>) -> _)] = &[
            ("Vec", &|args| args.first().map(|arg| qs!(span=> [#arg]))),
            ("Box", &|args| args.first().map(ToTokens::to_token_stream)),
            ("Rc", &|args| args.first().map(ToTokens::to_token_stream)),
            ("Arc", &|args| args.first().map(ToTokens::to_token_stream)),
            ("String", &|args| args.is_empty().then(|| qs!(span=> str))),
            ("CString", &|args| {
                // CStr is available via `core` since 1.64.0:
                // https://blog.rust-lang.org/2022/09/22/Rust-1.64.0.html#c-compatible-ffi-types-in-core-and-alloc
                let module = if rustversion::cfg!(since(1.64.0)) {
                    format_ident!("core")
                } else {
                    format_ident!("std")
                };
                args.is_empty().then(|| qs!(span=> ::#module::ffi::CStr))
            }),
            ("OsString", &|args| {
                args.is_empty().then(|| qs!(span=> ::std::ffi::OsStr))
            }),
            ("PathBuf", &|args| {
                args.is_empty().then(|| qs!(span=> ::std::path::Path))
            }),
            ("Cow", &|args| {
                args.iter()
                    .find(|arg| matches!(arg, syn::GenericArgument::Type(_)))
                    .map(ToTokens::to_token_stream)
            }),
        ];

        let err = || {
            let inferable_types = deref_target_inference_table
                .iter()
                .map(|(name, _)| format!("- {name}"))
                .join("\n");

            err!(
                &kind.key,
                "can't infer the `Deref::Target` for the getter from the member's type; \
                please specify the return type (target of the deref coercion) explicitly \
                in parentheses without the leading `&`;\n\
                example: `#[builder(getter(deref(TargetTypeHere))]`\n\
                \n\
                automatic deref target detection is supported only for the following types:\n\
                {inferable_types}",
            )
        };

        let path = underlying_member_ty.as_path_no_qself().ok_or_else(err)?;

        let last_segment = path.segments.last().ok_or_else(err)?;

        let empty_punctuated = Punctuated::new();

        let args = match &last_segment.arguments {
            syn::PathArguments::AngleBracketed(args) => &args.args,
            _ => &empty_punctuated,
        };

        let last_segment_ident_str = last_segment.ident.to_string();

        let inferred = deref_target_inference_table
            .iter()
            .find(|(name, _)| last_segment_ident_str == *name)
            .and_then(|(_, infer)| infer(args))
            .ok_or_else(err)?;

        Ok(quote!(&#inferred))
    }
}