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;
27 use syntax::{ast, ptr};
28 use syntax::codemap::{mk_sp, Span};
29 use syntax::print::pprust;
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 = subexpr_list.pop().unwrap();
45 let parent_rewrite = try_opt!(expr.rewrite(context, width, offset));
46 let (extra_indent, extend) = if !parent_rewrite.contains('\n') && is_continuable(parent) ||
47 parent_rewrite.len() <= context.config.tab_spaces {
48 (parent_rewrite.len(), true)
50 (context.config.tab_spaces, false)
52 let indent = offset + extra_indent;
54 let max_width = try_opt!(width.checked_sub(extra_indent));
55 let mut rewrites = try_opt!(subexpr_list.iter()
64 .collect::<Option<Vec<_>>>());
66 // Total of all items excluding the last.
67 let almost_total = rewrites.split_last()
71 .fold(0, |a, b| a + first_line_width(b)) +
73 let total_width = almost_total + first_line_width(rewrites.last().unwrap());
74 let veto_single_line = if context.config.take_source_hints && subexpr_list.len() > 1 {
75 // Look at the source code. Unless all chain elements start on the same
76 // line, we won't consider putting them on a single line either.
77 let first_line_no = context.codemap.lookup_char_pos(subexpr_list[0].span.lo).line;
81 .any(|ex| context.codemap.lookup_char_pos(ex.span.hi).line != first_line_no)
86 let fits_single_line = !veto_single_line &&
87 match subexpr_list[0].node {
88 ast::Expr_::ExprMethodCall(ref method_name, ref types, ref expressions)
89 if context.config.chains_overflow_last => {
90 let (last, init) = rewrites.split_last_mut().unwrap();
92 if init.iter().all(|s| !s.contains('\n')) && total_width <= width {
93 let last_rewrite = width.checked_sub(almost_total)
94 .and_then(|inner_width| {
95 rewrite_method_call(method_name.node,
101 offset + almost_total)
104 Some(mut string) => {
105 ::std::mem::swap(&mut string, last);
114 _ => total_width <= width && rewrites.iter().all(|s| !s.contains('\n')),
117 let connector = if fits_single_line {
120 format!("\n{}", indent.to_string(context.config))
123 let first_connector = if extend {
129 Some(format!("{}{}{}",
132 rewrites.join(&connector)))
135 fn pop_expr_chain<'a>(expr: &'a ast::Expr) -> Option<&'a ast::Expr> {
137 ast::Expr_::ExprMethodCall(_, _, ref expressions) => {
138 Some(&expressions[0])
140 ast::Expr_::ExprTupField(ref subexpr, _) |
141 ast::Expr_::ExprField(ref subexpr, _) => {
148 fn rewrite_chain_expr(expr: &ast::Expr,
150 context: &RewriteContext,
155 ast::Expr_::ExprMethodCall(ref method_name, ref types, ref expressions) => {
156 let inner = &RewriteContext { block_indent: offset, ..*context };
157 rewrite_method_call(method_name.node,
165 ast::Expr_::ExprField(_, ref field) => {
166 Some(format!(".{}", field.node))
168 ast::Expr_::ExprTupField(_, ref field) => {
169 Some(format!(".{}", field.node))
175 // Determines we can continue formatting a given expression on the same line.
176 fn is_continuable(expr: &ast::Expr) -> bool {
178 ast::Expr_::ExprPath(..) => true,
183 fn rewrite_method_call(method_name: ast::Ident,
184 types: &[ptr::P<ast::Ty>],
185 args: &[ptr::P<ast::Expr>],
187 context: &RewriteContext,
191 let type_str = if types.is_empty() {
194 let type_list = types.iter().map(|ty| pprust::ty_to_string(ty)).collect::<Vec<_>>();
195 format!("::<{}>", type_list.join(", "))
198 let callee_str = format!(".{}{}", method_name, type_str);
199 let span = mk_sp(args[0].span.hi, span.hi);
201 rewrite_call(context, &callee_str, &args[1..], span, width, offset)