]> git.lizzy.rs Git - rust.git/blob - src/vertical.rs
Merge pull request #1968 from topecongiro/issue-1967
[rust.git] / src / vertical.rs
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.
4 //
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.
10
11 // Format with vertical alignment.
12
13 use std::cmp;
14
15 use syntax::ast;
16 use syntax::codemap::{BytePos, Span};
17
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,
24             SeparatorPlace};
25 use rewrite::{Rewrite, RewriteContext};
26 use utils::{contains_skip, is_attributes_extendable, mk_sp};
27
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(
33         &self,
34         context: &RewriteContext,
35         shape: Shape,
36         prefix_max_width: usize,
37     ) -> Option<String>;
38 }
39
40 impl AlignedItem for ast::StructField {
41     fn skip(&self) -> bool {
42         contains_skip(&self.attrs)
43     }
44
45     fn get_span(&self) -> Span {
46         self.span()
47     }
48
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())
53         } else {
54             mk_sp(self.attrs.last().unwrap().span.hi(), self.span.lo())
55         };
56         let attrs_extendable = context.config.attributes_on_same_line_as_field()
57             && is_attributes_extendable(&attrs_str);
58         rewrite_struct_field_prefix(context, self).and_then(|field_str| {
59             combine_strs_with_missing_comments(
60                 context,
61                 &attrs_str,
62                 &field_str,
63                 missing_span,
64                 shape,
65                 attrs_extendable,
66             )
67         })
68     }
69
70     fn rewrite_aligned_item(
71         &self,
72         context: &RewriteContext,
73         shape: Shape,
74         prefix_max_width: usize,
75     ) -> Option<String> {
76         rewrite_struct_field(context, self, shape, prefix_max_width)
77     }
78 }
79
80 impl AlignedItem for ast::Field {
81     fn skip(&self) -> bool {
82         contains_skip(&self.attrs)
83     }
84
85     fn get_span(&self) -> Span {
86         self.span()
87     }
88
89     fn rewrite_prefix(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
90         let attrs_str = try_opt!(self.attrs.rewrite(context, shape));
91         let name = &self.ident.node.to_string();
92         let missing_span = if self.attrs.is_empty() {
93             mk_sp(self.span.lo(), self.span.lo())
94         } else {
95             mk_sp(self.attrs.last().unwrap().span.hi(), self.span.lo())
96         };
97         combine_strs_with_missing_comments(
98             context,
99             &attrs_str,
100             name,
101             missing_span,
102             shape,
103             is_attributes_extendable(&attrs_str),
104         )
105     }
106
107     fn rewrite_aligned_item(
108         &self,
109         context: &RewriteContext,
110         shape: Shape,
111         prefix_max_width: usize,
112     ) -> Option<String> {
113         rewrite_field(context, self, shape, prefix_max_width)
114     }
115 }
116
117 pub fn rewrite_with_alignment<T: AlignedItem>(
118     fields: &[T],
119     context: &RewriteContext,
120     shape: Shape,
121     span: Span,
122     one_line_width: usize,
123 ) -> Option<String> {
124     let (spaces, group_index) = if context.config.struct_field_align_threshold() > 0 {
125         group_aligned_items(context, fields)
126     } else {
127         ("", fields.len() - 1)
128     };
129     let init = &fields[0..group_index + 1];
130     let rest = &fields[group_index + 1..];
131     let init_last_pos = if rest.is_empty() {
132         span.hi()
133     } else {
134         // Decide whether the missing comments should stick to init or rest.
135         let init_hi = init[init.len() - 1].get_span().hi();
136         let rest_lo = rest[0].get_span().lo();
137         let missing_span = mk_sp(init_hi, rest_lo);
138         let missing_span = mk_sp(
139             context.codemap.span_after(missing_span, ","),
140             missing_span.hi(),
141         );
142
143         let snippet = context.snippet(missing_span);
144         if snippet.trim_left().starts_with("//") {
145             let offset = snippet.lines().next().map_or(0, |l| l.len());
146             // 2 = "," + "\n"
147             init_hi + BytePos(offset as u32 + 2)
148         } else if snippet.trim_left().starts_with("/*") {
149             let comment_lines = snippet
150                 .lines()
151                 .position(|line| line.trim_right().ends_with("*/"))
152                 .unwrap_or(0);
153
154             let offset = snippet
155                 .lines()
156                 .take(comment_lines + 1)
157                 .collect::<Vec<_>>()
158                 .join("\n")
159                 .len();
160
161             init_hi + BytePos(offset as u32 + 2)
162         } else {
163             missing_span.lo()
164         }
165     };
166     let init_span = mk_sp(span.lo(), init_last_pos);
167     let one_line_width = if rest.is_empty() { one_line_width } else { 0 };
168     let result = try_opt!(rewrite_aligned_items_inner(
169         context,
170         init,
171         init_span,
172         shape.indent,
173         one_line_width,
174     ));
175     if rest.is_empty() {
176         Some(result + spaces)
177     } else {
178         let rest_span = mk_sp(init_last_pos, span.hi());
179         let rest_str = try_opt!(rewrite_with_alignment(
180             rest,
181             context,
182             shape,
183             rest_span,
184             one_line_width,
185         ));
186         Some(
187             result + spaces + "\n"
188                 + &shape
189                     .indent
190                     .block_indent(context.config)
191                     .to_string(context.config) + &rest_str,
192         )
193     }
194 }
195
196 fn struct_field_preix_max_min_width<T: AlignedItem>(
197     context: &RewriteContext,
198     fields: &[T],
199     shape: Shape,
200 ) -> (usize, usize) {
201     fields
202         .iter()
203         .map(|field| {
204             field
205                 .rewrite_prefix(context, shape)
206                 .and_then(|field_str| if field_str.contains('\n') {
207                     None
208                 } else {
209                     Some(field_str.len())
210                 })
211         })
212         .fold(Some((0, ::std::usize::MAX)), |acc, len| match (acc, len) {
213             (Some((max_len, min_len)), Some(len)) => {
214                 Some((cmp::max(max_len, len), cmp::min(min_len, len)))
215             }
216             _ => None,
217         })
218         .unwrap_or((0, 0))
219 }
220
221 fn rewrite_aligned_items_inner<T: AlignedItem>(
222     context: &RewriteContext,
223     fields: &[T],
224     span: Span,
225     offset: Indent,
226     one_line_width: usize,
227 ) -> Option<String> {
228     let item_indent = offset.block_indent(context.config);
229     // 1 = ","
230     let item_shape = try_opt!(Shape::indented(item_indent, context.config).sub_width(1));
231     let (mut field_prefix_max_width, field_prefix_min_width) =
232         struct_field_preix_max_min_width(context, fields, item_shape);
233     let max_diff = field_prefix_max_width
234         .checked_sub(field_prefix_min_width)
235         .unwrap_or(0);
236     if max_diff > context.config.struct_field_align_threshold() {
237         field_prefix_max_width = 0;
238     }
239
240     let items = itemize_list(
241         context.codemap,
242         fields.iter(),
243         "}",
244         |field| field.get_span().lo(),
245         |field| field.get_span().hi(),
246         |field| field.rewrite_aligned_item(context, item_shape, field_prefix_max_width),
247         span.lo(),
248         span.hi(),
249         false,
250     ).collect::<Vec<_>>();
251
252     let tactic = definitive_tactic(
253         &items,
254         ListTactic::HorizontalVertical,
255         Separator::Comma,
256         one_line_width,
257     );
258
259     let fmt = ListFormatting {
260         tactic: tactic,
261         separator: ",",
262         trailing_separator: context.config.trailing_comma(),
263         separator_place: SeparatorPlace::Back,
264         shape: item_shape,
265         ends_with_newline: true,
266         preserve_newline: true,
267         config: context.config,
268     };
269     write_list(&items, &fmt)
270 }
271
272 fn group_aligned_items<T: AlignedItem>(
273     context: &RewriteContext,
274     fields: &[T],
275 ) -> (&'static str, usize) {
276     let mut index = 0;
277     for i in 0..fields.len() - 1 {
278         if fields[i].skip() {
279             return ("", index);
280         }
281         // See if there are comments or empty lines between fields.
282         let span = mk_sp(fields[i].get_span().hi(), fields[i + 1].get_span().lo());
283         let snippet = context
284             .snippet(span)
285             .lines()
286             .skip(1)
287             .collect::<Vec<_>>()
288             .join("\n");
289         let spacings = if snippet.lines().rev().skip(1).any(|l| l.trim().is_empty()) {
290             "\n"
291         } else {
292             ""
293         };
294         if contains_comment(&snippet) || snippet.lines().count() > 1 {
295             return (spacings, index);
296         }
297         index += 1;
298     }
299     ("", index)
300 }