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