-
Notifications
You must be signed in to change notification settings - Fork 888
/
comment.rs
2007 lines (1834 loc) · 69.4 KB
/
comment.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 and tools for comments.
use std::{self, borrow::Cow, iter};
use itertools::{multipeek, MultiPeek};
use lazy_static::lazy_static;
use regex::Regex;
use rustc_span::Span;
use crate::config::Config;
use crate::rewrite::RewriteContext;
use crate::shape::{Indent, Shape};
use crate::string::{rewrite_string, StringFormat};
use crate::utils::{
count_newlines, first_line_width, last_line_width, trim_left_preserve_layout,
trimmed_last_line_width, unicode_str_width,
};
use crate::{ErrorKind, FormattingError};
lazy_static! {
/// A regex matching reference doc links.
///
/// ```markdown
/// /// An [example].
/// ///
/// /// [example]: this::is::a::link
/// ```
static ref REFERENCE_LINK_URL: Regex = Regex::new(r"^\[.+\]\s?:").unwrap();
}
fn is_custom_comment(comment: &str) -> bool {
if !comment.starts_with("//") {
false
} else if let Some(c) = comment.chars().nth(2) {
!c.is_alphanumeric() && !c.is_whitespace()
} else {
false
}
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub(crate) enum CommentStyle<'a> {
DoubleSlash,
TripleSlash,
Doc,
SingleBullet,
DoubleBullet,
Exclamation,
Custom(&'a str),
}
fn custom_opener(s: &str) -> &str {
s.lines().next().map_or("", |first_line| {
first_line
.find(' ')
.map_or(first_line, |space_index| &first_line[0..=space_index])
})
}
impl<'a> CommentStyle<'a> {
/// Returns `true` if the commenting style covers a line only.
pub(crate) fn is_line_comment(&self) -> bool {
match *self {
CommentStyle::DoubleSlash
| CommentStyle::TripleSlash
| CommentStyle::Doc
| CommentStyle::Custom(_) => true,
_ => false,
}
}
/// Returns `true` if the commenting style can span over multiple lines.
pub(crate) fn is_block_comment(&self) -> bool {
match *self {
CommentStyle::SingleBullet | CommentStyle::DoubleBullet | CommentStyle::Exclamation => {
true
}
_ => false,
}
}
/// Returns `true` if the commenting style is for documentation.
pub(crate) fn is_doc_comment(&self) -> bool {
matches!(*self, CommentStyle::TripleSlash | CommentStyle::Doc)
}
pub(crate) fn opener(&self) -> &'a str {
match *self {
CommentStyle::DoubleSlash => "// ",
CommentStyle::TripleSlash => "/// ",
CommentStyle::Doc => "//! ",
CommentStyle::SingleBullet => "/* ",
CommentStyle::DoubleBullet => "/** ",
CommentStyle::Exclamation => "/*! ",
CommentStyle::Custom(opener) => opener,
}
}
pub(crate) fn closer(&self) -> &'a str {
match *self {
CommentStyle::DoubleSlash
| CommentStyle::TripleSlash
| CommentStyle::Custom(..)
| CommentStyle::Doc => "",
CommentStyle::SingleBullet | CommentStyle::DoubleBullet | CommentStyle::Exclamation => {
" */"
}
}
}
pub(crate) fn line_start(&self) -> &'a str {
match *self {
CommentStyle::DoubleSlash => "// ",
CommentStyle::TripleSlash => "/// ",
CommentStyle::Doc => "//! ",
CommentStyle::SingleBullet | CommentStyle::DoubleBullet | CommentStyle::Exclamation => {
" * "
}
CommentStyle::Custom(opener) => opener,
}
}
pub(crate) fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) {
(self.opener(), self.closer(), self.line_start())
}
}
pub(crate) fn comment_style(orig: &str, normalize_comments: bool) -> CommentStyle<'_> {
if !normalize_comments {
if orig.starts_with("/**") && !orig.starts_with("/**/") {
CommentStyle::DoubleBullet
} else if orig.starts_with("/*!") {
CommentStyle::Exclamation
} else if orig.starts_with("/*") {
CommentStyle::SingleBullet
} else if orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/') {
CommentStyle::TripleSlash
} else if orig.starts_with("//!") {
CommentStyle::Doc
} else if is_custom_comment(orig) {
CommentStyle::Custom(custom_opener(orig))
} else {
CommentStyle::DoubleSlash
}
} else if (orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/'))
|| (orig.starts_with("/**") && !orig.starts_with("/**/"))
{
CommentStyle::TripleSlash
} else if orig.starts_with("//!") || orig.starts_with("/*!") {
CommentStyle::Doc
} else if is_custom_comment(orig) {
CommentStyle::Custom(custom_opener(orig))
} else {
CommentStyle::DoubleSlash
}
}
/// Returns true if the last line of the passed string finishes with a block-comment.
pub(crate) fn is_last_comment_block(s: &str) -> bool {
s.trim_end().ends_with("*/")
}
/// Combine `prev_str` and `next_str` into a single `String`. `span` may contain
/// comments between two strings. If there are such comments, then that will be
/// recovered. If `allow_extend` is true and there is no comment between the two
/// strings, then they will be put on a single line as long as doing so does not
/// exceed max width.
pub(crate) fn combine_strs_with_missing_comments(
context: &RewriteContext<'_>,
prev_str: &str,
next_str: &str,
span: Span,
shape: Shape,
allow_extend: bool,
) -> Option<String> {
trace!(
"combine_strs_with_missing_comments `{}` `{}` {:?} {:?}",
prev_str,
next_str,
span,
shape
);
let mut result =
String::with_capacity(prev_str.len() + next_str.len() + shape.indent.width() + 128);
result.push_str(prev_str);
let mut allow_one_line = !prev_str.contains('\n') && !next_str.contains('\n');
let first_sep =
if prev_str.is_empty() || next_str.is_empty() || trimmed_last_line_width(prev_str) == 0 {
""
} else {
" "
};
let mut one_line_width =
last_line_width(prev_str) + first_line_width(next_str) + first_sep.len();
let config = context.config;
let indent = shape.indent;
let missing_comment = rewrite_missing_comment(span, shape, context)?;
if missing_comment.is_empty() {
if allow_extend && one_line_width <= shape.width {
result.push_str(first_sep);
} else if !prev_str.is_empty() {
result.push_str(&indent.to_string_with_newline(config))
}
result.push_str(next_str);
return Some(result);
}
// We have a missing comment between the first expression and the second expression.
// Peek the the original source code and find out whether there is a newline between the first
// expression and the second expression or the missing comment. We will preserve the original
// layout whenever possible.
let original_snippet = context.snippet(span);
let prefer_same_line = if let Some(pos) = original_snippet.find('/') {
!original_snippet[..pos].contains('\n')
} else {
!original_snippet.contains('\n')
};
one_line_width -= first_sep.len();
let first_sep = if prev_str.is_empty() || missing_comment.is_empty() {
Cow::from("")
} else {
let one_line_width = last_line_width(prev_str) + first_line_width(&missing_comment) + 1;
if prefer_same_line && one_line_width <= shape.width {
Cow::from(" ")
} else {
indent.to_string_with_newline(config)
}
};
result.push_str(&first_sep);
result.push_str(&missing_comment);
let second_sep = if missing_comment.is_empty() || next_str.is_empty() {
Cow::from("")
} else if missing_comment.starts_with("//") {
indent.to_string_with_newline(config)
} else {
one_line_width += missing_comment.len() + first_sep.len() + 1;
allow_one_line &= !missing_comment.starts_with("//") && !missing_comment.contains('\n');
if prefer_same_line && allow_one_line && one_line_width <= shape.width {
Cow::from(" ")
} else {
indent.to_string_with_newline(config)
}
};
result.push_str(&second_sep);
result.push_str(next_str);
Some(result)
}
pub(crate) fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config) -> Option<String> {
identify_comment(orig, false, shape, config, true)
}
pub(crate) fn rewrite_comment(
orig: &str,
block_style: bool,
shape: Shape,
config: &Config,
) -> Option<String> {
identify_comment(orig, block_style, shape, config, false)
}
fn identify_comment(
orig: &str,
block_style: bool,
shape: Shape,
config: &Config,
is_doc_comment: bool,
) -> Option<String> {
let style = comment_style(orig, false);
// Computes the byte length of line taking into account a newline if the line is part of a
// paragraph.
fn compute_len(orig: &str, line: &str) -> usize {
if orig.len() > line.len() {
if orig.as_bytes()[line.len()] == b'\r' {
line.len() + 2
} else {
line.len() + 1
}
} else {
line.len()
}
}
// Get the first group of line comments having the same commenting style.
//
// Returns a tuple with:
// - a boolean indicating if there is a blank line
// - a number indicating the size of the first group of comments
fn consume_same_line_comments(
style: CommentStyle<'_>,
orig: &str,
line_start: &str,
) -> (bool, usize) {
let mut first_group_ending = 0;
let mut hbl = false;
for line in orig.lines() {
let trimmed_line = line.trim_start();
if trimmed_line.is_empty() {
hbl = true;
break;
} else if trimmed_line.starts_with(line_start)
|| comment_style(trimmed_line, false) == style
{
first_group_ending += compute_len(&orig[first_group_ending..], line);
} else {
break;
}
}
(hbl, first_group_ending)
}
let (has_bare_lines, first_group_ending) = match style {
CommentStyle::DoubleSlash | CommentStyle::TripleSlash | CommentStyle::Doc => {
let line_start = style.line_start().trim_start();
consume_same_line_comments(style, orig, line_start)
}
CommentStyle::Custom(opener) => {
let trimmed_opener = opener.trim_end();
consume_same_line_comments(style, orig, trimmed_opener)
}
// for a block comment, search for the closing symbol
CommentStyle::DoubleBullet | CommentStyle::SingleBullet | CommentStyle::Exclamation => {
let closer = style.closer().trim_start();
let mut count = orig.matches(closer).count();
let mut closing_symbol_offset = 0;
let mut hbl = false;
let mut first = true;
for line in orig.lines() {
closing_symbol_offset += compute_len(&orig[closing_symbol_offset..], line);
let mut trimmed_line = line.trim_start();
if !trimmed_line.starts_with('*')
&& !trimmed_line.starts_with("//")
&& !trimmed_line.starts_with("/*")
{
hbl = true;
}
// Remove opener from consideration when searching for closer
if first {
let opener = style.opener().trim_end();
trimmed_line = &trimmed_line[opener.len()..];
first = false;
}
if trimmed_line.ends_with(closer) {
count -= 1;
if count == 0 {
break;
}
}
}
(hbl, closing_symbol_offset)
}
};
let (first_group, rest) = orig.split_at(first_group_ending);
let rewritten_first_group =
if !config.normalize_comments() && has_bare_lines && style.is_block_comment() {
trim_left_preserve_layout(first_group, shape.indent, config)?
} else if !config.normalize_comments()
&& !config.wrap_comments()
&& !config.format_code_in_doc_comments()
{
light_rewrite_comment(first_group, shape.indent, config, is_doc_comment)
} else {
rewrite_comment_inner(
first_group,
block_style,
style,
shape,
config,
is_doc_comment || style.is_doc_comment(),
)?
};
if rest.is_empty() {
Some(rewritten_first_group)
} else {
identify_comment(
rest.trim_start(),
block_style,
shape,
config,
is_doc_comment,
)
.map(|rest_str| {
format!(
"{}\n{}{}{}",
rewritten_first_group,
// insert back the blank line
if has_bare_lines && style.is_line_comment() {
"\n"
} else {
""
},
shape.indent.to_string(config),
rest_str
)
})
}
}
/// Enum indicating if the code block contains rust based on attributes
enum CodeBlockAttribute {
Rust,
NotRust,
}
impl CodeBlockAttribute {
/// Parse comma separated attributes list. Return rust only if all
/// attributes are valid rust attributes
/// See <https://doc.rust-lang.org/rustdoc/print.html#attributes>
fn new(attributes: &str) -> CodeBlockAttribute {
for attribute in attributes.split(',') {
match attribute.trim() {
"" | "rust" | "should_panic" | "no_run" | "edition2015" | "edition2018"
| "edition2021" => (),
"ignore" | "compile_fail" | "text" => return CodeBlockAttribute::NotRust,
_ => return CodeBlockAttribute::NotRust,
}
}
CodeBlockAttribute::Rust
}
}
/// Block that is formatted as an item.
///
/// An item starts with either a star `*` a dash `-` or a greater-than `>`.
/// Different level of indentation are handled by shrinking the shape accordingly.
struct ItemizedBlock {
/// the lines that are identified as part of an itemized block
lines: Vec<String>,
/// the number of characters (typically whitespaces) up to the item sigil
indent: usize,
/// the string that marks the start of an item
opener: String,
/// sequence of characters (typically whitespaces) to prefix new lines that are part of the item
line_start: String,
}
impl ItemizedBlock {
/// Returns `true` if the line is formatted as an item
fn is_itemized_line(line: &str) -> bool {
let trimmed = line.trim_start();
trimmed.starts_with("* ") || trimmed.starts_with("- ") || trimmed.starts_with("> ")
}
/// Creates a new ItemizedBlock described with the given line.
/// The `is_itemized_line` needs to be called first.
fn new(line: &str) -> ItemizedBlock {
let space_to_sigil = line.chars().take_while(|c| c.is_whitespace()).count();
// +2 = '* ', which will add the appropriate amount of whitespace to keep itemized
// content formatted correctly.
let mut indent = space_to_sigil + 2;
let mut line_start = " ".repeat(indent);
// Markdown blockquote start with a "> "
if line.trim_start().starts_with(">") {
// remove the original +2 indent because there might be multiple nested block quotes
// and it's easier to reason about the final indent by just taking the length
// of th new line_start. We update the indent because it effects the max width
// of each formatted line.
line_start = itemized_block_quote_start(line, line_start, 2);
indent = line_start.len();
}
ItemizedBlock {
lines: vec![line[indent..].to_string()],
indent,
opener: line[..indent].to_string(),
line_start,
}
}
/// Returns a `StringFormat` used for formatting the content of an item.
fn create_string_format<'a>(&'a self, fmt: &'a StringFormat<'_>) -> StringFormat<'a> {
StringFormat {
opener: "",
closer: "",
line_start: "",
line_end: "",
shape: Shape::legacy(fmt.shape.width.saturating_sub(self.indent), Indent::empty()),
trim_end: true,
config: fmt.config,
}
}
/// Returns `true` if the line is part of the current itemized block.
/// If it is, then it is added to the internal lines list.
fn add_line(&mut self, line: &str) -> bool {
if !ItemizedBlock::is_itemized_line(line)
&& self.indent <= line.chars().take_while(|c| c.is_whitespace()).count()
{
self.lines.push(line.to_string());
return true;
}
false
}
/// Returns the block as a string, with each line trimmed at the start.
fn trimmed_block_as_string(&self) -> String {
self.lines
.iter()
.map(|line| format!("{} ", line.trim_start()))
.collect::<String>()
}
/// Returns the block as a string under its original form.
fn original_block_as_string(&self) -> String {
self.lines.join("\n")
}
}
/// Determine the line_start when formatting markdown block quotes.
/// The original line_start likely contains indentation (whitespaces), which we'd like to
/// replace with '> ' characters.
fn itemized_block_quote_start(line: &str, mut line_start: String, remove_indent: usize) -> String {
let quote_level = line
.chars()
.take_while(|c| !c.is_alphanumeric())
.fold(0, |acc, c| if c == '>' { acc + 1 } else { acc });
for _ in 0..remove_indent {
line_start.pop();
}
for _ in 0..quote_level {
line_start.push_str("> ")
}
line_start
}
struct CommentRewrite<'a> {
result: String,
code_block_buffer: String,
is_prev_line_multi_line: bool,
code_block_attr: Option<CodeBlockAttribute>,
item_block: Option<ItemizedBlock>,
comment_line_separator: String,
indent_str: String,
max_width: usize,
fmt_indent: Indent,
fmt: StringFormat<'a>,
opener: String,
closer: String,
line_start: String,
style: CommentStyle<'a>,
}
impl<'a> CommentRewrite<'a> {
fn new(
orig: &'a str,
block_style: bool,
shape: Shape,
config: &'a Config,
) -> CommentRewrite<'a> {
let ((opener, closer, line_start), style) = if block_style {
(
CommentStyle::SingleBullet.to_str_tuplet(),
CommentStyle::SingleBullet,
)
} else {
let style = comment_style(orig, config.normalize_comments());
(style.to_str_tuplet(), style)
};
let max_width = shape
.width
.checked_sub(closer.len() + opener.len())
.unwrap_or(1);
let indent_str = shape.indent.to_string_with_newline(config).to_string();
let mut cr = CommentRewrite {
result: String::with_capacity(orig.len() * 2),
code_block_buffer: String::with_capacity(128),
is_prev_line_multi_line: false,
code_block_attr: None,
item_block: None,
comment_line_separator: format!("{}{}", indent_str, line_start),
max_width,
indent_str,
fmt_indent: shape.indent,
fmt: StringFormat {
opener: "",
closer: "",
line_start,
line_end: "",
shape: Shape::legacy(max_width, shape.indent),
trim_end: true,
config,
},
opener: opener.to_owned(),
closer: closer.to_owned(),
line_start: line_start.to_owned(),
style,
};
cr.result.push_str(opener);
cr
}
fn join_block(s: &str, sep: &str) -> String {
let mut result = String::with_capacity(s.len() + 128);
let mut iter = s.lines().peekable();
while let Some(line) = iter.next() {
result.push_str(line);
result.push_str(match iter.peek() {
Some(next_line) if next_line.is_empty() => sep.trim_end(),
Some(..) => sep,
None => "",
});
}
result
}
/// Check if any characters were written to the result buffer after the start of the comment.
/// when calling [`CommentRewrite::new()`] the result buffer is initiazlied with the opening
/// characters for the comment.
fn buffer_contains_comment(&self) -> bool {
// if self.result.len() < self.opener.len() then an empty comment is in the buffer
// if self.result.len() > self.opener.len() then a non empty comment is in the buffer
self.result.len() != self.opener.len()
}
fn finish(mut self) -> String {
if !self.code_block_buffer.is_empty() {
// There is a code block that is not properly enclosed by backticks.
// We will leave them untouched.
self.result.push_str(&self.comment_line_separator);
self.result.push_str(&Self::join_block(
&trim_custom_comment_prefix(&self.code_block_buffer),
&self.comment_line_separator,
));
}
if let Some(ref ib) = self.item_block {
// the last few lines are part of an itemized block
self.fmt.shape = Shape::legacy(self.max_width, self.fmt_indent);
let item_fmt = ib.create_string_format(&self.fmt);
// only push a comment_line_separator for ItemizedBlocks if the comment is not empty
if self.buffer_contains_comment() {
self.result.push_str(&self.comment_line_separator);
}
self.result.push_str(&ib.opener);
match rewrite_string(
&ib.trimmed_block_as_string(),
&item_fmt,
self.max_width.saturating_sub(ib.indent),
) {
Some(s) => self.result.push_str(&Self::join_block(
&s,
&format!("{}{}", self.comment_line_separator, ib.line_start),
)),
None => self.result.push_str(&Self::join_block(
&ib.original_block_as_string(),
&self.comment_line_separator,
)),
};
}
self.result.push_str(&self.closer);
if self.result.ends_with(&self.opener) && self.opener.ends_with(' ') {
// Trailing space.
self.result.pop();
}
self.result
}
fn handle_line(
&mut self,
orig: &'a str,
i: usize,
line: &'a str,
has_leading_whitespace: bool,
is_doc_comment: bool,
) -> bool {
let num_newlines = count_newlines(orig);
let is_last = i == num_newlines;
let needs_new_comment_line = if self.style.is_block_comment() {
num_newlines > 0 || self.buffer_contains_comment()
} else {
self.buffer_contains_comment()
};
if let Some(ref mut ib) = self.item_block {
if ib.add_line(line) {
return false;
}
self.is_prev_line_multi_line = false;
self.fmt.shape = Shape::legacy(self.max_width, self.fmt_indent);
let item_fmt = ib.create_string_format(&self.fmt);
// only push a comment_line_separator if we need to start a new comment line
if needs_new_comment_line {
self.result.push_str(&self.comment_line_separator);
}
self.result.push_str(&ib.opener);
match rewrite_string(
&ib.trimmed_block_as_string(),
&item_fmt,
self.max_width.saturating_sub(ib.indent),
) {
Some(s) => self.result.push_str(&Self::join_block(
&s,
&format!("{}{}", self.comment_line_separator, ib.line_start),
)),
None => self.result.push_str(&Self::join_block(
&ib.original_block_as_string(),
&self.comment_line_separator,
)),
};
} else if self.code_block_attr.is_some() {
if line.starts_with("```") {
let code_block = match self.code_block_attr.as_ref().unwrap() {
CodeBlockAttribute::Rust
if self.fmt.config.format_code_in_doc_comments()
&& !self.code_block_buffer.is_empty() =>
{
let mut config = self.fmt.config.clone();
config.set().wrap_comments(false);
let comment_max_width = config
.doc_comment_code_block_width()
.min(config.max_width());
config.set().max_width(comment_max_width);
if let Some(s) =
crate::format_code_block(&self.code_block_buffer, &config, false)
{
trim_custom_comment_prefix(&s.snippet)
} else {
trim_custom_comment_prefix(&self.code_block_buffer)
}
}
_ => trim_custom_comment_prefix(&self.code_block_buffer),
};
if !code_block.is_empty() {
self.result.push_str(&self.comment_line_separator);
self.result
.push_str(&Self::join_block(&code_block, &self.comment_line_separator));
}
self.code_block_buffer.clear();
self.result.push_str(&self.comment_line_separator);
self.result.push_str(line);
self.code_block_attr = None;
} else {
self.code_block_buffer
.push_str(&hide_sharp_behind_comment(line));
self.code_block_buffer.push('\n');
}
return false;
}
self.code_block_attr = None;
self.item_block = None;
if let Some(stripped) = line.strip_prefix("```") {
self.code_block_attr = Some(CodeBlockAttribute::new(stripped))
} else if self.fmt.config.wrap_comments() && ItemizedBlock::is_itemized_line(line) {
let ib = ItemizedBlock::new(line);
self.item_block = Some(ib);
return false;
}
if self.result == self.opener {
let force_leading_whitespace = &self.opener == "/* " && count_newlines(orig) == 0;
if !has_leading_whitespace && !force_leading_whitespace && self.result.ends_with(' ') {
self.result.pop();
}
if line.is_empty() {
return false;
}
} else if self.is_prev_line_multi_line && !line.is_empty() {
self.result.push(' ')
} else if is_last && line.is_empty() {
// trailing blank lines are unwanted
if !self.closer.is_empty() {
self.result.push_str(&self.indent_str);
}
return true;
} else {
self.result.push_str(&self.comment_line_separator);
if !has_leading_whitespace && self.result.ends_with(' ') {
self.result.pop();
}
}
let is_markdown_header_doc_comment = is_doc_comment && line.starts_with("#");
// We only want to wrap the comment if:
// 1) wrap_comments = true is configured
// 2) The comment is not the start of a markdown header doc comment
// 3) The comment width exceeds the shape's width
// 4) No URLS were found in the comment
let should_wrap_comment = self.fmt.config.wrap_comments()
&& !is_markdown_header_doc_comment
&& unicode_str_width(line) > self.fmt.shape.width
&& !has_url(line);
if should_wrap_comment {
match rewrite_string(line, &self.fmt, self.max_width) {
Some(ref s) => {
self.is_prev_line_multi_line = s.contains('\n');
self.result.push_str(s);
}
None if self.is_prev_line_multi_line => {
// We failed to put the current `line` next to the previous `line`.
// Remove the trailing space, then start rewrite on the next line.
self.result.pop();
self.result.push_str(&self.comment_line_separator);
self.fmt.shape = Shape::legacy(self.max_width, self.fmt_indent);
match rewrite_string(line, &self.fmt, self.max_width) {
Some(ref s) => {
self.is_prev_line_multi_line = s.contains('\n');
self.result.push_str(s);
}
None => {
self.is_prev_line_multi_line = false;
self.result.push_str(line);
}
}
}
None => {
self.is_prev_line_multi_line = false;
self.result.push_str(line);
}
}
self.fmt.shape = if self.is_prev_line_multi_line {
// 1 = " "
let offset = 1 + last_line_width(&self.result) - self.line_start.len();
Shape {
width: self.max_width.saturating_sub(offset),
indent: self.fmt_indent,
offset: self.fmt.shape.offset + offset,
}
} else {
Shape::legacy(self.max_width, self.fmt_indent)
};
} else {
if line.is_empty() && self.result.ends_with(' ') && !is_last {
// Remove space if this is an empty comment or a doc comment.
self.result.pop();
}
self.result.push_str(line);
self.fmt.shape = Shape::legacy(self.max_width, self.fmt_indent);
self.is_prev_line_multi_line = false;
}
false
}
}
fn rewrite_comment_inner(
orig: &str,
block_style: bool,
style: CommentStyle<'_>,
shape: Shape,
config: &Config,
is_doc_comment: bool,
) -> Option<String> {
let mut rewriter = CommentRewrite::new(orig, block_style, shape, config);
let line_breaks = count_newlines(orig.trim_end());
let lines = orig
.lines()
.enumerate()
.map(|(i, mut line)| {
line = trim_end_unless_two_whitespaces(line.trim_start(), is_doc_comment);
// Drop old closer.
if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
line = line[..(line.len() - 2)].trim_end();
}
line
})
.map(|s| left_trim_comment_line(s, &style))
.map(|(line, has_leading_whitespace)| {
if orig.starts_with("/*") && line_breaks == 0 {
(
line.trim_start(),
has_leading_whitespace || config.normalize_comments(),
)
} else {
(line, has_leading_whitespace || config.normalize_comments())
}
});
for (i, (line, has_leading_whitespace)) in lines.enumerate() {
if rewriter.handle_line(orig, i, line, has_leading_whitespace, is_doc_comment) {
break;
}
}
Some(rewriter.finish())
}
const RUSTFMT_CUSTOM_COMMENT_PREFIX: &str = "//#### ";
fn hide_sharp_behind_comment(s: &str) -> Cow<'_, str> {
let s_trimmed = s.trim();
if s_trimmed.starts_with("# ") || s_trimmed == "#" {
Cow::from(format!("{}{}", RUSTFMT_CUSTOM_COMMENT_PREFIX, s))
} else {
Cow::from(s)
}
}
fn trim_custom_comment_prefix(s: &str) -> String {
s.lines()
.map(|line| {
let left_trimmed = line.trim_start();
if left_trimmed.starts_with(RUSTFMT_CUSTOM_COMMENT_PREFIX) {
left_trimmed.trim_start_matches(RUSTFMT_CUSTOM_COMMENT_PREFIX)
} else {
line
}
})
.collect::<Vec<_>>()
.join("\n")
}
/// Returns `true` if the given string MAY include URLs or alike.
fn has_url(s: &str) -> bool {
// This function may return false positive, but should get its job done in most cases.
s.contains("https://")
|| s.contains("http://")
|| s.contains("ftp://")
|| s.contains("file://")
|| REFERENCE_LINK_URL.is_match(s)
}
/// Given the span, rewrite the missing comment inside it if available.
/// Note that the given span must only include comments (or leading/trailing whitespaces).
pub(crate) fn rewrite_missing_comment(
span: Span,
shape: Shape,
context: &RewriteContext<'_>,
) -> Option<String> {
let missing_snippet = context.snippet(span);
let trimmed_snippet = missing_snippet.trim();
// check the span starts with a comment
let pos = trimmed_snippet.find('/');
if !trimmed_snippet.is_empty() && pos.is_some() {
rewrite_comment(trimmed_snippet, false, shape, context.config)
} else {
Some(String::new())
}
}
/// Recover the missing comments in the specified span, if available.
/// The layout of the comments will be preserved as long as it does not break the code
/// and its total width does not exceed the max width.
pub(crate) fn recover_missing_comment_in_span(
span: Span,
shape: Shape,
context: &RewriteContext<'_>,
used_width: usize,
) -> Option<String> {
let missing_comment = rewrite_missing_comment(span, shape, context)?;
if missing_comment.is_empty() {
Some(String::new())
} else {
let missing_snippet = context.snippet(span);
let pos = missing_snippet.find('/')?;
// 1 = ` `
let total_width = missing_comment.len() + used_width + 1;
let force_new_line_before_comment =
missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
let sep = if force_new_line_before_comment {
shape.indent.to_string_with_newline(context.config)
} else {
Cow::from(" ")
};
Some(format!("{}{}", sep, missing_comment))
}
}
/// Trim trailing whitespaces unless they consist of two or more whitespaces.
fn trim_end_unless_two_whitespaces(s: &str, is_doc_comment: bool) -> &str {
if is_doc_comment && s.ends_with(" ") {
s
} else {
s.trim_end()
}
}
/// Trims whitespace and aligns to indent, but otherwise does not change comments.
fn light_rewrite_comment(
orig: &str,
offset: Indent,