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