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::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 => {
62 (context.block_indent.block_indent(context.config), false)
64 BlockIndentStyle::Visual => {
65 (offset + Indent::new(context.config.tab_spaces, 0), false)
70 let max_width = try_opt!((width + offset.width()).checked_sub(indent.width()));
71 let mut rewrites = try_opt!(subexpr_list.iter()
80 .collect::<Option<Vec<_>>>());
82 // Total of all items excluding the last.
83 let almost_total = rewrites[..rewrites.len() - 1]
85 .fold(0, |a, b| a + first_line_width(b)) +
87 let total_width = almost_total + first_line_width(rewrites.last().unwrap());
88 let veto_single_line = if context.config.take_source_hints && subexpr_list.len() > 1 {
89 // Look at the source code. Unless all chain elements start on the same
90 // line, we won't consider putting them on a single line either.
91 let last_span = context.snippet(mk_sp(subexpr_list[1].span.hi, total_span.hi));
92 let first_span = context.snippet(subexpr_list[1].span);
93 let last_iter = last_span.chars().take_while(|c| c.is_whitespace());
95 first_span.chars().chain(last_iter).any(|c| c == '\n')
100 let fits_single_line = !veto_single_line &&
101 match subexpr_list[0].node {
102 ast::Expr_::ExprMethodCall(ref method_name, ref types, ref expressions)
103 if context.config.chains_overflow_last => {
104 let len = rewrites.len();
105 let (init, last) = rewrites.split_at_mut(len - 1);
106 let last = &mut last[0];
108 if init.iter().all(|s| !s.contains('\n')) && total_width <= width {
109 let last_rewrite = width.checked_sub(almost_total)
110 .and_then(|inner_width| {
111 rewrite_method_call(method_name.node,
117 offset + almost_total)
120 Some(mut string) => {
121 ::std::mem::swap(&mut string, last);
130 _ => total_width <= width && rewrites.iter().all(|s| !s.contains('\n')),
133 let connector = if fits_single_line && !parent_rewrite.contains('\n') {
136 format!("\n{}", indent.to_string(context.config))
139 let first_connector = if extend {
145 Some(format!("{}{}{}",
148 rewrites.join(&connector)))
151 // States whether an expression's last line exclusively consists of closing
152 // parens, braces and brackets in its idiomatic formatting.
153 fn is_block_expr(expr: &ast::Expr, repr: &str) -> bool {
155 ast::Expr_::ExprStruct(..) |
156 ast::Expr_::ExprWhile(..) |
157 ast::Expr_::ExprWhileLet(..) |
158 ast::Expr_::ExprIf(..) |
159 ast::Expr_::ExprIfLet(..) |
160 ast::Expr_::ExprBlock(..) |
161 ast::Expr_::ExprLoop(..) |
162 ast::Expr_::ExprForLoop(..) |
163 ast::Expr_::ExprMatch(..) => repr.contains('\n'),
164 ast::Expr_::ExprParen(ref expr) |
165 ast::Expr_::ExprBinary(_, _, ref expr) |
166 ast::Expr_::ExprIndex(_, ref expr) |
167 ast::Expr_::ExprUnary(_, ref expr) => is_block_expr(expr, repr),
172 fn pop_expr_chain<'a>(expr: &'a ast::Expr) -> Option<&'a ast::Expr> {
174 ast::Expr_::ExprMethodCall(_, _, ref expressions) => {
175 Some(&expressions[0])
177 ast::Expr_::ExprTupField(ref subexpr, _) |
178 ast::Expr_::ExprField(ref subexpr, _) => {
185 fn rewrite_chain_expr(expr: &ast::Expr,
187 context: &RewriteContext,
192 ast::Expr_::ExprMethodCall(ref method_name, ref types, ref expressions) => {
193 let inner = &RewriteContext { block_indent: offset, ..*context };
194 rewrite_method_call(method_name.node,
202 ast::Expr_::ExprField(_, ref field) => {
203 Some(format!(".{}", field.node))
205 ast::Expr_::ExprTupField(_, ref field) => {
206 Some(format!(".{}", field.node))
212 // Determines we can continue formatting a given expression on the same line.
213 fn is_continuable(expr: &ast::Expr) -> bool {
215 ast::Expr_::ExprPath(..) => true,
220 fn rewrite_method_call(method_name: ast::Ident,
221 types: &[ptr::P<ast::Ty>],
222 args: &[ptr::P<ast::Expr>],
224 context: &RewriteContext,
228 let (lo, type_str) = if types.is_empty() {
229 (args[0].span.hi, String::new())
231 let type_list = types.iter().map(|ty| pprust::ty_to_string(ty)).collect::<Vec<_>>();
233 (types.last().unwrap().span.hi,
234 format!("::<{}>", type_list.join(", ")))
237 let callee_str = format!(".{}{}", method_name, type_str);
238 let span = mk_sp(lo, span.hi);
240 rewrite_call(context, &callee_str, &args[1..], span, width, offset)