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