]> git.lizzy.rs Git - rust.git/blob - src/pairs.rs
Simplify situations in which the last sub-expr in a bin-op can go multiline without...
[rust.git] / src / pairs.rs
1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use syntax::ast;
12
13 use config::lists::*;
14 use config::IndentStyle;
15 use rewrite::{Rewrite, RewriteContext};
16 use shape::Shape;
17 use utils::{first_line_width, is_single_line, last_line_width, trimmed_last_line_width, wrap_str};
18
19 /// Sigils that decorate a binop pair.
20 #[derive(new, Clone, Copy)]
21 pub(crate) struct PairParts<'a> {
22     prefix: &'a str,
23     infix: &'a str,
24     suffix: &'a str,
25 }
26
27 impl<'a> PairParts<'a> {
28     pub(crate) fn infix(infix: &'a str) -> PairParts<'a> {
29         PairParts {
30             prefix: "",
31             infix,
32             suffix: "",
33         }
34     }
35 }
36
37 // Flattens a tree of pairs into a list and tries to rewrite them all at once.
38 // FIXME would be nice to reuse the lists API for this, but because each separator
39 // can be different, we can't.
40 pub(crate) fn rewrite_all_pairs(
41     expr: &ast::Expr,
42     shape: Shape,
43     context: &RewriteContext,
44 ) -> Option<String> {
45     // First we try formatting on one line.
46     if let Some(list) = expr.flatten(false) {
47         if let Some(r) = rewrite_pairs_one_line(&list, shape, context) {
48             return Some(r);
49         }
50     }
51
52     // We can't format on line, so try many. When we flatten here we make sure
53     // to only flatten pairs with the same operator, that way we don't
54     // necessarily need one line per sub-expression, but we don't do anything
55     // too funny wrt precedence.
56     expr.flatten(true)
57         .and_then(|list| rewrite_pairs_multiline(list, shape, context))
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.
62 fn 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 (e, s) in list.list.iter().zip(list.separators.iter()) {
73         let cur_shape = base_shape.offset_left(last_line_width(&result))?;
74         let rewrite = e.rewrite(context, cur_shape)?;
75
76         if !is_single_line(&rewrite) || result.len() > shape.width {
77             return None;
78         }
79
80         result.push_str(&rewrite);
81         result.push(' ');
82         result.push_str(s);
83         result.push(' ');
84     }
85
86     let prefix_len = result.len();
87     let last = list.list.last().unwrap();
88     let cur_shape = base_shape.offset_left(last_line_width(&result))?;
89     let last_rewrite = last.rewrite(context, cur_shape)?;
90     result.push_str(&last_rewrite);
91
92     if first_line_width(&result) > shape.width {
93         return None;
94     }
95
96     // Check the last expression in the list. We sometimes let this expression
97     // go over multiple lines, but we check for some ugly conditions.
98     if !(is_single_line(&result) || last_rewrite.starts_with('{'))
99         && (last_rewrite.starts_with('(') || prefix_len > context.config.tab_spaces())
100     {
101         return None;
102     }
103
104     wrap_str(result, context.config.max_width(), shape)
105 }
106
107 fn rewrite_pairs_multiline<T: Rewrite>(
108     list: PairList<T>,
109     shape: Shape,
110     context: &RewriteContext,
111 ) -> Option<String> {
112     let rhs_offset = shape.rhs_overhead(&context.config);
113     let nested_shape = (match context.config.indent_style() {
114         IndentStyle::Visual => shape.visual_indent(0),
115         IndentStyle::Block => shape.block_indent(context.config.tab_spaces()),
116     })
117     .with_max_width(&context.config)
118     .sub_width(rhs_offset)?;
119
120     let indent_str = nested_shape.indent.to_string_with_newline(context.config);
121     let mut result = String::new();
122
123     let rewrite = list.list[0].rewrite(context, shape)?;
124     result.push_str(&rewrite);
125
126     for (e, 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(s.len() + 2 + trimmed_last_line_width(&result))
139             {
140                 if let Some(rewrite) = e.rewrite(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         let nested_overhead = s.len() + 1;
151         let line_shape = match context.config.binop_separator() {
152             SeparatorPlace::Back => {
153                 result.push(' ');
154                 result.push_str(s);
155                 result.push_str(&indent_str);
156                 nested_shape.sub_width(nested_overhead)?
157             }
158             SeparatorPlace::Front => {
159                 result.push_str(&indent_str);
160                 result.push_str(s);
161                 result.push(' ');
162                 nested_shape.offset_left(nested_overhead)?
163             }
164         };
165
166         let rewrite = e.rewrite(context, line_shape)?;
167         result.push_str(&rewrite);
168     }
169     Some(result)
170 }
171
172 // Rewrites a single pair.
173 pub(crate) fn rewrite_pair<LHS, RHS>(
174     lhs: &LHS,
175     rhs: &RHS,
176     pp: PairParts,
177     context: &RewriteContext,
178     shape: Shape,
179     separator_place: SeparatorPlace,
180 ) -> Option<String>
181 where
182     LHS: Rewrite,
183     RHS: Rewrite,
184 {
185     let tab_spaces = context.config.tab_spaces();
186     let lhs_overhead = match separator_place {
187         SeparatorPlace::Back => shape.used_width() + pp.prefix.len() + pp.infix.trim_right().len(),
188         SeparatorPlace::Front => shape.used_width(),
189     };
190     let lhs_shape = Shape {
191         width: context.budget(lhs_overhead),
192         ..shape
193     };
194     let lhs_result = lhs
195         .rewrite(context, lhs_shape)
196         .map(|lhs_str| format!("{}{}", pp.prefix, lhs_str))?;
197
198     // Try to put both lhs and rhs on the same line.
199     let rhs_orig_result = shape
200         .offset_left(last_line_width(&lhs_result) + pp.infix.len())
201         .and_then(|s| s.sub_width(pp.suffix.len()))
202         .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
203     if let Some(ref rhs_result) = rhs_orig_result {
204         // If the length of the lhs is equal to or shorter than the tab width or
205         // the rhs looks like block expression, we put the rhs on the same
206         // line with the lhs even if the rhs is multi-lined.
207         let allow_same_line = lhs_result.len() <= tab_spaces || rhs_result
208             .lines()
209             .next()
210             .map(|first_line| first_line.ends_with('{'))
211             .unwrap_or(false);
212         if !rhs_result.contains('\n') || allow_same_line {
213             let one_line_width = last_line_width(&lhs_result)
214                 + pp.infix.len()
215                 + first_line_width(rhs_result)
216                 + pp.suffix.len();
217             if one_line_width <= shape.width {
218                 return Some(format!(
219                     "{}{}{}{}",
220                     lhs_result, pp.infix, rhs_result, pp.suffix
221                 ));
222             }
223         }
224     }
225
226     // We have to use multiple lines.
227     // Re-evaluate the rhs because we have more space now:
228     let mut rhs_shape = match context.config.indent_style() {
229         IndentStyle::Visual => shape
230             .sub_width(pp.suffix.len() + pp.prefix.len())?
231             .visual_indent(pp.prefix.len()),
232         IndentStyle::Block => {
233             // Try to calculate the initial constraint on the right hand side.
234             let rhs_overhead = shape.rhs_overhead(context.config);
235             Shape::indented(shape.indent.block_indent(context.config), context.config)
236                 .sub_width(rhs_overhead)?
237         }
238     };
239     let infix = match separator_place {
240         SeparatorPlace::Back => pp.infix.trim_right(),
241         SeparatorPlace::Front => pp.infix.trim_left(),
242     };
243     if separator_place == SeparatorPlace::Front {
244         rhs_shape = rhs_shape.offset_left(infix.len())?;
245     }
246     let rhs_result = rhs.rewrite(context, rhs_shape)?;
247     let indent_str = rhs_shape.indent.to_string_with_newline(context.config);
248     let infix_with_sep = match separator_place {
249         SeparatorPlace::Back => format!("{}{}", infix, indent_str),
250         SeparatorPlace::Front => format!("{}{}", indent_str, infix),
251     };
252     Some(format!(
253         "{}{}{}{}",
254         lhs_result, infix_with_sep, rhs_result, pp.suffix
255     ))
256 }
257
258 // A pair which forms a tree and can be flattened (e.g., binops).
259 trait FlattenPair: Rewrite + Sized {
260     // If `_same_op` is `true`, then we only combine binops with the same
261     // operator into the list. E.g,, if the source is `a * b + c`, if `_same_op`
262     // is true, we make `[(a * b), c]` if `_same_op` is false, we make
263     // `[a, b, c]`
264     fn flatten(&self, _same_op: bool) -> Option<PairList<Self>> {
265         None
266     }
267 }
268
269 struct PairList<'a, 'b, T: Rewrite + 'b> {
270     list: Vec<&'b T>,
271     separators: Vec<&'a str>,
272 }
273
274 impl FlattenPair for ast::Expr {
275     fn flatten(&self, same_op: bool) -> Option<PairList<ast::Expr>> {
276         let top_op = match self.node {
277             ast::ExprKind::Binary(op, _, _) => op.node,
278             _ => return None,
279         };
280
281         // Turn a tree of binop expressions into a list using a depth-first,
282         // in-order traversal.
283         let mut stack = vec![];
284         let mut list = vec![];
285         let mut separators = vec![];
286         let mut node = self;
287         loop {
288             match node.node {
289                 ast::ExprKind::Binary(op, ref lhs, _) if !same_op || op.node == top_op => {
290                     stack.push(node);
291                     node = lhs;
292                 }
293                 _ => {
294                     list.push(node);
295                     if let Some(pop) = stack.pop() {
296                         match pop.node {
297                             ast::ExprKind::Binary(op, _, ref rhs) => {
298                                 separators.push(op.node.to_string());
299                                 node = rhs;
300                             }
301                             _ => unreachable!(),
302                         }
303                     } else {
304                         break;
305                     }
306                 }
307             }
308         }
309
310         assert_eq!(list.len() - 1, separators.len());
311         Some(PairList {
312             list,
313             separators,
314         })
315     }
316 }
317
318 impl FlattenPair for ast::Ty {}
319 impl FlattenPair for ast::Pat {}