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 rewrite_last = || rewrite_chain_subexpr(last_subexpr, total_span, context, nested_shape);
186 let (last_subexpr_str, fits_single_line) = if all_in_one_line || extend_last_subexr {
187 parent_shape.offset_left(almost_total).map(|shape| {
188 if let Some(rw) = rewrite_chain_subexpr(last_subexpr, total_span, context, shape) {
189 let line_count = rw.lines().count();
190 let fits_single_line = almost_total + first_line_width(&rw) <= one_line_budget;
191 if (line_count >= 5 && fits_single_line) || extend_last_subexr {
194 match rewrite_last() {
195 Some(ref new_rw) if !fits_single_line => (Some(new_rw.clone()), false),
196 Some(ref new_rw) if new_rw.lines().count() >= line_count => {
197 (Some(rw), fits_single_line)
199 new_rw @ Some(..) => (new_rw, false),
200 _ => (Some(rw), fits_single_line),
204 (rewrite_last(), false)
208 (rewrite_last(), false)
210 rewrites.push(last_subexpr_str?);
212 let connector = if fits_single_line && !parent_rewrite_contains_newline {
213 // Yay, we can put everything on one line.
217 if context.force_one_line_chain {
220 format!("\n{}", nested_shape.indent.to_string(context.config))
223 let first_connector = if is_small_parent || fits_single_line
224 || last_line_extendable(&parent_rewrite)
225 || context.config.chain_indent() == IndentStyle::Visual
232 let subexpr_num = subexpr_list.len();
233 let result = if is_small_parent && rewrites.len() > 1 {
234 let second_connector = choose_first_connector(
239 &subexpr_list[..subexpr_num - 1],
248 join_rewrites(&rewrites[1..], &subexpr_list[..subexpr_num - 1], &connector)
255 join_rewrites(&rewrites, subexpr_list, &connector)
258 let result = format!("{}{}", result, repeat_try(suffix_try_num));
259 wrap_str(result, context.config.max_width(), shape)
262 fn is_extendable_parent(context: &RewriteContext, parent_str: &str) -> bool {
263 context.config.chain_indent() == IndentStyle::Block && last_line_extendable(parent_str)
266 // True if the chain is only `?`s.
267 fn chain_only_try(exprs: &[ast::Expr]) -> bool {
268 exprs.iter().all(|e| if let ast::ExprKind::Try(_) = e.node {
275 // Try to rewrite and replace the last non-try child. Return `true` if
276 // replacing succeeds.
277 fn repeat_try(try_count: usize) -> String {
278 iter::repeat("?").take(try_count).collect::<String>()
284 context: &RewriteContext,
286 ) -> Option<String> {
287 let sub_expr = expr.rewrite(context, shape.sub_width(try_count)?)?;
288 Some(format!("{}{}", sub_expr, repeat_try(try_count)))
291 fn join_rewrites(rewrites: &[String], subexps: &[ast::Expr], connector: &str) -> String {
292 let mut rewrite_iter = rewrites.iter();
293 let mut result = rewrite_iter.next().unwrap().clone();
294 let mut subexpr_iter = subexps.iter().rev();
297 for (rewrite, expr) in rewrite_iter.zip(subexpr_iter) {
299 ast::ExprKind::Try(_) => (),
300 _ => result.push_str(connector),
302 result.push_str(&rewrite[..]);
308 // States whether an expression's last line exclusively consists of closing
309 // parens, braces, and brackets in its idiomatic formatting.
310 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
312 ast::ExprKind::Mac(..) | ast::ExprKind::Call(..) => {
313 context.use_block_indent() && repr.contains('\n')
315 ast::ExprKind::Struct(..) |
316 ast::ExprKind::While(..) |
317 ast::ExprKind::WhileLet(..) |
318 ast::ExprKind::If(..) |
319 ast::ExprKind::IfLet(..) |
320 ast::ExprKind::Block(..) |
321 ast::ExprKind::Loop(..) |
322 ast::ExprKind::ForLoop(..) |
323 ast::ExprKind::Match(..) => repr.contains('\n'),
324 ast::ExprKind::Paren(ref expr) |
325 ast::ExprKind::Binary(_, _, ref expr) |
326 ast::ExprKind::Index(_, ref expr) |
327 ast::ExprKind::Unary(_, ref expr) => is_block_expr(context, expr, repr),
332 // Returns the root of the chain and a Vec of the prefixes of the rest of the chain.
333 // E.g., for input `a.b.c` we return (`a`, [`a.b.c`, `a.b`])
334 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> (ast::Expr, Vec<ast::Expr>) {
335 let mut subexpr_list = vec![expr.clone()];
337 while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
338 subexpr_list.push(subexpr.clone());
341 let parent = subexpr_list.pop().unwrap();
342 (parent, subexpr_list)
345 fn chain_indent(context: &RewriteContext, shape: Shape) -> Shape {
346 match context.config.chain_indent() {
347 IndentStyle::Visual => shape.visual_indent(0),
348 IndentStyle::Block => shape
349 .block_indent(context.config.tab_spaces())
350 .with_max_width(context.config),
354 // Returns the expression's subexpression, if it exists. When the subexpr
355 // is a try! macro, we'll convert it to shorthand when the option is set.
356 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
358 ast::ExprKind::MethodCall(_, ref expressions) => {
359 Some(convert_try(&expressions[0], context))
361 ast::ExprKind::TupField(ref subexpr, _) |
362 ast::ExprKind::Field(ref subexpr, _) |
363 ast::ExprKind::Try(ref subexpr) => Some(convert_try(subexpr, context)),
368 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
370 ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
371 if let Some(subexpr) = convert_try_mac(mac, context) {
381 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
383 fn rewrite_chain_subexpr(
386 context: &RewriteContext,
388 ) -> Option<String> {
389 let rewrite_element = |expr_str: String| if expr_str.len() <= shape.width {
396 ast::ExprKind::MethodCall(ref segment, ref expressions) => {
397 let types = match segment.parameters {
398 Some(ref params) => match **params {
399 ast::PathParameters::AngleBracketed(ref data) => &data.types[..],
404 rewrite_method_call(segment.identifier, types, expressions, span, context, shape)
406 ast::ExprKind::Field(_, ref field) => rewrite_element(format!(".{}", field.node)),
407 ast::ExprKind::TupField(ref expr, ref field) => {
408 let space = match expr.node {
409 ast::ExprKind::TupField(..) => " ",
412 rewrite_element(format!("{}.{}", space, field.node))
414 ast::ExprKind::Try(_) => rewrite_element(String::from("?")),
419 // Determines if we can continue formatting a given expression on the same line.
420 fn is_continuable(expr: &ast::Expr) -> bool {
422 ast::ExprKind::Path(..) => true,
427 fn is_try(expr: &ast::Expr) -> bool {
429 ast::ExprKind::Try(..) => true,
434 fn choose_first_connector<'a>(
435 context: &RewriteContext,
437 first_child_str: &str,
439 subexpr_list: &[ast::Expr],
442 if subexpr_list.is_empty() {
444 } else if extend || subexpr_list.last().map_or(false, is_try)
445 || is_extendable_parent(context, parent_str)
447 // 1 = ";", being conservative here.
448 if last_line_width(parent_str) + first_line_width(first_child_str) + 1
449 <= context.config.max_width()
460 fn rewrite_method_call(
461 method_name: ast::Ident,
462 types: &[ptr::P<ast::Ty>],
463 args: &[ptr::P<ast::Expr>],
465 context: &RewriteContext,
467 ) -> Option<String> {
468 let (lo, type_str) = if types.is_empty() {
469 (args[0].span.hi(), String::new())
471 let type_list = types
473 .map(|ty| ty.rewrite(context, shape))
474 .collect::<Option<Vec<_>>>()?;
476 let type_str = if context.config.spaces_within_angle_brackets() && !type_list.is_empty() {
477 format!("::< {} >", type_list.join(", "))
479 format!("::<{}>", type_list.join(", "))
482 (types.last().unwrap().span.hi(), type_str)
485 let callee_str = format!(".{}{}", method_name, type_str);
486 let span = mk_sp(lo, span.hi());
488 rewrite_call(context, &callee_str, &args[1..], span, shape)