]> git.lizzy.rs Git - rust.git/blob - src/chains.rs
Add try macro to try shorthand conversion tests
[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_base_indent` is the indent to use for
23 /// blocks in the parent/root/base of the chain.
24 /// E.g., `let foo = { aaaa; bbb; ccc }.bar.baz();`, we would layout for the
25 /// following values of `chain_base_indent`:
26 /// Visual:
27 /// ```
28 /// let foo = {
29 ///               aaaa;
30 ///               bbb;
31 ///               ccc
32 ///           }
33 ///           .bar
34 ///           .baz();
35 /// ```
36 /// Inherit:
37 /// ```
38 /// let foo = {
39 ///     aaaa;
40 ///     bbb;
41 ///     ccc
42 /// }
43 /// .bar
44 /// .baz();
45 /// ```
46 /// Tabbed:
47 /// ```
48 /// let foo = {
49 ///         aaaa;
50 ///         bbb;
51 ///         ccc
52 ///     }
53 ///     .bar
54 ///     .baz();
55 /// ```
56 ///
57 /// `chain_indent` dictates how the rest of the chain is aligned.
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 /// `chains_overflow_last` applies only to chains where the last item is a
79 /// method call. Usually, any line break in a chain sub-expression causes the
80 /// whole chain to be split with newlines at each `.`. With `chains_overflow_last`
81 /// true, then we allow the last method call to spill over multiple lines without
82 /// forcing the rest of the chain to be split.
83
84 use Indent;
85 use rewrite::{Rewrite, RewriteContext};
86 use utils::{wrap_str, first_line_width};
87 use expr::rewrite_call;
88 use config::BlockIndentStyle;
89 use macros::convert_try_mac;
90
91 use syntax::{ast, ptr};
92 use syntax::codemap::{mk_sp, Span};
93
94 pub fn rewrite_chain(expr: &ast::Expr,
95                      context: &RewriteContext,
96                      width: usize,
97                      offset: Indent)
98                      -> Option<String> {
99     let total_span = expr.span;
100     let (parent, subexpr_list) = make_subexpr_list(expr, context);
101
102     // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
103     let parent_block_indent = chain_base_indent(context, offset);
104     let parent_context = &RewriteContext { block_indent: parent_block_indent, ..*context };
105     let parent_rewrite = try_opt!(parent.rewrite(parent_context, width, offset));
106
107     // Decide how to layout the rest of the chain. `extend` is true if we can
108     // put the first non-parent item on the same line as the parent.
109     let (indent, extend) = if !parent_rewrite.contains('\n') && is_continuable(&parent) ||
110                               parent_rewrite.len() <= context.config.tab_spaces {
111
112         let indent = if let ast::ExprKind::Try(..) = subexpr_list.last().unwrap().node {
113             parent_block_indent.block_indent(context.config)
114         } else {
115             chain_indent(context, offset + Indent::new(0, parent_rewrite.len()))
116         };
117         (indent, true)
118     } else if is_block_expr(&parent, &parent_rewrite) {
119         // The parent is a block, so align the rest of the chain with the closing
120         // brace.
121         (parent_block_indent, false)
122     } else if parent_rewrite.contains('\n') {
123         (chain_indent(context, parent_block_indent.block_indent(context.config)), false)
124     } else {
125         (chain_indent_newline(context, offset + Indent::new(0, parent_rewrite.len())), false)
126     };
127
128     let max_width = try_opt!((width + offset.width()).checked_sub(indent.width()));
129     let mut rewrites = try_opt!(subexpr_list.iter()
130         .rev()
131         .map(|e| rewrite_chain_subexpr(e, total_span, context, max_width, indent))
132         .collect::<Option<Vec<_>>>());
133
134     // Total of all items excluding the last.
135     let almost_total = rewrites[..rewrites.len() - 1]
136         .iter()
137         .fold(0, |a, b| a + first_line_width(b)) + parent_rewrite.len();
138     let total_width = almost_total + first_line_width(rewrites.last().unwrap());
139
140     let veto_single_line = if context.config.take_source_hints && subexpr_list.len() > 1 {
141         // Look at the source code. Unless all chain elements start on the same
142         // line, we won't consider putting them on a single line either.
143         let last_span = context.snippet(mk_sp(subexpr_list[1].span.hi, total_span.hi));
144         let first_span = context.snippet(subexpr_list[1].span);
145         let last_iter = last_span.chars().take_while(|c| c.is_whitespace());
146
147         first_span.chars().chain(last_iter).any(|c| c == '\n')
148     } else {
149         false
150     };
151
152     let mut fits_single_line = !veto_single_line && total_width <= width;
153     if fits_single_line {
154         let len = rewrites.len();
155         let (init, last) = rewrites.split_at_mut(len - 1);
156         fits_single_line = init.iter().all(|s| !s.contains('\n'));
157
158         if fits_single_line {
159             fits_single_line = match expr.node {
160                 ref e @ ast::ExprKind::MethodCall(..) if context.config.chains_overflow_last => {
161                     rewrite_method_call_with_overflow(e,
162                                                       &mut last[0],
163                                                       almost_total,
164                                                       width,
165                                                       total_span,
166                                                       context,
167                                                       offset)
168                 }
169                 _ => !last[0].contains('\n'),
170             }
171         }
172     }
173
174     let connector = if fits_single_line && !parent_rewrite.contains('\n') {
175         // Yay, we can put everything on one line.
176         String::new()
177     } else {
178         // Use new lines.
179         format!("\n{}", indent.to_string(context.config))
180     };
181
182     let first_connector = if extend {
183         ""
184     } else {
185         &*connector
186     };
187
188     wrap_str(format!("{}{}{}",
189                      parent_rewrite,
190                      first_connector,
191                      join_rewrites(&rewrites, &subexpr_list, &connector)),
192              context.config.max_width,
193              width,
194              offset)
195 }
196
197 fn join_rewrites(rewrites: &[String], subexps: &[ast::Expr], connector: &str) -> String {
198     let mut rewrite_iter = rewrites.iter();
199     let mut result = rewrite_iter.next().unwrap().clone();
200     let mut subexpr_iter = subexps.iter().rev();
201     subexpr_iter.next();
202
203     for (rewrite, expr) in rewrite_iter.zip(subexpr_iter) {
204         match expr.node {
205             ast::ExprKind::Try(_) => (),
206             _ => result.push_str(connector),
207         };
208         result.push_str(&rewrite[..]);
209     }
210
211     result
212 }
213
214 // States whether an expression's last line exclusively consists of closing
215 // parens, braces, and brackets in its idiomatic formatting.
216 fn is_block_expr(expr: &ast::Expr, repr: &str) -> bool {
217     match expr.node {
218         ast::ExprKind::Struct(..) |
219         ast::ExprKind::While(..) |
220         ast::ExprKind::WhileLet(..) |
221         ast::ExprKind::If(..) |
222         ast::ExprKind::IfLet(..) |
223         ast::ExprKind::Block(..) |
224         ast::ExprKind::Loop(..) |
225         ast::ExprKind::ForLoop(..) |
226         ast::ExprKind::Match(..) => repr.contains('\n'),
227         ast::ExprKind::Paren(ref expr) |
228         ast::ExprKind::Binary(_, _, ref expr) |
229         ast::ExprKind::Index(_, ref expr) |
230         ast::ExprKind::Unary(_, ref expr) => is_block_expr(expr, repr),
231         _ => false,
232     }
233 }
234
235 // Returns the root of the chain and a Vec of the prefixes of the rest of the chain.
236 // E.g., for input `a.b.c` we return (`a`, [`a.b.c`, `a.b`])
237 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> (ast::Expr, Vec<ast::Expr>) {
238     let mut subexpr_list = vec![expr.clone()];
239
240     while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
241         subexpr_list.push(subexpr.clone());
242     }
243
244     let parent = subexpr_list.pop().unwrap();
245     (parent, subexpr_list)
246 }
247
248 fn chain_base_indent(context: &RewriteContext, offset: Indent) -> Indent {
249     match context.config.chain_base_indent {
250         BlockIndentStyle::Visual => offset,
251         BlockIndentStyle::Inherit => context.block_indent,
252         BlockIndentStyle::Tabbed => context.block_indent.block_indent(context.config),
253     }
254 }
255
256 fn chain_indent(context: &RewriteContext, offset: Indent) -> Indent {
257     match context.config.chain_indent {
258         BlockIndentStyle::Visual => offset,
259         BlockIndentStyle::Inherit => context.block_indent,
260         BlockIndentStyle::Tabbed => context.block_indent.block_indent(context.config),
261     }
262 }
263
264 // Ignores visual indenting because this function should be called where it is
265 // not possible to use visual indentation because we are starting on a newline.
266 fn chain_indent_newline(context: &RewriteContext, _offset: Indent) -> Indent {
267     match context.config.chain_indent {
268         BlockIndentStyle::Inherit => context.block_indent,
269         BlockIndentStyle::Visual | BlockIndentStyle::Tabbed => {
270             context.block_indent.block_indent(context.config)
271         }
272     }
273 }
274
275 fn rewrite_method_call_with_overflow(expr_kind: &ast::ExprKind,
276                                      last: &mut String,
277                                      almost_total: usize,
278                                      width: usize,
279                                      total_span: Span,
280                                      context: &RewriteContext,
281                                      offset: Indent)
282                                      -> bool {
283     if let &ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) = expr_kind {
284         let budget = match width.checked_sub(almost_total) {
285             Some(b) => b,
286             None => return false,
287         };
288         let mut last_rewrite = rewrite_method_call(method_name.node,
289                                                    types,
290                                                    expressions,
291                                                    total_span,
292                                                    context,
293                                                    budget,
294                                                    offset + almost_total);
295
296         if let Some(ref mut s) = last_rewrite {
297             ::std::mem::swap(s, last);
298             true
299         } else {
300             false
301         }
302     } else {
303         unreachable!();
304     }
305 }
306
307 // Returns the expression's subexpression, if it exists. When the subexpr
308 // is a try! macro, we'll convert it to shorthand when the option is set.
309 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
310     match expr.node {
311         ast::ExprKind::MethodCall(_, _, ref expressions) => {
312             Some(convert_try(&expressions[0], context))
313         }
314         ast::ExprKind::TupField(ref subexpr, _) |
315         ast::ExprKind::Field(ref subexpr, _) |
316         ast::ExprKind::Try(ref subexpr) => Some(convert_try(subexpr, context)),
317         _ => None,
318     }
319 }
320
321 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
322     match expr.node {
323         ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand => {
324             if let Some(subexpr) = convert_try_mac(mac, context) {
325                 subexpr
326             } else {
327                 expr.clone()
328             }
329         }
330         _ => expr.clone(),
331     }
332 }
333
334 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
335 // `.c`.
336 fn rewrite_chain_subexpr(expr: &ast::Expr,
337                          span: Span,
338                          context: &RewriteContext,
339                          width: usize,
340                          offset: Indent)
341                          -> Option<String> {
342     match expr.node {
343         ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) => {
344             let inner = &RewriteContext { block_indent: offset, ..*context };
345             rewrite_method_call(method_name.node,
346                                 types,
347                                 expressions,
348                                 span,
349                                 inner,
350                                 width,
351                                 offset)
352         }
353         ast::ExprKind::Field(_, ref field) => {
354             let s = format!(".{}", field.node);
355             if s.len() <= width {
356                 Some(s)
357             } else {
358                 None
359             }
360         }
361         ast::ExprKind::TupField(_, ref field) => {
362             let s = format!(".{}", field.node);
363             if s.len() <= width {
364                 Some(s)
365             } else {
366                 None
367             }
368         }
369         ast::ExprKind::Try(_) => {
370             if width >= 1 {
371                 Some("?".into())
372             } else {
373                 None
374             }
375         }
376         _ => unreachable!(),
377     }
378 }
379
380 // Determines if we can continue formatting a given expression on the same line.
381 fn is_continuable(expr: &ast::Expr) -> bool {
382     match expr.node {
383         ast::ExprKind::Path(..) => true,
384         _ => false,
385     }
386 }
387
388 fn rewrite_method_call(method_name: ast::Ident,
389                        types: &[ptr::P<ast::Ty>],
390                        args: &[ptr::P<ast::Expr>],
391                        span: Span,
392                        context: &RewriteContext,
393                        width: usize,
394                        offset: Indent)
395                        -> Option<String> {
396     let (lo, type_str) = if types.is_empty() {
397         (args[0].span.hi, String::new())
398     } else {
399         let type_list: Vec<_> = try_opt!(types.iter()
400             .map(|ty| ty.rewrite(context, width, offset))
401             .collect());
402
403         (types.last().unwrap().span.hi, format!("::<{}>", type_list.join(", ")))
404     };
405
406     let callee_str = format!(".{}{}", method_name, type_str);
407     let span = mk_sp(lo, span.hi);
408
409     rewrite_call(context, &callee_str, &args[1..], span, width, offset)
410 }