1 // Copyright 2017 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 // Format with vertical alignment.
16 use syntax::codemap::{BytePos, Span};
18 use {Indent, Shape, Spanned};
19 use codemap::SpanUtils;
20 use comment::{combine_strs_with_missing_comments, contains_comment};
21 use expr::rewrite_field;
22 use items::{rewrite_struct_field, rewrite_struct_field_prefix};
23 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListTactic, Separator,
25 use rewrite::{Rewrite, RewriteContext};
26 use utils::{contains_skip, is_attributes_extendable, mk_sp};
28 pub trait AlignedItem {
29 fn skip(&self) -> bool;
30 fn get_span(&self) -> Span;
31 fn rewrite_prefix(&self, context: &RewriteContext, shape: Shape) -> Option<String>;
32 fn rewrite_aligned_item(
34 context: &RewriteContext,
36 prefix_max_width: usize,
40 impl AlignedItem for ast::StructField {
41 fn skip(&self) -> bool {
42 contains_skip(&self.attrs)
45 fn get_span(&self) -> Span {
49 fn rewrite_prefix(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
50 let attrs_str = try_opt!(self.attrs.rewrite(context, shape));
51 let missing_span = if self.attrs.is_empty() {
52 mk_sp(self.span.lo(), self.span.lo())
54 mk_sp(self.attrs.last().unwrap().span.hi(), self.span.lo())
56 rewrite_struct_field_prefix(context, self).and_then(|field_str| {
57 combine_strs_with_missing_comments(
63 is_attributes_extendable(&attrs_str),
68 fn rewrite_aligned_item(
70 context: &RewriteContext,
72 prefix_max_width: usize,
74 rewrite_struct_field(context, self, shape, prefix_max_width)
78 impl AlignedItem for ast::Field {
79 fn skip(&self) -> bool {
80 contains_skip(&self.attrs)
83 fn get_span(&self) -> Span {
87 fn rewrite_prefix(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
88 let attrs_str = try_opt!(self.attrs.rewrite(context, shape));
89 let name = &self.ident.node.to_string();
90 let missing_span = if self.attrs.is_empty() {
91 mk_sp(self.span.lo(), self.span.lo())
93 mk_sp(self.attrs.last().unwrap().span.hi(), self.span.lo())
95 combine_strs_with_missing_comments(
101 is_attributes_extendable(&attrs_str),
105 fn rewrite_aligned_item(
107 context: &RewriteContext,
109 prefix_max_width: usize,
110 ) -> Option<String> {
111 rewrite_field(context, self, shape, prefix_max_width)
115 pub fn rewrite_with_alignment<T: AlignedItem>(
117 context: &RewriteContext,
120 one_line_width: usize,
121 ) -> Option<String> {
122 let (spaces, group_index) = if context.config.struct_field_align_threshold() > 0 {
123 group_aligned_items(context, fields)
125 ("", fields.len() - 1)
127 let init = &fields[0..group_index + 1];
128 let rest = &fields[group_index + 1..];
129 let init_last_pos = if rest.is_empty() {
132 // Decide whether the missing comments should stick to init or rest.
133 let init_hi = init[init.len() - 1].get_span().hi();
134 let rest_lo = rest[0].get_span().lo();
135 let missing_span = mk_sp(init_hi, rest_lo);
136 let missing_span = mk_sp(
137 context.codemap.span_after(missing_span, ","),
141 let snippet = context.snippet(missing_span);
142 if snippet.trim_left().starts_with("//") {
143 let offset = snippet.lines().next().map_or(0, |l| l.len());
145 init_hi + BytePos(offset as u32 + 2)
146 } else if snippet.trim_left().starts_with("/*") {
147 let comment_lines = snippet
149 .position(|line| line.trim_right().ends_with("*/"))
154 .take(comment_lines + 1)
159 init_hi + BytePos(offset as u32 + 2)
164 let init_span = mk_sp(span.lo(), init_last_pos);
165 let one_line_width = if rest.is_empty() { one_line_width } else { 0 };
166 let result = try_opt!(rewrite_aligned_items_inner(
174 Some(result + spaces)
176 let rest_span = mk_sp(init_last_pos, span.hi());
177 let rest_str = try_opt!(rewrite_with_alignment(
185 result + spaces + "\n" +
188 .block_indent(context.config)
189 .to_string(context.config) + &rest_str,
194 fn struct_field_preix_max_min_width<T: AlignedItem>(
195 context: &RewriteContext,
198 ) -> (usize, usize) {
203 .rewrite_prefix(context, shape)
204 .and_then(|field_str| if field_str.contains('\n') {
207 Some(field_str.len())
210 .fold(Some((0, ::std::usize::MAX)), |acc, len| match (acc, len) {
211 (Some((max_len, min_len)), Some(len)) => {
212 Some((cmp::max(max_len, len), cmp::min(min_len, len)))
219 fn rewrite_aligned_items_inner<T: AlignedItem>(
220 context: &RewriteContext,
224 one_line_width: usize,
225 ) -> Option<String> {
226 let item_indent = offset.block_indent(context.config);
228 let item_shape = try_opt!(Shape::indented(item_indent, context.config).sub_width(1));
229 let (mut field_prefix_max_width, field_prefix_min_width) =
230 struct_field_preix_max_min_width(context, fields, item_shape);
231 let max_diff = field_prefix_max_width
232 .checked_sub(field_prefix_min_width)
234 if max_diff > context.config.struct_field_align_threshold() {
235 field_prefix_max_width = 0;
238 let items = itemize_list(
242 |field| field.get_span().lo(),
243 |field| field.get_span().hi(),
244 |field| field.rewrite_aligned_item(context, item_shape, field_prefix_max_width),
248 ).collect::<Vec<_>>();
250 let tactic = definitive_tactic(
252 ListTactic::HorizontalVertical,
257 let fmt = ListFormatting {
260 trailing_separator: context.config.trailing_comma(),
261 separator_place: SeparatorPlace::Back,
263 ends_with_newline: true,
264 preserve_newline: true,
265 config: context.config,
267 write_list(&items, &fmt)
270 fn group_aligned_items<T: AlignedItem>(
271 context: &RewriteContext,
273 ) -> (&'static str, usize) {
275 for i in 0..fields.len() - 1 {
276 if fields[i].skip() {
279 // See if there are comments or empty lines between fields.
280 let span = mk_sp(fields[i].get_span().hi(), fields[i + 1].get_span().lo());
281 let snippet = context
287 let spacings = if snippet.lines().rev().skip(1).any(|l| l.trim().is_empty()) {
292 if contains_comment(&snippet) || snippet.lines().count() > 1 {
293 return (spacings, index);