-
Notifications
You must be signed in to change notification settings - Fork 888
/
items.rs
3323 lines (3027 loc) · 111 KB
/
items.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Formatting top-level items - functions, structs, enums, traits, impls.
use std::borrow::Cow;
use std::cmp::{max, min, Ordering};
use regex::Regex;
use rustc_ast::visit;
use rustc_ast::{ast, ptr};
use rustc_span::{source_map, symbol, BytePos, Span, DUMMY_SP};
use crate::config::lists::*;
use crate::config::{BraceStyle, Config, IndentStyle};
use crate::formatting::{
attr::filter_inline_attrs,
comment::{
combine_strs_with_missing_comments, contains_comment, is_last_comment_block,
recover_comment_removed, recover_missing_comment_in_span, rewrite_missing_comment,
FindUncommented,
},
expr::{
is_empty_block, is_simple_block_stmt, rewrite_assign_rhs, rewrite_assign_rhs_expr,
rewrite_assign_rhs_with, RhsTactics,
},
lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator},
macros::{rewrite_macro, MacroPosition},
overflow,
reorder::compare_as_versions,
rewrite::{Rewrite, RewriteContext},
shape::{Indent, Shape},
source_map::{LineRangeUtils, SpanUtils},
spanned::Spanned,
stmt::Stmt,
utils::*,
vertical::rewrite_with_alignment,
visitor::FmtVisitor,
};
const DEFAULT_VISIBILITY: ast::Visibility = source_map::Spanned {
node: ast::VisibilityKind::Inherited,
span: DUMMY_SP,
};
fn type_annotation_separator(config: &Config) -> &str {
colon_spaces(config)
}
// Statements of the form
// let pat: ty = init;
impl Rewrite for ast::Local {
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
debug!(
"Local::rewrite {:?} {} {:?}",
self, shape.width, shape.indent
);
skip_out_of_file_lines_range!(context, self.span);
if contains_skip(&self.attrs) {
return None;
}
let attrs_str = self.attrs.rewrite(context, shape)?;
let mut result = if attrs_str.is_empty() {
"let ".to_owned()
} else {
combine_strs_with_missing_comments(
context,
&attrs_str,
"let ",
mk_sp(
self.attrs.last().map(|a| a.span.hi()).unwrap(),
self.span.lo(),
),
shape,
false,
)?
};
// 4 = "let ".len()
let pat_shape = shape.offset_left(4)?;
// 1 = ;
let pat_shape = pat_shape.sub_width(1)?;
let pat_str = self.pat.rewrite(context, pat_shape)?;
result.push_str(&pat_str);
// String that is placed within the assignment pattern and expression.
let infix = {
let mut infix = String::with_capacity(32);
if let Some(ref ty) = self.ty {
let separator = type_annotation_separator(context.config);
let ty_shape = if pat_str.contains('\n') {
shape.with_max_width(context.config)
} else {
shape
}
.offset_left(last_line_width(&result) + separator.len())?
// 2 = ` =`
.sub_width(2)?;
let rewrite = ty.rewrite(context, ty_shape)?;
infix.push_str(separator);
infix.push_str(&rewrite);
}
if self.init.is_some() {
infix.push_str(" =");
}
infix
};
result.push_str(&infix);
if let Some(ref ex) = self.init {
let base_span = if let Some(ref ty) = self.ty {
mk_sp(ty.span.hi(), self.span.hi())
} else {
mk_sp(self.pat.span.hi(), self.span.hi())
};
if let Some(offset) = context.snippet(base_span).find_uncommented("=") {
let base_span_lo = base_span.lo();
let assign_lo = base_span_lo + BytePos(offset as u32);
let comment_start_pos = if let Some(ref ty) = self.ty {
ty.span.hi()
} else {
self.pat.span.hi()
};
let comment_before_assign =
context.snippet(mk_sp(comment_start_pos, assign_lo)).trim();
let assign_hi = base_span_lo + BytePos((offset + 1) as u32);
let rhs_span_lo = ex.span.lo();
let comment_end_pos = if ex.attrs.is_empty() {
rhs_span_lo
} else {
let attr_span_lo = ex.attrs.first().unwrap().span.lo();
// for the case using block
// ex. let x = { #![my_attr]do_something(); }
if rhs_span_lo < attr_span_lo {
rhs_span_lo
} else {
attr_span_lo
}
};
let comment_after_assign =
context.snippet(mk_sp(assign_hi, comment_end_pos)).trim();
if !comment_before_assign.is_empty() {
let new_indent_str = &pat_shape
.block_indent(0)
.to_string_with_newline(context.config);
result = format!("{}{}{}", comment_before_assign, new_indent_str, result);
}
if !comment_after_assign.is_empty() {
let new_indent_str =
&shape.block_indent(0).to_string_with_newline(context.config);
result.push_str(new_indent_str);
result.push_str(comment_after_assign);
result.push_str(new_indent_str);
}
}
// 1 = trailing semicolon;
let nested_shape = shape.sub_width(1)?;
let rhs = rewrite_assign_rhs_expr(
context,
&result,
&**ex,
nested_shape,
RhsTactics::Default,
)?;
result = result + &rhs;
}
result.push(';');
Some(result)
}
}
// FIXME convert to using rewrite style rather than visitor
// FIXME format modules in this style
#[allow(dead_code)]
#[derive(Debug)]
struct Item<'a> {
keyword: &'static str,
abi: Cow<'static, str>,
vis: Option<&'a ast::Visibility>,
body: Vec<BodyElement<'a>>,
span: Span,
}
impl<'a> Item<'a> {
fn from_foreign_mod(
fm: &'a ast::ForeignMod,
span: Span,
config: &Config,
attrs: &[ast::Attribute],
) -> Item<'a> {
Item {
keyword: "",
abi: format_extern(
ast::Extern::from_abi(fm.abi),
config.force_explicit_abi(),
true,
Some(attrs),
),
vis: None,
body: fm
.items
.iter()
.map(|i| BodyElement::ForeignItem(i))
.collect(),
span,
}
}
}
#[derive(Debug)]
enum BodyElement<'a> {
// Stmt(&'a ast::Stmt),
// Field(&'a ast::Field),
// Variant(&'a ast::Variant),
// Item(&'a ast::Item),
ForeignItem(&'a ast::ForeignItem),
}
impl BodyElement<'_> {
pub(crate) fn span(&self) -> Span {
match self {
BodyElement::ForeignItem(fi) => fi.span(),
}
}
}
/// Represents a fn's signature.
pub(crate) struct FnSig<'a> {
decl: &'a ast::FnDecl,
generics: &'a ast::Generics,
ext: ast::Extern,
is_async: Cow<'a, ast::Async>,
constness: ast::Const,
defaultness: ast::Defaultness,
unsafety: ast::Unsafe,
visibility: ast::Visibility,
}
impl<'a> FnSig<'a> {
pub(crate) fn from_method_sig(
method_sig: &'a ast::FnSig,
generics: &'a ast::Generics,
visibility: ast::Visibility,
) -> FnSig<'a> {
FnSig {
unsafety: method_sig.header.unsafety,
is_async: Cow::Borrowed(&method_sig.header.asyncness),
constness: method_sig.header.constness,
defaultness: ast::Defaultness::Final,
ext: method_sig.header.ext,
decl: &*method_sig.decl,
generics,
visibility,
}
}
pub(crate) fn from_fn_kind(
fn_kind: &'a visit::FnKind<'_>,
generics: &'a ast::Generics,
decl: &'a ast::FnDecl,
defaultness: ast::Defaultness,
) -> FnSig<'a> {
match *fn_kind {
visit::FnKind::Fn(fn_ctxt, _, fn_sig, vis, _) => match fn_ctxt {
visit::FnCtxt::Assoc(..) => {
let mut fn_sig = FnSig::from_method_sig(fn_sig, generics, vis.clone());
fn_sig.defaultness = defaultness;
fn_sig
}
_ => FnSig {
decl,
generics,
ext: fn_sig.header.ext,
constness: fn_sig.header.constness,
is_async: Cow::Borrowed(&fn_sig.header.asyncness),
defaultness,
unsafety: fn_sig.header.unsafety,
visibility: vis.clone(),
},
},
_ => unreachable!(),
}
}
fn to_str(&self, context: &RewriteContext<'_>) -> String {
let mut result = String::with_capacity(128);
// Vis defaultness constness unsafety abi.
result.push_str(&*format_visibility(context, &self.visibility));
result.push_str(format_defaultness(self.defaultness));
result.push_str(format_constness(self.constness));
result.push_str(format_async(*self.is_async));
result.push_str(format_unsafety(self.unsafety));
result.push_str(&format_extern(
self.ext,
context.config.force_explicit_abi(),
false,
None,
));
result
}
}
impl<'a> FmtVisitor<'a> {
fn format_item(&mut self, item: &Item<'_>) {
self.buffer.push_str(&item.abi);
let snippet = self.snippet(item.span);
let brace_pos = snippet.find_uncommented("{").unwrap();
self.push_str("{");
if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
// FIXME: this skips comments between the extern keyword and the opening
// brace.
self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
self.block_indent = self.block_indent.block_indent(self.config);
if item.body.is_empty() {
self.format_missing_no_indent(item.span.hi() - BytePos(1));
self.block_indent = self.block_indent.block_unindent(self.config);
let indent_str = self.block_indent.to_string(self.config);
self.push_str(&indent_str);
} else {
let first_non_ws = item.body.first().map(|s| s.span().lo());
if let Some(opening_nls) = self.advance_to_first_block_item(first_non_ws) {
self.push_str(&opening_nls);
}
for item in &item.body {
self.format_body_element(item);
}
self.block_indent = self.block_indent.block_unindent(self.config);
self.format_missing_with_indent(item.span.hi() - BytePos(1));
}
}
self.push_str("}");
self.last_pos = item.span.hi();
}
fn format_body_element(&mut self, element: &BodyElement<'_>) {
match *element {
BodyElement::ForeignItem(item) => self.format_foreign_item(item),
}
}
pub(crate) fn format_foreign_mod(
&mut self,
fm: &ast::ForeignMod,
span: Span,
attrs: &[ast::Attribute],
) {
let item = Item::from_foreign_mod(fm, span, self.config, attrs);
self.format_item(&item);
}
fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
let rewrite = item.rewrite(&self.get_context(), self.shape());
let hi = item.span.hi();
let span = if item.attrs.is_empty() {
item.span
} else {
mk_sp(item.attrs[0].span.lo(), hi)
};
self.push_rewrite(span, rewrite);
self.last_pos = hi;
}
pub(crate) fn rewrite_fn_before_block(
&mut self,
indent: Indent,
ident: symbol::Ident,
fn_sig: &FnSig<'_>,
span: Span,
) -> Option<(String, FnBraceStyle)> {
let context = self.get_context();
let mut fn_brace_style = newline_for_brace(self.config, &fn_sig.generics.where_clause);
let (result, force_newline_brace) =
rewrite_fn_base(&context, indent, ident, fn_sig, span, fn_brace_style)?;
// 2 = ` {`
if self.config.brace_style() == BraceStyle::AlwaysNextLine
|| force_newline_brace
|| last_line_width(&result) + 2 > self.shape().width
{
fn_brace_style = FnBraceStyle::NextLine
}
Some((result, fn_brace_style))
}
pub(crate) fn rewrite_required_fn(
&mut self,
indent: Indent,
ident: symbol::Ident,
sig: &ast::FnSig,
generics: &ast::Generics,
span: Span,
) -> Option<String> {
// Drop semicolon or it will be interpreted as comment.
let span = mk_sp(span.lo(), span.hi() - BytePos(1));
let context = self.get_context();
let (mut result, _) = rewrite_fn_base(
&context,
indent,
ident,
&FnSig::from_method_sig(sig, generics, DEFAULT_VISIBILITY),
span,
FnBraceStyle::None,
)?;
// Re-attach semicolon
result.push(';');
Some(result)
}
pub(crate) fn single_line_fn(
&self,
fn_str: &str,
block: &ast::Block,
inner_attrs: Option<&[ast::Attribute]>,
) -> Option<String> {
if fn_str.contains('\n') || inner_attrs.map_or(false, |a| !a.is_empty()) {
return None;
}
let context = self.get_context();
if self.config.empty_item_single_line()
&& is_empty_block(&context, block, None)
&& self.block_indent.width() + fn_str.len() + 3 <= self.config.max_width()
&& !last_line_contains_single_line_comment(fn_str)
{
return Some(format!("{} {{}}", fn_str));
}
if !self.config.fn_single_line() || !is_simple_block_stmt(&context, block, None) {
return None;
}
let res = Stmt::from_ast_node(block.stmts.first()?, true)
.rewrite(&self.get_context(), self.shape())?;
let width = self.block_indent.width() + fn_str.len() + res.len() + 5;
if !res.contains('\n') && width <= self.config.max_width() {
Some(format!("{} {{ {} }}", fn_str, res))
} else {
None
}
}
pub(crate) fn visit_static(&mut self, static_parts: &StaticParts<'_>) {
let rewrite = rewrite_static(&self.get_context(), static_parts, self.block_indent);
self.push_rewrite(static_parts.span, rewrite);
}
pub(crate) fn visit_struct(&mut self, struct_parts: &StructParts<'_>) {
let is_tuple = matches!(struct_parts.def, ast::VariantData::Tuple(..));
let rewrite = format_struct(&self.get_context(), struct_parts, self.block_indent, None)
.map(|s| if is_tuple { s + ";" } else { s });
self.push_rewrite(struct_parts.span, rewrite);
}
pub(crate) fn visit_enum(
&mut self,
ident: symbol::Ident,
vis: &ast::Visibility,
enum_def: &ast::EnumDef,
generics: &ast::Generics,
span: Span,
) {
let enum_header =
format_header(&self.get_context(), "enum ", ident, vis, self.block_indent);
self.push_str(&enum_header);
let enum_snippet = self.snippet(span);
let brace_pos = enum_snippet.find_uncommented("{").unwrap();
let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
let generics_str = format_generics(
&self.get_context(),
generics,
self.config.brace_style(),
if enum_def.variants.is_empty() {
BracePos::ForceSameLine
} else {
BracePos::Auto
},
self.block_indent,
// make a span that starts right after `enum Foo`
mk_sp(ident.span.hi(), body_start),
last_line_width(&enum_header),
)
.unwrap();
self.push_str(&generics_str);
self.last_pos = body_start;
match self.format_variant_list(enum_def, body_start, span.hi()) {
Some(ref s) if enum_def.variants.is_empty() => self.push_str(s),
rw => {
self.push_rewrite(mk_sp(body_start, span.hi()), rw);
self.block_indent = self.block_indent.block_unindent(self.config);
}
}
}
// Format the body of an enum definition
fn format_variant_list(
&mut self,
enum_def: &ast::EnumDef,
body_lo: BytePos,
body_hi: BytePos,
) -> Option<String> {
if enum_def.variants.is_empty() {
let mut buffer = String::with_capacity(128);
// 1 = "}"
let span = mk_sp(body_lo, body_hi - BytePos(1));
format_empty_struct_or_tuple(
&self.get_context(),
span,
self.block_indent,
&mut buffer,
"",
"}",
);
return Some(buffer);
}
let mut result = String::with_capacity(1024);
let original_offset = self.block_indent;
self.block_indent = self.block_indent.block_indent(self.config);
// If enum variants have discriminants, try to vertically align those,
// provided the discrims are not shifted too much to the right
let align_threshold: usize = self.config.enum_discrim_align_threshold();
let discr_ident_lens: Vec<usize> = enum_def
.variants
.iter()
.filter(|var| var.disr_expr.is_some())
.map(|var| rewrite_ident(&self.get_context(), var.ident).len())
.collect();
// cut the list at the point of longest discrim shorter than the threshold
// All of the discrims under the threshold will get padded, and all above - left as is.
let pad_discrim_ident_to = *discr_ident_lens
.iter()
.filter(|&l| *l <= align_threshold)
.max()
.unwrap_or(&0);
let itemize_list_with = |one_line_width: usize| {
itemize_list(
self.snippet_provider,
enum_def.variants.iter(),
"}",
",",
|f| {
if !f.attrs.is_empty() {
f.attrs[0].span.lo()
} else {
f.span.lo()
}
},
|f| f.span.hi(),
|f| self.format_variant(f, one_line_width, pad_discrim_ident_to),
body_lo,
body_hi,
false,
)
.collect()
};
let mut items: Vec<_> = itemize_list_with(self.config.struct_variant_width());
// If one of the variants use multiple lines, use multi-lined formatting for all variants.
let has_multiline_variant = items.iter().any(|item| item.inner_as_ref().contains('\n'));
let has_single_line_variant = items.iter().any(|item| !item.inner_as_ref().contains('\n'));
if has_multiline_variant && has_single_line_variant {
items = itemize_list_with(0);
}
let shape = self.shape().sub_width(2)?;
let fmt = ListFormatting::new(shape, self.config)
.trailing_separator(self.config.trailing_comma())
.preserve_newline(true);
let list = write_list(&items, &fmt)?;
result.push_str(&list);
result.push_str(&original_offset.to_string_with_newline(self.config));
result.push('}');
Some(result)
}
// Variant of an enum.
fn format_variant(
&self,
field: &ast::Variant,
one_line_width: usize,
pad_discrim_ident_to: usize,
) -> Option<String> {
if contains_skip(&field.attrs) {
let lo = field.attrs[0].span.lo();
let span = mk_sp(lo, field.span.hi());
return Some(self.snippet(span).to_owned());
}
let context = self.get_context();
// 1 = ','
let shape = self.shape().sub_width(1)?;
let attrs_str = field.attrs.rewrite(&context, shape)?;
let lo = field
.attrs
.last()
.map_or(field.span.lo(), |attr| attr.span.hi());
let span = mk_sp(lo, field.span.lo());
let variant_body = match field.data {
ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => format_struct(
&context,
&StructParts::from_variant(field),
self.block_indent,
Some(one_line_width),
)?,
ast::VariantData::Unit(..) => rewrite_ident(&context, field.ident).to_owned(),
};
let variant_body = if let Some(ref expr) = field.disr_expr {
let lhs = format!("{:1$} =", variant_body, pad_discrim_ident_to);
rewrite_assign_rhs_with(
&context,
lhs,
&*expr.value,
shape,
RhsTactics::AllowOverflow,
)?
} else {
variant_body
};
combine_strs_with_missing_comments(&context, &attrs_str, &variant_body, span, shape, false)
}
fn visit_impl_items(&mut self, items: &[ptr::P<ast::AssocItem>]) {
if self.get_context().config.reorder_impl_items() {
// Create visitor for each items, then reorder them.
let mut buffer = vec![];
for item in items {
self.visit_impl_item(item);
buffer.push((self.buffer.clone(), item.clone()));
self.buffer.clear();
}
fn is_type(ty: &Option<rustc_ast::ptr::P<ast::Ty>>) -> bool {
if let Some(lty) = ty {
if let ast::TyKind::ImplTrait(..) = lty.kind {
return false;
}
}
true
}
fn is_opaque(ty: &Option<rustc_ast::ptr::P<ast::Ty>>) -> bool {
!is_type(ty)
}
fn both_type(
a: &Option<rustc_ast::ptr::P<ast::Ty>>,
b: &Option<rustc_ast::ptr::P<ast::Ty>>,
) -> bool {
is_type(a) && is_type(b)
}
fn both_opaque(
a: &Option<rustc_ast::ptr::P<ast::Ty>>,
b: &Option<rustc_ast::ptr::P<ast::Ty>>,
) -> bool {
is_opaque(a) && is_opaque(b)
}
// In rustc-ap-v638 the `OpaqueTy` AssocItemKind was removed but
// we still need to differentiate to maintain sorting order.
// type -> opaque -> const -> macro -> method
use ast::AssocItemKind::*;
fn need_empty_line(a: &ast::AssocItemKind, b: &ast::AssocItemKind) -> bool {
match (a, b) {
(TyAlias(_, _, _, ref lty), TyAlias(_, _, _, ref rty))
if both_type(lty, rty) || both_opaque(lty, rty) =>
{
false
}
(Const(..), Const(..)) => false,
_ => true,
}
}
buffer.sort_by(|(_, a), (_, b)| match (&a.kind, &b.kind) {
(TyAlias(_, _, _, ref lty), TyAlias(_, _, _, ref rty))
if both_type(lty, rty) || both_opaque(lty, rty) =>
{
compare_as_versions(&a.ident.as_str(), &b.ident.as_str())
}
(Const(..), Const(..)) | (MacCall(..), MacCall(..)) => {
compare_as_versions(&a.ident.as_str(), &b.ident.as_str())
}
(Fn(..), Fn(..)) => a.span.lo().cmp(&b.span.lo()),
(TyAlias(_, _, _, ref ty), _) if is_type(ty) => Ordering::Less,
(_, TyAlias(_, _, _, ref ty)) if is_type(ty) => Ordering::Greater,
(TyAlias(..), _) => Ordering::Less,
(_, TyAlias(..)) => Ordering::Greater,
(Const(..), _) => Ordering::Less,
(_, Const(..)) => Ordering::Greater,
(MacCall(..), _) => Ordering::Less,
(_, MacCall(..)) => Ordering::Greater,
});
let mut prev_kind = None;
for (buf, item) in buffer {
// Make sure that there are at least a single empty line between
// different impl items.
if prev_kind
.as_ref()
.map_or(false, |prev_kind| need_empty_line(prev_kind, &item.kind))
{
self.push_str("\n");
}
let indent_str = self.block_indent.to_string_with_newline(self.config);
self.push_str(&indent_str);
self.push_str(buf.trim());
prev_kind = Some(item.kind.clone());
}
} else {
for item in items {
self.visit_impl_item(item);
}
}
}
}
pub(crate) fn format_impl(
context: &RewriteContext<'_>,
item: &ast::Item,
offset: Indent,
) -> Option<String> {
if let ast::ItemKind::Impl {
ref generics,
ref self_ty,
ref items,
..
} = item.kind
{
let mut result = String::with_capacity(128);
let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
let sep = offset.to_string_with_newline(context.config);
result.push_str(&ref_and_type);
let where_budget = if result.contains('\n') {
context.config.max_width()
} else {
context.budget(last_line_width(&result))
};
let mut option = WhereClauseOption::snuggled(&ref_and_type);
let snippet = context.snippet(item.span);
let open_pos = snippet.find_uncommented("{")? + 1;
if !contains_comment(&snippet[open_pos..])
&& items.is_empty()
&& generics.where_clause.predicates.len() == 1
&& !result.contains('\n')
{
option.suppress_comma();
option.snuggle();
option.allow_single_line();
}
let missing_span = mk_sp(self_ty.span.hi(), item.span.hi());
let where_span_end = context.snippet_provider.opt_span_before(missing_span, "{");
let where_clause_str = rewrite_where_clause(
context,
&generics.where_clause,
context.config.brace_style(),
Shape::legacy(where_budget, offset.block_only()),
false,
"{",
where_span_end,
self_ty.span.hi(),
option,
)?;
// If there is no where-clause, we may have missing comments between the trait name and
// the opening brace.
if generics.where_clause.predicates.is_empty() {
if let Some(hi) = where_span_end {
match recover_missing_comment_in_span(
mk_sp(self_ty.span.hi(), hi),
Shape::indented(offset, context.config),
context,
last_line_width(&result),
) {
Some(ref missing_comment) if !missing_comment.is_empty() => {
result.push_str(missing_comment);
}
_ => {}
}
}
}
if is_impl_single_line(context, items.as_slice(), &result, &where_clause_str, item)? {
result.push_str(&where_clause_str);
if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
// if the where_clause contains extra comments AND
// there is only one where-clause predicate
// recover the suppressed comma in single line where_clause formatting
if generics.where_clause.predicates.len() == 1 {
result.push_str(",");
}
result.push_str(&format!("{}{{{}}}", sep, sep));
} else {
result.push_str(" {}");
}
return Some(result);
}
result.push_str(&where_clause_str);
let need_newline = last_line_contains_single_line_comment(&result) || result.contains('\n');
match context.config.brace_style() {
_ if need_newline => result.push_str(&sep),
BraceStyle::AlwaysNextLine => result.push_str(&sep),
BraceStyle::PreferSameLine => result.push(' '),
BraceStyle::SameLineWhere => {
if !where_clause_str.is_empty() {
result.push_str(&sep);
} else {
result.push(' ');
}
}
}
result.push('{');
// this is an impl body snippet(impl SampleImpl { /* here */ })
let lo = max(self_ty.span.hi(), generics.where_clause.span.hi());
let snippet = context.snippet(mk_sp(lo, item.span.hi()));
let open_pos = snippet.find_uncommented("{")? + 1;
if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
let mut visitor = FmtVisitor::from_context(context);
let item_indent = offset.block_only().block_indent(context.config);
visitor.block_indent = item_indent;
visitor.last_pos = lo + BytePos(open_pos as u32);
let first_non_ws = inner_attributes(&item.attrs)
.first()
.map(|a| a.span.lo())
.or_else(|| items.first().map(|i| i.span().lo()));
if let Some(opening_nls) = visitor.advance_to_first_block_item(first_non_ws) {
result.push_str(&opening_nls);
}
visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
visitor.visit_impl_items(items);
visitor.format_missing(item.span.hi() - BytePos(1));
let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
result.push_str(&inner_indent_str);
result.push_str(visitor.buffer.trim());
result.push_str(&outer_indent_str);
} else if need_newline || !context.config.empty_item_single_line() {
result.push_str(&sep);
}
result.push('}');
Some(result)
} else {
unreachable!();
}
}
fn is_impl_single_line(
context: &RewriteContext<'_>,
items: &[ptr::P<ast::AssocItem>],
result: &str,
where_clause_str: &str,
item: &ast::Item,
) -> Option<bool> {
let snippet = context.snippet(item.span);
let open_pos = snippet.find_uncommented("{")? + 1;
Some(
context.config.empty_item_single_line()
&& items.is_empty()
&& !result.contains('\n')
&& result.len() + where_clause_str.len() <= context.config.max_width()
&& !contains_comment(&snippet[open_pos..]),
)
}
fn format_impl_ref_and_type(
context: &RewriteContext<'_>,
item: &ast::Item,
offset: Indent,
) -> Option<String> {
if let ast::ItemKind::Impl {
unsafety,
polarity,
defaultness,
constness,
ref generics,
of_trait: ref trait_ref,
ref self_ty,
..
} = item.kind
{
let mut result = String::with_capacity(128);
result.push_str(&format_visibility(context, &item.vis));
result.push_str(format_defaultness(defaultness));
result.push_str(format_unsafety(unsafety));
let shape = Shape::indented(offset + last_line_width(&result), context.config);
let generics_str = rewrite_generics(context, "impl", generics, shape)?;
result.push_str(&generics_str);
result.push_str(format_constness_right(constness));
let polarity_str = match polarity {
ast::ImplPolarity::Negative(_) => "!",
ast::ImplPolarity::Positive => "",
};
if let Some(ref trait_ref) = *trait_ref {
let result_len = last_line_width(&result);
result.push_str(&rewrite_trait_ref(
context,
trait_ref,
offset,
polarity_str,
result_len,
)?);
}
// Try to put the self type in a single line.
// ` for`
let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
// If there is no where-clause adapt budget for type formatting to take space and curly
// brace into account.
match context.config.brace_style() {
BraceStyle::AlwaysNextLine => 0,
_ => 2,
}
} else {
0
};
let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
// 1 = space before the type.
let budget = context.budget(used_space + 1);
if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
if !self_ty_str.contains('\n') {
if trait_ref.is_some() {
result.push_str(" for ");
} else {
result.push(' ');
}
result.push_str(&self_ty_str);
return Some(result);
}
}
// Couldn't fit the self type on a single line, put it on a new line.
result.push('\n');
// Add indentation of one additional tab.
let new_line_offset = offset.block_indent(context.config);
result.push_str(&new_line_offset.to_string(context.config));
if trait_ref.is_some() {
result.push_str("for ");
}
let budget = context.budget(last_line_width(&result));
let type_offset = match context.config.indent_style() {
IndentStyle::Visual => new_line_offset + trait_ref_overhead,
IndentStyle::Block => new_line_offset,
};
result.push_str(&*self_ty.rewrite(context, Shape::legacy(budget, type_offset))?);
Some(result)
} else {