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.
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.
11 // Formatting of chained expressions, i.e. expressions which are chained by
12 // dots: struct and enum field access and method calls.
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.
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.
23 use rewrite::{Rewrite, RewriteContext};
24 use utils::{wrap_str, first_line_width};
25 use expr::rewrite_call;
26 use config::BlockIndentStyle;
28 use syntax::{ast, ptr};
29 use syntax::codemap::{mk_sp, Span};
31 pub fn rewrite_chain(mut expr: &ast::Expr,
32 context: &RewriteContext,
36 let total_span = expr.span;
37 let mut subexpr_list = vec![expr];
39 while let Some(subexpr) = pop_expr_chain(expr) {
40 subexpr_list.push(subexpr);
44 let parent_block_indent = match context.config.chain_base_indent {
45 BlockIndentStyle::Visual => offset,
46 BlockIndentStyle::Inherit => context.block_indent,
47 BlockIndentStyle::Tabbed => context.block_indent.block_indent(context.config),
49 let parent_context = &RewriteContext { block_indent: parent_block_indent, ..*context };
50 let parent = subexpr_list.pop().unwrap();
51 let parent_rewrite = try_opt!(expr.rewrite(parent_context, width, offset));
52 let (indent, extend) = if !parent_rewrite.contains('\n') && is_continuable(parent) ||
53 parent_rewrite.len() <= context.config.tab_spaces {
54 (offset + Indent::new(0, parent_rewrite.len()), true)
55 } else if is_block_expr(parent, &parent_rewrite) {
56 (parent_block_indent, false)
58 match context.config.chain_indent {
59 BlockIndentStyle::Inherit => (context.block_indent, false),
60 BlockIndentStyle::Tabbed => (context.block_indent.block_indent(context.config), false),
61 BlockIndentStyle::Visual => (offset + Indent::new(context.config.tab_spaces, 0), false),
65 let max_width = try_opt!((width + offset.width()).checked_sub(indent.width()));
66 let mut rewrites = try_opt!(subexpr_list.iter()
75 .collect::<Option<Vec<_>>>());
77 // Total of all items excluding the last.
78 let almost_total = rewrites[..rewrites.len() - 1]
80 .fold(0, |a, b| a + first_line_width(b)) +
82 let total_width = almost_total + first_line_width(rewrites.last().unwrap());
83 let veto_single_line = if context.config.take_source_hints && subexpr_list.len() > 1 {
84 // Look at the source code. Unless all chain elements start on the same
85 // line, we won't consider putting them on a single line either.
86 let last_span = context.snippet(mk_sp(subexpr_list[1].span.hi, total_span.hi));
87 let first_span = context.snippet(subexpr_list[1].span);
88 let last_iter = last_span.chars().take_while(|c| c.is_whitespace());
90 first_span.chars().chain(last_iter).any(|c| c == '\n')
95 let fits_single_line = !veto_single_line &&
96 match subexpr_list[0].node {
97 ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions)
98 if context.config.chains_overflow_last => {
99 let len = rewrites.len();
100 let (init, last) = rewrites.split_at_mut(len - 1);
101 let last = &mut last[0];
103 if init.iter().all(|s| !s.contains('\n')) && total_width <= width {
104 let last_rewrite = width.checked_sub(almost_total)
105 .and_then(|inner_width| {
106 rewrite_method_call(method_name.node,
112 offset + almost_total)
115 Some(mut string) => {
116 ::std::mem::swap(&mut string, last);
125 _ => total_width <= width && rewrites.iter().all(|s| !s.contains('\n')),
128 let connector = if fits_single_line && !parent_rewrite.contains('\n') {
131 format!("\n{}", indent.to_string(context.config))
134 let first_connector = if extend {
140 wrap_str(format!("{}{}{}",
143 rewrites.join(&connector)),
144 context.config.max_width,
149 // States whether an expression's last line exclusively consists of closing
150 // parens, braces and brackets in its idiomatic formatting.
151 fn is_block_expr(expr: &ast::Expr, repr: &str) -> bool {
153 ast::ExprKind::Struct(..) |
154 ast::ExprKind::While(..) |
155 ast::ExprKind::WhileLet(..) |
156 ast::ExprKind::If(..) |
157 ast::ExprKind::IfLet(..) |
158 ast::ExprKind::Block(..) |
159 ast::ExprKind::Loop(..) |
160 ast::ExprKind::ForLoop(..) |
161 ast::ExprKind::Match(..) => repr.contains('\n'),
162 ast::ExprKind::Paren(ref expr) |
163 ast::ExprKind::Binary(_, _, ref expr) |
164 ast::ExprKind::Index(_, ref expr) |
165 ast::ExprKind::Unary(_, ref expr) => is_block_expr(expr, repr),
170 fn pop_expr_chain(expr: &ast::Expr) -> Option<&ast::Expr> {
172 ast::ExprKind::MethodCall(_, _, ref expressions) => Some(&expressions[0]),
173 ast::ExprKind::TupField(ref subexpr, _) |
174 ast::ExprKind::Field(ref subexpr, _) => Some(subexpr),
179 fn rewrite_chain_expr(expr: &ast::Expr,
181 context: &RewriteContext,
186 ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) => {
187 let inner = &RewriteContext { block_indent: offset, ..*context };
188 rewrite_method_call(method_name.node,
196 ast::ExprKind::Field(_, ref field) => {
197 let s = format!(".{}", field.node);
198 if s.len() <= width {
204 ast::ExprKind::TupField(_, ref field) => {
205 let s = format!(".{}", field.node);
206 if s.len() <= width {
216 // Determines we can continue formatting a given expression on the same line.
217 fn is_continuable(expr: &ast::Expr) -> bool {
219 ast::ExprKind::Path(..) => true,
224 fn rewrite_method_call(method_name: ast::Ident,
225 types: &[ptr::P<ast::Ty>],
226 args: &[ptr::P<ast::Expr>],
228 context: &RewriteContext,
232 let (lo, type_str) = if types.is_empty() {
233 (args[0].span.hi, String::new())
235 let type_list: Vec<_> = try_opt!(types.iter()
236 .map(|ty| ty.rewrite(context, width, offset))
239 (types.last().unwrap().span.hi, format!("::<{}>", type_list.join(", ")))
242 let callee_str = format!(".{}{}", method_name, type_str);
243 let span = mk_sp(lo, span.hi);
245 rewrite_call(context, &callee_str, &args[1..], span, width, offset)