]> git.lizzy.rs Git - rust.git/blob - src/chains.rs
Try overflowing the last element of chain only if it goes multi line
[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 /// Visual:
28 /// ```
29 /// let foo = {
30 ///               aaaa;
31 ///               bbb;
32 ///               ccc
33 ///           }
34 ///           .bar
35 ///           .baz();
36 /// ```
37 /// Inherit:
38 /// ```
39 /// let foo = {
40 ///     aaaa;
41 ///     bbb;
42 ///     ccc
43 /// }
44 /// .bar
45 /// .baz();
46 /// ```
47 /// Tabbed:
48 /// ```
49 /// let foo = {
50 ///         aaaa;
51 ///         bbb;
52 ///         ccc
53 ///     }
54 ///     .bar
55 ///     .baz();
56 /// ```
57 ///
58 /// If the first item in the chain is a block expression, we align the dots with
59 /// the braces.
60 /// Visual:
61 /// ```
62 /// let a = foo.bar
63 ///            .baz()
64 ///            .qux
65 /// ```
66 /// Inherit:
67 /// ```
68 /// let a = foo.bar
69 /// .baz()
70 /// .qux
71 /// ```
72 /// Tabbed:
73 /// ```
74 /// let a = foo.bar
75 ///     .baz()
76 ///     .qux
77 /// ```
78
79 use Shape;
80 use rewrite::{Rewrite, RewriteContext};
81 use utils::{wrap_str, first_line_width, last_line_width, mk_sp};
82 use expr::rewrite_call;
83 use config::IndentStyle;
84 use macros::convert_try_mac;
85
86 use std::cmp::min;
87 use std::iter;
88 use syntax::{ast, ptr};
89 use syntax::codemap::Span;
90
91 pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -> Option<String> {
92     debug!("rewrite_chain {:?}", shape);
93     let total_span = expr.span;
94     let (parent, subexpr_list) = make_subexpr_list(expr, context);
95
96     // Bail out if the chain is just try sugar, i.e., an expression followed by
97     // any number of `?`s.
98     if chain_only_try(&subexpr_list) {
99         return rewrite_try(&parent, subexpr_list.len(), context, shape);
100     }
101     let trailing_try_num = subexpr_list
102         .iter()
103         .take_while(|e| match e.node {
104             ast::ExprKind::Try(..) => true,
105             _ => false,
106         })
107         .count();
108
109     // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
110     let parent_shape = if is_block_expr(context, &parent, "\n") {
111         match context.config.chain_indent() {
112             IndentStyle::Visual => shape.visual_indent(0),
113             IndentStyle::Block => shape.block(),
114         }
115     } else {
116         shape
117     };
118     let parent_rewrite = try_opt!(parent.rewrite(context, parent_shape));
119     let parent_rewrite_contains_newline = parent_rewrite.contains('\n');
120     let is_small_parent = parent_rewrite.len() <= context.config.tab_spaces();
121
122     // Decide how to layout the rest of the chain. `extend` is true if we can
123     // put the first non-parent item on the same line as the parent.
124     let first_subexpr_is_try = subexpr_list.last().map_or(false, is_try);
125     let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
126         let nested_shape = if first_subexpr_is_try {
127             parent_shape.block_indent(context.config.tab_spaces())
128         } else {
129             chain_indent(context, shape.add_offset(parent_rewrite.len()))
130         };
131         (
132             nested_shape,
133             context.config.chain_indent() == IndentStyle::Visual || is_small_parent,
134         )
135     } else if is_block_expr(context, &parent, &parent_rewrite) {
136         match context.config.chain_indent() {
137             // Try to put the first child on the same line with parent's last line
138             IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
139             // The parent is a block, so align the rest of the chain with the closing
140             // brace.
141             IndentStyle::Visual => (parent_shape, false),
142         }
143     } else if parent_rewrite_contains_newline {
144         (chain_indent(context, parent_shape), false)
145     } else {
146         (shape.block_indent(context.config.tab_spaces()), false)
147     };
148
149     let other_child_shape = nested_shape.with_max_width(context.config);
150
151     let first_child_shape = if extend {
152         let overhead = last_line_width(&parent_rewrite);
153         let offset = parent_rewrite.lines().rev().next().unwrap().trim().len();
154         match context.config.chain_indent() {
155             IndentStyle::Visual => try_opt!(parent_shape.offset_left(overhead)),
156             IndentStyle::Block => try_opt!(parent_shape.block().offset_left(offset)),
157         }
158     } else {
159         other_child_shape
160     };
161     debug!(
162         "child_shapes {:?} {:?}",
163         first_child_shape,
164         other_child_shape
165     );
166
167     let child_shape_iter = Some(first_child_shape).into_iter().chain(
168         ::std::iter::repeat(other_child_shape).take(subexpr_list.len() - 1),
169     );
170     let iter = subexpr_list.iter().rev().zip(child_shape_iter);
171     let mut rewrites = try_opt!(
172         iter.map(|(e, shape)| {
173             rewrite_chain_subexpr(e, total_span, context, shape)
174         }).collect::<Option<Vec<_>>>()
175     );
176
177     // Total of all items excluding the last.
178     let last_non_try_index = rewrites.len() - (1 + trailing_try_num);
179     let almost_total = rewrites[..last_non_try_index].iter().fold(
180         0,
181         |a, b| a + first_line_width(b),
182     ) + parent_rewrite.len();
183     let one_line_len = rewrites.iter().fold(0, |a, r| a + first_line_width(r)) +
184         parent_rewrite.len();
185
186     let one_line_budget = min(shape.width, context.config.chain_one_line_max());
187     let veto_single_line = if one_line_len > one_line_budget {
188         if rewrites.len() > 1 {
189             true
190         } else if rewrites.len() == 1 {
191             context.config.chain_split_single_child() || one_line_len > shape.width
192         } else {
193             false
194         }
195     } else if context.config.take_source_hints() && subexpr_list.len() > 1 {
196         // Look at the source code. Unless all chain elements start on the same
197         // line, we won't consider putting them on a single line either.
198         let last_span = context.snippet(mk_sp(subexpr_list[1].span.hi, total_span.hi));
199         let first_span = context.snippet(subexpr_list[1].span);
200         let last_iter = last_span.chars().take_while(|c| c.is_whitespace());
201
202         first_span.chars().chain(last_iter).any(|c| c == '\n')
203     } else {
204         false
205     };
206
207     let mut fits_single_line = !veto_single_line && almost_total <= shape.width;
208     if fits_single_line {
209         let len = rewrites.len();
210         let (init, last) = rewrites.split_at_mut(len - (1 + trailing_try_num));
211         fits_single_line = init.iter().all(|s| !s.contains('\n'));
212
213         if fits_single_line {
214             fits_single_line = match expr.node {
215                 ref e @ ast::ExprKind::MethodCall(..) => {
216                     if rewrite_method_call_with_overflow(
217                         e,
218                         &mut last[0],
219                         almost_total,
220                         total_span,
221                         context,
222                         shape,
223                     )
224                     {
225                         // If the first line of the last method does not fit into a single line
226                         // after the others, allow new lines.
227                         almost_total + first_line_width(&last[0]) < context.config.max_width()
228                     } else {
229                         false
230                     }
231                 }
232                 _ => !last[0].contains('\n'),
233             }
234         }
235     }
236
237     // Try overflowing the last element if we are using block indent.
238     if !fits_single_line && context.use_block_indent() {
239         let (init, last) = rewrites.split_at_mut(last_non_try_index);
240         let almost_single_line = init.iter().all(|s| !s.contains('\n'));
241         if almost_single_line && last[0].contains('\n') {
242             let overflow_shape = Shape {
243                 width: one_line_budget,
244                 ..parent_shape
245             };
246             fits_single_line = rewrite_last_child_with_overflow(
247                 context,
248                 &subexpr_list[trailing_try_num],
249                 overflow_shape,
250                 total_span,
251                 almost_total,
252                 one_line_budget,
253                 &mut last[0],
254             );
255         }
256     }
257
258     let connector = if fits_single_line && !parent_rewrite_contains_newline {
259         // Yay, we can put everything on one line.
260         String::new()
261     } else {
262         // Use new lines.
263         if context.force_one_line_chain {
264             return None;
265         }
266         format!("\n{}", nested_shape.indent.to_string(context.config))
267     };
268
269     let first_connector = choose_first_connector(
270         context,
271         &parent_rewrite,
272         &rewrites[0],
273         &connector,
274         &subexpr_list,
275         extend,
276     );
277
278     if is_small_parent && rewrites.len() > 1 {
279         let second_connector = choose_first_connector(
280             context,
281             &rewrites[0],
282             &rewrites[1],
283             &connector,
284             &subexpr_list[0..subexpr_list.len() - 1],
285             false,
286         );
287         wrap_str(
288             format!(
289                 "{}{}{}{}{}",
290                 parent_rewrite,
291                 first_connector,
292                 rewrites[0],
293                 second_connector,
294                 join_rewrites(
295                     &rewrites[1..],
296                     &subexpr_list[0..subexpr_list.len() - 1],
297                     &connector,
298                 )
299             ),
300             context.config.max_width(),
301             shape,
302         )
303     } else {
304         wrap_str(
305             format!(
306                 "{}{}{}",
307                 parent_rewrite,
308                 first_connector,
309                 join_rewrites(&rewrites, &subexpr_list, &connector)
310             ),
311             context.config.max_width(),
312             shape,
313         )
314     }
315 }
316
317 fn is_extendable_parent(context: &RewriteContext, parent_str: &str) -> bool {
318     context.config.chain_indent() == IndentStyle::Block &&
319         parent_str.lines().last().map_or(false, |s| {
320             s.trim()
321                 .chars()
322                 .all(|c| c == ')' || c == ']' || c == '}' || c == '?')
323         })
324 }
325
326 // True if the chain is only `?`s.
327 fn chain_only_try(exprs: &[ast::Expr]) -> bool {
328     exprs.iter().all(|e| if let ast::ExprKind::Try(_) = e.node {
329         true
330     } else {
331         false
332     })
333 }
334
335 // Try to rewrite and replace the last non-try child. Return `true` if
336 // replacing succeeds.
337 fn rewrite_last_child_with_overflow(
338     context: &RewriteContext,
339     expr: &ast::Expr,
340     shape: Shape,
341     span: Span,
342     almost_total: usize,
343     one_line_budget: usize,
344     last_child: &mut String,
345 ) -> bool {
346     if let Some(shape) = shape.shrink_left(almost_total) {
347         if let Some(ref mut rw) = rewrite_chain_subexpr(expr, span, context, shape) {
348             if almost_total + first_line_width(rw) <= one_line_budget && rw.lines().count() > 3 {
349                 ::std::mem::swap(last_child, rw);
350                 return true;
351             }
352         }
353     }
354     false
355 }
356
357 pub fn rewrite_try(
358     expr: &ast::Expr,
359     try_count: usize,
360     context: &RewriteContext,
361     shape: Shape,
362 ) -> Option<String> {
363     let sub_expr = try_opt!(expr.rewrite(context, try_opt!(shape.sub_width(try_count))));
364     Some(format!(
365         "{}{}",
366         sub_expr,
367         iter::repeat("?").take(try_count).collect::<String>()
368     ))
369 }
370
371 fn join_rewrites(rewrites: &[String], subexps: &[ast::Expr], connector: &str) -> String {
372     let mut rewrite_iter = rewrites.iter();
373     let mut result = rewrite_iter.next().unwrap().clone();
374     let mut subexpr_iter = subexps.iter().rev();
375     subexpr_iter.next();
376
377     for (rewrite, expr) in rewrite_iter.zip(subexpr_iter) {
378         match expr.node {
379             ast::ExprKind::Try(_) => (),
380             _ => result.push_str(connector),
381         };
382         result.push_str(&rewrite[..]);
383     }
384
385     result
386 }
387
388 // States whether an expression's last line exclusively consists of closing
389 // parens, braces, and brackets in its idiomatic formatting.
390 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
391     match expr.node {
392         ast::ExprKind::Mac(..) |
393         ast::ExprKind::Call(..) => context.use_block_indent() && repr.contains('\n'),
394         ast::ExprKind::Struct(..) |
395         ast::ExprKind::While(..) |
396         ast::ExprKind::WhileLet(..) |
397         ast::ExprKind::If(..) |
398         ast::ExprKind::IfLet(..) |
399         ast::ExprKind::Block(..) |
400         ast::ExprKind::Loop(..) |
401         ast::ExprKind::ForLoop(..) |
402         ast::ExprKind::Match(..) => repr.contains('\n'),
403         ast::ExprKind::Paren(ref expr) |
404         ast::ExprKind::Binary(_, _, ref expr) |
405         ast::ExprKind::Index(_, ref expr) |
406         ast::ExprKind::Unary(_, ref expr) => is_block_expr(context, expr, repr),
407         _ => false,
408     }
409 }
410
411 // Returns the root of the chain and a Vec of the prefixes of the rest of the chain.
412 // E.g., for input `a.b.c` we return (`a`, [`a.b.c`, `a.b`])
413 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> (ast::Expr, Vec<ast::Expr>) {
414     let mut subexpr_list = vec![expr.clone()];
415
416     while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
417         subexpr_list.push(subexpr.clone());
418     }
419
420     let parent = subexpr_list.pop().unwrap();
421     (parent, subexpr_list)
422 }
423
424 fn chain_indent(context: &RewriteContext, shape: Shape) -> Shape {
425     match context.config.chain_indent() {
426         IndentStyle::Visual => shape.visual_indent(0),
427         IndentStyle::Block => shape.block_indent(context.config.tab_spaces()),
428     }
429 }
430
431 fn rewrite_method_call_with_overflow(
432     expr_kind: &ast::ExprKind,
433     last: &mut String,
434     almost_total: usize,
435     total_span: Span,
436     context: &RewriteContext,
437     shape: Shape,
438 ) -> bool {
439     if let &ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) = expr_kind {
440         let shape = match shape.shrink_left(almost_total) {
441             Some(b) => b,
442             None => return false,
443         };
444         let mut last_rewrite = rewrite_method_call(
445             method_name.node,
446             types,
447             expressions,
448             total_span,
449             context,
450             shape,
451         );
452
453         if let Some(ref mut s) = last_rewrite {
454             ::std::mem::swap(s, last);
455             true
456         } else {
457             false
458         }
459     } else {
460         unreachable!();
461     }
462 }
463
464 // Returns the expression's subexpression, if it exists. When the subexpr
465 // is a try! macro, we'll convert it to shorthand when the option is set.
466 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
467     match expr.node {
468         ast::ExprKind::MethodCall(_, _, ref expressions) => {
469             Some(convert_try(&expressions[0], context))
470         }
471         ast::ExprKind::TupField(ref subexpr, _) |
472         ast::ExprKind::Field(ref subexpr, _) |
473         ast::ExprKind::Try(ref subexpr) => Some(convert_try(subexpr, context)),
474         _ => None,
475     }
476 }
477
478 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
479     match expr.node {
480         ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
481             if let Some(subexpr) = convert_try_mac(mac, context) {
482                 subexpr
483             } else {
484                 expr.clone()
485             }
486         }
487         _ => expr.clone(),
488     }
489 }
490
491 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
492 // `.c`.
493 fn rewrite_chain_subexpr(
494     expr: &ast::Expr,
495     span: Span,
496     context: &RewriteContext,
497     shape: Shape,
498 ) -> Option<String> {
499     let rewrite_element = |expr_str: String| if expr_str.len() <= shape.width {
500         Some(expr_str)
501     } else {
502         None
503     };
504
505     match expr.node {
506         ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) => {
507             rewrite_method_call(method_name.node, types, expressions, span, context, shape)
508         }
509         ast::ExprKind::Field(_, ref field) => rewrite_element(format!(".{}", field.node)),
510         ast::ExprKind::TupField(ref expr, ref field) => {
511             let space = match expr.node {
512                 ast::ExprKind::TupField(..) => " ",
513                 _ => "",
514             };
515             rewrite_element(format!("{}.{}", space, field.node))
516         }
517         ast::ExprKind::Try(_) => rewrite_element(String::from("?")),
518         _ => unreachable!(),
519     }
520 }
521
522 // Determines if we can continue formatting a given expression on the same line.
523 fn is_continuable(expr: &ast::Expr) -> bool {
524     match expr.node {
525         ast::ExprKind::Path(..) => true,
526         _ => false,
527     }
528 }
529
530 fn is_try(expr: &ast::Expr) -> bool {
531     match expr.node {
532         ast::ExprKind::Try(..) => true,
533         _ => false,
534     }
535 }
536
537 fn choose_first_connector<'a>(
538     context: &RewriteContext,
539     parent_str: &str,
540     first_child_str: &str,
541     connector: &'a str,
542     subexpr_list: &[ast::Expr],
543     extend: bool,
544 ) -> &'a str {
545     if subexpr_list.is_empty() {
546         ""
547     } else if extend || subexpr_list.last().map_or(false, is_try) ||
548                is_extendable_parent(context, parent_str)
549     {
550         // 1 = ";", being conservative here.
551         if last_line_width(parent_str) + first_line_width(first_child_str) + 1 <=
552             context.config.max_width()
553         {
554             ""
555         } else {
556             connector
557         }
558     } else {
559         connector
560     }
561 }
562
563 fn rewrite_method_call(
564     method_name: ast::Ident,
565     types: &[ptr::P<ast::Ty>],
566     args: &[ptr::P<ast::Expr>],
567     span: Span,
568     context: &RewriteContext,
569     shape: Shape,
570 ) -> Option<String> {
571     let (lo, type_str) = if types.is_empty() {
572         (args[0].span.hi, String::new())
573     } else {
574         let type_list: Vec<_> =
575             try_opt!(types.iter().map(|ty| ty.rewrite(context, shape)).collect());
576
577         let type_str = if context.config.spaces_within_angle_brackets() && type_list.len() > 0 {
578             format!("::< {} >", type_list.join(", "))
579         } else {
580             format!("::<{}>", type_list.join(", "))
581         };
582
583         (types.last().unwrap().span.hi, type_str)
584     };
585
586     let callee_str = format!(".{}{}", method_name, type_str);
587     let span = mk_sp(lo, span.hi);
588
589     rewrite_call(context, &callee_str, &args[1..], span, shape)
590 }