1 // Format with vertical alignment.
5 use itertools::Itertools;
7 use syntax::source_map::{BytePos, Span};
9 use crate::comment::{combine_strs_with_missing_comments, contains_comment};
10 use crate::config::lists::*;
11 use crate::expr::rewrite_field;
12 use crate::items::{rewrite_struct_field, rewrite_struct_field_prefix};
14 definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator,
16 use crate::rewrite::{Rewrite, RewriteContext};
17 use crate::shape::{Indent, Shape};
18 use crate::source_map::SpanUtils;
19 use crate::spanned::Spanned;
20 use crate::utils::{contains_skip, is_attributes_extendable, mk_sp, rewrite_ident};
22 pub(crate) trait AlignedItem {
23 fn skip(&self) -> bool;
24 fn get_span(&self) -> Span;
25 fn rewrite_prefix(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>;
26 fn rewrite_aligned_item(
28 context: &RewriteContext<'_>,
30 prefix_max_width: usize,
34 impl AlignedItem for ast::StructField {
35 fn skip(&self) -> bool {
36 contains_skip(&self.attrs)
39 fn get_span(&self) -> Span {
43 fn rewrite_prefix(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
44 let attrs_str = self.attrs.rewrite(context, shape)?;
45 let missing_span = if self.attrs.is_empty() {
46 mk_sp(self.span.lo(), self.span.lo())
48 mk_sp(self.attrs.last().unwrap().span.hi(), self.span.lo())
50 let attrs_extendable = self.ident.is_none() && is_attributes_extendable(&attrs_str);
51 rewrite_struct_field_prefix(context, self).and_then(|field_str| {
52 combine_strs_with_missing_comments(
63 fn rewrite_aligned_item(
65 context: &RewriteContext<'_>,
67 prefix_max_width: usize,
69 rewrite_struct_field(context, self, shape, prefix_max_width)
73 impl AlignedItem for ast::Field {
74 fn skip(&self) -> bool {
75 contains_skip(&self.attrs)
78 fn get_span(&self) -> Span {
82 fn rewrite_prefix(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
83 let attrs_str = self.attrs.rewrite(context, shape)?;
84 let name = rewrite_ident(context, self.ident);
85 let missing_span = if self.attrs.is_empty() {
86 mk_sp(self.span.lo(), self.span.lo())
88 mk_sp(self.attrs.last().unwrap().span.hi(), self.span.lo())
90 combine_strs_with_missing_comments(
96 is_attributes_extendable(&attrs_str),
100 fn rewrite_aligned_item(
102 context: &RewriteContext<'_>,
104 prefix_max_width: usize,
105 ) -> Option<String> {
106 rewrite_field(context, self, shape, prefix_max_width)
110 pub(crate) fn rewrite_with_alignment<T: AlignedItem>(
112 context: &RewriteContext<'_>,
115 one_line_width: usize,
116 ) -> Option<String> {
117 let (spaces, group_index) = if context.config.struct_field_align_threshold() > 0 {
118 group_aligned_items(context, fields)
120 ("", fields.len() - 1)
122 let init = &fields[0..=group_index];
123 let rest = &fields[group_index + 1..];
124 let init_last_pos = if rest.is_empty() {
127 // Decide whether the missing comments should stick to init or rest.
128 let init_hi = init[init.len() - 1].get_span().hi();
129 let rest_lo = rest[0].get_span().lo();
130 let missing_span = mk_sp(init_hi, rest_lo);
131 let missing_span = mk_sp(
132 context.snippet_provider.span_after(missing_span, ","),
136 let snippet = context.snippet(missing_span);
137 if snippet.trim_start().starts_with("//") {
138 let offset = snippet.lines().next().map_or(0, str::len);
140 init_hi + BytePos(offset as u32 + 2)
141 } else if snippet.trim_start().starts_with("/*") {
142 let comment_lines = snippet
144 .position(|line| line.trim_end().ends_with("*/"))
149 .take(comment_lines + 1)
154 init_hi + BytePos(offset as u32 + 2)
159 let init_span = mk_sp(span.lo(), init_last_pos);
160 let one_line_width = if rest.is_empty() { one_line_width } else { 0 };
162 rewrite_aligned_items_inner(context, init, init_span, shape.indent, one_line_width)?;
164 Some(result + spaces)
166 let rest_span = mk_sp(init_last_pos, span.hi());
167 let rest_str = rewrite_with_alignment(rest, context, shape, rest_span, one_line_width)?;
172 &shape.indent.to_string(context.config),
178 fn struct_field_prefix_max_min_width<T: AlignedItem>(
179 context: &RewriteContext<'_>,
182 ) -> (usize, usize) {
186 field.rewrite_prefix(context, shape).and_then(|field_str| {
187 if field_str.contains('\n') {
190 Some(field_str.len())
194 .fold_options((0, ::std::usize::MAX), |(max_len, min_len), len| {
195 (cmp::max(max_len, len), cmp::min(min_len, len))
200 fn rewrite_aligned_items_inner<T: AlignedItem>(
201 context: &RewriteContext<'_>,
205 one_line_width: usize,
206 ) -> Option<String> {
208 let item_shape = Shape::indented(offset, context.config).sub_width(1)?;
209 let (mut field_prefix_max_width, field_prefix_min_width) =
210 struct_field_prefix_max_min_width(context, fields, item_shape);
211 let max_diff = field_prefix_max_width.saturating_sub(field_prefix_min_width);
212 if max_diff > context.config.struct_field_align_threshold() {
213 field_prefix_max_width = 0;
216 let mut items = itemize_list(
217 context.snippet_provider,
221 |field| field.get_span().lo(),
222 |field| field.get_span().hi(),
223 |field| field.rewrite_aligned_item(context, item_shape, field_prefix_max_width),
228 .collect::<Vec<_>>();
230 let tactic = definitive_tactic(
232 ListTactic::HorizontalVertical,
237 if tactic == DefinitiveListTactic::Horizontal {
238 // since the items fits on a line, there is no need to align them
240 |field: &T| -> Option<String> { field.rewrite_aligned_item(context, item_shape, 0) };
243 .zip(items.iter_mut())
244 .for_each(|(field, list_item): (&T, &mut ListItem)| {
245 if list_item.item.is_some() {
246 list_item.item = do_rewrite(field);
251 let fmt = ListFormatting::new(item_shape, context.config)
253 .trailing_separator(context.config.trailing_comma())
254 .preserve_newline(true);
255 write_list(&items, &fmt)
258 fn group_aligned_items<T: AlignedItem>(
259 context: &RewriteContext<'_>,
261 ) -> (&'static str, usize) {
263 for i in 0..fields.len() - 1 {
264 if fields[i].skip() {
267 // See if there are comments or empty lines between fields.
268 let span = mk_sp(fields[i].get_span().hi(), fields[i + 1].get_span().lo());
269 let snippet = context
275 let spacings = if snippet
278 .any(|l| l.trim().is_empty())
284 if contains_comment(&snippet) || snippet.lines().count() > 1 {
285 return (spacings, index);