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};
30 use syntax::print::pprust;
32 pub fn rewrite_chain(mut expr: &ast::Expr,
33 context: &RewriteContext,
37 let total_span = expr.span;
38 let mut subexpr_list = vec![expr];
40 while let Some(subexpr) = pop_expr_chain(expr) {
41 subexpr_list.push(subexpr);
45 let parent_block_indent = match context.config.chain_base_indent {
46 BlockIndentStyle::Visual => offset,
47 BlockIndentStyle::Inherit => context.block_indent,
48 BlockIndentStyle::Tabbed => context.block_indent.block_indent(context.config),
50 let parent_context = &RewriteContext { block_indent: parent_block_indent, ..*context };
51 let parent = subexpr_list.pop().unwrap();
52 let parent_rewrite = try_opt!(expr.rewrite(parent_context, width, offset));
53 let (indent, extend) = if !parent_rewrite.contains('\n') && is_continuable(parent) ||
54 parent_rewrite.len() <= context.config.tab_spaces {
55 (offset + Indent::new(0, parent_rewrite.len()), true)
56 } else if is_block_expr(parent, &parent_rewrite) {
57 (parent_block_indent, false)
59 match context.config.chain_indent {
60 BlockIndentStyle::Inherit => (context.block_indent, false),
61 BlockIndentStyle::Tabbed => (context.block_indent.block_indent(context.config), false),
62 BlockIndentStyle::Visual => (offset + Indent::new(context.config.tab_spaces, 0), false),
66 let max_width = try_opt!((width + offset.width()).checked_sub(indent.width()));
67 let mut rewrites = try_opt!(subexpr_list.iter()
76 .collect::<Option<Vec<_>>>());
78 // Total of all items excluding the last.
79 let almost_total = rewrites[..rewrites.len() - 1]
81 .fold(0, |a, b| a + first_line_width(b)) +
83 let total_width = almost_total + first_line_width(rewrites.last().unwrap());
84 let veto_single_line = if context.config.take_source_hints && subexpr_list.len() > 1 {
85 // Look at the source code. Unless all chain elements start on the same
86 // line, we won't consider putting them on a single line either.
87 let last_span = context.snippet(mk_sp(subexpr_list[1].span.hi, total_span.hi));
88 let first_span = context.snippet(subexpr_list[1].span);
89 let last_iter = last_span.chars().take_while(|c| c.is_whitespace());
91 first_span.chars().chain(last_iter).any(|c| c == '\n')
96 let fits_single_line = !veto_single_line &&
97 match subexpr_list[0].node {
98 ast::Expr_::ExprMethodCall(ref method_name, ref types, ref expressions)
99 if context.config.chains_overflow_last => {
100 let len = rewrites.len();
101 let (init, last) = rewrites.split_at_mut(len - 1);
102 let last = &mut last[0];
104 if init.iter().all(|s| !s.contains('\n')) && total_width <= width {
105 let last_rewrite = width.checked_sub(almost_total)
106 .and_then(|inner_width| {
107 rewrite_method_call(method_name.node,
113 offset + almost_total)
116 Some(mut string) => {
117 ::std::mem::swap(&mut string, last);
126 _ => total_width <= width && rewrites.iter().all(|s| !s.contains('\n')),
129 let connector = if fits_single_line && !parent_rewrite.contains('\n') {
132 format!("\n{}", indent.to_string(context.config))
135 let first_connector = if extend {
141 wrap_str(format!("{}{}{}",
144 rewrites.join(&connector)),
145 context.config.max_width,
150 // States whether an expression's last line exclusively consists of closing
151 // parens, braces and brackets in its idiomatic formatting.
152 fn is_block_expr(expr: &ast::Expr, repr: &str) -> bool {
154 ast::Expr_::ExprStruct(..) |
155 ast::Expr_::ExprWhile(..) |
156 ast::Expr_::ExprWhileLet(..) |
157 ast::Expr_::ExprIf(..) |
158 ast::Expr_::ExprIfLet(..) |
159 ast::Expr_::ExprBlock(..) |
160 ast::Expr_::ExprLoop(..) |
161 ast::Expr_::ExprForLoop(..) |
162 ast::Expr_::ExprMatch(..) => repr.contains('\n'),
163 ast::Expr_::ExprParen(ref expr) |
164 ast::Expr_::ExprBinary(_, _, ref expr) |
165 ast::Expr_::ExprIndex(_, ref expr) |
166 ast::Expr_::ExprUnary(_, ref expr) => is_block_expr(expr, repr),
171 fn pop_expr_chain(expr: &ast::Expr) -> Option<&ast::Expr> {
173 ast::Expr_::ExprMethodCall(_, _, ref expressions) => Some(&expressions[0]),
174 ast::Expr_::ExprTupField(ref subexpr, _) |
175 ast::Expr_::ExprField(ref subexpr, _) => Some(subexpr),
180 fn rewrite_chain_expr(expr: &ast::Expr,
182 context: &RewriteContext,
187 ast::Expr_::ExprMethodCall(ref method_name, ref types, ref expressions) => {
188 let inner = &RewriteContext { block_indent: offset, ..*context };
189 rewrite_method_call(method_name.node,
197 ast::Expr_::ExprField(_, ref field) => {
198 let s = format!(".{}", field.node);
199 if s.len() <= width {
205 ast::Expr_::ExprTupField(_, ref field) => {
206 let s = format!(".{}", field.node);
207 if s.len() <= width {
217 // Determines we can continue formatting a given expression on the same line.
218 fn is_continuable(expr: &ast::Expr) -> bool {
220 ast::Expr_::ExprPath(..) => true,
225 fn rewrite_method_call(method_name: ast::Ident,
226 types: &[ptr::P<ast::Ty>],
227 args: &[ptr::P<ast::Expr>],
229 context: &RewriteContext,
233 let (lo, type_str) = if types.is_empty() {
234 (args[0].span.hi, String::new())
236 let type_list = types.iter().map(|ty| pprust::ty_to_string(ty)).collect::<Vec<_>>();
238 (types.last().unwrap().span.hi,
239 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)