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 = parent_is_block || (is_small_parent && !parent_rewrite_contains_newline && is_continuable(&chain.parent.expr));
166 let first_child_shape = if extend {
167 let offset = trimmed_last_line_width(&parent_rewrite) + chain.parent.tries;
168 other_child_shape.offset_left(offset)?
173 "child_shapes {:?} {:?}",
174 first_child_shape, other_child_shape
177 let mut rewrites: Vec<String> = Vec::with_capacity(chain.children.len());
178 let mut is_block_like = Vec::with_capacity(chain.children.len());
179 is_block_like.push(true);
180 for (i, item) in chain.children.iter().enumerate() {
181 let shape = if *is_block_like.last().unwrap() && !(extend && i == 0) {
186 let rewrite = rewrite_chain_subexpr(&item.expr, context, shape)?;
187 is_block_like.push(is_block_expr(context, &item.expr, &rewrite));
188 rewrites.push(format!("{}{}", rewrite, "?".repeat(item.tries)));
191 // Total of all items excluding the last.
192 let extend_last_subexpr = if is_small_parent {
193 rewrites.len() == 1 && last_line_extendable(&rewrites[0])
195 rewrites.is_empty() && last_line_extendable(&parent_rewrite)
197 let almost_total = if extend_last_subexpr {
198 last_line_width(&parent_rewrite)
200 rewrites.iter().fold(0, |a, b| a + b.len()) + parent_rewrite.len()
202 let one_line_budget = if rewrites.is_empty() {
205 min(shape.width, context.config.width_heuristics().chain_width)
207 let all_in_one_line = !parent_rewrite_contains_newline
208 && rewrites.iter().all(|s| !s.contains('\n'))
209 && almost_total < one_line_budget;
210 let last_shape = if is_block_like[rewrites.len()] {
214 }.sub_width(shape.rhs_overhead(context.config) + last.tries)?;
216 // Rewrite the last child. The last child of a chain requires special treatment. We need to
217 // know whether 'overflowing' the last child make a better formatting:
219 // A chain with overflowing the last child:
221 // parent.child1.child2.last_child(
228 // A chain without overflowing the last child (in vertical layout):
233 // .last_child(a, b, c)
236 // In particular, overflowing is effective when the last child is a method with a multi-lined
237 // block-like argument (e.g. closure):
239 // parent.child1.child2.last_child(|a, b, c| {
240 // let x = foo(a, b, c);
241 // let y = bar(a, b, c);
249 // `rewrite_last` rewrites the last child on its own line. We use a closure here instead of
250 // directly calling `rewrite_chain_subexpr()` to avoid exponential blowup.
251 let (last_subexpr_str, fits_single_line) = if all_in_one_line || extend_last_subexpr {
252 // First we try to 'overflow' the last child and see if it looks better than using
254 shape.offset_left(almost_total).map(|shape| {
255 if let Some(rw) = rewrite_chain_subexpr(&last.expr, context, shape) {
256 // We allow overflowing here only if both of the following conditions match:
257 // 1. The entire chain fits in a single line except the last child.
258 // 2. `last_child_str.lines().count() >= 5`.
259 let line_count = rw.lines().count();
260 let fits_single_line = almost_total + first_line_width(&rw) <= one_line_budget;
261 if fits_single_line && line_count >= 5 {
264 // We could not know whether overflowing is better than using vertical layout,
265 // just by looking at the overflowed rewrite. Now we rewrite the last child
266 // on its own line, and compare two rewrites to choose which is better.
267 match rewrite_chain_subexpr(&last.expr, context, last_shape) {
268 Some(ref new_rw) if !fits_single_line => (Some(new_rw.clone()), false),
269 Some(ref new_rw) if new_rw.lines().count() >= line_count => {
270 (Some(rw), fits_single_line)
272 new_rw @ Some(..) => (new_rw, false),
273 _ => (Some(rw), fits_single_line),
277 (rewrite_chain_subexpr(&last.expr, context, last_shape), false)
281 (rewrite_chain_subexpr(&last.expr, context, last_shape), false)
283 rewrites.push(last_subexpr_str?);
284 // We should never look at this, since we only look at the block-ness of the
285 // previous item in the chain.
286 is_block_like.push(false);
288 let connector = if fits_single_line && !parent_rewrite_contains_newline {
289 // Yay, we can put everything on one line.
293 if *context.force_one_line_chain.borrow() {
296 other_child_shape.indent.to_string_with_newline(context.config)
299 let first_connector = if is_small_parent
301 || last_line_extendable(&parent_rewrite)
308 let result = if is_small_parent && rewrites.len() > 1 {
309 let second_connector = if fits_single_line
310 || rewrites[1] == "?"
311 || last_line_extendable(&rewrites[0])
323 join_rewrites(&rewrites[1..], &is_block_like[2..], &connector),
330 join_rewrites(&rewrites, &is_block_like[1..], &connector),
333 let result = format!("{}{}", result, "?".repeat(last.tries));
337 fn rewrite_chain_visual(mut chain: Chain, context: &RewriteContext, shape: Shape) -> Option<String> {
338 let last = chain.children.pop().unwrap();
340 // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
341 let parent_shape = if is_block_expr(context, &chain.parent.expr, "\n") {
342 shape.visual_indent(0)
346 let parent_rewrite = chain.parent.expr
347 .rewrite(context, parent_shape)
348 .map(|parent_rw| parent_rw + &"?".repeat(chain.parent.tries))?;
349 let parent_rewrite_contains_newline = parent_rewrite.contains('\n');
351 let other_child_shape = shape.visual_indent(0).with_max_width(context.config);
353 // Decide how to layout the rest of the chain. `extend` is true if we can
354 // put the first non-parent item on the same line as the parent.
355 let extend = !parent_rewrite_contains_newline && is_continuable(&chain.parent.expr);
357 let first_child_shape = if extend {
358 let overhead = last_line_width(&parent_rewrite);
359 parent_shape.offset_left(overhead)?
364 "child_shapes {:?} {:?}",
365 first_child_shape, other_child_shape
368 let mut rewrites: Vec<String> = Vec::with_capacity(chain.children.len());
369 for (i, item) in chain.children.iter().enumerate() {
370 let shape = if i == 0 {
375 let rewrite = rewrite_chain_subexpr(&item.expr, context, shape)?;
376 rewrites.push(format!("{}{}", rewrite, "?".repeat(item.tries)));
379 // Total of all items excluding the last.
380 let almost_total = rewrites.iter().fold(0, |a, b| a + b.len()) + parent_rewrite.len() + last.tries;
381 let one_line_budget = if rewrites.is_empty() {
384 min(shape.width, context.config.width_heuristics().chain_width)
386 let all_in_one_line = !parent_rewrite_contains_newline
387 && rewrites.iter().all(|s| !s.contains('\n'))
388 && almost_total < one_line_budget;
390 other_child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?;
392 // Rewrite the last child. The last child of a chain requires special treatment. We need to
393 // know whether 'overflowing' the last child make a better formatting:
395 // A chain with overflowing the last child:
397 // parent.child1.child2.last_child(
404 // A chain without overflowing the last child (in vertical layout):
409 // .last_child(a, b, c)
412 // In particular, overflowing is effective when the last child is a method with a multi-lined
413 // block-like argument (e.g. closure):
415 // parent.child1.child2.last_child(|a, b, c| {
416 // let x = foo(a, b, c);
417 // let y = bar(a, b, c);
425 let mut last_subexpr_str = None;
426 let mut fits_single_line = false;
429 // First we try to 'overflow' the last child and see if it looks better than using
431 if let Some(shape) = parent_shape.offset_left(almost_total) {
432 if let Some(rw) = rewrite_chain_subexpr(&last.expr, context, shape) {
433 // We allow overflowing here only if both of the following conditions match:
434 // 1. The entire chain fits in a single line except the last child.
435 // 2. `last_child_str.lines().count() >= 5`.
436 let line_count = rw.lines().count();
437 let could_fit_single_line = almost_total + first_line_width(&rw) <= one_line_budget;
438 if could_fit_single_line && line_count >= 5 {
439 last_subexpr_str = Some(rw);
440 fits_single_line = true;
442 // We could not know whether overflowing is better than using vertical layout,
443 // just by looking at the overflowed rewrite. Now we rewrite the last child
444 // on its own line, and compare two rewrites to choose which is better.
445 match rewrite_chain_subexpr(&last.expr, context, last_shape) {
446 Some(ref new_rw) if !could_fit_single_line => {
447 last_subexpr_str = Some(new_rw.clone());
449 Some(ref new_rw) if new_rw.lines().count() >= line_count => {
450 last_subexpr_str = Some(rw);
451 fits_single_line = could_fit_single_line;
453 new_rw @ Some(..) => {
454 last_subexpr_str = new_rw;
457 last_subexpr_str = Some(rw);
458 fits_single_line = could_fit_single_line;
466 last_subexpr_str = last_subexpr_str.or_else(|| rewrite_chain_subexpr(&last.expr, context, last_shape));
467 rewrites.push(last_subexpr_str?);
469 let connector = if fits_single_line && !parent_rewrite_contains_newline {
470 // Yay, we can put everything on one line.
474 if *context.force_one_line_chain.borrow() {
477 other_child_shape.indent.to_string_with_newline(context.config)
480 let result = format!("{}{}{}",
482 join_rewrites_vis(&rewrites, &connector),
483 "?".repeat(last.tries),
485 wrap_str(result, context.config.max_width(), shape)
488 fn join_rewrites(rewrites: &[String], is_block_like: &[bool], connector: &str) -> String {
489 let mut rewrite_iter = rewrites.iter();
490 let mut result = rewrite_iter.next().unwrap().clone();
492 for (rewrite, prev_is_block_like) in rewrite_iter.zip(is_block_like.iter()) {
493 if rewrite != "?" && !prev_is_block_like {
494 result.push_str(connector);
496 result.push_str(&rewrite);
502 fn join_rewrites_vis(rewrites: &[String], connector: &str) -> String {
503 let mut rewrite_iter = rewrites.iter();
504 let mut result = rewrite_iter.next().unwrap().clone();
506 for rewrite in rewrite_iter {
508 result.push_str(connector);
510 result.push_str(&rewrite);
516 // States whether an expression's last line exclusively consists of closing
517 // parens, braces, and brackets in its idiomatic formatting.
518 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
520 ast::ExprKind::Mac(..) | ast::ExprKind::Call(..) => {
521 context.use_block_indent() && repr.contains('\n')
523 ast::ExprKind::Struct(..)
524 | ast::ExprKind::While(..)
525 | ast::ExprKind::WhileLet(..)
526 | ast::ExprKind::If(..)
527 | ast::ExprKind::IfLet(..)
528 | ast::ExprKind::Block(..)
529 | ast::ExprKind::Loop(..)
530 | ast::ExprKind::ForLoop(..)
531 | ast::ExprKind::Match(..) => repr.contains('\n'),
532 ast::ExprKind::Paren(ref expr)
533 | ast::ExprKind::Binary(_, _, ref expr)
534 | ast::ExprKind::Index(_, ref expr)
535 | ast::ExprKind::Unary(_, ref expr)
536 | ast::ExprKind::Closure(_, _, _, _, ref expr, _) => is_block_expr(context, expr, repr),
537 ast::ExprKind::MethodCall(_, ref exprs) => {
538 // TODO maybe should be like Call
539 is_block_expr(context, exprs.last().unwrap(), repr)
545 // Returns a Vec of the prefixes of the chain.
546 // E.g., for input `a.b.c` we return [`a.b.c`, `a.b`, 'a']
547 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> Vec<ast::Expr> {
548 let mut subexpr_list = vec![expr.clone()];
550 while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
551 subexpr_list.push(subexpr.clone());
557 // Returns the expression's subexpression, if it exists. When the subexpr
558 // is a try! macro, we'll convert it to shorthand when the option is set.
559 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
561 ast::ExprKind::MethodCall(_, ref expressions) => {
562 Some(convert_try(&expressions[0], context))
564 ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) => {
565 Some(convert_try(subexpr, context))
571 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
573 ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
574 if let Some(subexpr) = convert_try_mac(mac, context) {
584 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
586 fn rewrite_chain_subexpr(
588 context: &RewriteContext,
590 ) -> Option<String> {
591 let rewrite_element = |expr_str: String| {
592 if expr_str.len() <= shape.width {
600 ast::ExprKind::MethodCall(ref segment, ref expressions) => {
601 let types = match segment.args {
602 Some(ref params) => match **params {
603 ast::GenericArgs::AngleBracketed(ref data) => &data.args[..],
608 rewrite_method_call(segment.ident, types, expressions, expr.span, context, shape)
610 ast::ExprKind::Field(ref nested, ref field) => {
611 let space = if is_tup_field_access(expr) && is_tup_field_access(nested) {
616 rewrite_element(format!("{}.{}", space, field.name))
618 ast::ExprKind::Try(_) => rewrite_element(String::from("?")),
623 fn is_tup_field_access(expr: &ast::Expr) -> bool {
625 ast::ExprKind::Field(_, ref field) => {
626 field.name.to_string().chars().all(|c| c.is_digit(10))
632 // Determines if we can continue formatting a given expression on the same line.
633 fn is_continuable(expr: &ast::Expr) -> bool {
635 ast::ExprKind::Path(..) => true,
640 fn rewrite_method_call(
641 method_name: ast::Ident,
642 types: &[ast::GenericArg],
643 args: &[ptr::P<ast::Expr>],
645 context: &RewriteContext,
647 ) -> Option<String> {
648 let (lo, type_str) = if types.is_empty() {
649 (args[0].span.hi(), String::new())
651 let type_list = types
653 .map(|ty| ty.rewrite(context, shape))
654 .collect::<Option<Vec<_>>>()?;
656 let type_str = format!("::<{}>", type_list.join(", "));
658 (types.last().unwrap().span().hi(), type_str)
661 let callee_str = format!(".{}{}", method_name, type_str);
662 let span = mk_sp(lo, span.hi());
664 rewrite_call(context, &callee_str, &args[1..], span, shape)