1use crate::config as rumdl_config;
15use crate::lint_context::LintContext;
16use crate::rule::{LintWarning, Rule};
17use crate::rules::md013_line_length::MD013LineLength;
18use std::path::Path;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum DocCommentKind {
23 Outer,
25 Inner,
27}
28
29#[derive(Debug, Clone)]
31pub struct DocCommentLineInfo {
32 pub leading_whitespace: String,
34 pub prefix: String,
37}
38
39#[derive(Debug, Clone)]
41pub struct DocCommentBlock {
42 pub kind: DocCommentKind,
44 pub start_line: usize,
46 pub end_line: usize,
48 pub byte_start: usize,
50 pub byte_end: usize,
52 pub markdown: String,
54 pub line_metadata: Vec<DocCommentLineInfo>,
56 pub prefix_byte_lengths: Vec<usize>,
59}
60
61fn classify_doc_comment_line(line: &str) -> Option<(DocCommentKind, String, String)> {
76 let trimmed = line.trim_start();
77 let leading_ws = &line[..line.len() - trimmed.len()];
78
79 if trimmed.starts_with("////") {
81 return None;
82 }
83
84 if let Some(after) = trimmed.strip_prefix("///") {
85 let prefix = if after.starts_with(' ') || after.starts_with('\t') {
87 format!("///{}", &after[..1])
88 } else {
89 "///".to_string()
90 };
91 Some((DocCommentKind::Outer, leading_ws.to_string(), prefix))
92 } else if let Some(after) = trimmed.strip_prefix("//!") {
93 let prefix = if after.starts_with(' ') || after.starts_with('\t') {
94 format!("//!{}", &after[..1])
95 } else {
96 "//!".to_string()
97 };
98 Some((DocCommentKind::Inner, leading_ws.to_string(), prefix))
99 } else {
100 None
101 }
102}
103
104#[derive(Clone, Copy, PartialEq, Eq)]
106enum LexState {
107 Code,
108 LineComment,
109 BlockComment(usize),
110 Str,
111 RawStr(usize),
112}
113
114fn lines_starting_in_code(content: &str) -> Vec<bool> {
125 let bytes = content.as_bytes();
126 let mut starts = vec![true];
127 let mut state = LexState::Code;
128 let mut i = 0;
129 while i < bytes.len() {
130 let byte = bytes[i];
131 if byte == b'\n' {
132 if state == LexState::LineComment {
133 state = LexState::Code;
134 }
135 starts.push(state == LexState::Code);
136 i += 1;
137 continue;
138 }
139 let next = bytes.get(i + 1).copied();
140 match state {
141 LexState::Code => match byte {
142 b'/' if next == Some(b'/') => {
143 state = LexState::LineComment;
144 i += 2;
145 }
146 b'/' if next == Some(b'*') => {
147 state = LexState::BlockComment(1);
148 i += 2;
149 }
150 b'"' => {
151 state = LexState::Str;
152 i += 1;
153 }
154 b'\'' => i = skip_char_literal(bytes, i),
155 _ if byte == b'_' || byte.is_ascii_alphanumeric() || !byte.is_ascii() => {
156 let start = i;
157 while i < bytes.len()
158 && (bytes[i] == b'_' || bytes[i].is_ascii_alphanumeric() || !bytes[i].is_ascii())
159 {
160 i += 1;
161 }
162 if matches!(&bytes[start..i], b"r" | b"br" | b"cr") {
163 let hashes = bytes[i..].iter().take_while(|&&b| b == b'#').count();
164 if bytes.get(i + hashes) == Some(&b'"') {
166 state = LexState::RawStr(hashes);
167 i += hashes + 1;
168 }
169 }
170 }
171 _ => i += 1,
172 },
173 LexState::LineComment => i += 1,
174 LexState::BlockComment(depth) => {
175 if byte == b'/' && next == Some(b'*') {
176 state = LexState::BlockComment(depth + 1);
177 i += 2;
178 } else if byte == b'*' && next == Some(b'/') {
179 state = if depth == 1 {
180 LexState::Code
181 } else {
182 LexState::BlockComment(depth - 1)
183 };
184 i += 2;
185 } else {
186 i += 1;
187 }
188 }
189 LexState::Str => match byte {
190 b'\\' if next != Some(b'\n') => i += 2,
193 b'"' => {
194 state = LexState::Code;
195 i += 1;
196 }
197 _ => i += 1,
198 },
199 LexState::RawStr(hashes) => {
200 let closes =
201 byte == b'"' && bytes[i + 1..].iter().take(hashes).filter(|&&b| b == b'#').count() == hashes;
202 if closes {
203 state = LexState::Code;
204 i += hashes + 1;
205 } else {
206 i += 1;
207 }
208 }
209 }
210 }
211 starts
212}
213
214fn skip_char_literal(bytes: &[u8], quote: usize) -> usize {
218 let after = quote + 1;
219 if bytes.get(after) == Some(&b'\\') {
220 let mut i = after + 2;
222 while i < bytes.len() && bytes[i] != b'\'' && bytes[i] != b'\n' {
223 i += 1;
224 }
225 return if bytes.get(i) == Some(&b'\'') { i + 1 } else { after };
226 }
227 let char_len = match bytes.get(after) {
228 Some(&b) if b < 0x80 => 1,
229 Some(&b) if b >= 0xF0 => 4,
230 Some(&b) if b >= 0xE0 => 3,
231 Some(_) => 2,
232 None => return after,
233 };
234 if bytes.get(after + char_len) == Some(&b'\'') {
235 after + char_len + 1
236 } else {
237 after
238 }
239}
240
241pub fn extract_doc_comment_blocks(content: &str) -> Vec<DocCommentBlock> {
256 let mut blocks = Vec::new();
257 let mut current_block: Option<DocCommentBlock> = None;
258 let mut byte_offset = 0;
259
260 let lines: Vec<&str> = content.split('\n').collect();
261 let num_lines = lines.len();
262 let starts_in_code = lines_starting_in_code(content);
263
264 for (line_idx, line) in lines.iter().enumerate() {
265 let line_byte_start = byte_offset;
266 let has_newline = line_idx < num_lines - 1 || content.ends_with('\n');
268 let line_byte_end = byte_offset + line.len() + usize::from(has_newline);
269
270 let doc_comment = if starts_in_code[line_idx] {
271 classify_doc_comment_line(line)
272 } else {
273 None
274 };
275 if let Some((kind, leading_ws, prefix)) = doc_comment {
276 let prefix_byte_len = leading_ws.len() + prefix.len();
279 let md_content = &line[prefix_byte_len..];
280
281 let line_info = DocCommentLineInfo {
282 leading_whitespace: leading_ws,
283 prefix,
284 };
285
286 match current_block.as_mut() {
287 Some(block) if block.kind == kind => {
288 block.end_line = line_idx;
290 block.byte_end = line_byte_end;
291 block.markdown.push('\n');
292 block.markdown.push_str(md_content);
293 block.line_metadata.push(line_info);
294 block.prefix_byte_lengths.push(prefix_byte_len);
295 }
296 _ => {
297 if let Some(block) = current_block.take() {
299 blocks.push(block);
300 }
301 current_block = Some(DocCommentBlock {
303 kind,
304 start_line: line_idx,
305 end_line: line_idx,
306 byte_start: line_byte_start,
307 byte_end: line_byte_end,
308 markdown: md_content.to_string(),
309 line_metadata: vec![line_info],
310 prefix_byte_lengths: vec![prefix_byte_len],
311 });
312 }
313 }
314 } else {
315 if let Some(block) = current_block.take() {
317 blocks.push(block);
318 }
319 }
320
321 byte_offset = line_byte_end;
322 }
323
324 if let Some(block) = current_block.take() {
326 blocks.push(block);
327 }
328
329 blocks
330}
331
332pub const SKIPPED_RULES: &[&str] = &["MD025", "MD033", "MD040", "MD041", "MD047", "MD051", "MD052", "MD054"];
343
344pub fn is_rust_source(path: &Path) -> bool {
353 path.extension().is_some_and(|ext| ext == "rs")
354}
355
356pub fn check_doc_comment_blocks(
364 content: &str,
365 rules: &[Box<dyn Rule>],
366 config: &rumdl_config::Config,
367) -> Vec<LintWarning> {
368 let blocks = extract_doc_comment_blocks(content);
369 let mut all_warnings = Vec::new();
370
371 for block in &blocks {
372 if block.markdown.trim().is_empty() {
374 continue;
375 }
376
377 let ctx = LintContext::new(&block.markdown, config.markdown_flavor(), None);
378
379 for rule in rules {
380 if SKIPPED_RULES.contains(&rule.name()) {
381 continue;
382 }
383
384 let doc_rule: Box<dyn Rule>;
388 let effective_rule: &dyn Rule = if rule.name() == "MD013" {
389 if let Some(md013) = rule.as_any().downcast_ref::<MD013LineLength>() {
390 doc_rule = Box::new(md013.with_code_blocks_disabled());
391 doc_rule.as_ref()
392 } else {
393 rule.as_ref()
394 }
395 } else {
396 rule.as_ref()
397 };
398
399 if let Ok(rule_warnings) = effective_rule.check(&ctx) {
400 let rule_warnings =
403 crate::retain_reportable_warnings(&ctx, Some(config), rule.name(), rule_warnings, None);
404 for warning in rule_warnings {
405 let file_line = warning.line + block.start_line;
410 let file_end_line = warning.end_line + block.start_line;
411
412 let block_line_idx = warning.line.saturating_sub(1);
414 let col_offset = block.prefix_byte_lengths.get(block_line_idx).copied().unwrap_or(0);
415 let file_column = warning.column + col_offset;
416
417 let block_end_line_idx = warning.end_line.saturating_sub(1);
418 let end_col_offset = block.prefix_byte_lengths.get(block_end_line_idx).copied().unwrap_or(0);
419 let file_end_column = warning.end_column + end_col_offset;
420
421 all_warnings.push(LintWarning {
422 line: file_line,
423 end_line: file_end_line,
424 column: file_column,
425 end_column: file_end_column,
426 fix: None,
427 ..warning
428 });
429 }
430 }
431 }
432 }
433
434 all_warnings
435}
436
437#[cfg(test)]
438mod tests {
439 use super::*;
440
441 #[test]
442 fn test_classify_outer_doc_comment() {
443 let (kind, ws, prefix) = classify_doc_comment_line("/// Hello").unwrap();
444 assert_eq!(kind, DocCommentKind::Outer);
445 assert_eq!(ws, "");
446 assert_eq!(prefix, "/// ");
447 }
448
449 #[test]
450 fn test_classify_inner_doc_comment() {
451 let (kind, ws, prefix) = classify_doc_comment_line("//! Module doc").unwrap();
452 assert_eq!(kind, DocCommentKind::Inner);
453 assert_eq!(ws, "");
454 assert_eq!(prefix, "//! ");
455 }
456
457 #[test]
458 fn test_classify_empty_outer() {
459 let (kind, ws, prefix) = classify_doc_comment_line("///").unwrap();
460 assert_eq!(kind, DocCommentKind::Outer);
461 assert_eq!(ws, "");
462 assert_eq!(prefix, "///");
463 }
464
465 #[test]
466 fn test_classify_empty_inner() {
467 let (kind, ws, prefix) = classify_doc_comment_line("//!").unwrap();
468 assert_eq!(kind, DocCommentKind::Inner);
469 assert_eq!(ws, "");
470 assert_eq!(prefix, "//!");
471 }
472
473 #[test]
474 fn test_classify_indented() {
475 let (kind, ws, prefix) = classify_doc_comment_line(" /// Indented").unwrap();
476 assert_eq!(kind, DocCommentKind::Outer);
477 assert_eq!(ws, " ");
478 assert_eq!(prefix, "/// ");
479 }
480
481 #[test]
482 fn test_classify_no_space_after_prefix() {
483 let (kind, ws, prefix) = classify_doc_comment_line("///content").unwrap();
485 assert_eq!(kind, DocCommentKind::Outer);
486 assert_eq!(ws, "");
487 assert_eq!(prefix, "///");
488 }
489
490 #[test]
491 fn test_classify_tab_after_prefix() {
492 let (kind, ws, prefix) = classify_doc_comment_line("///\tcontent").unwrap();
493 assert_eq!(kind, DocCommentKind::Outer);
494 assert_eq!(ws, "");
495 assert_eq!(prefix, "///\t");
496 }
497
498 #[test]
499 fn test_classify_inner_no_space() {
500 let (kind, _, prefix) = classify_doc_comment_line("//!content").unwrap();
501 assert_eq!(kind, DocCommentKind::Inner);
502 assert_eq!(prefix, "//!");
503 }
504
505 #[test]
506 fn test_classify_four_slashes_is_not_doc() {
507 assert!(classify_doc_comment_line("//// Not a doc comment").is_none());
508 }
509
510 #[test]
511 fn test_classify_regular_comment() {
512 assert!(classify_doc_comment_line("// Regular comment").is_none());
513 }
514
515 #[test]
516 fn test_classify_code_line() {
517 assert!(classify_doc_comment_line("let x = 3;").is_none());
518 }
519
520 #[test]
521 fn test_extract_no_space_content() {
522 let content = "///no space here\n";
523 let blocks = extract_doc_comment_blocks(content);
524 assert_eq!(blocks.len(), 1);
525 assert_eq!(blocks[0].markdown, "no space here");
526 }
527
528 #[test]
529 fn test_extract_strips_tab_separator() {
530 let blocks = extract_doc_comment_blocks("///\t# Heading\n");
531 assert_eq!(blocks.len(), 1);
532 assert_eq!(blocks[0].markdown, "# Heading");
533 assert_eq!(blocks[0].line_metadata[0].prefix, "///\t");
534 assert_eq!(blocks[0].prefix_byte_lengths[0], 4);
535 }
536
537 #[test]
538 fn test_extract_keeps_whitespace_after_the_separator() {
539 let blocks = extract_doc_comment_blocks("/// \tcode\n");
540 assert_eq!(blocks.len(), 1);
541 assert_eq!(blocks[0].markdown, "\tcode");
542 assert_eq!(blocks[0].prefix_byte_lengths[0], 4);
543 }
544
545 #[test]
546 fn test_extract_basic_outer_block() {
547 let content = "/// First line\n/// Second line\nfn foo() {}\n";
548 let blocks = extract_doc_comment_blocks(content);
549 assert_eq!(blocks.len(), 1);
550 assert_eq!(blocks[0].kind, DocCommentKind::Outer);
551 assert_eq!(blocks[0].start_line, 0);
552 assert_eq!(blocks[0].end_line, 1);
553 assert_eq!(blocks[0].markdown, "First line\nSecond line");
554 assert_eq!(blocks[0].line_metadata.len(), 2);
555 }
556
557 #[test]
558 fn test_extract_basic_inner_block() {
559 let content = "//! Module doc\n//! More info\n\nuse std::io;\n";
560 let blocks = extract_doc_comment_blocks(content);
561 assert_eq!(blocks.len(), 1);
562 assert_eq!(blocks[0].kind, DocCommentKind::Inner);
563 assert_eq!(blocks[0].markdown, "Module doc\nMore info");
564 }
565
566 #[test]
567 fn test_extract_multiple_blocks() {
568 let content = "/// Block 1\nfn foo() {}\n/// Block 2\nfn bar() {}\n";
569 let blocks = extract_doc_comment_blocks(content);
570 assert_eq!(blocks.len(), 2);
571 assert_eq!(blocks[0].markdown, "Block 1");
572 assert_eq!(blocks[0].start_line, 0);
573 assert_eq!(blocks[1].markdown, "Block 2");
574 assert_eq!(blocks[1].start_line, 2);
575 }
576
577 #[test]
578 fn test_extract_mixed_kinds_separate_blocks() {
579 let content = "//! Inner\n/// Outer\n";
580 let blocks = extract_doc_comment_blocks(content);
581 assert_eq!(blocks.len(), 2);
582 assert_eq!(blocks[0].kind, DocCommentKind::Inner);
583 assert_eq!(blocks[1].kind, DocCommentKind::Outer);
584 }
585
586 #[test]
587 fn test_extract_empty_doc_line() {
588 let content = "/// First\n///\n/// Third\n";
589 let blocks = extract_doc_comment_blocks(content);
590 assert_eq!(blocks.len(), 1);
591 assert_eq!(blocks[0].markdown, "First\n\nThird");
592 }
593
594 #[test]
595 fn test_extract_preserves_extra_space() {
596 let content = "/// Two spaces\n";
597 let blocks = extract_doc_comment_blocks(content);
598 assert_eq!(blocks.len(), 1);
599 assert_eq!(blocks[0].markdown, " Two spaces");
600 }
601
602 #[test]
603 fn test_extract_indented_doc_comments() {
604 let content = " /// Indented\n /// More\n";
605 let blocks = extract_doc_comment_blocks(content);
606 assert_eq!(blocks.len(), 1);
607 assert_eq!(blocks[0].markdown, "Indented\nMore");
608 assert_eq!(blocks[0].line_metadata[0].leading_whitespace, " ");
609 }
610
611 #[test]
612 fn test_no_doc_comments() {
613 let content = "fn main() {\n let x = 3;\n}\n";
614 let blocks = extract_doc_comment_blocks(content);
615 assert!(blocks.is_empty());
616 }
617
618 #[test]
619 fn test_byte_offsets() {
620 let content = "/// Hello\nfn foo() {}\n/// World\n";
621 let blocks = extract_doc_comment_blocks(content);
622 assert_eq!(blocks.len(), 2);
623 assert_eq!(blocks[0].byte_start, 0);
625 assert_eq!(blocks[0].byte_end, 10);
626 assert_eq!(blocks[1].byte_start, 22);
628 assert_eq!(blocks[1].byte_end, 32);
629 }
630
631 #[test]
632 fn test_byte_offsets_no_trailing_newline() {
633 let content = "/// Hello";
634 let blocks = extract_doc_comment_blocks(content);
635 assert_eq!(blocks.len(), 1);
636 assert_eq!(blocks[0].byte_start, 0);
637 assert_eq!(blocks[0].byte_end, content.len());
639 }
640
641 fn markdown_of(content: &str) -> Vec<String> {
643 extract_doc_comment_blocks(content)
644 .into_iter()
645 .map(|block| block.markdown)
646 .collect()
647 }
648
649 #[test]
650 fn test_a_doc_comment_inside_a_raw_string_is_text() {
651 let content = "const S: &str = r#\"\n/// #Heading\n\"#;\n/// After\nfn f() {}\n";
652 assert_eq!(markdown_of(content), ["After"]);
653 }
654
655 #[test]
656 fn test_a_raw_string_ends_only_at_its_own_hash_count() {
657 let content = "const S: &str = r##\"\n\"#\n/// Inside\n\"##;\n/// After\n";
658 assert_eq!(markdown_of(content), ["After"]);
659 }
660
661 #[test]
662 fn test_byte_and_c_raw_strings_are_strings() {
663 for opener in ["br\"", "cr#\""] {
664 let closer = if opener.contains('#') { "\"#" } else { "\"" };
665 let content = format!("let s = {opener}\n/// Inside\n{closer};\n/// After\n");
666 assert_eq!(markdown_of(&content), ["After"], "{opener}");
667 }
668 }
669
670 #[test]
671 fn test_a_raw_identifier_opens_no_string() {
672 let content = "let r#type = 1;\n/// After\n";
673 assert_eq!(markdown_of(content), ["After"]);
674 }
675
676 #[test]
677 fn test_a_doc_comment_inside_a_string_is_text() {
678 let content = "let s = \"a \\\" quote\n/// Inside\n\";\n/// After\n";
679 assert_eq!(markdown_of(content), ["After"]);
680 }
681
682 #[test]
683 fn test_a_line_continuation_keeps_the_string_open() {
684 let content = "let s = \"a\\\n/// Inside\n\";\n/// After\n";
685 assert_eq!(markdown_of(content), ["After"]);
686 }
687
688 #[test]
689 fn test_a_doc_comment_inside_a_nested_block_comment_is_text() {
690 let content = "/* outer /* inner */\n/// Inside\n*/\n/// After\n";
691 assert_eq!(markdown_of(content), ["After"]);
692 }
693
694 #[test]
695 fn test_a_block_doc_comment_body_is_not_extracted() {
696 let content = "/**\n/// Inside\n */\n/// After\n";
697 assert_eq!(markdown_of(content), ["After"]);
698 }
699
700 #[test]
701 fn test_a_quote_in_a_char_literal_opens_no_string() {
702 for literal in ["'\"'", "'\\''", "b'\"'", "'\\u{22}'", "'é'"] {
703 let content = format!("let c = {literal};\n/// After\n");
704 assert_eq!(markdown_of(&content), ["After"], "{literal}");
705 }
706 }
707
708 #[test]
709 fn test_a_lifetime_is_not_a_char_literal() {
710 let content = "fn f<'a>(s: &'a str) -> &'a str { \"\n/// Inside\n\" }\nlet c = 'x';\n/// After\n";
714 assert_eq!(markdown_of(content), ["After"]);
715 }
716
717 #[test]
718 fn test_quotes_in_comments_open_no_string() {
719 let content = "// don't \"\n/// One\nfn f() {}\n/* \" */\n/// Two\n";
720 assert_eq!(markdown_of(content), ["One", "Two"]);
721 }
722
723 #[test]
724 fn test_prefix_byte_lengths() {
725 let content = " /// Indented\n/// Top-level\n";
726 let blocks = extract_doc_comment_blocks(content);
727 assert_eq!(blocks.len(), 1);
728 assert_eq!(blocks[0].prefix_byte_lengths[0], 8);
730 assert_eq!(blocks[0].prefix_byte_lengths[1], 4);
732 }
733}