bon_macros/builder/builder_gen/input_fn.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 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
use super::models::FinishFnParams;
use super::top_level_config::TopLevelConfig;
use super::{
AssocMethodCtx, AssocMethodReceiverCtx, BuilderGenCtx, FinishFnBody, Generics, Member,
MemberOrigin, RawMember,
};
use crate::builder::builder_gen::models::{BuilderGenCtxParams, BuilderTypeParams, StartFnParams};
use crate::normalization::{GenericsNamespace, NormalizeSelfTy, SyntaxVariant};
use crate::parsing::{ItemSigConfig, SpannedKey};
use crate::util::prelude::*;
use std::borrow::Cow;
use std::rc::Rc;
use syn::punctuated::Punctuated;
use syn::visit::Visit;
use syn::visit_mut::VisitMut;
pub(crate) struct FnInputCtx<'a> {
namespace: &'a GenericsNamespace,
fn_item: SyntaxVariant<syn::ItemFn>,
impl_ctx: Option<Rc<ImplCtx>>,
config: TopLevelConfig,
start_fn: StartFnParams,
self_ty_prefix: Option<String>,
}
pub(crate) struct FnInputCtxParams<'a> {
pub(crate) namespace: &'a GenericsNamespace,
pub(crate) fn_item: SyntaxVariant<syn::ItemFn>,
pub(crate) impl_ctx: Option<Rc<ImplCtx>>,
pub(crate) config: TopLevelConfig,
}
pub(crate) struct ImplCtx {
pub(crate) self_ty: Box<syn::Type>,
pub(crate) generics: syn::Generics,
/// Lint suppressions from the original item that will be inherited by all items
/// generated by the macro. If the original syntax used `#[expect(...)]`,
/// then it must be represented as `#[allow(...)]` here.
pub(crate) allow_attrs: Vec<syn::Attribute>,
}
impl<'a> FnInputCtx<'a> {
pub(crate) fn new(params: FnInputCtxParams<'a>) -> Self {
let start_fn = params.config.start_fn.clone();
let start_fn_ident = start_fn
.name
.map(SpannedKey::into_value)
.unwrap_or_else(|| {
let fn_ident = ¶ms.fn_item.norm.sig.ident;
// Special case for the method named `new`. We rename it to `builder`
// since this is the name that is conventionally used by starting
// function in the builder pattern. We also want to make
// the `#[builder]` attribute on the method `new` fully compatible
// with deriving a builder from a struct.
if params.impl_ctx.is_some() && fn_ident == "new" {
syn::Ident::new("builder", fn_ident.span())
} else {
fn_ident.clone()
}
});
let start_fn = StartFnParams {
ident: start_fn_ident,
vis: start_fn.vis.map(SpannedKey::into_value),
docs: start_fn
.docs
.map(SpannedKey::into_value)
.unwrap_or_else(|| {
params
.fn_item
.norm
.attrs
.iter()
.filter(|attr| attr.is_doc_expr())
.cloned()
.collect()
}),
// Override on the start fn to use the generics from the
// target function itself. We must not duplicate the generics
// from the impl block here
generics: Some(Generics::new(
params
.fn_item
.norm
.sig
.generics
.params
.iter()
.cloned()
.collect(),
params.fn_item.norm.sig.generics.where_clause.clone(),
)),
};
let self_ty_prefix = params.impl_ctx.as_deref().and_then(|impl_ctx| {
let prefix = impl_ctx
.self_ty
.as_path()?
.path
.segments
.last()?
.ident
.to_string();
Some(prefix)
});
Self {
namespace: params.namespace,
fn_item: params.fn_item,
impl_ctx: params.impl_ctx,
config: params.config,
self_ty_prefix,
start_fn,
}
}
fn assoc_method_ctx(&self) -> Result<Option<AssocMethodCtx>> {
let self_ty = match self.impl_ctx.as_deref() {
Some(impl_ctx) => impl_ctx.self_ty.clone(),
None => return Ok(None),
};
Ok(Some(AssocMethodCtx {
self_ty,
receiver: self.assoc_method_receiver_ctx()?,
}))
}
fn assoc_method_receiver_ctx(&self) -> Result<Option<AssocMethodReceiverCtx>> {
let receiver = match self.fn_item.norm.sig.receiver() {
Some(receiver) => receiver,
None => return Ok(None),
};
let builder_attr_on_receiver = receiver
.attrs
.iter()
.find(|attr| attr.path().is_ident("builder"));
if let Some(attr) = builder_attr_on_receiver {
bail!(
attr,
"#[builder] attributes on the receiver are not supported"
);
}
let self_ty = match self.impl_ctx.as_deref() {
Some(impl_ctx) => &impl_ctx.self_ty,
None => return Ok(None),
};
let mut without_self_keyword = receiver.ty.clone();
NormalizeSelfTy { self_ty }.visit_type_mut(&mut without_self_keyword);
Ok(Some(AssocMethodReceiverCtx {
with_self_keyword: receiver.clone(),
without_self_keyword,
}))
}
fn generics(&self) -> Generics {
let impl_ctx = self.impl_ctx.as_ref();
let norm_fn_params = &self.fn_item.norm.sig.generics.params;
let params = impl_ctx
.map(|impl_ctx| merge_generic_params(&impl_ctx.generics.params, norm_fn_params))
.unwrap_or_else(|| norm_fn_params.iter().cloned().collect());
let where_clauses = [
self.fn_item.norm.sig.generics.where_clause.clone(),
impl_ctx.and_then(|impl_ctx| impl_ctx.generics.where_clause.clone()),
];
let where_clause = where_clauses
.into_iter()
.flatten()
.reduce(|mut combined, clause| {
combined.predicates.extend(clause.predicates);
combined
});
Generics::new(params, where_clause)
}
pub(crate) fn adapted_fn(&self) -> Result<syn::ItemFn> {
let mut orig = self.fn_item.orig.clone();
if let Some(name) = self.config.start_fn.name.as_deref() {
if *name == orig.sig.ident {
bail!(
&name,
"the starting function name must be different from the name \
of the positional function under the #[builder] attribute"
)
}
} else {
// By default the original positional function becomes hidden.
orig.vis = syn::Visibility::Inherited;
// We don't use a random name here because the name of this function
// can be used by other macros that may need a stable identifier.
// For example, if `#[tracing::instrument]` is placed on the function,
// the function name will be used as a span name. The name of the span
// may be indexed in some logs database (e.g. Grafana Loki). If the name
// of the span changes the DB index may grow and also log queries won't
// be stable.
orig.sig.ident = format_ident!("__orig_{}", orig.sig.ident.raw_name());
// Remove all doc comments from the function itself to avoid docs duplication
// which may lead to duplicating doc tests, which in turn implies repeated doc
// tests execution, which means worse tests performance.
//
// We don't do this for the case when the positional function is exposed
// alongside the builder which implies that the docs should be visible
// as the function itself is visible.
orig.attrs.retain(|attr| !attr.is_doc_expr());
orig.attrs.extend([syn::parse_quote!(#[doc(hidden)])]);
}
// Remove any `#[builder]` attributes that were meant for this proc macro.
orig.attrs.retain(|attr| !attr.path().is_ident("builder"));
// Remove all doc comments attributes from function arguments, because they are
// not valid in that position in regular Rust code. The cool trick is that they
// are still valid syntactically when a proc macro like this one pre-processes
// them and removes them from the expanded code. We use the doc comments to put
// them on the generated setter methods.
//
// We also strip all `builder(...)` attributes because this macro processes them
// and they aren't needed in the output.
for arg in &mut orig.sig.inputs {
arg.attrs_mut()
.retain(|attr| !attr.is_doc_expr() && !attr.path().is_ident("builder"));
}
orig.attrs.push(syn::parse_quote!(#[allow(
// It's fine if there are too many positional arguments in the function
// because the whole purpose of this macro is to fight with this problem
// at the call site by generating a builder, while keeping the fn definition
// site the same with tons of positional arguments which don't harm readability
// there because their names are explicitly specified at the definition site.
clippy::too_many_arguments,
// It's fine to use many bool arguments in the function signature because
// all of them will be named at the call site when the builder is used.
clippy::fn_params_excessive_bools,
)]));
Ok(orig)
}
pub(crate) fn into_builder_gen_ctx(self) -> Result<BuilderGenCtx> {
let assoc_method_ctx = self.assoc_method_ctx()?;
if self.impl_ctx.is_none() {
let explanation = "\
but #[bon] attribute is absent on top of the impl block; this \
additional #[bon] attribute on the impl block is required for \
the macro to see the type of `Self` and properly generate \
the builder struct definition adjacently to the impl block.";
if let Some(receiver) = &self.fn_item.orig.sig.receiver() {
bail!(
&receiver.self_token,
"function contains a `self` parameter {explanation}"
);
}
let mut ctx = FindSelfReference::default();
ctx.visit_item_fn(&self.fn_item.orig);
if let Some(self_span) = ctx.self_span {
bail!(
&self_span,
"function contains a `Self` type reference {explanation}"
);
}
}
let members = self
.fn_item
.apply_ref(|fn_item| fn_item.sig.inputs.iter().filter_map(syn::FnArg::as_typed))
.into_iter()
.map(|arg| {
let pat = match arg.norm.pat.as_ref() {
syn::Pat::Ident(pat) => pat,
_ => bail!(
&arg.orig.pat,
"use a simple `identifier: type` syntax for the function argument; \
destructuring patterns in arguments aren't supported by the `#[builder]`",
),
};
let ty = SyntaxVariant {
norm: arg.norm.ty.clone(),
orig: arg.orig.ty.clone(),
};
Ok(RawMember {
attrs: &arg.norm.attrs,
ident: pat.ident.clone(),
ty,
})
})
.collect::<Result<Vec<_>>>()?;
let members = Member::from_raw(&self.config.on, MemberOrigin::FnArg, members)?;
let generics = self.generics();
let finish_fn_body = FnCallBody {
sig: self.adapted_fn()?.sig,
impl_ctx: self.impl_ctx.clone(),
};
let ItemSigConfig {
name: finish_fn_ident,
vis: finish_fn_vis,
docs: finish_fn_docs,
} = self.config.finish_fn;
let is_special_builder_method = self.impl_ctx.is_some()
&& (self.fn_item.norm.sig.ident == "new" || self.fn_item.norm.sig.ident == "builder");
let finish_fn_ident = finish_fn_ident
.map(SpannedKey::into_value)
.unwrap_or_else(|| {
// For `builder` methods the `build` finisher is more conventional
if is_special_builder_method {
format_ident!("build")
} else {
format_ident!("call")
}
});
let finish_fn_docs = finish_fn_docs
.map(SpannedKey::into_value)
.unwrap_or_else(|| {
vec![syn::parse_quote! {
/// Finishes building and performs the requested action.
}]
});
let finish_fn = FinishFnParams {
ident: finish_fn_ident,
vis: finish_fn_vis.map(SpannedKey::into_value),
unsafety: self.fn_item.norm.sig.unsafety,
asyncness: self.fn_item.norm.sig.asyncness,
must_use: get_must_use_attribute(&self.fn_item.norm.attrs)?,
body: Box::new(finish_fn_body),
output: self.fn_item.norm.sig.output,
attrs: finish_fn_docs,
};
let fn_allows = self
.fn_item
.norm
.attrs
.iter()
.filter_map(syn::Attribute::to_allow);
let allow_attrs = self
.impl_ctx
.as_ref()
.into_iter()
.flat_map(|impl_ctx| impl_ctx.allow_attrs.iter().cloned())
.chain(fn_allows)
.collect();
let builder_ident = || {
let user_override = self.config.builder_type.name.map(SpannedKey::into_value);
if let Some(user_override) = user_override {
return user_override;
}
let ty_prefix = self.self_ty_prefix.unwrap_or_default();
// A special case for the `new` or `builder` method.
// We don't insert the `Builder` suffix in this case because
// this special case should be compatible with deriving
// a builder from a struct.
//
// We can arrive inside of this branch only if the function under
// the macro is called `new` or `builder`.
if is_special_builder_method {
return format_ident!("{ty_prefix}Builder");
}
let pascal_case_fn = self.fn_item.norm.sig.ident.snake_to_pascal_case();
format_ident!("{ty_prefix}{pascal_case_fn}Builder")
};
let builder_type = BuilderTypeParams {
ident: builder_ident(),
derives: self.config.derive,
docs: self.config.builder_type.docs.map(SpannedKey::into_value),
vis: self.config.builder_type.vis.map(SpannedKey::into_value),
};
BuilderGenCtx::new(BuilderGenCtxParams {
bon: self.config.bon,
namespace: Cow::Borrowed(self.namespace),
members,
allow_attrs,
on: self.config.on,
assoc_method_ctx,
generics,
orig_item_vis: self.fn_item.norm.vis,
builder_type,
state_mod: self.config.state_mod,
start_fn: self.start_fn,
finish_fn,
})
}
}
struct FnCallBody {
sig: syn::Signature,
impl_ctx: Option<Rc<ImplCtx>>,
}
impl FinishFnBody for FnCallBody {
fn generate(&self, ctx: &BuilderGenCtx) -> TokenStream {
let asyncness = &self.sig.asyncness;
let maybe_await = asyncness.is_some().then(|| quote!(.await));
// Filter out lifetime generic arguments, because they are not needed
// to be specified explicitly when calling the function. This also avoids
// the problem that it's not always possible to specify lifetimes in
// the turbofish syntax. See the problem of late-bound lifetimes specification
// in the issue https://github.com/rust-lang/rust/issues/42868
let generic_args = self
.sig
.generics
.params
.iter()
.filter(|arg| !matches!(arg, syn::GenericParam::Lifetime(_)))
.map(syn::GenericParam::to_generic_argument);
let prefix = self
.sig
.receiver()
.map(|_| {
let receiver_field = &ctx.ident_pool.receiver;
quote!(self.#receiver_field.)
})
.or_else(|| {
let self_ty = &self.impl_ctx.as_deref()?.self_ty;
Some(quote!(<#self_ty>::))
});
let fn_ident = &self.sig.ident;
// The variables with values of members are in scope for this expression.
let member_vars = ctx.members.iter().map(Member::orig_ident);
quote! {
#prefix #fn_ident::<#(#generic_args,)*>(
#( #member_vars ),*
)
#maybe_await
}
}
}
/// To merge generic params we need to make sure lifetimes are always the first
/// in the resulting list according to Rust syntax restrictions.
fn merge_generic_params(
left: &Punctuated<syn::GenericParam, syn::Token![,]>,
right: &Punctuated<syn::GenericParam, syn::Token![,]>,
) -> Vec<syn::GenericParam> {
let is_lifetime = |param: &&_| matches!(param, &&syn::GenericParam::Lifetime(_));
let (left_lifetimes, left_rest): (Vec<_>, Vec<_>) = left.iter().partition(is_lifetime);
let (right_lifetimes, right_rest): (Vec<_>, Vec<_>) = right.iter().partition(is_lifetime);
left_lifetimes
.into_iter()
.chain(right_lifetimes)
.chain(left_rest)
.chain(right_rest)
.cloned()
.collect()
}
#[derive(Default)]
struct FindSelfReference {
self_span: Option<Span>,
}
impl Visit<'_> for FindSelfReference {
fn visit_item(&mut self, _: &syn::Item) {
// Don't recurse into nested items. We are interested in the reference
// to `Self` on the current item level
}
fn visit_path(&mut self, path: &syn::Path) {
if self.self_span.is_some() {
return;
}
syn::visit::visit_path(self, path);
let first_segment = match path.segments.first() {
Some(first_segment) => first_segment,
_ => return,
};
if first_segment.ident == "Self" {
self.self_span = Some(first_segment.ident.span());
}
}
}
fn get_must_use_attribute(attrs: &[syn::Attribute]) -> Result<Option<syn::Attribute>> {
let mut iter = attrs
.iter()
.filter(|attr| attr.meta.path().is_ident("must_use"));
let result = iter.next();
if let Some(second) = iter.next() {
bail!(
second,
"found multiple #[must_use], but bon only works with exactly one or zero."
);
}
if let Some(attr) = result {
if let syn::AttrStyle::Inner(_) = attr.style {
bail!(
attr,
"#[must_use] attribute must be placed on the function itself, \
not inside it."
);
}
}
Ok(result.cloned())
}