]> git.lizzy.rs Git - rust.git/blob - src/pairs.rs
Merge pull request #3017 from matthiaskrgr/typo
[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(context, 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(context, 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 last = list.list.last().unwrap();
87     let cur_shape = base_shape.offset_left(last_line_width(&result))?;
88     let rewrite = last.rewrite(context, cur_shape)?;
89     result.push_str(&rewrite);
90
91     if first_line_width(&result) > shape.width {
92         return None;
93     }
94
95     // Check the last expression in the list. We let this expression go over
96     // multiple lines, but we check that if this is necessary, then we can't
97     // do better using multi-line formatting.
98     if !is_single_line(&result) {
99         let multiline_shape = shape.offset_left(list.separators.last().unwrap().len() + 1)?;
100         let multiline_list: PairList<T> = PairList {
101             list: vec![last],
102             separators: vec![],
103             separator_place: list.separator_place,
104         };
105         // Format as if we were multi-line.
106         if let Some(rewrite) = rewrite_pairs_multiline(multiline_list, multiline_shape, context) {
107             // Also, don't let expressions surrounded by parens go multi-line,
108             // this looks really bad.
109             if rewrite.starts_with('(') || is_single_line(&rewrite) {
110                 return None;
111             }
112         }
113     }
114
115     wrap_str(result, context.config.max_width(), shape)
116 }
117
118 fn rewrite_pairs_multiline<T: Rewrite>(
119     list: PairList<T>,
120     shape: Shape,
121     context: &RewriteContext,
122 ) -> Option<String> {
123     let rhs_offset = shape.rhs_overhead(&context.config);
124     let nested_shape = (match context.config.indent_style() {
125         IndentStyle::Visual => shape.visual_indent(0),
126         IndentStyle::Block => shape.block_indent(context.config.tab_spaces()),
127     }).with_max_width(&context.config)
128     .sub_width(rhs_offset)?;
129
130     let indent_str = nested_shape.indent.to_string_with_newline(context.config);
131     let mut result = String::new();
132
133     let rewrite = list.list[0].rewrite(context, shape)?;
134     result.push_str(&rewrite);
135
136     for (e, s) in list.list[1..].iter().zip(list.separators.iter()) {
137         // The following test checks if we should keep two subexprs on the same
138         // line. We do this if not doing so would create an orphan and there is
139         // enough space to do so.
140         let offset = if result.contains('\n') {
141             0
142         } else {
143             shape.used_width()
144         };
145         if last_line_width(&result) + offset <= nested_shape.used_width() {
146             // We must snuggle the next line onto the previous line to avoid an orphan.
147             if let Some(line_shape) =
148                 shape.offset_left(s.len() + 2 + trimmed_last_line_width(&result))
149             {
150                 if let Some(rewrite) = e.rewrite(context, line_shape) {
151                     result.push(' ');
152                     result.push_str(s);
153                     result.push(' ');
154                     result.push_str(&rewrite);
155                     continue;
156                 }
157             }
158         }
159
160         let nested_overhead = s.len() + 1;
161         let line_shape = match context.config.binop_separator() {
162             SeparatorPlace::Back => {
163                 result.push(' ');
164                 result.push_str(s);
165                 result.push_str(&indent_str);
166                 nested_shape.sub_width(nested_overhead)?
167             }
168             SeparatorPlace::Front => {
169                 result.push_str(&indent_str);
170                 result.push_str(s);
171                 result.push(' ');
172                 nested_shape.offset_left(nested_overhead)?
173             }
174         };
175
176         let rewrite = e.rewrite(context, line_shape)?;
177         result.push_str(&rewrite);
178     }
179     Some(result)
180 }
181
182 // Rewrites a single pair.
183 pub(crate) fn rewrite_pair<LHS, RHS>(
184     lhs: &LHS,
185     rhs: &RHS,
186     pp: PairParts,
187     context: &RewriteContext,
188     shape: Shape,
189     separator_place: SeparatorPlace,
190 ) -> Option<String>
191 where
192     LHS: Rewrite,
193     RHS: Rewrite,
194 {
195     let tab_spaces = context.config.tab_spaces();
196     let lhs_overhead = match separator_place {
197         SeparatorPlace::Back => shape.used_width() + pp.prefix.len() + pp.infix.trim_right().len(),
198         SeparatorPlace::Front => shape.used_width(),
199     };
200     let lhs_shape = Shape {
201         width: context.budget(lhs_overhead),
202         ..shape
203     };
204     let lhs_result = lhs
205         .rewrite(context, lhs_shape)
206         .map(|lhs_str| format!("{}{}", pp.prefix, lhs_str))?;
207
208     // Try to put both lhs and rhs on the same line.
209     let rhs_orig_result = shape
210         .offset_left(last_line_width(&lhs_result) + pp.infix.len())
211         .and_then(|s| s.sub_width(pp.suffix.len()))
212         .and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
213     if let Some(ref rhs_result) = rhs_orig_result {
214         // If the length of the lhs is equal to or shorter than the tab width or
215         // the rhs looks like block expression, we put the rhs on the same
216         // line with the lhs even if the rhs is multi-lined.
217         let allow_same_line = lhs_result.len() <= tab_spaces || rhs_result
218             .lines()
219             .next()
220             .map(|first_line| first_line.ends_with('{'))
221             .unwrap_or(false);
222         if !rhs_result.contains('\n') || allow_same_line {
223             let one_line_width = last_line_width(&lhs_result)
224                 + pp.infix.len()
225                 + first_line_width(rhs_result)
226                 + pp.suffix.len();
227             if one_line_width <= shape.width {
228                 return Some(format!(
229                     "{}{}{}{}",
230                     lhs_result, pp.infix, rhs_result, pp.suffix
231                 ));
232             }
233         }
234     }
235
236     // We have to use multiple lines.
237     // Re-evaluate the rhs because we have more space now:
238     let mut rhs_shape = match context.config.indent_style() {
239         IndentStyle::Visual => shape
240             .sub_width(pp.suffix.len() + pp.prefix.len())?
241             .visual_indent(pp.prefix.len()),
242         IndentStyle::Block => {
243             // Try to calculate the initial constraint on the right hand side.
244             let rhs_overhead = shape.rhs_overhead(context.config);
245             Shape::indented(shape.indent.block_indent(context.config), context.config)
246                 .sub_width(rhs_overhead)?
247         }
248     };
249     let infix = match separator_place {
250         SeparatorPlace::Back => pp.infix.trim_right(),
251         SeparatorPlace::Front => pp.infix.trim_left(),
252     };
253     if separator_place == SeparatorPlace::Front {
254         rhs_shape = rhs_shape.offset_left(infix.len())?;
255     }
256     let rhs_result = rhs.rewrite(context, rhs_shape)?;
257     let indent_str = rhs_shape.indent.to_string_with_newline(context.config);
258     let infix_with_sep = match separator_place {
259         SeparatorPlace::Back => format!("{}{}", infix, indent_str),
260         SeparatorPlace::Front => format!("{}{}", indent_str, infix),
261     };
262     Some(format!(
263         "{}{}{}{}",
264         lhs_result, infix_with_sep, rhs_result, pp.suffix
265     ))
266 }
267
268 // A pair which forms a tree and can be flattened (e.g., binops).
269 trait FlattenPair: Rewrite + Sized {
270     // If `_same_op` is `true`, then we only combine binops with the same
271     // operator into the list. E.g,, if the source is `a * b + c`, if `_same_op`
272     // is true, we make `[(a * b), c]` if `_same_op` is false, we make
273     // `[a, b, c]`
274     fn flatten(&self, _context: &RewriteContext, _same_op: bool) -> Option<PairList<Self>> {
275         None
276     }
277 }
278
279 struct PairList<'a, 'b, T: Rewrite + 'b> {
280     list: Vec<&'b T>,
281     separators: Vec<&'a str>,
282     separator_place: SeparatorPlace,
283 }
284
285 impl FlattenPair for ast::Expr {
286     fn flatten(&self, context: &RewriteContext, same_op: bool) -> Option<PairList<ast::Expr>> {
287         let top_op = match self.node {
288             ast::ExprKind::Binary(op, _, _) => op.node,
289             _ => return None,
290         };
291
292         // Turn a tree of binop expressions into a list using a depth-first,
293         // in-order traversal.
294         let mut stack = vec![];
295         let mut list = vec![];
296         let mut separators = vec![];
297         let mut node = self;
298         loop {
299             match node.node {
300                 ast::ExprKind::Binary(op, ref lhs, _) if !same_op || op.node == top_op => {
301                     stack.push(node);
302                     node = lhs;
303                 }
304                 _ => {
305                     list.push(node);
306                     if let Some(pop) = stack.pop() {
307                         match pop.node {
308                             ast::ExprKind::Binary(op, _, ref rhs) => {
309                                 separators.push(op.node.to_string());
310                                 node = rhs;
311                             }
312                             _ => unreachable!(),
313                         }
314                     } else {
315                         break;
316                     }
317                 }
318             }
319         }
320
321         assert_eq!(list.len() - 1, separators.len());
322         Some(PairList {
323             list,
324             separators,
325             separator_place: context.config.binop_separator(),
326         })
327     }
328 }
329
330 impl FlattenPair for ast::Ty {}
331 impl FlattenPair for ast::Pat {}