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