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 (offset + Indent::new(context.config.tab_spaces, 0), false)
62 let max_width = try_opt!((width + offset.width()).checked_sub(indent.width()));
63 let mut rewrites = try_opt!(subexpr_list.iter()
72 .collect::<Option<Vec<_>>>());
74 // Total of all items excluding the last.
75 let almost_total = rewrites[..rewrites.len() - 1]
77 .fold(0, |a, b| a + first_line_width(b)) +
79 let total_width = almost_total + first_line_width(rewrites.last().unwrap());
80 let veto_single_line = if context.config.take_source_hints && subexpr_list.len() > 1 {
81 // Look at the source code. Unless all chain elements start on the same
82 // line, we won't consider putting them on a single line either.
83 let first_line_no = context.codemap.lookup_char_pos(subexpr_list[0].span.lo).line;
87 .any(|ex| context.codemap.lookup_char_pos(ex.span.hi).line != first_line_no)
92 let fits_single_line = !veto_single_line &&
93 match subexpr_list[0].node {
94 ast::Expr_::ExprMethodCall(ref method_name, ref types, ref expressions)
95 if context.config.chains_overflow_last => {
96 let len = rewrites.len();
97 let (init, last) = rewrites.split_at_mut(len - 1);
98 let last = &mut last[0];
100 if init.iter().all(|s| !s.contains('\n')) && total_width <= width {
101 let last_rewrite = width.checked_sub(almost_total)
102 .and_then(|inner_width| {
103 rewrite_method_call(method_name.node,
109 offset + almost_total)
112 Some(mut string) => {
113 ::std::mem::swap(&mut string, last);
122 _ => total_width <= width && rewrites.iter().all(|s| !s.contains('\n')),
125 let connector = if fits_single_line && !parent_rewrite.contains('\n') {
128 format!("\n{}", indent.to_string(context.config))
131 let first_connector = if extend {
137 Some(format!("{}{}{}",
140 rewrites.join(&connector)))
143 // States whether an expression's last line exclusively consists of closing
144 // parens, braces and brackets in its idiomatic formatting.
145 fn is_block_expr(expr: &ast::Expr, repr: &str) -> bool {
147 ast::Expr_::ExprStruct(..) |
148 ast::Expr_::ExprWhile(..) |
149 ast::Expr_::ExprWhileLet(..) |
150 ast::Expr_::ExprIf(..) |
151 ast::Expr_::ExprIfLet(..) |
152 ast::Expr_::ExprBlock(..) |
153 ast::Expr_::ExprLoop(..) |
154 ast::Expr_::ExprForLoop(..) |
155 ast::Expr_::ExprMatch(..) => repr.contains('\n'),
156 ast::Expr_::ExprParen(ref expr) |
157 ast::Expr_::ExprBinary(_, _, ref expr) |
158 ast::Expr_::ExprIndex(_, ref expr) |
159 ast::Expr_::ExprUnary(_, ref expr) => is_block_expr(expr, repr),
164 fn pop_expr_chain<'a>(expr: &'a ast::Expr) -> Option<&'a ast::Expr> {
166 ast::Expr_::ExprMethodCall(_, _, ref expressions) => {
167 Some(&expressions[0])
169 ast::Expr_::ExprTupField(ref subexpr, _) |
170 ast::Expr_::ExprField(ref subexpr, _) => {
177 fn rewrite_chain_expr(expr: &ast::Expr,
179 context: &RewriteContext,
184 ast::Expr_::ExprMethodCall(ref method_name, ref types, ref expressions) => {
185 let inner = &RewriteContext { block_indent: offset, ..*context };
186 rewrite_method_call(method_name.node,
194 ast::Expr_::ExprField(_, ref field) => {
195 Some(format!(".{}", field.node))
197 ast::Expr_::ExprTupField(_, ref field) => {
198 Some(format!(".{}", field.node))
204 // Determines we can continue formatting a given expression on the same line.
205 fn is_continuable(expr: &ast::Expr) -> bool {
207 ast::Expr_::ExprPath(..) => true,
212 fn rewrite_method_call(method_name: ast::Ident,
213 types: &[ptr::P<ast::Ty>],
214 args: &[ptr::P<ast::Expr>],
216 context: &RewriteContext,
220 let type_str = if types.is_empty() {
223 let type_list = types.iter().map(|ty| pprust::ty_to_string(ty)).collect::<Vec<_>>();
224 format!("::<{}>", type_list.join(", "))
227 let callee_str = format!(".{}{}", method_name, type_str);
228 let span = mk_sp(args[0].span.hi, span.hi);
230 rewrite_call(context, &callee_str, &args[1..], span, width, offset)