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