]> git.lizzy.rs Git - rust.git/blob - src/chains.rs
Run wrap_str() only when chain_indent is set to "Visual"
[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     if context.config.chain_indent() == IndentStyle::Visual {
270         wrap_str(result, context.config.max_width(), shape)
271     } else {
272         Some(result)
273     }
274 }
275
276 fn is_extendable_parent(context: &RewriteContext, parent_str: &str) -> bool {
277     context.config.chain_indent() == IndentStyle::Block && last_line_extendable(parent_str)
278 }
279
280 // True if the chain is only `?`s.
281 fn chain_only_try(exprs: &[ast::Expr]) -> bool {
282     exprs.iter().all(|e| if let ast::ExprKind::Try(_) = e.node {
283         true
284     } else {
285         false
286     })
287 }
288
289 // Try to rewrite and replace the last non-try child. Return `true` if
290 // replacing succeeds.
291 fn repeat_try(try_count: usize) -> String {
292     iter::repeat("?").take(try_count).collect::<String>()
293 }
294
295 fn rewrite_try(
296     expr: &ast::Expr,
297     try_count: usize,
298     context: &RewriteContext,
299     shape: Shape,
300 ) -> Option<String> {
301     let sub_expr = expr.rewrite(context, shape.sub_width(try_count)?)?;
302     Some(format!("{}{}", sub_expr, repeat_try(try_count)))
303 }
304
305 fn join_rewrites(rewrites: &[String], subexps: &[ast::Expr], connector: &str) -> String {
306     let mut rewrite_iter = rewrites.iter();
307     let mut result = rewrite_iter.next().unwrap().clone();
308     let mut subexpr_iter = subexps.iter().rev();
309     subexpr_iter.next();
310
311     for (rewrite, expr) in rewrite_iter.zip(subexpr_iter) {
312         match expr.node {
313             ast::ExprKind::Try(_) => (),
314             _ => result.push_str(connector),
315         };
316         result.push_str(&rewrite[..]);
317     }
318
319     result
320 }
321
322 // States whether an expression's last line exclusively consists of closing
323 // parens, braces, and brackets in its idiomatic formatting.
324 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
325     match expr.node {
326         ast::ExprKind::Mac(..) | ast::ExprKind::Call(..) => {
327             context.use_block_indent() && repr.contains('\n')
328         }
329         ast::ExprKind::Struct(..) |
330         ast::ExprKind::While(..) |
331         ast::ExprKind::WhileLet(..) |
332         ast::ExprKind::If(..) |
333         ast::ExprKind::IfLet(..) |
334         ast::ExprKind::Block(..) |
335         ast::ExprKind::Loop(..) |
336         ast::ExprKind::ForLoop(..) |
337         ast::ExprKind::Match(..) => repr.contains('\n'),
338         ast::ExprKind::Paren(ref expr) |
339         ast::ExprKind::Binary(_, _, ref expr) |
340         ast::ExprKind::Index(_, ref expr) |
341         ast::ExprKind::Unary(_, ref expr) => is_block_expr(context, expr, repr),
342         _ => false,
343     }
344 }
345
346 // Returns the root of the chain and a Vec of the prefixes of the rest of the chain.
347 // E.g., for input `a.b.c` we return (`a`, [`a.b.c`, `a.b`])
348 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> (ast::Expr, Vec<ast::Expr>) {
349     let mut subexpr_list = vec![expr.clone()];
350
351     while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
352         subexpr_list.push(subexpr.clone());
353     }
354
355     let parent = subexpr_list.pop().unwrap();
356     (parent, subexpr_list)
357 }
358
359 fn chain_indent(context: &RewriteContext, shape: Shape) -> Shape {
360     match context.config.chain_indent() {
361         IndentStyle::Visual => shape.visual_indent(0),
362         IndentStyle::Block => shape
363             .block_indent(context.config.tab_spaces())
364             .with_max_width(context.config),
365     }
366 }
367
368 // Returns the expression's subexpression, if it exists. When the subexpr
369 // is a try! macro, we'll convert it to shorthand when the option is set.
370 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
371     match expr.node {
372         ast::ExprKind::MethodCall(_, ref expressions) => {
373             Some(convert_try(&expressions[0], context))
374         }
375         ast::ExprKind::TupField(ref subexpr, _) |
376         ast::ExprKind::Field(ref subexpr, _) |
377         ast::ExprKind::Try(ref subexpr) => Some(convert_try(subexpr, context)),
378         _ => None,
379     }
380 }
381
382 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
383     match expr.node {
384         ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
385             if let Some(subexpr) = convert_try_mac(mac, context) {
386                 subexpr
387             } else {
388                 expr.clone()
389             }
390         }
391         _ => expr.clone(),
392     }
393 }
394
395 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
396 // `.c`.
397 fn rewrite_chain_subexpr(
398     expr: &ast::Expr,
399     span: Span,
400     context: &RewriteContext,
401     shape: Shape,
402 ) -> Option<String> {
403     let rewrite_element = |expr_str: String| if expr_str.len() <= shape.width {
404         Some(expr_str)
405     } else {
406         None
407     };
408
409     match expr.node {
410         ast::ExprKind::MethodCall(ref segment, ref expressions) => {
411             let types = match segment.parameters {
412                 Some(ref params) => match **params {
413                     ast::PathParameters::AngleBracketed(ref data) => &data.types[..],
414                     _ => &[],
415                 },
416                 _ => &[],
417             };
418             rewrite_method_call(segment.identifier, types, expressions, span, context, shape)
419         }
420         ast::ExprKind::Field(_, ref field) => rewrite_element(format!(".{}", field.node)),
421         ast::ExprKind::TupField(ref expr, ref field) => {
422             let space = match expr.node {
423                 ast::ExprKind::TupField(..) => " ",
424                 _ => "",
425             };
426             rewrite_element(format!("{}.{}", space, field.node))
427         }
428         ast::ExprKind::Try(_) => rewrite_element(String::from("?")),
429         _ => unreachable!(),
430     }
431 }
432
433 // Determines if we can continue formatting a given expression on the same line.
434 fn is_continuable(expr: &ast::Expr) -> bool {
435     match expr.node {
436         ast::ExprKind::Path(..) => true,
437         _ => false,
438     }
439 }
440
441 fn is_try(expr: &ast::Expr) -> bool {
442     match expr.node {
443         ast::ExprKind::Try(..) => true,
444         _ => false,
445     }
446 }
447
448 fn choose_first_connector<'a>(
449     context: &RewriteContext,
450     parent_str: &str,
451     first_child_str: &str,
452     connector: &'a str,
453     subexpr_list: &[ast::Expr],
454     extend: bool,
455 ) -> &'a str {
456     if subexpr_list.is_empty() {
457         ""
458     } else if extend || subexpr_list.last().map_or(false, is_try)
459         || is_extendable_parent(context, parent_str)
460     {
461         // 1 = ";", being conservative here.
462         if last_line_width(parent_str) + first_line_width(first_child_str) + 1
463             <= context.config.max_width()
464         {
465             ""
466         } else {
467             connector
468         }
469     } else {
470         connector
471     }
472 }
473
474 fn rewrite_method_call(
475     method_name: ast::Ident,
476     types: &[ptr::P<ast::Ty>],
477     args: &[ptr::P<ast::Expr>],
478     span: Span,
479     context: &RewriteContext,
480     shape: Shape,
481 ) -> Option<String> {
482     let (lo, type_str) = if types.is_empty() {
483         (args[0].span.hi(), String::new())
484     } else {
485         let type_list = types
486             .iter()
487             .map(|ty| ty.rewrite(context, shape))
488             .collect::<Option<Vec<_>>>()?;
489
490         let type_str = if context.config.spaces_within_angle_brackets() && !type_list.is_empty() {
491             format!("::< {} >", type_list.join(", "))
492         } else {
493             format!("::<{}>", type_list.join(", "))
494         };
495
496         (types.last().unwrap().span.hi(), type_str)
497     };
498
499     let callee_str = format!(".{}{}", method_name, type_str);
500     let span = mk_sp(lo, span.hi());
501
502     rewrite_call(context, &callee_str, &args[1..], span, shape)
503 }