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