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};
74 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 total_span = expr.span;
88 let (parent, subexpr_list) = make_subexpr_list(expr, context);
90 // Bail out if the chain is just try sugar, i.e., an expression followed by
91 // any number of `?`s.
92 if chain_only_try(&subexpr_list) {
93 return rewrite_try(&parent, subexpr_list.len(), context, shape);
95 let suffix_try_num = subexpr_list.iter().take_while(|e| is_try(e)).count();
96 let prefix_try_num = subexpr_list.iter().rev().take_while(|e| is_try(e)).count();
98 // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
99 let parent_shape = if is_block_expr(context, &parent, "\n") {
100 match context.config.indent_style() {
101 IndentStyle::Visual => shape.visual_indent(0),
102 IndentStyle::Block => shape,
107 let parent_rewrite = parent
108 .rewrite(context, parent_shape)
109 .map(|parent_rw| parent_rw + &"?".repeat(prefix_try_num))?;
110 let parent_rewrite_contains_newline = parent_rewrite.contains('\n');
111 let is_small_parent = shape.offset + parent_rewrite.len() <= context.config.tab_spaces();
113 // Decide how to layout the rest of the chain. `extend` is true if we can
114 // put the first non-parent item on the same line as the parent.
115 let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
117 chain_indent(context, shape.add_offset(parent_rewrite.len())),
118 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
120 } else if is_block_expr(context, &parent, &parent_rewrite) {
121 match context.config.indent_style() {
122 // Try to put the first child on the same line with parent's last line
123 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
124 // The parent is a block, so align the rest of the chain with the closing
126 IndentStyle::Visual => (parent_shape, false),
130 chain_indent(context, shape.add_offset(parent_rewrite.len())),
135 let other_child_shape = nested_shape.with_max_width(context.config);
137 let first_child_shape = if extend {
138 let overhead = last_line_width(&parent_rewrite);
139 let offset = trimmed_last_line_width(&parent_rewrite) + prefix_try_num;
140 match context.config.indent_style() {
141 IndentStyle::Visual => parent_shape.offset_left(overhead)?,
142 IndentStyle::Block => parent_shape.offset_left(offset)?,
148 "child_shapes {:?} {:?}",
149 first_child_shape, other_child_shape
152 let child_shape_iter = Some(first_child_shape)
154 .chain(iter::repeat(other_child_shape));
155 let subexpr_num = subexpr_list.len();
156 let last_subexpr = &subexpr_list[suffix_try_num];
157 let subexpr_list = &subexpr_list[suffix_try_num..subexpr_num - prefix_try_num];
158 let iter = subexpr_list.iter().skip(1).rev().zip(child_shape_iter);
159 let mut rewrites = iter
160 .map(|(e, shape)| rewrite_chain_subexpr(e, total_span, context, shape))
161 .collect::<Option<Vec<_>>>()?;
163 // Total of all items excluding the last.
164 let extend_last_subexpr = if is_small_parent {
165 rewrites.len() == 1 && last_line_extendable(&rewrites[0])
167 rewrites.is_empty() && last_line_extendable(&parent_rewrite)
169 let almost_total = if extend_last_subexpr {
170 last_line_width(&parent_rewrite)
172 rewrites.iter().fold(0, |a, b| a + b.len()) + parent_rewrite.len()
174 let one_line_budget = if rewrites.is_empty() {
177 min(shape.width, context.config.width_heuristics().chain_width)
179 let all_in_one_line = !parent_rewrite_contains_newline
180 && rewrites.iter().all(|s| !s.contains('\n'))
181 && almost_total < one_line_budget;
182 let last_shape = if rewrites.is_empty() {
186 }.sub_width(shape.rhs_overhead(context.config) + suffix_try_num)?;
188 // Rewrite the last child. The last child of a chain requires special treatment. We need to
189 // know whether 'overflowing' the last child make a better formatting:
191 // A chain with overflowing the last child:
193 // parent.child1.child2.last_child(
200 // A chain without overflowing the last child (in vertical layout):
205 // .last_child(a, b, c)
208 // In particular, overflowing is effective when the last child is a method with a multi-lined
209 // block-like argument (e.g. closure):
211 // parent.child1.child2.last_child(|a, b, c| {
212 // let x = foo(a, b, c);
213 // let y = bar(a, b, c);
221 // `rewrite_last` rewrites the last child on its own line. We use a closure here instead of
222 // directly calling `rewrite_chain_subexpr()` to avoid exponential blowup.
223 let rewrite_last = || rewrite_chain_subexpr(last_subexpr, total_span, context, last_shape);
224 let (last_subexpr_str, fits_single_line) = if all_in_one_line || extend_last_subexpr {
225 // First we try to 'overflow' the last child and see if it looks better than using
227 parent_shape.offset_left(almost_total).map(|shape| {
228 if let Some(rw) = rewrite_chain_subexpr(last_subexpr, total_span, context, shape) {
229 // We allow overflowing here only if both of the following conditions match:
230 // 1. The entire chain fits in a single line expect the last child.
231 // 2. `last_child_str.lines().count() >= 5`.
232 let line_count = rw.lines().count();
233 let fits_single_line = almost_total + first_line_width(&rw) <= one_line_budget;
234 if fits_single_line && line_count >= 5 {
237 // We could not know whether overflowing is better than using vertical layout,
238 // just by looking at the overflowed rewrite. Now we rewrite the last child
239 // on its own line, and compare two rewrites to choose which is better.
240 match rewrite_last() {
241 Some(ref new_rw) if !fits_single_line => (Some(new_rw.clone()), false),
242 Some(ref new_rw) if new_rw.lines().count() >= line_count => {
243 (Some(rw), fits_single_line)
245 new_rw @ Some(..) => (new_rw, false),
246 _ => (Some(rw), fits_single_line),
250 (rewrite_last(), false)
254 (rewrite_last(), false)
256 rewrites.push(last_subexpr_str?);
258 let connector = if fits_single_line && !parent_rewrite_contains_newline {
259 // Yay, we can put everything on one line.
263 if *context.force_one_line_chain.borrow() {
266 nested_shape.indent.to_string_with_newline(context.config)
269 let first_connector = if is_small_parent
271 || last_line_extendable(&parent_rewrite)
272 || context.config.indent_style() == IndentStyle::Visual
279 let result = if is_small_parent && rewrites.len() > 1 {
280 let second_connector = if fits_single_line
281 || rewrites[1] == "?"
282 || last_line_extendable(&rewrites[0])
283 || context.config.indent_style() == IndentStyle::Visual
295 join_rewrites(&rewrites[1..], &connector)
302 join_rewrites(&rewrites, &connector)
305 let result = format!("{}{}", result, "?".repeat(suffix_try_num));
306 if context.config.indent_style() == IndentStyle::Visual {
307 wrap_str(result, context.config.max_width(), shape)
313 // True if the chain is only `?`s.
314 fn chain_only_try(exprs: &[ast::Expr]) -> bool {
315 exprs.iter().all(|e| {
316 if let ast::ExprKind::Try(_) = e.node {
327 context: &RewriteContext,
329 ) -> Option<String> {
330 let sub_expr = expr.rewrite(context, shape.sub_width(try_count)?)?;
331 Some(format!("{}{}", sub_expr, "?".repeat(try_count)))
334 fn join_rewrites(rewrites: &[String], connector: &str) -> String {
335 let mut rewrite_iter = rewrites.iter();
336 let mut result = rewrite_iter.next().unwrap().clone();
338 for rewrite in rewrite_iter {
340 result.push_str(connector);
342 result.push_str(&rewrite);
348 // States whether an expression's last line exclusively consists of closing
349 // parens, braces, and brackets in its idiomatic formatting.
350 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
352 ast::ExprKind::Mac(..) | ast::ExprKind::Call(..) => {
353 context.use_block_indent() && repr.contains('\n')
355 ast::ExprKind::Struct(..)
356 | ast::ExprKind::While(..)
357 | ast::ExprKind::WhileLet(..)
358 | ast::ExprKind::If(..)
359 | ast::ExprKind::IfLet(..)
360 | ast::ExprKind::Block(..)
361 | ast::ExprKind::Loop(..)
362 | ast::ExprKind::ForLoop(..)
363 | ast::ExprKind::Match(..) => repr.contains('\n'),
364 ast::ExprKind::Paren(ref expr)
365 | ast::ExprKind::Binary(_, _, ref expr)
366 | ast::ExprKind::Index(_, ref expr)
367 | ast::ExprKind::Unary(_, ref expr) => is_block_expr(context, expr, repr),
372 // Returns the root of the chain and a Vec of the prefixes of the rest of the chain.
373 // E.g., for input `a.b.c` we return (`a`, [`a.b.c`, `a.b`])
374 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> (ast::Expr, Vec<ast::Expr>) {
375 let mut subexpr_list = vec![expr.clone()];
377 while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
378 subexpr_list.push(subexpr.clone());
381 let parent = subexpr_list.pop().unwrap();
382 (parent, subexpr_list)
385 fn chain_indent(context: &RewriteContext, shape: Shape) -> Shape {
386 match context.config.indent_style() {
387 IndentStyle::Visual => shape.visual_indent(0),
388 IndentStyle::Block => shape
389 .block_indent(context.config.tab_spaces())
390 .with_max_width(context.config),
394 // Returns the expression's subexpression, if it exists. When the subexpr
395 // is a try! macro, we'll convert it to shorthand when the option is set.
396 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
398 ast::ExprKind::MethodCall(_, ref expressions) => {
399 Some(convert_try(&expressions[0], context))
401 ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) => {
402 Some(convert_try(subexpr, context))
408 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
410 ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
411 if let Some(subexpr) = convert_try_mac(mac, context) {
421 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
423 fn rewrite_chain_subexpr(
426 context: &RewriteContext,
428 ) -> Option<String> {
429 let rewrite_element = |expr_str: String| {
430 if expr_str.len() <= shape.width {
438 ast::ExprKind::MethodCall(ref segment, ref expressions) => {
439 let types = match segment.parameters {
440 Some(ref params) => match **params {
441 ast::PathParameters::AngleBracketed(ref data) => &data.types[..],
446 rewrite_method_call(segment.ident, types, expressions, span, context, shape)
448 ast::ExprKind::Field(ref nested, ref field) => {
449 let space = if is_tup_field_access(expr) && is_tup_field_access(nested) {
454 rewrite_element(format!("{}.{}", space, field.name))
456 ast::ExprKind::Try(_) => rewrite_element(String::from("?")),
461 fn is_tup_field_access(expr: &ast::Expr) -> bool {
463 ast::ExprKind::Field(_, ref field) => {
464 field.name.to_string().chars().all(|c| c.is_digit(10))
470 // Determines if we can continue formatting a given expression on the same line.
471 fn is_continuable(expr: &ast::Expr) -> bool {
473 ast::ExprKind::Path(..) => true,
478 fn is_try(expr: &ast::Expr) -> bool {
480 ast::ExprKind::Try(..) => true,
485 fn rewrite_method_call(
486 method_name: ast::Ident,
487 types: &[ptr::P<ast::Ty>],
488 args: &[ptr::P<ast::Expr>],
490 context: &RewriteContext,
492 ) -> Option<String> {
493 let (lo, type_str) = if types.is_empty() {
494 (args[0].span.hi(), String::new())
496 let type_list = types
498 .map(|ty| ty.rewrite(context, shape))
499 .collect::<Option<Vec<_>>>()?;
501 let type_str = format!("::<{}>", type_list.join(", "));
503 (types.last().unwrap().span.hi(), type_str)
506 let callee_str = format!(".{}{}", method_name, type_str);
507 let span = mk_sp(lo, span.hi());
509 rewrite_call(context, &callee_str, &args[1..], span, shape)