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