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 suffix_try_num = subexpr_list.iter().take_while(|e| is_try(e)).count();
102 let prefix_try_num = subexpr_list.iter().rev().take_while(|e| is_try(e)).count();
104 // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
105 let parent_shape = if is_block_expr(context, &parent, "\n") {
106 match context.config.chain_indent() {
107 IndentStyle::Visual => shape.visual_indent(0),
108 IndentStyle::Block => shape,
113 let parent_rewrite = parent
114 .rewrite(context, parent_shape)
115 .map(|parent_rw| parent_rw + &repeat_try(prefix_try_num))?;
116 let parent_rewrite_contains_newline = parent_rewrite.contains('\n');
117 let is_small_parent = parent_rewrite.len() <= context.config.tab_spaces();
119 // Decide how to layout the rest of the chain. `extend` is true if we can
120 // put the first non-parent item on the same line as the parent.
121 let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
123 chain_indent(context, shape.add_offset(parent_rewrite.len())),
124 context.config.chain_indent() == IndentStyle::Visual || is_small_parent,
126 } else if is_block_expr(context, &parent, &parent_rewrite) {
127 match context.config.chain_indent() {
128 // Try to put the first child on the same line with parent's last line
129 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
130 // The parent is a block, so align the rest of the chain with the closing
132 IndentStyle::Visual => (parent_shape, false),
136 chain_indent(context, shape.add_offset(parent_rewrite.len())),
141 let other_child_shape = nested_shape.with_max_width(context.config);
143 let first_child_shape = if extend {
144 let overhead = last_line_width(&parent_rewrite);
145 let offset = parent_rewrite.lines().rev().next().unwrap().trim().len();
146 match context.config.chain_indent() {
147 IndentStyle::Visual => parent_shape.offset_left(overhead)?,
148 IndentStyle::Block => parent_shape.block().offset_left(offset)?,
154 "child_shapes {:?} {:?}",
159 let child_shape_iter = Some(first_child_shape)
161 .chain(iter::repeat(other_child_shape));
162 let subexpr_num = subexpr_list.len();
163 let last_subexpr = &subexpr_list[suffix_try_num];
164 let subexpr_list = &subexpr_list[suffix_try_num..subexpr_num - prefix_try_num];
165 let iter = subexpr_list.iter().skip(1).rev().zip(child_shape_iter);
166 let mut rewrites = iter.map(|(e, shape)| {
167 rewrite_chain_subexpr(e, total_span, context, shape)
168 }).collect::<Option<Vec<_>>>()?;
170 // Total of all items excluding the last.
171 let extend_last_subexr = last_line_extendable(&parent_rewrite) && rewrites.is_empty();
172 let almost_total = if extend_last_subexr {
173 last_line_width(&parent_rewrite)
175 rewrites.iter().fold(0, |a, b| a + b.len()) + parent_rewrite.len()
177 let one_line_budget = if rewrites.is_empty() && !context.config.chain_split_single_child() {
180 min(shape.width, context.config.chain_one_line_max())
182 let all_in_one_line = !parent_rewrite_contains_newline
183 && rewrites.iter().all(|s| !s.contains('\n'))
184 && almost_total < one_line_budget;
185 let last_shape = if rewrites.is_empty() {
186 // We only have a single child.
189 match context.config.chain_indent() {
190 IndentStyle::Visual => other_child_shape.sub_width(shape.rhs_overhead(context.config))?,
191 IndentStyle::Block => other_child_shape,
194 let last_shape = last_shape.sub_width(suffix_try_num)?;
195 let rewrite_last = || rewrite_chain_subexpr(last_subexpr, total_span, context, last_shape);
196 let (last_subexpr_str, fits_single_line) = if all_in_one_line || extend_last_subexr {
197 parent_shape.offset_left(almost_total).map(|shape| {
198 if let Some(rw) = rewrite_chain_subexpr(last_subexpr, total_span, context, shape) {
199 let line_count = rw.lines().count();
200 let fits_single_line = almost_total + first_line_width(&rw) <= one_line_budget;
201 if (line_count >= 5 && fits_single_line) || extend_last_subexr {
204 match rewrite_last() {
205 Some(ref new_rw) if !fits_single_line => (Some(new_rw.clone()), false),
206 Some(ref new_rw) if new_rw.lines().count() >= line_count => {
207 (Some(rw), fits_single_line)
209 new_rw @ Some(..) => (new_rw, false),
210 _ => (Some(rw), fits_single_line),
214 (rewrite_last(), false)
218 (rewrite_last(), false)
220 rewrites.push(last_subexpr_str?);
222 let connector = if fits_single_line && !parent_rewrite_contains_newline {
223 // Yay, we can put everything on one line.
227 if context.force_one_line_chain {
230 format!("\n{}", nested_shape.indent.to_string(context.config))
233 let first_connector = if is_small_parent || fits_single_line
234 || last_line_extendable(&parent_rewrite)
235 || context.config.chain_indent() == IndentStyle::Visual
242 let subexpr_num = subexpr_list.len();
243 let result = if is_small_parent && rewrites.len() > 1 {
244 let second_connector = choose_first_connector(
249 &subexpr_list[..subexpr_num - 1],
258 join_rewrites(&rewrites[1..], &subexpr_list[..subexpr_num - 1], &connector)
265 join_rewrites(&rewrites, subexpr_list, &connector)
268 let result = format!("{}{}", result, repeat_try(suffix_try_num));
269 wrap_str(result, context.config.max_width(), shape)
272 fn is_extendable_parent(context: &RewriteContext, parent_str: &str) -> bool {
273 context.config.chain_indent() == IndentStyle::Block && last_line_extendable(parent_str)
276 // True if the chain is only `?`s.
277 fn chain_only_try(exprs: &[ast::Expr]) -> bool {
278 exprs.iter().all(|e| if let ast::ExprKind::Try(_) = e.node {
285 // Try to rewrite and replace the last non-try child. Return `true` if
286 // replacing succeeds.
287 fn repeat_try(try_count: usize) -> String {
288 iter::repeat("?").take(try_count).collect::<String>()
294 context: &RewriteContext,
296 ) -> Option<String> {
297 let sub_expr = expr.rewrite(context, shape.sub_width(try_count)?)?;
298 Some(format!("{}{}", sub_expr, repeat_try(try_count)))
301 fn join_rewrites(rewrites: &[String], subexps: &[ast::Expr], connector: &str) -> String {
302 let mut rewrite_iter = rewrites.iter();
303 let mut result = rewrite_iter.next().unwrap().clone();
304 let mut subexpr_iter = subexps.iter().rev();
307 for (rewrite, expr) in rewrite_iter.zip(subexpr_iter) {
309 ast::ExprKind::Try(_) => (),
310 _ => result.push_str(connector),
312 result.push_str(&rewrite[..]);
318 // States whether an expression's last line exclusively consists of closing
319 // parens, braces, and brackets in its idiomatic formatting.
320 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
322 ast::ExprKind::Mac(..) | ast::ExprKind::Call(..) => {
323 context.use_block_indent() && repr.contains('\n')
325 ast::ExprKind::Struct(..) |
326 ast::ExprKind::While(..) |
327 ast::ExprKind::WhileLet(..) |
328 ast::ExprKind::If(..) |
329 ast::ExprKind::IfLet(..) |
330 ast::ExprKind::Block(..) |
331 ast::ExprKind::Loop(..) |
332 ast::ExprKind::ForLoop(..) |
333 ast::ExprKind::Match(..) => repr.contains('\n'),
334 ast::ExprKind::Paren(ref expr) |
335 ast::ExprKind::Binary(_, _, ref expr) |
336 ast::ExprKind::Index(_, ref expr) |
337 ast::ExprKind::Unary(_, ref expr) => is_block_expr(context, expr, repr),
342 // Returns the root of the chain and a Vec of the prefixes of the rest of the chain.
343 // E.g., for input `a.b.c` we return (`a`, [`a.b.c`, `a.b`])
344 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> (ast::Expr, Vec<ast::Expr>) {
345 let mut subexpr_list = vec![expr.clone()];
347 while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
348 subexpr_list.push(subexpr.clone());
351 let parent = subexpr_list.pop().unwrap();
352 (parent, subexpr_list)
355 fn chain_indent(context: &RewriteContext, shape: Shape) -> Shape {
356 match context.config.chain_indent() {
357 IndentStyle::Visual => shape.visual_indent(0),
358 IndentStyle::Block => shape
359 .block_indent(context.config.tab_spaces())
360 .with_max_width(context.config),
364 // Returns the expression's subexpression, if it exists. When the subexpr
365 // is a try! macro, we'll convert it to shorthand when the option is set.
366 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
368 ast::ExprKind::MethodCall(_, ref expressions) => {
369 Some(convert_try(&expressions[0], context))
371 ast::ExprKind::TupField(ref subexpr, _) |
372 ast::ExprKind::Field(ref subexpr, _) |
373 ast::ExprKind::Try(ref subexpr) => Some(convert_try(subexpr, context)),
378 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
380 ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
381 if let Some(subexpr) = convert_try_mac(mac, context) {
391 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
393 fn rewrite_chain_subexpr(
396 context: &RewriteContext,
398 ) -> Option<String> {
399 let rewrite_element = |expr_str: String| if expr_str.len() <= shape.width {
406 ast::ExprKind::MethodCall(ref segment, ref expressions) => {
407 let types = match segment.parameters {
408 Some(ref params) => match **params {
409 ast::PathParameters::AngleBracketed(ref data) => &data.types[..],
414 rewrite_method_call(segment.identifier, types, expressions, span, context, shape)
416 ast::ExprKind::Field(_, ref field) => rewrite_element(format!(".{}", field.node)),
417 ast::ExprKind::TupField(ref expr, ref field) => {
418 let space = match expr.node {
419 ast::ExprKind::TupField(..) => " ",
422 rewrite_element(format!("{}.{}", space, field.node))
424 ast::ExprKind::Try(_) => rewrite_element(String::from("?")),
429 // Determines if we can continue formatting a given expression on the same line.
430 fn is_continuable(expr: &ast::Expr) -> bool {
432 ast::ExprKind::Path(..) => true,
437 fn is_try(expr: &ast::Expr) -> bool {
439 ast::ExprKind::Try(..) => true,
444 fn choose_first_connector<'a>(
445 context: &RewriteContext,
447 first_child_str: &str,
449 subexpr_list: &[ast::Expr],
452 if subexpr_list.is_empty() {
454 } else if extend || subexpr_list.last().map_or(false, is_try)
455 || is_extendable_parent(context, parent_str)
457 // 1 = ";", being conservative here.
458 if last_line_width(parent_str) + first_line_width(first_child_str) + 1
459 <= context.config.max_width()
470 fn rewrite_method_call(
471 method_name: ast::Ident,
472 types: &[ptr::P<ast::Ty>],
473 args: &[ptr::P<ast::Expr>],
475 context: &RewriteContext,
477 ) -> Option<String> {
478 let (lo, type_str) = if types.is_empty() {
479 (args[0].span.hi(), String::new())
481 let type_list = types
483 .map(|ty| ty.rewrite(context, shape))
484 .collect::<Option<Vec<_>>>()?;
486 let type_str = if context.config.spaces_within_angle_brackets() && !type_list.is_empty() {
487 format!("::< {} >", type_list.join(", "))
489 format!("::<{}>", type_list.join(", "))
492 (types.last().unwrap().span.hi(), type_str)
495 let callee_str = format!(".{}{}", method_name, type_str);
496 let span = mk_sp(lo, span.hi());
498 rewrite_call(context, &callee_str, &args[1..], span, shape)