src/builder/builder_gen/getters.rs
src/builder/builder_gen/getters.rs, line 87-191
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()
},
}
}
}
}
}
All occurrences of unsafe { ... } in this file appear inside quote! { ... } macro invocations. They are token streams assembled for code generation and execute in the downstream compilation context, not inside this proc macro. The macro itself contains no unsafe Rust. The safety invariant for each generated unsafe block (Option is Some because of the typestate IsSet bound) is documented by SAFETY comments in the token-stream literal. This justifies uses-unsafe = false for the macro crate itself.