Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Issue 6470: Preserve Space after colon if followed by absolute path declaration (::) #6475

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 31 additions & 5 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ use crate::string::{StringFormat, rewrite_string};
use crate::types::{PathContext, rewrite_path};
use crate::utils::{
colon_spaces, contains_skip, count_newlines, filtered_str_fits, first_line_ends_with,
inner_attributes, last_line_extendable, last_line_width, mk_sp, outer_attributes,
semicolon_for_expr, unicode_str_width, wrap_str,
inner_attributes, is_absolute_decl_path, last_line_extendable, last_line_width, mk_sp,
outer_attributes, semicolon_for_expr, unicode_str_width, wrap_str,
};
use crate::vertical::rewrite_with_alignment;
use crate::visitor::FmtVisitor;
Expand Down Expand Up @@ -1880,8 +1880,27 @@ pub(crate) fn wrap_struct_field(
}
}

pub(crate) fn struct_lit_field_separator(config: &Config) -> &str {
colon_spaces(config)
pub(crate) fn struct_lit_field_separator(config: &Config, force_space_after_colon: bool) -> &str {
colon_spaces(config, force_space_after_colon)
}

fn extract_ast_path_from_expr(expr: &ast::Expr) -> Option<&ast::Path> {
match &expr.kind {
ast::ExprKind::Call(ptr_expr, ..) => extract_ast_path_from_expr(&*ptr_expr),
ast::ExprKind::MethodCall(box_method_call, ..) => {
extract_ast_path_from_expr(&*box_method_call.receiver)
}
ast::ExprKind::Binary(_, left_expr, ..) => extract_ast_path_from_expr(&*left_expr),
ast::ExprKind::Cast(ptr_expr, ..) => extract_ast_path_from_expr(&*ptr_expr),
ast::ExprKind::Type(ptr_expr, ..) => extract_ast_path_from_expr(&*ptr_expr),
ast::ExprKind::Field(ptr_expr, ..) => extract_ast_path_from_expr(&*ptr_expr),
ast::ExprKind::Index(ptr_expr, ..) => extract_ast_path_from_expr(&*ptr_expr),
ast::ExprKind::Range(Some(start_expr), ..) => extract_ast_path_from_expr(&*start_expr),
ast::ExprKind::Path(_, path, ..) => Some(&path),
ast::ExprKind::MacCall(mac, ..) => Some(&(*mac).path),
ast::ExprKind::Struct(ptr_struct_expr, ..) => Some(&(*ptr_struct_expr).path),
_ => None,
}
}

pub(crate) fn rewrite_field(
Expand All @@ -1901,7 +1920,14 @@ pub(crate) fn rewrite_field(
if field.is_shorthand {
Ok(attrs_str + name)
} else {
let mut separator = String::from(struct_lit_field_separator(context.config));
let force_space_after_colon = match extract_ast_path_from_expr(&field.expr) {
Some(path) => is_absolute_decl_path(path),
_ => false,
};
let mut separator = String::from(struct_lit_field_separator(
context.config,
force_space_after_colon,
));
for _ in 0..prefix_max_width.saturating_sub(name.len()) {
separator.push(' ');
}
Expand Down
34 changes: 24 additions & 10 deletions src/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ const DEFAULT_VISIBILITY: ast::Visibility = ast::Visibility {
tokens: None,
};

fn type_annotation_separator(config: &Config) -> &str {
colon_spaces(config)
fn type_annotation_separator(config: &Config, force_space_after_colon: bool) -> &str {
colon_spaces(config, force_space_after_colon)
}

// Statements of the form
Expand Down Expand Up @@ -96,7 +96,9 @@ impl Rewrite for ast::Local {
let mut infix = String::with_capacity(32);

if let Some(ref ty) = self.ty {
let separator = type_annotation_separator(context.config);
let force_space_after_colon = is_ty_kind_with_absolute_decl(&(*ty).kind);
let separator = type_annotation_separator(context.config, force_space_after_colon);

let ty_shape = if pat_str.contains('\n') {
shape.with_max_width(context.config)
} else {
Expand Down Expand Up @@ -1890,10 +1892,14 @@ fn rewrite_ty<R: Rewrite>(
Ok(result)
}

fn type_annotation_spacing(config: &Config) -> (&str, &str) {
fn type_annotation_spacing(config: &Config, force_space_after_colon: bool) -> (&str, &str) {
(
if config.space_before_colon() { " " } else { "" },
if config.space_after_colon() { " " } else { "" },
if force_space_after_colon || config.space_after_colon() {
" "
} else {
""
},
)
}

Expand All @@ -1903,7 +1909,8 @@ pub(crate) fn rewrite_struct_field_prefix(
) -> RewriteResult {
let vis = format_visibility(context, &field.vis);
let safety = format_safety(field.safety);
let type_annotation_spacing = type_annotation_spacing(context.config);
let force_space_after_colon = is_ty_kind_with_absolute_decl(&(*field.ty).kind);
let type_annotation_spacing = type_annotation_spacing(context.config, force_space_after_colon);
Ok(match field.ident {
Some(name) => format!(
"{vis}{safety}{}{}:",
Expand Down Expand Up @@ -1939,7 +1946,8 @@ pub(crate) fn rewrite_struct_field(
return Ok(context.snippet(field.span()).to_owned());
}

let type_annotation_spacing = type_annotation_spacing(context.config);
let force_space_after_colon = is_ty_kind_with_absolute_decl(&(*field.ty).kind);
let type_annotation_spacing = type_annotation_spacing(context.config, force_space_after_colon);
let prefix = rewrite_struct_field_prefix(context, field)?;

let attrs_str = field.attrs.rewrite_result(context, shape)?;
Expand Down Expand Up @@ -2091,7 +2099,11 @@ fn rewrite_static(
return None;
}

let colon = colon_spaces(context.config);
// if after a semicolon is absolute path declaration (::) need to force
// space after colon, because ::: syntax cannot compile
let force_space_after_colon = is_ty_kind_with_absolute_decl(&static_parts.ty.kind);
let colon = colon_spaces(context.config, force_space_after_colon);

let mut prefix = format!(
"{}{}{}{} {}{}{}",
format_visibility(context, static_parts.vis),
Expand Down Expand Up @@ -2294,7 +2306,8 @@ impl Rewrite for ast::Param {
let (before_comment, after_comment) =
get_missing_param_comments(context, self.pat.span, self.ty.span, shape);
result.push_str(&before_comment);
result.push_str(colon_spaces(context.config));
let force_space_after_colon = is_ty_kind_with_absolute_decl(&(*self.ty).kind);
result.push_str(colon_spaces(context.config, force_space_after_colon));
result.push_str(&after_comment);
let overhead = last_line_width(&result);
let max_width = shape
Expand Down Expand Up @@ -2322,7 +2335,8 @@ impl Rewrite for ast::Param {
!has_multiple_attr_lines,
)?;
result.push_str(&before_comment);
result.push_str(colon_spaces(context.config));
let force_space_after_colon = is_ty_kind_with_absolute_decl(&(*self.ty).kind);
result.push_str(colon_spaces(context.config, force_space_after_colon));
result.push_str(&after_comment);
let overhead = last_line_width(&result);
let max_width = shape
Expand Down
39 changes: 33 additions & 6 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ use crate::source_map::SpanUtils;
use crate::spanned::Spanned;
use crate::utils::{
colon_spaces, extra_offset, first_line_width, format_extern, format_mutability,
last_line_extendable, last_line_width, mk_sp, rewrite_ident,
is_absolute_decl_path, is_ty_kind_with_absolute_decl, last_line_extendable, last_line_width,
mk_sp, rewrite_ident,
};

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Expand Down Expand Up @@ -434,8 +435,8 @@ where
}
}

fn type_bound_colon(context: &RewriteContext<'_>) -> &'static str {
colon_spaces(context.config)
fn type_bound_colon(context: &RewriteContext<'_>, force_space_after_colon: bool) -> &'static str {
colon_spaces(context.config, force_space_after_colon)
}

// If the return type is multi-lined, then force to use multiple lines for
Expand All @@ -454,6 +455,27 @@ fn get_tactics(item_vec: &[ListItem], output: &str, shape: Shape) -> DefinitiveL
}
}

fn is_bound_starts_with_absolut_decl(bounds: &ast::GenericBounds) -> bool {
if bounds.len() == 0 {
false
} else {
let first_bound = &bounds[0];
match first_bound {
ast::GenericBound::Trait(poly_trait_ref) => {
let plain_trait_modifiers = ast::TraitBoundModifiers {
constness: ast::BoundConstness::Never,
asyncness: ast::BoundAsyncness::Normal,
polarity: ast::BoundPolarity::Positive,
};
poly_trait_ref.modifiers == plain_trait_modifiers
&& poly_trait_ref.bound_generic_params.len() == 0
&& is_absolute_decl_path(&poly_trait_ref.trait_ref.path)
}
_ => false,
}
}
}

impl Rewrite for ast::WherePredicate {
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
self.rewrite_result(context, shape).ok()
Expand All @@ -469,7 +491,9 @@ impl Rewrite for ast::WherePredicate {
..
}) => {
let type_str = bounded_ty.rewrite_result(context, shape)?;
let colon = type_bound_colon(context).trim_end();
let force_space_after_colon = is_bound_starts_with_absolut_decl(bounds);
is_ty_kind_with_absolute_decl(&(*bounded_ty).kind);
let colon = type_bound_colon(context, force_space_after_colon).trim_end();
let lhs = if let Some(binder_str) =
rewrite_bound_params(context, shape, bound_generic_params)
{
Expand Down Expand Up @@ -565,7 +589,9 @@ fn rewrite_bounded_lifetime(
if bounds.is_empty() {
Ok(result)
} else {
let colon = type_bound_colon(context);
// the code for this point is `x:&'a SomeType`,
// so, no need to force adding space after colon
let colon = type_bound_colon(context, false);
let overhead = last_line_width(&result) + colon.len();
let shape = shape.sub_width(overhead, span)?;
let result = format!(
Expand Down Expand Up @@ -680,7 +706,8 @@ impl Rewrite for ast::GenericParam {
};

if !self.bounds.is_empty() {
param.push_str(type_bound_colon(context));
let force_space_after_colon = is_bound_starts_with_absolut_decl(&self.bounds);
param.push_str(type_bound_colon(context, force_space_after_colon));
param.push_str(&self.bounds.rewrite_result(context, shape)?)
}
if let ast::GenericParamKind::Type {
Expand Down
19 changes: 17 additions & 2 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -423,9 +423,9 @@ pub(crate) fn filtered_str_fits(snippet: &str, max_width: usize, shape: Shape) -
}

#[inline]
pub(crate) fn colon_spaces(config: &Config) -> &'static str {
pub(crate) fn colon_spaces(config: &Config, force_space_after_colon: bool) -> &'static str {
let before = config.space_before_colon();
let after = config.space_after_colon();
let after = force_space_after_colon || config.space_after_colon();
match (before, after) {
(true, true) => " : ",
(true, false) => " :",
Expand Down Expand Up @@ -715,3 +715,18 @@ mod test {
);
}
}

pub(crate) fn is_absolute_decl_path(path: &ast::Path) -> bool {
let segments = &path.segments;
match segments.first() {
Some(path_segment) => path_segment.ident.name == symbol::kw::PathRoot,
None => false,
}
}

pub(crate) fn is_ty_kind_with_absolute_decl(ty_kind: &ast::TyKind) -> bool {
match ty_kind {
ast::TyKind::Path(None, ast_path) => is_absolute_decl_path(ast_path),
_ => false,
}
}
Loading
Loading