try to write the parameter on a new line in case the attribute/parameter together are over max_width

This commit is contained in:
Stéphane Campinas 2020-10-06 03:44:48 +02:00 committed by Caleb Cartwright
parent a59cac29f4
commit c2f0e99d85
2 changed files with 35 additions and 12 deletions

View File

@ -10,7 +10,8 @@
use crate::shape::{Indent, Shape};
use crate::string::{rewrite_string, StringFormat};
use crate::utils::{
count_newlines, first_line_width, last_line_width, trim_left_preserve_layout, unicode_str_width,
count_newlines, first_line_width, last_line_width, trim_left_preserve_layout,
trimmed_last_line_width, unicode_str_width,
};
use crate::{ErrorKind, FormattingError};
@ -171,11 +172,12 @@ pub(crate) fn combine_strs_with_missing_comments(
String::with_capacity(prev_str.len() + next_str.len() + shape.indent.width() + 128);
result.push_str(prev_str);
let mut allow_one_line = !prev_str.contains('\n') && !next_str.contains('\n');
let first_sep = if prev_str.is_empty() || next_str.is_empty() {
""
} else {
" "
};
let first_sep =
if prev_str.is_empty() || next_str.is_empty() || trimmed_last_line_width(prev_str) == 0 {
""
} else {
" "
};
let mut one_line_width =
last_line_width(prev_str) + first_line_width(next_str) + first_sep.len();

View File

@ -1980,12 +1980,13 @@ fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>
has_multiple_attr_lines,
)
} else if is_named_param(self) {
let param_name = &self
.pat
.rewrite(context, Shape::legacy(shape.width, shape.indent))?;
let mut result = combine_strs_with_missing_comments(
context,
&param_attrs_result,
&self
.pat
.rewrite(context, Shape::legacy(shape.width, shape.indent))?,
param_name,
span,
shape,
!has_multiple_attr_lines,
@ -1999,10 +2000,30 @@ fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>
result.push_str(&after_comment);
let overhead = last_line_width(&result);
let max_width = shape.width.checked_sub(overhead)?;
let ty_str = self
if let Some(ty_str) = self
.ty
.rewrite(context, Shape::legacy(max_width, shape.indent))?;
result.push_str(&ty_str);
.rewrite(context, Shape::legacy(max_width, shape.indent))
{
result.push_str(&ty_str);
} else {
result = combine_strs_with_missing_comments(
context,
&(param_attrs_result + &shape.to_string_with_newline(context.config)),
param_name,
span,
shape,
!has_multiple_attr_lines,
)?;
result.push_str(&before_comment);
result.push_str(colon_spaces(context.config));
result.push_str(&after_comment);
let overhead = last_line_width(&result);
let max_width = shape.width.checked_sub(overhead)?;
let ty_str = self
.ty
.rewrite(context, Shape::legacy(max_width, shape.indent))?;
result.push_str(&ty_str);
}
}
Some(result)