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`:
50 //! If the first item in the chain is a block expression, we align the dots with
68 use config::IndentStyle;
69 use expr::rewrite_call;
70 use macros::convert_try_mac;
71 use rewrite::{Rewrite, RewriteContext};
75 first_line_width, last_line_extendable, last_line_width, mk_sp, trimmed_last_line_width,
82 use syntax::codemap::Span;
83 use syntax::{ast, ptr};
85 pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -> Option<String> {
86 debug!("rewrite_chain {:?}", shape);
87 let chain = Chain::from_ast(expr, context);
88 // If this is just an expression with some `?`s, then format it trivially and
90 if chain.children.is_empty() {
91 let rewrite = chain.parent.expr.rewrite(context, shape.sub_width(chain.parent.tries)?)?;
92 return Some(format!("{}{}", rewrite, "?".repeat(chain.parent.tries)));
95 match context.config.indent_style() {
96 IndentStyle::Block => rewrite_chain_block(chain, context, shape),
97 IndentStyle::Visual => rewrite_chain_visual(chain, context, shape),
101 // An expression plus trailing `?`s to be formatted together.
109 // TODO do we need to clone the exprs?
110 children: Vec<ChainItem>,
114 fn from_ast(expr: &ast::Expr, context: &RewriteContext) -> Chain {
115 let mut subexpr_list = make_subexpr_list(expr, context);
117 // Un-parse the expression tree into ChainItems
118 let mut children = vec![];
119 let mut sub_tries = 0;
121 if subexpr_list.is_empty() {
125 let subexpr = subexpr_list.pop().unwrap();
127 ast::ExprKind::Try(_) => sub_tries += 1,
129 children.push(ChainItem {
130 expr: subexpr.clone(),
139 parent: children.pop().unwrap(),
140 children: children.into_iter().rev().collect(),
145 fn rewrite_chain_block(mut chain: Chain, context: &RewriteContext, shape: Shape) -> Option<String> {
146 let last = chain.children.pop().unwrap();
148 // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
149 let parent_rewrite = chain.parent.expr
150 .rewrite(context, shape)
151 .map(|parent_rw| parent_rw + &"?".repeat(chain.parent.tries))?;
152 let parent_rewrite_contains_newline = parent_rewrite.contains('\n');
153 let is_small_parent = shape.offset + parent_rewrite.len() <= context.config.tab_spaces();
154 let parent_is_block = is_block_expr(context, &chain.parent.expr, &parent_rewrite);
156 // Decide how to layout the rest of the chain. `extend` is true if we can
157 // put the first non-parent item on the same line as the parent.
158 let other_child_shape = if parent_is_block {
161 shape.block_indent(context.config.tab_spaces())
162 }.with_max_width(context.config);
164 let extend = if !parent_rewrite_contains_newline && is_continuable(&chain.parent.expr) {
170 let first_child_shape = if extend {
171 let offset = trimmed_last_line_width(&parent_rewrite) + chain.parent.tries;
172 other_child_shape.offset_left(offset)?
177 "child_shapes {:?} {:?}",
178 first_child_shape, other_child_shape
181 let mut rewrites: Vec<String> = Vec::with_capacity(chain.children.len());
182 let mut is_block_like = Vec::with_capacity(chain.children.len());
183 is_block_like.push(true);
184 for (i, item) in chain.children.iter().enumerate() {
185 let shape = if *is_block_like.last().unwrap() && !(extend && i == 0) {
190 let rewrite = rewrite_chain_subexpr(&item.expr, context, shape)?;
191 is_block_like.push(is_block_expr(context, &item.expr, &rewrite));
192 rewrites.push(format!("{}{}", rewrite, "?".repeat(item.tries)));
195 // Total of all items excluding the last.
196 let extend_last_subexpr = if is_small_parent {
197 rewrites.len() == 1 && last_line_extendable(&rewrites[0])
199 rewrites.is_empty() && last_line_extendable(&parent_rewrite)
201 let almost_total = if extend_last_subexpr {
202 last_line_width(&parent_rewrite)
204 rewrites.iter().fold(0, |a, b| a + b.len()) + parent_rewrite.len()
206 let one_line_budget = if rewrites.is_empty() {
209 min(shape.width, context.config.width_heuristics().chain_width)
211 let all_in_one_line = !parent_rewrite_contains_newline
212 && rewrites.iter().all(|s| !s.contains('\n'))
213 && almost_total < one_line_budget;
214 let last_shape = if is_block_like[rewrites.len()] {
218 }.sub_width(shape.rhs_overhead(context.config) + last.tries)?;
220 // Rewrite the last child. The last child of a chain requires special treatment. We need to
221 // know whether 'overflowing' the last child make a better formatting:
223 // A chain with overflowing the last child:
225 // parent.child1.child2.last_child(
232 // A chain without overflowing the last child (in vertical layout):
237 // .last_child(a, b, c)
240 // In particular, overflowing is effective when the last child is a method with a multi-lined
241 // block-like argument (e.g. closure):
243 // parent.child1.child2.last_child(|a, b, c| {
244 // let x = foo(a, b, c);
245 // let y = bar(a, b, c);
253 // `rewrite_last` rewrites the last child on its own line. We use a closure here instead of
254 // directly calling `rewrite_chain_subexpr()` to avoid exponential blowup.
255 let (last_subexpr_str, fits_single_line) = if all_in_one_line || extend_last_subexpr {
256 // First we try to 'overflow' the last child and see if it looks better than using
258 shape.offset_left(almost_total).map(|shape| {
259 if let Some(rw) = rewrite_chain_subexpr(&last.expr, context, shape) {
260 // We allow overflowing here only if both of the following conditions match:
261 // 1. The entire chain fits in a single line except the last child.
262 // 2. `last_child_str.lines().count() >= 5`.
263 let line_count = rw.lines().count();
264 let fits_single_line = almost_total + first_line_width(&rw) <= one_line_budget;
265 if fits_single_line && line_count >= 5 {
268 // We could not know whether overflowing is better than using vertical layout,
269 // just by looking at the overflowed rewrite. Now we rewrite the last child
270 // on its own line, and compare two rewrites to choose which is better.
271 match rewrite_chain_subexpr(&last.expr, context, last_shape) {
272 Some(ref new_rw) if !fits_single_line => (Some(new_rw.clone()), false),
273 Some(ref new_rw) if new_rw.lines().count() >= line_count => {
274 (Some(rw), fits_single_line)
276 new_rw @ Some(..) => (new_rw, false),
277 _ => (Some(rw), fits_single_line),
281 (rewrite_chain_subexpr(&last.expr, context, last_shape), false)
285 (rewrite_chain_subexpr(&last.expr, context, last_shape), false)
287 rewrites.push(last_subexpr_str?);
288 // We should never look at this, since we only look at the block-ness of the
289 // previous item in the chain.
290 is_block_like.push(false);
292 let connector = if fits_single_line && !parent_rewrite_contains_newline {
293 // Yay, we can put everything on one line.
297 if *context.force_one_line_chain.borrow() {
300 other_child_shape.indent.to_string_with_newline(context.config)
303 let first_connector = if is_small_parent
305 || last_line_extendable(&parent_rewrite)
312 let result = if is_small_parent && rewrites.len() > 1 {
313 let second_connector = if fits_single_line
314 || rewrites[1] == "?"
315 || last_line_extendable(&rewrites[0])
327 join_rewrites(&rewrites[1..], &is_block_like[2..], &connector),
334 join_rewrites(&rewrites, &is_block_like[1..], &connector),
337 let result = format!("{}{}", result, "?".repeat(last.tries));
341 fn rewrite_chain_visual(mut chain: Chain, context: &RewriteContext, shape: Shape) -> Option<String> {
342 let last = chain.children.pop().unwrap();
344 // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
345 let parent_shape = if is_block_expr(context, &chain.parent.expr, "\n") {
346 shape.visual_indent(0)
350 let parent_rewrite = chain.parent.expr
351 .rewrite(context, parent_shape)
352 .map(|parent_rw| parent_rw + &"?".repeat(chain.parent.tries))?;
353 let parent_rewrite_contains_newline = parent_rewrite.contains('\n');
354 let is_small_parent = shape.offset + parent_rewrite.len() <= context.config.tab_spaces();
356 let other_child_shape = shape.visual_indent(0).with_max_width(context.config);
358 // Decide how to layout the rest of the chain. `extend` is true if we can
359 // put the first non-parent item on the same line as the parent.
360 let extend = !parent_rewrite_contains_newline && is_continuable(&chain.parent.expr);
362 let first_child_shape = if extend {
363 let overhead = last_line_width(&parent_rewrite);
364 parent_shape.offset_left(overhead)?
369 "child_shapes {:?} {:?}",
370 first_child_shape, other_child_shape
373 let mut rewrites: Vec<String> = Vec::with_capacity(chain.children.len());
374 for (i, item) in chain.children.iter().enumerate() {
375 let shape = if i == 0 {
380 let rewrite = rewrite_chain_subexpr(&item.expr, context, shape)?;
381 rewrites.push(format!("{}{}", rewrite, "?".repeat(item.tries)));
384 // Total of all items excluding the last.
385 let extend_last_subexpr = if is_small_parent {
386 rewrites.len() == 1 && last_line_extendable(&rewrites[0])
388 rewrites.is_empty() && last_line_extendable(&parent_rewrite)
390 let almost_total = if extend_last_subexpr {
391 last_line_width(&parent_rewrite)
393 rewrites.iter().fold(0, |a, b| a + b.len()) + parent_rewrite.len()
395 let one_line_budget = if rewrites.is_empty() {
398 min(shape.width, context.config.width_heuristics().chain_width)
400 let all_in_one_line = !parent_rewrite_contains_newline
401 && rewrites.iter().all(|s| !s.contains('\n'))
402 && almost_total < one_line_budget;
404 other_child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?;
406 // Rewrite the last child. The last child of a chain requires special treatment. We need to
407 // know whether 'overflowing' the last child make a better formatting:
409 // A chain with overflowing the last child:
411 // parent.child1.child2.last_child(
418 // A chain without overflowing the last child (in vertical layout):
423 // .last_child(a, b, c)
426 // In particular, overflowing is effective when the last child is a method with a multi-lined
427 // block-like argument (e.g. closure):
429 // parent.child1.child2.last_child(|a, b, c| {
430 // let x = foo(a, b, c);
431 // let y = bar(a, b, c);
439 let (last_subexpr_str, fits_single_line) = if all_in_one_line || extend_last_subexpr {
440 // First we try to 'overflow' the last child and see if it looks better than using
442 parent_shape.offset_left(almost_total).map(|shape| {
443 if let Some(rw) = rewrite_chain_subexpr(&last.expr, context, shape) {
444 // We allow overflowing here only if both of the following conditions match:
445 // 1. The entire chain fits in a single line except the last child.
446 // 2. `last_child_str.lines().count() >= 5`.
447 let line_count = rw.lines().count();
448 let fits_single_line = almost_total + first_line_width(&rw) <= one_line_budget;
449 if fits_single_line && line_count >= 5 {
452 // We could not know whether overflowing is better than using vertical layout,
453 // just by looking at the overflowed rewrite. Now we rewrite the last child
454 // on its own line, and compare two rewrites to choose which is better.
455 match rewrite_chain_subexpr(&last.expr, context, last_shape) {
456 Some(ref new_rw) if !fits_single_line => (Some(new_rw.clone()), false),
457 Some(ref new_rw) if new_rw.lines().count() >= line_count => {
458 (Some(rw), fits_single_line)
460 new_rw @ Some(..) => (new_rw, false),
461 _ => (Some(rw), fits_single_line),
465 (rewrite_chain_subexpr(&last.expr, context, last_shape), false)
469 (rewrite_chain_subexpr(&last.expr, context, last_shape), false)
471 rewrites.push(last_subexpr_str?);
473 let connector = if fits_single_line && !parent_rewrite_contains_newline {
474 // Yay, we can put everything on one line.
478 if *context.force_one_line_chain.borrow() {
481 other_child_shape.indent.to_string_with_newline(context.config)
484 let result = if is_small_parent && rewrites.len() > 1 {
489 join_rewrites_vis(&rewrites[1..], &connector),
495 join_rewrites_vis(&rewrites, &connector),
498 let result = format!("{}{}", result, "?".repeat(last.tries));
499 wrap_str(result, context.config.max_width(), shape)
502 fn join_rewrites(rewrites: &[String], is_block_like: &[bool], connector: &str) -> String {
503 let mut rewrite_iter = rewrites.iter();
504 let mut result = rewrite_iter.next().unwrap().clone();
506 for (rewrite, prev_is_block_like) in rewrite_iter.zip(is_block_like.iter()) {
507 if rewrite != "?" && !prev_is_block_like {
508 result.push_str(connector);
510 result.push_str(&rewrite);
516 fn join_rewrites_vis(rewrites: &[String], connector: &str) -> String {
517 let mut rewrite_iter = rewrites.iter();
518 let mut result = rewrite_iter.next().unwrap().clone();
520 for rewrite in rewrite_iter {
522 result.push_str(connector);
524 result.push_str(&rewrite);
530 // States whether an expression's last line exclusively consists of closing
531 // parens, braces, and brackets in its idiomatic formatting.
532 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
534 ast::ExprKind::Mac(..) | ast::ExprKind::Call(..) => {
535 context.use_block_indent() && repr.contains('\n')
537 ast::ExprKind::Struct(..)
538 | ast::ExprKind::While(..)
539 | ast::ExprKind::WhileLet(..)
540 | ast::ExprKind::If(..)
541 | ast::ExprKind::IfLet(..)
542 | ast::ExprKind::Block(..)
543 | ast::ExprKind::Loop(..)
544 | ast::ExprKind::ForLoop(..)
545 | ast::ExprKind::Match(..) => repr.contains('\n'),
546 ast::ExprKind::Paren(ref expr)
547 | ast::ExprKind::Binary(_, _, ref expr)
548 | ast::ExprKind::Index(_, ref expr)
549 | ast::ExprKind::Unary(_, ref expr)
550 | ast::ExprKind::Closure(_, _, _, _, ref expr, _) => is_block_expr(context, expr, repr),
551 ast::ExprKind::MethodCall(_, ref exprs) => {
552 // TODO maybe should be like Call
553 is_block_expr(context, exprs.last().unwrap(), repr)
559 // Returns a Vec of the prefixes of the chain.
560 // E.g., for input `a.b.c` we return [`a.b.c`, `a.b`, 'a']
561 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> Vec<ast::Expr> {
562 let mut subexpr_list = vec![expr.clone()];
564 while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
565 subexpr_list.push(subexpr.clone());
571 // Returns the expression's subexpression, if it exists. When the subexpr
572 // is a try! macro, we'll convert it to shorthand when the option is set.
573 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
575 ast::ExprKind::MethodCall(_, ref expressions) => {
576 Some(convert_try(&expressions[0], context))
578 ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) => {
579 Some(convert_try(subexpr, context))
585 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
587 ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
588 if let Some(subexpr) = convert_try_mac(mac, context) {
598 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
600 fn rewrite_chain_subexpr(
602 context: &RewriteContext,
604 ) -> Option<String> {
605 let rewrite_element = |expr_str: String| {
606 if expr_str.len() <= shape.width {
614 ast::ExprKind::MethodCall(ref segment, ref expressions) => {
615 let types = match segment.args {
616 Some(ref params) => match **params {
617 ast::GenericArgs::AngleBracketed(ref data) => &data.args[..],
622 rewrite_method_call(segment.ident, types, expressions, expr.span, context, shape)
624 ast::ExprKind::Field(ref nested, ref field) => {
625 let space = if is_tup_field_access(expr) && is_tup_field_access(nested) {
630 rewrite_element(format!("{}.{}", space, field.name))
632 ast::ExprKind::Try(_) => rewrite_element(String::from("?")),
637 fn is_tup_field_access(expr: &ast::Expr) -> bool {
639 ast::ExprKind::Field(_, ref field) => {
640 field.name.to_string().chars().all(|c| c.is_digit(10))
646 // Determines if we can continue formatting a given expression on the same line.
647 fn is_continuable(expr: &ast::Expr) -> bool {
649 ast::ExprKind::Path(..) => true,
654 fn rewrite_method_call(
655 method_name: ast::Ident,
656 types: &[ast::GenericArg],
657 args: &[ptr::P<ast::Expr>],
659 context: &RewriteContext,
661 ) -> Option<String> {
662 let (lo, type_str) = if types.is_empty() {
663 (args[0].span.hi(), String::new())
665 let type_list = types
667 .map(|ty| ty.rewrite(context, shape))
668 .collect::<Option<Vec<_>>>()?;
670 let type_str = format!("::<{}>", type_list.join(", "));
672 (types.last().unwrap().span().hi(), type_str)
675 let callee_str = format!(".{}{}", method_name, type_str);
676 let span = mk_sp(lo, span.hi());
678 rewrite_call(context, &callee_str, &args[1..], span, shape)