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 config::IndentStyle;
81 use expr::rewrite_call;
82 use macros::convert_try_mac;
83 use rewrite::{Rewrite, RewriteContext};
84 use utils::{first_line_width, last_line_extendable, last_line_width, mk_sp, wrap_str};
88 use syntax::{ast, ptr};
89 use syntax::codemap::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');
120 let is_small_parent = parent_rewrite.len() <= context.config.tab_spaces();
122 // Decide how to layout the rest of the chain. `extend` is true if we can
123 // put the first non-parent item on the same line as the parent.
124 let first_subexpr_is_try = subexpr_list.last().map_or(false, is_try);
125 let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
126 let nested_shape = if first_subexpr_is_try {
128 .block_indent(context.config.tab_spaces())
129 .with_max_width(context.config)
131 chain_indent(context, shape.add_offset(parent_rewrite.len()))
135 context.config.chain_indent() == IndentStyle::Visual || is_small_parent,
137 } else if is_block_expr(context, &parent, &parent_rewrite) {
138 match context.config.chain_indent() {
139 // Try to put the first child on the same line with parent's last line
140 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
141 // The parent is a block, so align the rest of the chain with the closing
143 IndentStyle::Visual => (parent_shape, false),
145 } else if parent_rewrite_contains_newline {
146 (chain_indent(context, parent_shape), false)
150 .block_indent(context.config.tab_spaces())
151 .with_max_width(context.config),
156 let other_child_shape = nested_shape.with_max_width(context.config);
158 let first_child_shape = if extend {
159 let overhead = last_line_width(&parent_rewrite);
160 let offset = parent_rewrite.lines().rev().next().unwrap().trim().len();
161 match context.config.chain_indent() {
162 IndentStyle::Visual => try_opt!(parent_shape.offset_left(overhead)),
163 IndentStyle::Block => try_opt!(parent_shape.block().offset_left(offset)),
169 "child_shapes {:?} {:?}",
174 let child_shape_iter = Some(first_child_shape).into_iter().chain(
175 ::std::iter::repeat(other_child_shape).take(subexpr_list.len() - 1),
177 let iter = subexpr_list.iter().rev().zip(child_shape_iter);
178 let mut rewrites = try_opt!(
179 iter.map(|(e, shape)| {
180 rewrite_chain_subexpr(e, total_span, context, shape)
181 }).collect::<Option<Vec<_>>>()
184 // Total of all items excluding the last.
185 let last_non_try_index = rewrites.len() - (1 + trailing_try_num);
186 let almost_total = rewrites[..last_non_try_index]
188 .fold(0, |a, b| a + first_line_width(b)) + parent_rewrite.len();
190 rewrites.iter().fold(0, |a, r| a + first_line_width(r)) + parent_rewrite.len();
192 let one_line_budget = min(shape.width, context.config.chain_one_line_max());
193 let veto_single_line = if one_line_len > one_line_budget {
194 if rewrites.len() > 1 {
196 } else if rewrites.len() == 1 {
197 context.config.chain_split_single_child() || one_line_len > shape.width
201 } else if context.config.take_source_hints() && subexpr_list.len() > 1 {
202 // Look at the source code. Unless all chain elements start on the same
203 // line, we won't consider putting them on a single line either.
204 let last_span = context.snippet(mk_sp(subexpr_list[1].span.hi, total_span.hi));
205 let first_span = context.snippet(subexpr_list[1].span);
206 let last_iter = last_span.chars().take_while(|c| c.is_whitespace());
208 first_span.chars().chain(last_iter).any(|c| c == '\n')
213 let mut fits_single_line = !veto_single_line && almost_total <= shape.width;
214 if fits_single_line {
215 let len = rewrites.len();
216 let (init, last) = rewrites.split_at_mut(len - (1 + trailing_try_num));
217 fits_single_line = init.iter().all(|s| !s.contains('\n'));
219 if fits_single_line {
220 fits_single_line = match expr.node {
221 ref e @ ast::ExprKind::MethodCall(..) => {
222 if rewrite_method_call_with_overflow(
230 // If the first line of the last method does not fit into a single line
231 // after the others, allow new lines.
232 almost_total + first_line_width(&last[0]) < context.config.max_width()
237 _ => !last[0].contains('\n'),
242 // Try overflowing the last element if we are using block indent and it goes multi line
243 // or it fits in a single line but goes over the max width.
244 if !fits_single_line && context.use_block_indent() {
245 let (init, last) = rewrites.split_at_mut(last_non_try_index);
246 let almost_single_line = init.iter().all(|s| !s.contains('\n'));
247 if almost_single_line && last[0].contains('\n') {
248 let overflow_shape = Shape {
249 width: one_line_budget,
252 fits_single_line = rewrite_last_child_with_overflow(
254 &subexpr_list[trailing_try_num],
264 let connector = if fits_single_line && !parent_rewrite_contains_newline {
265 // Yay, we can put everything on one line.
269 if context.force_one_line_chain {
272 format!("\n{}", nested_shape.indent.to_string(context.config))
275 let first_connector = choose_first_connector(
284 if is_small_parent && rewrites.len() > 1 {
285 let second_connector = choose_first_connector(
290 &subexpr_list[0..subexpr_list.len() - 1],
302 &subexpr_list[0..subexpr_list.len() - 1],
306 context.config.max_width(),
315 join_rewrites(&rewrites, &subexpr_list, &connector)
317 context.config.max_width(),
323 fn is_extendable_parent(context: &RewriteContext, parent_str: &str) -> bool {
324 context.config.chain_indent() == IndentStyle::Block && last_line_extendable(parent_str)
327 // True if the chain is only `?`s.
328 fn chain_only_try(exprs: &[ast::Expr]) -> bool {
329 exprs.iter().all(|e| if let ast::ExprKind::Try(_) = e.node {
336 // Try to rewrite and replace the last non-try child. Return `true` if
337 // replacing succeeds.
338 fn rewrite_last_child_with_overflow(
339 context: &RewriteContext,
344 one_line_budget: usize,
345 last_child: &mut String,
347 if let Some(shape) = shape.shrink_left(almost_total) {
348 if let Some(ref mut rw) = rewrite_chain_subexpr(expr, span, context, shape) {
349 if almost_total + first_line_width(rw) <= one_line_budget && rw.lines().count() > 3 {
350 ::std::mem::swap(last_child, rw);
361 context: &RewriteContext,
363 ) -> Option<String> {
364 let sub_expr = try_opt!(expr.rewrite(context, try_opt!(shape.sub_width(try_count))));
368 iter::repeat("?").take(try_count).collect::<String>()
372 fn join_rewrites(rewrites: &[String], subexps: &[ast::Expr], connector: &str) -> String {
373 let mut rewrite_iter = rewrites.iter();
374 let mut result = rewrite_iter.next().unwrap().clone();
375 let mut subexpr_iter = subexps.iter().rev();
378 for (rewrite, expr) in rewrite_iter.zip(subexpr_iter) {
380 ast::ExprKind::Try(_) => (),
381 _ => result.push_str(connector),
383 result.push_str(&rewrite[..]);
389 // States whether an expression's last line exclusively consists of closing
390 // parens, braces, and brackets in its idiomatic formatting.
391 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
393 ast::ExprKind::Mac(..) | ast::ExprKind::Call(..) => {
394 context.use_block_indent() && repr.contains('\n')
396 ast::ExprKind::Struct(..) |
397 ast::ExprKind::While(..) |
398 ast::ExprKind::WhileLet(..) |
399 ast::ExprKind::If(..) |
400 ast::ExprKind::IfLet(..) |
401 ast::ExprKind::Block(..) |
402 ast::ExprKind::Loop(..) |
403 ast::ExprKind::ForLoop(..) |
404 ast::ExprKind::Match(..) => repr.contains('\n'),
405 ast::ExprKind::Paren(ref expr) |
406 ast::ExprKind::Binary(_, _, ref expr) |
407 ast::ExprKind::Index(_, ref expr) |
408 ast::ExprKind::Unary(_, ref expr) => is_block_expr(context, expr, repr),
413 // Returns the root of the chain and a Vec of the prefixes of the rest of the chain.
414 // E.g., for input `a.b.c` we return (`a`, [`a.b.c`, `a.b`])
415 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> (ast::Expr, Vec<ast::Expr>) {
416 let mut subexpr_list = vec![expr.clone()];
418 while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
419 subexpr_list.push(subexpr.clone());
422 let parent = subexpr_list.pop().unwrap();
423 (parent, subexpr_list)
426 fn chain_indent(context: &RewriteContext, shape: Shape) -> Shape {
427 match context.config.chain_indent() {
428 IndentStyle::Visual => shape.visual_indent(0),
429 IndentStyle::Block => shape.block_indent(context.config.tab_spaces()),
433 fn rewrite_method_call_with_overflow(
434 expr_kind: &ast::ExprKind,
438 context: &RewriteContext,
441 if let &ast::ExprKind::MethodCall(ref segment, ref expressions) = expr_kind {
442 let shape = match shape.shrink_left(almost_total) {
444 None => return false,
446 let types = match segment.parameters {
447 Some(ref params) => match **params {
448 ast::PathParameters::AngleBracketed(ref data) => &data.types[..],
453 let mut last_rewrite = rewrite_method_call(
462 if let Some(ref mut s) = last_rewrite {
463 ::std::mem::swap(s, last);
473 // Returns the expression's subexpression, if it exists. When the subexpr
474 // is a try! macro, we'll convert it to shorthand when the option is set.
475 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
477 ast::ExprKind::MethodCall(_, ref expressions) => {
478 Some(convert_try(&expressions[0], context))
480 ast::ExprKind::TupField(ref subexpr, _) |
481 ast::ExprKind::Field(ref subexpr, _) |
482 ast::ExprKind::Try(ref subexpr) => Some(convert_try(subexpr, context)),
487 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
489 ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
490 if let Some(subexpr) = convert_try_mac(mac, context) {
500 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
502 fn rewrite_chain_subexpr(
505 context: &RewriteContext,
507 ) -> Option<String> {
508 let rewrite_element = |expr_str: String| if expr_str.len() <= shape.width {
515 ast::ExprKind::MethodCall(ref segment, ref expressions) => {
516 let types = match segment.parameters {
517 Some(ref params) => match **params {
518 ast::PathParameters::AngleBracketed(ref data) => &data.types[..],
523 rewrite_method_call(segment.identifier, types, expressions, span, context, shape)
525 ast::ExprKind::Field(_, ref field) => rewrite_element(format!(".{}", field.node)),
526 ast::ExprKind::TupField(ref expr, ref field) => {
527 let space = match expr.node {
528 ast::ExprKind::TupField(..) => " ",
531 rewrite_element(format!("{}.{}", space, field.node))
533 ast::ExprKind::Try(_) => rewrite_element(String::from("?")),
538 // Determines if we can continue formatting a given expression on the same line.
539 fn is_continuable(expr: &ast::Expr) -> bool {
541 ast::ExprKind::Path(..) => true,
546 fn is_try(expr: &ast::Expr) -> bool {
548 ast::ExprKind::Try(..) => true,
553 fn choose_first_connector<'a>(
554 context: &RewriteContext,
556 first_child_str: &str,
558 subexpr_list: &[ast::Expr],
561 if subexpr_list.is_empty() {
563 } else if extend || subexpr_list.last().map_or(false, is_try) ||
564 is_extendable_parent(context, parent_str)
566 // 1 = ";", being conservative here.
567 if last_line_width(parent_str) + first_line_width(first_child_str) + 1 <=
568 context.config.max_width()
579 fn rewrite_method_call(
580 method_name: ast::Ident,
581 types: &[ptr::P<ast::Ty>],
582 args: &[ptr::P<ast::Expr>],
584 context: &RewriteContext,
586 ) -> Option<String> {
587 let (lo, type_str) = if types.is_empty() {
588 (args[0].span.hi, String::new())
590 let type_list: Vec<_> =
591 try_opt!(types.iter().map(|ty| ty.rewrite(context, shape)).collect());
593 let type_str = if context.config.spaces_within_angle_brackets() && type_list.len() > 0 {
594 format!("::< {} >", type_list.join(", "))
596 format!("::<{}>", type_list.join(", "))
599 (types.last().unwrap().span.hi, type_str)
602 let callee_str = format!(".{}{}", method_name, type_str);
603 let span = mk_sp(lo, span.hi);
605 rewrite_call(context, &callee_str, &args[1..], span, shape)