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, method calls, and try shorthand (?).
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 /// Depends on config options: `chain_indent` is the indent to use for
23 /// blocks in the parent/root/base of the chain (and the rest of the chain's
25 /// E.g., `let foo = { aaaa; bbb; ccc }.bar.baz();`, we would layout for the
26 /// following values of `chain_indent`:
58 /// If the first item in the chain is a block expression, we align the dots with
80 use rewrite::{Rewrite, RewriteContext};
81 use utils::{wrap_str, first_line_width, last_line_width};
82 use expr::rewrite_call;
83 use config::IndentStyle;
84 use macros::convert_try_mac;
88 use syntax::{ast, ptr};
89 use syntax::codemap::{mk_sp, Span};
91 pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -> Option<String> {
92 debug!("rewrite_chain {:?}", shape);
93 let total_span = expr.span;
94 let (parent, subexpr_list) = make_subexpr_list(expr, context);
96 // Bail out if the chain is just try sugar, i.e., an expression followed by
97 // any number of `?`s.
98 if chain_only_try(&subexpr_list) {
99 return rewrite_try(&parent, subexpr_list.len(), context, shape);
101 let trailing_try_num = subexpr_list
103 .take_while(|e| match e.node {
104 ast::ExprKind::Try(..) => true,
109 // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
110 let parent_shape = if is_block_expr(context, &parent, "\n") {
111 match context.config.chain_indent() {
112 IndentStyle::Visual => shape.visual_indent(0),
113 IndentStyle::Block => shape.block(),
118 let parent_rewrite = try_opt!(parent.rewrite(context, parent_shape));
119 let parent_rewrite_contains_newline = parent_rewrite.contains('\n');
121 // Decide how to layout the rest of the chain. `extend` is true if we can
122 // put the first non-parent item on the same line as the parent.
123 let first_subexpr_is_try = match subexpr_list.last().unwrap().node {
124 ast::ExprKind::Try(..) => true,
127 let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
128 let nested_shape = if first_subexpr_is_try {
129 parent_shape.block_indent(context.config.tab_spaces())
131 chain_indent(context, shape.add_offset(parent_rewrite.len()))
134 context.config.chain_indent() == IndentStyle::Visual ||
135 parent_rewrite.len() <= context.config.tab_spaces())
136 } else if is_block_expr(context, &parent, &parent_rewrite) {
137 match context.config.chain_indent() {
138 // Try to put the first child on the same line with parent's last line
139 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
140 // The parent is a block, so align the rest of the chain with the closing
142 IndentStyle::Visual => (parent_shape, false),
144 } else if parent_rewrite_contains_newline {
145 (chain_indent(context, parent_shape), false)
147 (shape.block_indent(context.config.tab_spaces()), false)
150 let other_child_shape = nested_shape.with_max_width(context.config);
152 let first_child_shape = if extend {
153 let overhead = last_line_width(&parent_rewrite);
154 let offset = parent_rewrite.lines().rev().next().unwrap().trim().len();
155 match context.config.chain_indent() {
156 IndentStyle::Visual => try_opt!(parent_shape.offset_left(overhead)),
157 IndentStyle::Block => try_opt!(parent_shape.block().offset_left(offset)),
162 debug!("child_shapes {:?} {:?}",
166 let child_shape_iter =
167 Some(first_child_shape)
169 .chain(::std::iter::repeat(other_child_shape).take(subexpr_list.len() - 1));
170 let iter = subexpr_list.iter().rev().zip(child_shape_iter);
171 let mut rewrites = try_opt!(iter.map(|(e, shape)| {
172 rewrite_chain_subexpr(e, total_span, context, shape)
174 .collect::<Option<Vec<_>>>());
176 // Total of all items excluding the last.
177 let last_non_try_index = rewrites.len() - (1 + trailing_try_num);
178 let almost_total = rewrites[..last_non_try_index]
180 .fold(0, |a, b| a + first_line_width(b)) + parent_rewrite.len();
181 let one_line_len = rewrites.iter().fold(0, |a, r| a + first_line_width(r)) +
182 parent_rewrite.len();
184 let one_line_budget = min(shape.width, context.config.chain_one_line_max());
185 let veto_single_line = if one_line_len > one_line_budget {
186 if rewrites.len() > 1 {
188 } else if rewrites.len() == 1 {
189 context.config.chain_split_single_child() || one_line_len > shape.width
193 } else if context.config.take_source_hints() && subexpr_list.len() > 1 {
194 // Look at the source code. Unless all chain elements start on the same
195 // line, we won't consider putting them on a single line either.
196 let last_span = context.snippet(mk_sp(subexpr_list[1].span.hi, total_span.hi));
197 let first_span = context.snippet(subexpr_list[1].span);
198 let last_iter = last_span.chars().take_while(|c| c.is_whitespace());
200 first_span.chars().chain(last_iter).any(|c| c == '\n')
205 let mut fits_single_line = !veto_single_line && almost_total <= shape.width;
206 if fits_single_line {
207 let len = rewrites.len();
208 let (init, last) = rewrites.split_at_mut(len - (1 + trailing_try_num));
209 fits_single_line = init.iter().all(|s| !s.contains('\n'));
211 if fits_single_line {
212 fits_single_line = match expr.node {
213 ref e @ ast::ExprKind::MethodCall(..) => {
214 if rewrite_method_call_with_overflow(e,
220 // If the first line of the last method does not fit into a single line
221 // after the others, allow new lines.
222 almost_total + first_line_width(&last[0]) < context.config.max_width()
227 _ => !last[0].contains('\n'),
232 // Try overflowing the last element if we are using block indent.
233 if !fits_single_line && context.config.fn_call_style() == IndentStyle::Block {
234 let (init, last) = rewrites.split_at_mut(last_non_try_index);
235 let almost_single_line = init.iter().all(|s| !s.contains('\n'));
236 if almost_single_line {
237 let overflow_shape = Shape {
238 width: one_line_budget,
241 fits_single_line = rewrite_last_child_with_overflow(context,
242 &subexpr_list[trailing_try_num],
251 let connector = if fits_single_line && !parent_rewrite_contains_newline {
252 // Yay, we can put everything on one line.
256 format!("\n{}", nested_shape.indent.to_string(context.config))
259 let first_connector = if subexpr_list.is_empty() {
261 } else if extend || first_subexpr_is_try {
262 // 1 = ";", being conservative here.
263 if last_line_width(&parent_rewrite) + first_line_width(&rewrites[0]) + 1 <=
264 context.config.max_width() {
273 wrap_str(format!("{}{}{}",
276 join_rewrites(&rewrites, &subexpr_list, &connector)),
277 context.config.max_width(),
281 // True if the chain is only `?`s.
282 fn chain_only_try(exprs: &[ast::Expr]) -> bool {
283 exprs.iter().all(|e| if let ast::ExprKind::Try(_) = e.node {
290 // Try to rewrite and replace the last non-try child. Return `true` if
291 // replacing succeeds.
292 fn rewrite_last_child_with_overflow(context: &RewriteContext,
297 one_line_budget: usize,
298 last_child: &mut String)
300 if let Some(shape) = shape.shrink_left(almost_total) {
301 if let Some(ref mut rw) = rewrite_chain_subexpr(expr, span, context, shape) {
302 if almost_total + first_line_width(rw) <= one_line_budget {
303 ::std::mem::swap(last_child, rw);
311 pub fn rewrite_try(expr: &ast::Expr,
313 context: &RewriteContext,
316 let sub_expr = try_opt!(expr.rewrite(context, try_opt!(shape.sub_width(try_count))));
319 iter::repeat("?").take(try_count).collect::<String>()))
322 fn join_rewrites(rewrites: &[String], subexps: &[ast::Expr], connector: &str) -> String {
323 let mut rewrite_iter = rewrites.iter();
324 let mut result = rewrite_iter.next().unwrap().clone();
325 let mut subexpr_iter = subexps.iter().rev();
328 for (rewrite, expr) in rewrite_iter.zip(subexpr_iter) {
330 ast::ExprKind::Try(_) => (),
331 _ => result.push_str(connector),
333 result.push_str(&rewrite[..]);
339 // States whether an expression's last line exclusively consists of closing
340 // parens, braces, and brackets in its idiomatic formatting.
341 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
343 ast::ExprKind::Call(..) => {
344 context.config.fn_call_style() == IndentStyle::Block && repr.contains('\n')
346 ast::ExprKind::Struct(..) |
347 ast::ExprKind::While(..) |
348 ast::ExprKind::WhileLet(..) |
349 ast::ExprKind::If(..) |
350 ast::ExprKind::IfLet(..) |
351 ast::ExprKind::Block(..) |
352 ast::ExprKind::Loop(..) |
353 ast::ExprKind::ForLoop(..) |
354 ast::ExprKind::Match(..) => repr.contains('\n'),
355 ast::ExprKind::Paren(ref expr) |
356 ast::ExprKind::Binary(_, _, ref expr) |
357 ast::ExprKind::Index(_, ref expr) |
358 ast::ExprKind::Unary(_, ref expr) => is_block_expr(context, expr, repr),
363 // Returns the root of the chain and a Vec of the prefixes of the rest of the chain.
364 // E.g., for input `a.b.c` we return (`a`, [`a.b.c`, `a.b`])
365 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> (ast::Expr, Vec<ast::Expr>) {
366 let mut subexpr_list = vec![expr.clone()];
368 while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
369 subexpr_list.push(subexpr.clone());
372 let parent = subexpr_list.pop().unwrap();
373 (parent, subexpr_list)
376 fn chain_indent(context: &RewriteContext, shape: Shape) -> Shape {
377 match context.config.chain_indent() {
378 IndentStyle::Visual => shape.visual_indent(0),
379 IndentStyle::Block => shape.block_indent(context.config.tab_spaces()),
383 fn rewrite_method_call_with_overflow(expr_kind: &ast::ExprKind,
387 context: &RewriteContext,
390 if let &ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) = expr_kind {
391 let shape = match shape.shrink_left(almost_total) {
393 None => return false,
395 let mut last_rewrite = rewrite_method_call(method_name.node,
402 if let Some(ref mut s) = last_rewrite {
403 ::std::mem::swap(s, last);
413 // Returns the expression's subexpression, if it exists. When the subexpr
414 // is a try! macro, we'll convert it to shorthand when the option is set.
415 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
417 ast::ExprKind::MethodCall(_, _, ref expressions) => {
418 Some(convert_try(&expressions[0], context))
420 ast::ExprKind::TupField(ref subexpr, _) |
421 ast::ExprKind::Field(ref subexpr, _) |
422 ast::ExprKind::Try(ref subexpr) => Some(convert_try(subexpr, context)),
427 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
429 ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
430 if let Some(subexpr) = convert_try_mac(mac, context) {
440 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
442 fn rewrite_chain_subexpr(expr: &ast::Expr,
444 context: &RewriteContext,
447 let rewrite_element = |expr_str: String| if expr_str.len() <= shape.width {
454 ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) => {
455 rewrite_method_call(method_name.node, types, expressions, span, context, shape)
457 ast::ExprKind::Field(_, ref field) => rewrite_element(format!(".{}", field.node)),
458 ast::ExprKind::TupField(_, ref field) => rewrite_element(format!(".{}", field.node)),
459 ast::ExprKind::Try(_) => rewrite_element(String::from("?")),
464 // Determines if we can continue formatting a given expression on the same line.
465 fn is_continuable(expr: &ast::Expr) -> bool {
467 ast::ExprKind::Path(..) => true,
472 fn rewrite_method_call(method_name: ast::Ident,
473 types: &[ptr::P<ast::Ty>],
474 args: &[ptr::P<ast::Expr>],
476 context: &RewriteContext,
479 let (lo, type_str) = if types.is_empty() {
480 (args[0].span.hi, String::new())
482 let type_list: Vec<_> =
483 try_opt!(types.iter().map(|ty| ty.rewrite(context, shape)).collect());
485 let type_str = if context.config.spaces_within_angle_brackets() && type_list.len() > 0 {
486 format!("::< {} >", type_list.join(", "))
488 format!("::<{}>", type_list.join(", "))
491 (types.last().unwrap().span.hi, type_str)
494 let callee_str = format!(".{}{}", method_name, type_str);
495 let span = mk_sp(lo, span.hi);
497 rewrite_call(context, &callee_str, &args[1..], span, shape)