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