Skip to main content

rustfmt_nightly/
pairs.rs

1use rustc_ast::{ast, token};
2use rustc_span::Span;
3
4use crate::config::IndentStyle;
5use crate::config::lists::*;
6use crate::rewrite::{Rewrite, RewriteContext, RewriteErrorExt, RewriteResult};
7use crate::shape::Shape;
8use crate::spanned::Spanned;
9use crate::utils::{
10    first_line_width, is_single_line, last_line_width, trimmed_last_line_width, wrap_str,
11};
12
13/// Sigils that decorate a binop pair.
14#[derive(Clone, Copy)]
15pub(crate) struct PairParts<'a> {
16    prefix: &'a str,
17    infix: &'a str,
18    suffix: &'a str,
19}
20
21impl<'a> PairParts<'a> {
22    pub(crate) const fn new(prefix: &'a str, infix: &'a str, suffix: &'a str) -> Self {
23        Self {
24            prefix,
25            infix,
26            suffix,
27        }
28    }
29    pub(crate) fn infix(infix: &'a str) -> PairParts<'a> {
30        PairParts {
31            prefix: "",
32            infix,
33            suffix: "",
34        }
35    }
36}
37
38// Flattens a tree of pairs into a list and tries to rewrite them all at once.
39// FIXME would be nice to reuse the lists API for this, but because each separator
40// can be different, we can't.
41pub(crate) fn rewrite_all_pairs(
42    expr: &ast::Expr,
43    shape: Shape,
44    context: &RewriteContext<'_>,
45) -> RewriteResult {
46    expr.flatten(context, shape)
47        .unknown_error()
48        .and_then(|list| {
49            if list.let_chain_count() > 0 && !list.can_rewrite_let_chain_single_line() {
50                rewrite_pairs_multiline(&list, shape, context)
51            } else {
52                // First we try formatting on one line.
53                rewrite_pairs_one_line(&list, shape, context)
54                    .unknown_error()
55                    .or_else(|_| rewrite_pairs_multiline(&list, shape, context))
56            }
57        })
58}
59
60// This may return a multi-line result since we allow the last expression to go
61// multiline in a 'single line' formatting.
62fn rewrite_pairs_one_line<T: Rewrite>(
63    list: &PairList<'_, '_, T>,
64    shape: Shape,
65    context: &RewriteContext<'_>,
66) -> Option<String> {
67    assert!(list.list.len() >= 2, "Not a pair?");
68
69    let mut result = String::new();
70    let base_shape = shape.block();
71
72    for ((_, rewrite), s) in list.list.iter().zip(list.separators.iter()) {
73        if let Ok(rewrite) = rewrite {
74            if !is_single_line(rewrite) || result.len() > shape.width {
75                return None;
76            }
77
78            result.push_str(rewrite);
79            result.push(' ');
80            result.push_str(s);
81            result.push(' ');
82        } else {
83            return None;
84        }
85    }
86
87    let prefix_len = result.len();
88    let last = list.list.last()?.0;
89    let cur_shape = base_shape.offset_left_opt(last_line_width(&result))?;
90    let last_rewrite = last.rewrite(context, cur_shape)?;
91    result.push_str(&last_rewrite);
92
93    if first_line_width(&result) > shape.width {
94        return None;
95    }
96
97    // Check the last expression in the list. We sometimes let this expression
98    // go over multiple lines, but we check for some ugly conditions.
99    if !(is_single_line(&result) || last_rewrite.starts_with('{'))
100        && (last_rewrite.starts_with('(') || prefix_len > context.config.tab_spaces())
101    {
102        return None;
103    }
104
105    wrap_str(result, context.config.max_width(), shape)
106}
107
108fn rewrite_pairs_multiline<T: Rewrite>(
109    list: &PairList<'_, '_, T>,
110    shape: Shape,
111    context: &RewriteContext<'_>,
112) -> RewriteResult {
113    let rhs_offset = shape.rhs_overhead(context.config);
114    let nested_shape = (match context.config.indent_style() {
115        IndentStyle::Visual => shape.visual_indent(0),
116        IndentStyle::Block => shape.block_indent(context.config.tab_spaces()),
117    })
118    .with_max_width(context.config)
119    .sub_width(rhs_offset, list.span)?;
120
121    let indent_str = nested_shape.indent.to_string_with_newline(context.config);
122    let mut result = String::new();
123
124    result.push_str(list.list[0].1.as_ref().map_err(|err| err.clone())?);
125
126    for ((e, default_rw), s) in list.list[1..].iter().zip(list.separators.iter()) {
127        // The following test checks if we should keep two subexprs on the same
128        // line. We do this if not doing so would create an orphan and there is
129        // enough space to do so.
130        let offset = if result.contains('\n') {
131            0
132        } else {
133            shape.used_width()
134        };
135        if last_line_width(&result) + offset <= nested_shape.used_width() {
136            // We must snuggle the next line onto the previous line to avoid an orphan.
137            if let Some(line_shape) =
138                shape.offset_left_opt(s.len() + 2 + trimmed_last_line_width(&result))
139            {
140                if let Ok(rewrite) = e.rewrite_result(context, line_shape) {
141                    result.push(' ');
142                    result.push_str(s);
143                    result.push(' ');
144                    result.push_str(&rewrite);
145                    continue;
146                }
147            }
148        }
149
150        match context.config.binop_separator() {
151            SeparatorPlace::Back => {
152                result.push(' ');
153                result.push_str(s);
154                result.push_str(&indent_str);
155            }
156            SeparatorPlace::Front => {
157                result.push_str(&indent_str);
158                result.push_str(s);
159                result.push(' ');
160            }
161        }
162
163        result.push_str(default_rw.as_ref().map_err(|err| err.clone())?);
164    }
165    Ok(result)
166}
167
168// Rewrites a single pair.
169pub(crate) fn rewrite_pair<LHS, RHS>(
170    lhs: &LHS,
171    rhs: &RHS,
172    pp: PairParts<'_>,
173    context: &RewriteContext<'_>,
174    shape: Shape,
175    separator_place: SeparatorPlace,
176) -> RewriteResult
177where
178    LHS: Rewrite + Spanned,
179    RHS: Rewrite + Spanned,
180{
181    let tab_spaces = context.config.tab_spaces();
182    let lhs_overhead = match separator_place {
183        SeparatorPlace::Back => shape.used_width() + pp.prefix.len() + pp.infix.trim_end().len(),
184        SeparatorPlace::Front => shape.used_width(),
185    };
186    let lhs_shape = Shape {
187        width: context.budget(lhs_overhead),
188        ..shape
189    };
190    let lhs_result = lhs
191        .rewrite_result(context, lhs_shape)
192        .map(|lhs_str| format!("{}{}", pp.prefix, lhs_str))?;
193
194    // Try to put both lhs and rhs on the same line.
195    let rhs_orig_result = shape
196        .offset_left_opt(last_line_width(&lhs_result) + pp.infix.len())
197        .and_then(|s| s.sub_width_opt(pp.suffix.len()))
198        .and_then(|rhs_shape| rhs.rewrite_result(context, rhs_shape).ok());
199
200    if let Some(ref rhs_result) = rhs_orig_result {
201        // If the length of the lhs is equal to or shorter than the tab width or
202        // the rhs looks like block expression, we put the rhs on the same
203        // line with the lhs even if the rhs is multi-lined.
204        let allow_same_line = lhs_result.len() <= tab_spaces
205            || rhs_result
206                .lines()
207                .next()
208                .map(|first_line| first_line.ends_with('{'))
209                .unwrap_or(false);
210        if !rhs_result.contains('\n') || allow_same_line {
211            let one_line_width = last_line_width(&lhs_result)
212                + pp.infix.len()
213                + first_line_width(rhs_result)
214                + pp.suffix.len();
215            if one_line_width <= shape.width {
216                return Ok(format!(
217                    "{}{}{}{}",
218                    lhs_result, pp.infix, rhs_result, pp.suffix
219                ));
220            }
221        }
222    }
223
224    // We have to use multiple lines.
225    // Re-evaluate the rhs because we have more space now:
226    let mut rhs_shape = match context.config.indent_style() {
227        IndentStyle::Visual => shape
228            .sub_width(pp.suffix.len() + pp.prefix.len(), rhs.span())?
229            .visual_indent(pp.prefix.len()),
230        IndentStyle::Block => {
231            // Try to calculate the initial constraint on the right hand side.
232            let rhs_overhead = shape.rhs_overhead(context.config);
233            Shape::indented(shape.indent.block_indent(context.config), context.config)
234                .sub_width(rhs_overhead, rhs.span())?
235        }
236    };
237    let infix = match separator_place {
238        SeparatorPlace::Back => pp.infix.trim_end(),
239        SeparatorPlace::Front => pp.infix.trim_start(),
240    };
241    if separator_place == SeparatorPlace::Front {
242        rhs_shape = rhs_shape.offset_left(infix.len(), rhs.span())?;
243    }
244    let rhs_result = rhs.rewrite_result(context, rhs_shape)?;
245    let indent_str = rhs_shape.indent.to_string_with_newline(context.config);
246    let infix_with_sep = match separator_place {
247        SeparatorPlace::Back => format!("{infix}{indent_str}"),
248        SeparatorPlace::Front => format!("{indent_str}{infix}"),
249    };
250    Ok(format!(
251        "{}{}{}{}",
252        lhs_result, infix_with_sep, rhs_result, pp.suffix
253    ))
254}
255
256// A pair which forms a tree and can be flattened (e.g., binops).
257trait FlattenPair: Rewrite + Sized {
258    fn flatten(&self, _: &RewriteContext<'_>, _: Shape) -> Option<PairList<'_, '_, Self>> {
259        None
260    }
261}
262
263struct PairList<'a, 'b, T: Rewrite> {
264    list: Vec<(&'b T, RewriteResult)>,
265    separators: Vec<&'a str>,
266    span: Span,
267}
268
269fn is_ident_or_bool_lit(expr: &ast::Expr) -> bool {
270    match &expr.kind {
271        ast::ExprKind::Path(None, path) if path.segments.len() == 1 => true,
272        ast::ExprKind::Lit(token::Lit {
273            kind: token::LitKind::Bool,
274            ..
275        }) => true,
276        ast::ExprKind::Unary(_, expr)
277        | ast::ExprKind::AddrOf(_, _, expr)
278        | ast::ExprKind::Paren(expr)
279        | ast::ExprKind::Try(expr) => is_ident_or_bool_lit(expr),
280        _ => false,
281    }
282}
283
284impl<'a, 'b> PairList<'a, 'b, ast::Expr> {
285    fn let_chain_count(&self) -> usize {
286        self.list
287            .iter()
288            .filter(|(expr, _)| matches!(expr.kind, ast::ExprKind::Let(..)))
289            .count()
290    }
291
292    fn can_rewrite_let_chain_single_line(&self) -> bool {
293        if self.list.len() != 2 {
294            return false;
295        }
296
297        let fist_item_is_ident_or_bool_lit = is_ident_or_bool_lit(self.list[0].0);
298        let second_item_is_let_chain = matches!(self.list[1].0.kind, ast::ExprKind::Let(..));
299
300        fist_item_is_ident_or_bool_lit && second_item_is_let_chain
301    }
302}
303
304impl FlattenPair for ast::Expr {
305    fn flatten(
306        &self,
307        context: &RewriteContext<'_>,
308        shape: Shape,
309    ) -> Option<PairList<'_, '_, ast::Expr>> {
310        let top_op = match self.kind {
311            ast::ExprKind::Binary(op, _, _) => op.node,
312            _ => return None,
313        };
314
315        let default_rewrite = |node: &ast::Expr, sep: usize, is_first: bool| {
316            if is_first {
317                return node.rewrite_result(context, shape);
318            }
319            let nested_overhead = sep + 1;
320            let rhs_offset = shape.rhs_overhead(context.config);
321            let nested_shape = (match context.config.indent_style() {
322                IndentStyle::Visual => shape.visual_indent(0),
323                IndentStyle::Block => shape.block_indent(context.config.tab_spaces()),
324            })
325            .with_max_width(context.config)
326            .sub_width(rhs_offset, node.span)?;
327            let default_shape = match context.config.binop_separator() {
328                SeparatorPlace::Back => nested_shape.sub_width(nested_overhead, node.span)?,
329                SeparatorPlace::Front => nested_shape.offset_left(nested_overhead, node.span)?,
330            };
331            node.rewrite_result(context, default_shape)
332        };
333
334        // Turn a tree of binop expressions into a list using a depth-first,
335        // in-order traversal.
336        let mut stack = vec![];
337        let mut list = vec![];
338        let mut separators = vec![];
339        let mut node = self;
340        let span = self.span();
341        loop {
342            match node.kind {
343                ast::ExprKind::Binary(op, ref lhs, _) if op.node == top_op => {
344                    stack.push(node);
345                    node = lhs;
346                }
347                _ => {
348                    let op_len = separators.last().map_or(0, |s: &&str| s.len());
349                    let rw = default_rewrite(node, op_len, list.is_empty());
350                    list.push((node, rw));
351                    if let Some(pop) = stack.pop() {
352                        match pop.kind {
353                            ast::ExprKind::Binary(op, _, ref rhs) => {
354                                separators.push(op.node.as_str());
355                                node = rhs;
356                            }
357                            _ => unreachable!(),
358                        }
359                    } else {
360                        break;
361                    }
362                }
363            }
364        }
365
366        assert_eq!(list.len() - 1, separators.len());
367        Some(PairList {
368            list,
369            separators,
370            span,
371        })
372    }
373}
374
375impl FlattenPair for ast::Ty {}
376impl FlattenPair for ast::Pat {}