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