1use rustc_ast::{Label, ast};
2use rustc_span::Span;
3use thin_vec::thin_vec;
4use tracing::debug;
5
6use crate::attr::get_attrs_from_stmt;
7use crate::config::StyleEdition;
8use crate::config::lists::*;
9use crate::expr::{block_contains_comment, is_simple_block, is_unsafe_block, rewrite_cond};
10use crate::items::{span_hi_for_param, span_lo_for_param};
11use crate::lists::{ListFormatting, Separator, definitive_tactic, itemize_list, write_list};
12use crate::overflow::OverflowableItem;
13use crate::rewrite::{Rewrite, RewriteContext, RewriteError, RewriteErrorExt, RewriteResult};
14use crate::shape::Shape;
15use crate::source_map::SpanUtils;
16use crate::types::rewrite_bound_params;
17use crate::utils::{
18 NodeIdExt, format_coro, last_line_width, left_most_sub_expr, outer_attributes, stmt_expr,
19};
20
21pub(crate) fn rewrite_closure(
32 binder: &ast::ClosureBinder,
33 constness: ast::Const,
34 capture: ast::CaptureBy,
35 coroutine_marker: &Option<ast::CoroutineMarker>,
36 movability: ast::Movability,
37 fn_decl: &ast::FnDecl,
38 body: &ast::Expr,
39 span: Span,
40 context: &RewriteContext<'_>,
41 shape: Shape,
42) -> RewriteResult {
43 debug!("rewrite_closure {:?}", body);
44
45 let (prefix, extra_offset) = rewrite_closure_fn_decl(
46 binder,
47 constness,
48 capture,
49 coroutine_marker,
50 movability,
51 fn_decl,
52 body,
53 span,
54 context,
55 shape,
56 )?;
57 let body_shape = shape.offset_left(extra_offset, span)?;
59
60 if let ast::ExprKind::Block(ref block, _) = body.kind {
61 if block.stmts.is_empty() && !block_contains_comment(context, block) {
63 return body
64 .rewrite_result(context, shape)
65 .map(|s| format!("{} {}", prefix, s));
66 }
67
68 let result = match fn_decl.output {
69 ast::FnRetTy::Default(_) if !context.inside_macro() => {
70 try_rewrite_without_block(body, &prefix, context, shape, body_shape)
71 }
72 _ => Err(RewriteError::Unknown),
73 };
74
75 result.or_else(|_| {
76 rewrite_closure_block(body, &prefix, context, body_shape)
78 })
79 } else {
80 rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|_| {
81 rewrite_closure_with_block(body, &prefix, context, body_shape)
84 })
85 }
86}
87
88fn try_rewrite_without_block(
89 expr: &ast::Expr,
90 prefix: &str,
91 context: &RewriteContext<'_>,
92 shape: Shape,
93 body_shape: Shape,
94) -> RewriteResult {
95 let expr = get_inner_expr(expr, prefix, context);
96
97 if is_block_closure_forced(context, expr) {
98 rewrite_closure_with_block(expr, prefix, context, shape)
99 } else {
100 rewrite_closure_expr(expr, prefix, context, body_shape)
101 }
102}
103
104fn get_inner_expr<'a>(
105 expr: &'a ast::Expr,
106 prefix: &str,
107 context: &RewriteContext<'_>,
108) -> &'a ast::Expr {
109 if let ast::ExprKind::Block(ref block, ref label) = expr.kind {
110 if !needs_block(block, label, prefix, context) {
111 if let Some(expr) = block.stmts.first().and_then(stmt_expr) {
114 return get_inner_expr(expr, prefix, context);
115 }
116 }
117 }
118
119 expr
120}
121
122fn needs_block(
124 block: &ast::Block,
125 label: &Option<Label>,
126 prefix: &str,
127 context: &RewriteContext<'_>,
128) -> bool {
129 let has_attributes = block.stmts.first().map_or(false, |first_stmt| {
130 !get_attrs_from_stmt(first_stmt).is_empty()
131 });
132
133 is_unsafe_block(block)
134 || block.stmts.len() > 1
135 || has_attributes
136 || block_contains_comment(context, block)
137 || prefix.contains('\n')
138 || label.is_some()
139}
140
141fn veto_block(e: &ast::Expr) -> bool {
142 match e.kind {
143 ast::ExprKind::Call(..)
144 | ast::ExprKind::Binary(..)
145 | ast::ExprKind::Cast(..)
146 | ast::ExprKind::Type(..)
147 | ast::ExprKind::Assign(..)
148 | ast::ExprKind::AssignOp(..)
149 | ast::ExprKind::Field(..)
150 | ast::ExprKind::Index(..)
151 | ast::ExprKind::Range(..)
152 | ast::ExprKind::Try(..) => true,
153 _ => false,
154 }
155}
156
157fn rewrite_closure_with_block(
160 body: &ast::Expr,
161 prefix: &str,
162 context: &RewriteContext<'_>,
163 shape: Shape,
164) -> RewriteResult {
165 let left_most = left_most_sub_expr(body);
166 let veto_block = veto_block(body) && !expr_requires_semi_to_be_stmt(left_most);
167 if veto_block {
168 return Err(RewriteError::Unknown);
169 }
170
171 let outer_attrs = outer_attributes(&body.attrs);
173 let block = ast::Block {
174 stmts: thin_vec![ast::Stmt {
175 id: ast::NodeId::root(),
176 kind: ast::StmtKind::Expr(Box::new(body.clone())),
177 span: body.span,
178 }],
179 id: ast::NodeId::root(),
180 rules: ast::BlockCheckMode::Default,
181 span: outer_attrs
182 .first()
183 .map(|attr| attr.span.to(body.span))
184 .unwrap_or(body.span),
185 };
186 let block = crate::expr::rewrite_block_with_visitor(
187 context,
188 "",
189 &block,
190 Some(&outer_attrs),
191 None,
192 shape,
193 false,
194 )?;
195 Ok(format!("{prefix} {block}"))
196}
197
198fn rewrite_closure_expr(
200 expr: &ast::Expr,
201 prefix: &str,
202 context: &RewriteContext<'_>,
203 shape: Shape,
204) -> RewriteResult {
205 fn allow_multi_line(expr: &ast::Expr) -> bool {
206 match expr.kind {
207 ast::ExprKind::Match(..)
208 | ast::ExprKind::Gen(..)
209 | ast::ExprKind::Block(..)
210 | ast::ExprKind::TryBlock(..)
211 | ast::ExprKind::Loop(..)
212 | ast::ExprKind::Struct(..) => true,
213
214 ast::ExprKind::AddrOf(_, _, ref expr)
215 | ast::ExprKind::Try(ref expr)
216 | ast::ExprKind::Unary(_, ref expr)
217 | ast::ExprKind::Cast(ref expr, _) => allow_multi_line(expr),
218
219 _ => false,
220 }
221 }
222
223 let veto_multiline = (!allow_multi_line(expr) && !context.inside_macro())
226 || context.config.force_multiline_blocks();
227 expr.rewrite_result(context, shape)
228 .and_then(|rw| {
229 if veto_multiline && rw.contains('\n') {
230 Err(RewriteError::Unknown)
231 } else {
232 Ok(rw)
233 }
234 })
235 .map(|rw| format!("{} {}", prefix, rw))
236}
237
238fn rewrite_closure_block(
240 block: &ast::Expr,
241 prefix: &str,
242 context: &RewriteContext<'_>,
243 shape: Shape,
244) -> RewriteResult {
245 debug_assert!(
246 matches!(block.kind, ast::ExprKind::Block(..)),
247 "expected a block expression"
248 );
249
250 Ok(format!(
251 "{} {}",
252 prefix,
253 block.rewrite_result(context, shape)?
254 ))
255}
256
257fn rewrite_closure_fn_decl(
259 binder: &ast::ClosureBinder,
260 constness: ast::Const,
261 capture: ast::CaptureBy,
262 coroutine_marker: &Option<ast::CoroutineMarker>,
263 movability: ast::Movability,
264 fn_decl: &ast::FnDecl,
265 body: &ast::Expr,
266 span: Span,
267 context: &RewriteContext<'_>,
268 shape: Shape,
269) -> Result<(String, usize), RewriteError> {
270 let binder = match binder {
271 ast::ClosureBinder::For { generic_params, .. } if generic_params.is_empty() => {
272 "for<> ".to_owned()
273 }
274 ast::ClosureBinder::For { generic_params, .. } => {
275 let lifetime_str =
276 rewrite_bound_params(context, shape, generic_params).unknown_error()?;
277 format!("for<{lifetime_str}> ")
278 }
279 ast::ClosureBinder::NotPresent => "".to_owned(),
280 };
281
282 let const_ = if matches!(constness, ast::Const::Yes(_)) {
283 "const "
284 } else {
285 ""
286 };
287
288 let immovable = if movability == ast::Movability::Static {
289 "static "
290 } else {
291 ""
292 };
293 let coro = coroutine_marker.map_or_default(format_coro);
294 let capture_str = match capture {
295 ast::CaptureBy::Value { .. } => "move ",
296 ast::CaptureBy::Use { .. } => "use ",
297 ast::CaptureBy::Ref => "",
298 };
299 let offset = binder.len() + const_.len() + immovable.len() + coro.len() + capture_str.len();
302 let nested_shape = shape.shrink_left(offset, span)?.sub_width(4, span)?;
303
304 let param_offset = nested_shape.indent + 1;
306 let param_shape = nested_shape.offset_left(1, span)?.visual_indent(0);
307 let ret_str = fn_decl.output.rewrite_result(context, param_shape)?;
308
309 let param_items = itemize_list(
310 context.snippet_provider,
311 fn_decl.inputs.iter(),
312 "|",
313 ",",
314 |param| span_lo_for_param(param),
315 |param| span_hi_for_param(context, param),
316 |param| param.rewrite_result(context, param_shape),
317 context.snippet_provider.span_after(span, "|"),
318 body.span.lo(),
319 false,
320 );
321 let item_vec = param_items.collect::<Vec<_>>();
322 let horizontal_budget = nested_shape.width.saturating_sub(ret_str.len() + 1);
324 let tactic = definitive_tactic(
325 &item_vec,
326 ListTactic::HorizontalVertical,
327 Separator::Comma,
328 horizontal_budget,
329 );
330 let param_shape = match tactic {
331 DefinitiveListTactic::Horizontal => param_shape.sub_width(ret_str.len() + 1, span)?,
332 _ => param_shape,
333 };
334
335 let fmt = ListFormatting::new(param_shape, context.config)
336 .tactic(tactic)
337 .preserve_newline(true);
338 let list_str = write_list(&item_vec, &fmt)?;
339 let mut prefix = format!("{binder}{const_}{immovable}{coro}{capture_str}|{list_str}|");
340
341 if !ret_str.is_empty() {
342 if prefix.contains('\n') {
343 prefix.push('\n');
344 prefix.push_str(¶m_offset.to_string(context.config));
345 } else {
346 prefix.push(' ');
347 }
348 prefix.push_str(&ret_str);
349 }
350 let extra_offset = last_line_width(&prefix) + 1;
352
353 Ok((prefix, extra_offset))
354}
355
356pub(crate) fn rewrite_last_closure(
359 context: &RewriteContext<'_>,
360 expr: &ast::Expr,
361 shape: Shape,
362) -> RewriteResult {
363 debug!("rewrite_last_closure {:?}", expr);
364
365 if let ast::ExprKind::Closure(ref closure) = expr.kind {
366 let ast::Closure {
367 ref binder,
368 constness,
369 capture_clause,
370 ref coroutine_marker,
371 movability,
372 ref fn_decl,
373 ref body,
374 fn_decl_span: _,
375 fn_arg_span: _,
376 } = **closure;
377 let body = match body.kind {
378 ast::ExprKind::Block(ref block, ref label)
379 if !is_unsafe_block(block)
380 && !context.inside_macro()
381 && is_simple_block(context, block, Some(&body.attrs))
382 && label.is_none() =>
383 {
384 stmt_expr(&block.stmts[0]).unwrap_or(body)
385 }
386 _ => body,
387 };
388 let (prefix, extra_offset) = rewrite_closure_fn_decl(
389 binder,
390 constness,
391 capture_clause,
392 coroutine_marker,
393 movability,
394 fn_decl,
395 body,
396 expr.span,
397 context,
398 shape,
399 )?;
400 if prefix.contains('\n') {
402 return Err(RewriteError::Unknown);
403 }
404
405 let body_shape = shape.offset_left(extra_offset, expr.span)?;
406
407 if is_block_closure_forced(context, body) {
409 return rewrite_closure_with_block(body, &prefix, context, body_shape).map(
410 |body_str| {
411 match fn_decl.output {
412 ast::FnRetTy::Default(..) if body_str.lines().count() <= 7 => {
413 match rewrite_closure_expr(body, &prefix, context, shape) {
417 Ok(single_line_body_str)
418 if !single_line_body_str.contains('\n') =>
419 {
420 single_line_body_str
421 }
422 _ => body_str,
423 }
424 }
425 _ => body_str,
426 }
427 },
428 );
429 }
430
431 let is_multi_lined_cond = rewrite_cond(context, body, body_shape).map_or(false, |cond| {
434 cond.contains('\n') || cond.len() > body_shape.width
435 });
436 if is_multi_lined_cond {
437 return rewrite_closure_with_block(body, &prefix, context, body_shape);
438 }
439
440 return expr.rewrite_result(context, shape);
442 }
443 Err(RewriteError::Unknown)
444}
445
446pub(crate) fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
448 args.iter()
449 .filter_map(OverflowableItem::to_expr)
450 .filter(|expr| matches!(expr.kind, ast::ExprKind::Closure(..)))
451 .count()
452 > 1
453}
454
455fn is_block_closure_forced(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
456 if context.inside_macro() {
458 false
459 } else {
460 is_block_closure_forced_inner(expr, context.config.style_edition())
461 }
462}
463
464fn is_block_closure_forced_inner(expr: &ast::Expr, style_edition: StyleEdition) -> bool {
465 match expr.kind {
466 ast::ExprKind::If(..) | ast::ExprKind::While(..) | ast::ExprKind::ForLoop { .. } => true,
467 ast::ExprKind::Loop(..) if style_edition >= StyleEdition::Edition2024 => true,
468 ast::ExprKind::AddrOf(_, _, ref expr)
469 | ast::ExprKind::Try(ref expr)
470 | ast::ExprKind::Unary(_, ref expr)
471 | ast::ExprKind::Cast(ref expr, _) => is_block_closure_forced_inner(expr, style_edition),
472 _ => false,
473 }
474}
475
476fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool {
485 match e.kind {
486 ast::ExprKind::If(..)
487 | ast::ExprKind::Match(..)
488 | ast::ExprKind::Block(..)
489 | ast::ExprKind::While(..)
490 | ast::ExprKind::Loop(..)
491 | ast::ExprKind::ForLoop { .. }
492 | ast::ExprKind::TryBlock(..) => false,
493 _ => true,
494 }
495}