]> git.lizzy.rs Git - rust.git/blob - src/chains.rs
Tidy up and pass tests
[rust.git] / src / chains.rs
1 // Copyright 2015 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 //! Formatting of chained expressions, i.e. expressions which are chained by
12 //! dots: struct and enum field access, method calls, and try shorthand (?).
13 //!
14 //! Instead of walking these subexpressions one-by-one, as is our usual strategy
15 //! for expression formatting, we collect maximal sequences of these expressions
16 //! and handle them simultaneously.
17 //!
18 //! Whenever possible, the entire chain is put on a single line. If that fails,
19 //! we put each subexpression on a separate, much like the (default) function
20 //! argument function argument strategy.
21 //!
22 //! Depends on config options: `chain_indent` is the indent to use for
23 //! blocks in the parent/root/base of the chain (and the rest of the chain's
24 //! alignment).
25 //! E.g., `let foo = { aaaa; bbb; ccc }.bar.baz();`, we would layout for the
26 //! following values of `chain_indent`:
27 //! Block:
28 //! ```
29 //! let foo = {
30 //!     aaaa;
31 //!     bbb;
32 //!     ccc
33 //! }.bar
34 //!     .baz();
35 //! ```
36 //! Visual:
37 //! ```
38 //! let foo = {
39 //!               aaaa;
40 //!               bbb;
41 //!               ccc
42 //!           }
43 //!           .bar
44 //!           .baz();
45 //! ```
46 //!
47 //! If the first item in the chain is a block expression, we align the dots with
48 //! the braces.
49 //! Block:
50 //! ```
51 //! let a = foo.bar
52 //!     .baz()
53 //!     .qux
54 //! ```
55 //! Visual:
56 //! ```
57 //! let a = foo.bar
58 //!            .baz()
59 //!            .qux
60 //! ```
61
62 use config::IndentStyle;
63 use expr::rewrite_call;
64 use macros::convert_try_mac;
65 use rewrite::{Rewrite, RewriteContext};
66 use shape::Shape;
67 use utils::{first_line_width, last_line_extendable, last_line_width, mk_sp,
68             trimmed_last_line_width, wrap_str};
69
70 use std::borrow::Cow;
71 use std::cmp::min;
72 use std::iter;
73
74 use syntax::{ast, ptr};
75 use syntax::codemap::Span;
76
77 pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -> Option<String> {
78     debug!("rewrite_chain {:?}", shape);
79     let total_span = expr.span;
80     let (parent, subexpr_list) = make_subexpr_list(expr, context);
81
82     // Bail out if the chain is just try sugar, i.e., an expression followed by
83     // any number of `?`s.
84     if chain_only_try(&subexpr_list) {
85         return rewrite_try(&parent, subexpr_list.len(), context, shape);
86     }
87     let suffix_try_num = subexpr_list.iter().take_while(|e| is_try(e)).count();
88     let prefix_try_num = subexpr_list.iter().rev().take_while(|e| is_try(e)).count();
89
90     // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
91     let parent_shape = if is_block_expr(context, &parent, "\n") {
92         match context.config.indent_style() {
93             IndentStyle::Visual => shape.visual_indent(0),
94             IndentStyle::Block => shape,
95         }
96     } else {
97         shape
98     };
99     let parent_rewrite = parent
100         .rewrite(context, parent_shape)
101         .map(|parent_rw| parent_rw + &repeat_try(prefix_try_num))?;
102     let parent_rewrite_contains_newline = parent_rewrite.contains('\n');
103     let is_small_parent = parent_rewrite.len() <= context.config.tab_spaces();
104
105     // Decide how to layout the rest of the chain. `extend` is true if we can
106     // put the first non-parent item on the same line as the parent.
107     let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
108         (
109             chain_indent(context, shape.add_offset(parent_rewrite.len())),
110             context.config.indent_style() == IndentStyle::Visual || is_small_parent,
111         )
112     } else if is_block_expr(context, &parent, &parent_rewrite) {
113         match context.config.indent_style() {
114             // Try to put the first child on the same line with parent's last line
115             IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
116             // The parent is a block, so align the rest of the chain with the closing
117             // brace.
118             IndentStyle::Visual => (parent_shape, false),
119         }
120     } else {
121         (
122             chain_indent(context, shape.add_offset(parent_rewrite.len())),
123             false,
124         )
125     };
126
127     let other_child_shape = nested_shape.with_max_width(context.config);
128
129     let first_child_shape = if extend {
130         let overhead = last_line_width(&parent_rewrite);
131         let offset = trimmed_last_line_width(&parent_rewrite) + prefix_try_num;
132         match context.config.indent_style() {
133             IndentStyle::Visual => parent_shape.offset_left(overhead)?,
134             IndentStyle::Block => parent_shape.offset_left(offset)?,
135         }
136     } else {
137         other_child_shape
138     };
139     debug!(
140         "child_shapes {:?} {:?}",
141         first_child_shape, other_child_shape
142     );
143
144     let child_shape_iter = Some(first_child_shape)
145         .into_iter()
146         .chain(iter::repeat(other_child_shape));
147     let subexpr_num = subexpr_list.len();
148     let last_subexpr = &subexpr_list[suffix_try_num];
149     let subexpr_list = &subexpr_list[suffix_try_num..subexpr_num - prefix_try_num];
150     let iter = subexpr_list.iter().skip(1).rev().zip(child_shape_iter);
151     let mut rewrites = iter.map(|(e, shape)| rewrite_chain_subexpr(e, total_span, context, shape))
152         .collect::<Option<Vec<_>>>()?;
153
154     // Total of all items excluding the last.
155     let extend_last_subexpr = if is_small_parent {
156         rewrites.len() == 1 && last_line_extendable(&rewrites[0])
157     } else {
158         rewrites.is_empty() && last_line_extendable(&parent_rewrite)
159     };
160     let almost_total = if extend_last_subexpr {
161         last_line_width(&parent_rewrite)
162     } else {
163         rewrites.iter().fold(0, |a, b| a + b.len()) + parent_rewrite.len()
164     } + suffix_try_num;
165     let one_line_budget = if rewrites.is_empty() {
166         shape.width
167     } else {
168         min(shape.width, context.config.width_heuristics().chain_width)
169     };
170     let all_in_one_line = !parent_rewrite_contains_newline
171         && rewrites.iter().all(|s| !s.contains('\n'))
172         && almost_total < one_line_budget;
173     let last_shape = if rewrites.is_empty() {
174         first_child_shape
175     } else {
176         other_child_shape
177     }.sub_width(shape.rhs_overhead(context.config) + suffix_try_num)?;
178
179     // Rewrite the last child. The last child of a chain requires special treatment. We need to
180     // know whether 'overflowing' the last child make a better formatting:
181     //
182     // A chain with overflowing the last child:
183     // ```
184     // parent.child1.child2.last_child(
185     //     a,
186     //     b,
187     //     c,
188     // )
189     // ```
190     //
191     // A chain without overflowing the last child (in vertical layout):
192     // ```
193     // parent
194     //     .child1
195     //     .child2
196     //     .last_child(a, b, c)
197     // ```
198     //
199     // In particular, overflowing is effective when the last child is a method with a multi-lined
200     // block-like argument (e.g. closure):
201     // ```
202     // parent.child1.child2.last_child(|a, b, c| {
203     //     let x = foo(a, b, c);
204     //     let y = bar(a, b, c);
205     //
206     //     // ...
207     //
208     //     result
209     // })
210     // ```
211
212     // `rewrite_last` rewrites the last child on its own line. We use a closure here instead of
213     // directly calling `rewrite_chain_subexpr()` to avoid exponential blowup.
214     let rewrite_last = || rewrite_chain_subexpr(last_subexpr, total_span, context, last_shape);
215     let (last_subexpr_str, fits_single_line) = if all_in_one_line || extend_last_subexpr {
216         // First we try to 'overflow' the last child and see if it looks better than using
217         // vertical layout.
218         parent_shape.offset_left(almost_total).map(|shape| {
219             if let Some(rw) = rewrite_chain_subexpr(last_subexpr, total_span, context, shape) {
220                 // We allow overflowing here only if both of the following conditions match:
221                 // 1. The entire chain fits in a single line expect the last child.
222                 // 2. `last_child_str.lines().count() >= 5`.
223                 let line_count = rw.lines().count();
224                 let fits_single_line = almost_total + first_line_width(&rw) <= one_line_budget;
225                 if fits_single_line && line_count >= 5 {
226                     (Some(rw), true)
227                 } else {
228                     // We could not know whether overflowing is better than using vertical layout,
229                     // just by looking at the overflowed rewrite. Now we rewrite the last child
230                     // on its own line, and compare two rewrites to choose which is better.
231                     match rewrite_last() {
232                         Some(ref new_rw) if !fits_single_line => (Some(new_rw.clone()), false),
233                         Some(ref new_rw) if new_rw.lines().count() >= line_count => {
234                             (Some(rw), fits_single_line)
235                         }
236                         new_rw @ Some(..) => (new_rw, false),
237                         _ => (Some(rw), fits_single_line),
238                     }
239                 }
240             } else {
241                 (rewrite_last(), false)
242             }
243         })?
244     } else {
245         (rewrite_last(), false)
246     };
247     rewrites.push(last_subexpr_str?);
248
249     let connector = if fits_single_line && !parent_rewrite_contains_newline {
250         // Yay, we can put everything on one line.
251         Cow::from("")
252     } else {
253         // Use new lines.
254         if context.force_one_line_chain {
255             return None;
256         }
257         nested_shape.indent.to_string_with_newline(context.config)
258     };
259
260     let first_connector = if is_small_parent || fits_single_line
261         || last_line_extendable(&parent_rewrite)
262         || context.config.indent_style() == IndentStyle::Visual
263     {
264         ""
265     } else {
266         &connector
267     };
268
269     let result = if is_small_parent && rewrites.len() > 1 {
270         let second_connector = if fits_single_line || rewrites[1] == "?"
271             || last_line_extendable(&rewrites[0])
272             || context.config.indent_style() == IndentStyle::Visual
273         {
274             ""
275         } else {
276             &connector
277         };
278         format!(
279             "{}{}{}{}{}",
280             parent_rewrite,
281             first_connector,
282             rewrites[0],
283             second_connector,
284             join_rewrites(&rewrites[1..], &connector)
285         )
286     } else {
287         format!(
288             "{}{}{}",
289             parent_rewrite,
290             first_connector,
291             join_rewrites(&rewrites, &connector)
292         )
293     };
294     let result = format!("{}{}", result, repeat_try(suffix_try_num));
295     if context.config.indent_style() == IndentStyle::Visual {
296         wrap_str(result, context.config.max_width(), shape)
297     } else {
298         Some(result)
299     }
300 }
301
302 // True if the chain is only `?`s.
303 fn chain_only_try(exprs: &[ast::Expr]) -> bool {
304     exprs.iter().all(|e| {
305         if let ast::ExprKind::Try(_) = e.node {
306             true
307         } else {
308             false
309         }
310     })
311 }
312
313 // Try to rewrite and replace the last non-try child. Return `true` if
314 // replacing succeeds.
315 fn repeat_try(try_count: usize) -> String {
316     iter::repeat("?").take(try_count).collect::<String>()
317 }
318
319 fn rewrite_try(
320     expr: &ast::Expr,
321     try_count: usize,
322     context: &RewriteContext,
323     shape: Shape,
324 ) -> Option<String> {
325     let sub_expr = expr.rewrite(context, shape.sub_width(try_count)?)?;
326     Some(format!("{}{}", sub_expr, repeat_try(try_count)))
327 }
328
329 fn join_rewrites(rewrites: &[String], connector: &str) -> String {
330     let mut rewrite_iter = rewrites.iter();
331     let mut result = rewrite_iter.next().unwrap().clone();
332
333     for rewrite in rewrite_iter {
334         if rewrite != "?" {
335             result.push_str(connector);
336         }
337         result.push_str(&rewrite[..]);
338     }
339
340     result
341 }
342
343 // States whether an expression's last line exclusively consists of closing
344 // parens, braces, and brackets in its idiomatic formatting.
345 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
346     match expr.node {
347         ast::ExprKind::Mac(..) | ast::ExprKind::Call(..) => {
348             context.use_block_indent() && repr.contains('\n')
349         }
350         ast::ExprKind::Struct(..)
351         | ast::ExprKind::While(..)
352         | ast::ExprKind::WhileLet(..)
353         | ast::ExprKind::If(..)
354         | ast::ExprKind::IfLet(..)
355         | ast::ExprKind::Block(..)
356         | ast::ExprKind::Loop(..)
357         | ast::ExprKind::ForLoop(..)
358         | ast::ExprKind::Match(..) => repr.contains('\n'),
359         ast::ExprKind::Paren(ref expr)
360         | ast::ExprKind::Binary(_, _, ref expr)
361         | ast::ExprKind::Index(_, ref expr)
362         | ast::ExprKind::Unary(_, ref expr) => is_block_expr(context, expr, repr),
363         _ => false,
364     }
365 }
366
367 // Returns the root of the chain and a Vec of the prefixes of the rest of the chain.
368 // E.g., for input `a.b.c` we return (`a`, [`a.b.c`, `a.b`])
369 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> (ast::Expr, Vec<ast::Expr>) {
370     let mut subexpr_list = vec![expr.clone()];
371
372     while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
373         subexpr_list.push(subexpr.clone());
374     }
375
376     let parent = subexpr_list.pop().unwrap();
377     (parent, subexpr_list)
378 }
379
380 fn chain_indent(context: &RewriteContext, shape: Shape) -> Shape {
381     match context.config.indent_style() {
382         IndentStyle::Visual => shape.visual_indent(0),
383         IndentStyle::Block => shape
384             .block_indent(context.config.tab_spaces())
385             .with_max_width(context.config),
386     }
387 }
388
389 // Returns the expression's subexpression, if it exists. When the subexpr
390 // is a try! macro, we'll convert it to shorthand when the option is set.
391 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
392     match expr.node {
393         ast::ExprKind::MethodCall(_, ref expressions) => {
394             Some(convert_try(&expressions[0], context))
395         }
396         ast::ExprKind::TupField(ref subexpr, _)
397         | ast::ExprKind::Field(ref subexpr, _)
398         | ast::ExprKind::Try(ref subexpr) => Some(convert_try(subexpr, context)),
399         _ => None,
400     }
401 }
402
403 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
404     match expr.node {
405         ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
406             if let Some(subexpr) = convert_try_mac(mac, context) {
407                 subexpr
408             } else {
409                 expr.clone()
410             }
411         }
412         _ => expr.clone(),
413     }
414 }
415
416 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
417 // `.c`.
418 fn rewrite_chain_subexpr(
419     expr: &ast::Expr,
420     span: Span,
421     context: &RewriteContext,
422     shape: Shape,
423 ) -> Option<String> {
424     let rewrite_element = |expr_str: String| {
425         if expr_str.len() <= shape.width {
426             Some(expr_str)
427         } else {
428             None
429         }
430     };
431
432     match expr.node {
433         ast::ExprKind::MethodCall(ref segment, ref expressions) => {
434             let types = match segment.parameters {
435                 Some(ref params) => match **params {
436                     ast::PathParameters::AngleBracketed(ref data) => &data.types[..],
437                     _ => &[],
438                 },
439                 _ => &[],
440             };
441             rewrite_method_call(segment.identifier, types, expressions, span, context, shape)
442         }
443         ast::ExprKind::Field(_, ref field) => rewrite_element(format!(".{}", field.node)),
444         ast::ExprKind::TupField(ref expr, ref field) => {
445             let space = match expr.node {
446                 ast::ExprKind::TupField(..) => " ",
447                 _ => "",
448             };
449             rewrite_element(format!("{}.{}", space, field.node))
450         }
451         ast::ExprKind::Try(_) => rewrite_element(String::from("?")),
452         _ => unreachable!(),
453     }
454 }
455
456 // Determines if we can continue formatting a given expression on the same line.
457 fn is_continuable(expr: &ast::Expr) -> bool {
458     match expr.node {
459         ast::ExprKind::Path(..) => true,
460         _ => false,
461     }
462 }
463
464 fn is_try(expr: &ast::Expr) -> bool {
465     match expr.node {
466         ast::ExprKind::Try(..) => true,
467         _ => false,
468     }
469 }
470
471 fn rewrite_method_call(
472     method_name: ast::Ident,
473     types: &[ptr::P<ast::Ty>],
474     args: &[ptr::P<ast::Expr>],
475     span: Span,
476     context: &RewriteContext,
477     shape: Shape,
478 ) -> Option<String> {
479     let (lo, type_str) = if types.is_empty() {
480         (args[0].span.hi(), String::new())
481     } else {
482         let type_list = types
483             .iter()
484             .map(|ty| ty.rewrite(context, shape))
485             .collect::<Option<Vec<_>>>()?;
486
487         let type_str =
488             if context.config.spaces_within_parens_and_brackets() && !type_list.is_empty() {
489                 format!("::< {} >", type_list.join(", "))
490             } else {
491                 format!("::<{}>", type_list.join(", "))
492             };
493
494         (types.last().unwrap().span.hi(), type_str)
495     };
496
497     let callee_str = format!(".{}{}", method_name, type_str);
498     let span = mk_sp(lo, span.hi());
499
500     rewrite_call(context, &callee_str, &args[1..], span, shape)
501 }