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.
22 use rewrite::{Rewrite, RewriteContext};
23 use utils::{first_line_width, make_indent};
24 use expr::rewrite_call;
26 use syntax::{ast, ptr};
27 use syntax::codemap::{mk_sp, Span};
28 use syntax::print::pprust;
30 pub fn rewrite_chain(mut expr: &ast::Expr,
31 context: &RewriteContext,
35 let total_span = expr.span;
36 let mut subexpr_list = vec![expr];
38 while let Some(subexpr) = pop_expr_chain(expr) {
39 subexpr_list.push(subexpr);
43 let parent = subexpr_list.pop().unwrap();
44 let parent_rewrite = try_opt!(expr.rewrite(context, width, offset));
45 let (extra_indent, extend) = if !parent_rewrite.contains('\n') && is_continuable(parent) ||
46 parent_rewrite.len() <= context.config.tab_spaces {
47 (parent_rewrite.len(), true)
49 (context.config.tab_spaces, false)
51 let indent = offset + extra_indent;
53 let max_width = try_opt!(width.checked_sub(extra_indent));
54 let mut rewrites = try_opt!(subexpr_list.iter()
63 .collect::<Option<Vec<_>>>());
65 // Total of all items excluding the last.
66 let almost_total = rewrites.split_last()
70 .fold(0, |a, b| a + first_line_width(b)) +
72 let total_width = almost_total + first_line_width(rewrites.last().unwrap());
73 let veto_single_line = if context.config.take_source_hints && subexpr_list.len() > 1 {
74 // Look at the source code. Unless all chain elements start on the same
75 // line, we won't consider putting them on a single line either.
76 let first_line_no = context.codemap.lookup_char_pos(subexpr_list[0].span.lo).line;
80 .any(|ex| context.codemap.lookup_char_pos(ex.span.hi).line != first_line_no)
85 let fits_single_line = !veto_single_line &&
86 match subexpr_list[0].node {
87 ast::Expr_::ExprMethodCall(ref method_name, ref types, ref expressions)
88 if context.config.chains_overflow_last => {
89 let (last, init) = rewrites.split_last_mut().unwrap();
91 if init.iter().all(|s| !s.contains('\n')) && total_width <= width {
92 let last_rewrite = width.checked_sub(almost_total)
93 .and_then(|inner_width| {
94 rewrite_method_call(method_name.node,
100 offset + almost_total)
103 Some(mut string) => {
104 ::std::mem::swap(&mut string, last);
113 _ => total_width <= width && rewrites.iter().all(|s| !s.contains('\n')),
116 let connector = if fits_single_line {
119 format!("\n{}", make_indent(indent))
122 let first_connector = if extend {
128 Some(format!("{}{}{}", parent_rewrite, first_connector, rewrites.join(&connector)))
131 fn pop_expr_chain<'a>(expr: &'a ast::Expr) -> Option<&'a ast::Expr> {
133 ast::Expr_::ExprMethodCall(_, _, ref expressions) => {
134 Some(&expressions[0])
136 ast::Expr_::ExprTupField(ref subexpr, _) |
137 ast::Expr_::ExprField(ref subexpr, _) => {
144 fn rewrite_chain_expr(expr: &ast::Expr,
146 context: &RewriteContext,
151 ast::Expr_::ExprMethodCall(ref method_name, ref types, ref expressions) => {
152 let inner = &RewriteContext {
153 block_indent: offset,
156 rewrite_method_call(method_name.node, types, expressions, span, inner, width, offset)
158 ast::Expr_::ExprField(_, ref field) => {
159 Some(format!(".{}", field.node))
161 ast::Expr_::ExprTupField(_, ref field) => {
162 Some(format!(".{}", field.node))
168 // Determines we can continue formatting a given expression on the same line.
169 fn is_continuable(expr: &ast::Expr) -> bool {
171 ast::Expr_::ExprPath(..) => true,
176 fn rewrite_method_call(method_name: ast::Ident,
177 types: &[ptr::P<ast::Ty>],
178 args: &[ptr::P<ast::Expr>],
180 context: &RewriteContext,
184 let type_str = if types.is_empty() {
187 let type_list = types.iter().map(|ty| pprust::ty_to_string(ty)).collect::<Vec<_>>();
188 format!("::<{}>", type_list.join(", "))
191 let callee_str = format!(".{}{}", method_name, type_str);
192 let span = mk_sp(args[0].span.hi, span.hi);
194 rewrite_call(context, &callee_str, &args[1..], span, width, offset)