1#![warn(unreachable_pub)]
2#![warn(clippy::pedantic)]
3#![allow(clippy::doc_markdown)]
7#![allow(clippy::must_use_candidate)]
8#![allow(clippy::missing_errors_doc)]
9#![allow(clippy::missing_panics_doc)]
10#![allow(clippy::too_many_lines)]
11#![allow(clippy::if_not_else)]
12#![allow(clippy::similar_names)]
13#![allow(clippy::wildcard_imports)]
14#![allow(clippy::case_sensitive_file_extension_comparisons)]
15#![allow(clippy::doc_link_with_quotes)]
16#![allow(clippy::needless_raw_string_hashes)]
17#![allow(clippy::trivially_copy_pass_by_ref)]
18#![allow(clippy::struct_excessive_bools)]
19#![allow(clippy::fn_params_excessive_bools)]
20#![allow(clippy::elidable_lifetime_names)]
21#![allow(clippy::return_self_not_must_use)]
22#![allow(clippy::redundant_else)]
23#![allow(clippy::single_match_else)]
24#![allow(clippy::needless_continue)]
25#![allow(clippy::semicolon_if_nothing_returned)]
26#![allow(clippy::ignored_unit_patterns)]
27#![allow(clippy::unreadable_literal)]
28#![allow(clippy::implicit_hasher)]
29#![allow(clippy::ref_option)]
30#![allow(clippy::struct_field_names)]
31#![allow(clippy::unused_self)]
32#![allow(clippy::unnested_or_patterns)]
33#![allow(clippy::cast_precision_loss)]
34#![allow(clippy::cast_sign_loss)]
35#![allow(clippy::cast_possible_wrap)]
36#![allow(clippy::cast_possible_truncation)]
37#![allow(clippy::cast_lossless)]
38#![allow(clippy::items_after_statements)]
39#![allow(clippy::match_same_arms)]
40#![allow(clippy::format_push_string)]
41#![allow(clippy::no_effect_underscore_binding)]
44#![allow(clippy::default_trait_access)]
46#![allow(clippy::manual_string_new)]
49
50pub mod code_block_tools;
51pub mod config;
52pub mod discovery;
53pub mod doc_comment_lint;
54pub mod document_run;
55pub mod embedded_lint;
56pub mod encoding;
57pub mod exit_codes;
58pub mod filtered_lines;
59pub mod fix_coordinator;
60pub mod inline_config;
61pub mod linguist_data;
62pub mod lint_context;
63pub mod markdownlint_config;
64pub mod merge_conflict;
65pub mod profiling;
66pub mod rule;
67#[cfg(feature = "colored")]
68pub mod vscode;
69pub mod workspace_index;
70#[macro_use]
71pub mod rule_config;
72#[macro_use]
73pub mod rule_config_serde;
74pub mod rules;
75#[doc(hidden)]
76pub mod source_paths;
77pub mod types;
78pub mod utils;
79
80#[cfg(feature = "native")]
82pub mod lsp;
83#[cfg(feature = "colored")]
84pub mod output;
85
86#[cfg(feature = "wasm")]
88pub mod wasm;
89
90pub use rules::heading_utils::HeadingStyle;
91pub use rules::*;
92
93pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
94use crate::rule::{LintResult, Rule, RuleCategory};
95use crate::utils::calculate_indentation_width_default;
96#[cfg(not(target_arch = "wasm32"))]
97use std::time::Instant;
98
99#[derive(Debug, Default)]
101struct ContentCharacteristics {
102 has_headings: bool, has_lists: bool, has_links: bool, has_code: bool, has_emphasis: bool, has_html: bool, has_tables: bool, has_blockquotes: bool, has_images: bool, }
112
113fn has_potential_indented_code_indent(line: &str) -> bool {
116 calculate_indentation_width_default(line) >= 4
117}
118
119impl ContentCharacteristics {
120 fn analyze(content: &str) -> Self {
121 let mut chars = Self { ..Default::default() };
122
123 let mut has_atx_heading = false;
125 let mut has_setext_heading = false;
126
127 for line in content.lines() {
128 let trimmed = line.trim();
129
130 if !has_atx_heading
141 && (trimmed.starts_with('#')
142 || trimmed
143 .trim_start_matches([
144 '>', ' ', '\t', '-', '+', '*', '.', ')', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
145 ])
146 .starts_with('#'))
147 {
148 has_atx_heading = true;
149 }
150 let underline = trimmed.trim_start_matches(['>', ' ', '\t']);
153 if !has_setext_heading && !underline.is_empty() && underline.chars().all(|c| c == '=' || c == '-') {
154 has_setext_heading = true;
155 }
156
157 if !chars.has_lists
160 && (line.contains("* ")
161 || line.contains("- ")
162 || line.contains("+ ")
163 || trimmed.starts_with("* ")
164 || trimmed.starts_with("- ")
165 || trimmed.starts_with("+ ")
166 || trimmed.starts_with('*')
167 || trimmed.starts_with('-')
168 || trimmed.starts_with('+'))
169 {
170 chars.has_lists = true;
171 }
172 if !chars.has_lists
176 && ((trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) && trimmed.contains(['.', ')']))
177 || (trimmed.starts_with('>')
178 && trimmed.chars().any(|c| c.is_ascii_digit())
179 && trimmed.contains(['.', ')'])))
180 {
181 chars.has_lists = true;
182 }
183 if !chars.has_links
184 && (line.contains('[')
185 || line.contains("http://")
186 || line.contains("https://")
187 || line.contains("ftp://")
188 || line.contains("www."))
189 {
190 chars.has_links = true;
191 }
192 if !chars.has_images && line.contains("![") {
193 chars.has_images = true;
194 }
195 if !chars.has_code
196 && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
197 {
198 chars.has_code = true;
199 }
200 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
201 chars.has_emphasis = true;
202 }
203 if !chars.has_html && line.contains('<') {
204 chars.has_html = true;
205 }
206 if !chars.has_tables && line.contains('|') {
207 chars.has_tables = true;
208 }
209 if !chars.has_blockquotes && line.starts_with('>') {
210 chars.has_blockquotes = true;
211 }
212 }
213
214 chars.has_headings = has_atx_heading || has_setext_heading;
215 chars
216 }
217
218 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
220 match rule.category() {
221 RuleCategory::Heading => !self.has_headings,
222 RuleCategory::List => !self.has_lists,
223 RuleCategory::Link => !self.has_links && !self.has_images,
224 RuleCategory::Image => !self.has_images,
225 RuleCategory::CodeBlock => !self.has_code,
226 RuleCategory::Html => !self.has_html,
227 RuleCategory::Emphasis => !self.has_emphasis,
228 RuleCategory::Blockquote => !self.has_blockquotes,
229 RuleCategory::Table => !self.has_tables,
230 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
232 }
233 }
234}
235
236#[cfg(feature = "native")]
241fn compute_content_hash(content: &str) -> String {
242 #[cfg(feature = "profiling")]
243 let start = std::time::Instant::now();
244 let hash = blake3::hash(content.as_bytes()).to_hex().to_string();
245 #[cfg(feature = "profiling")]
246 profiling::record_duration("index: hash content", start.elapsed());
247 hash
248}
249
250#[cfg(not(feature = "native"))]
252fn compute_content_hash(content: &str) -> String {
253 use std::hash::{DefaultHasher, Hash, Hasher};
254 let mut hasher = DefaultHasher::new();
255 content.hash(&mut hasher);
256 format!("{:016x}", hasher.finish())
257}
258
259pub fn lint(
266 content: &str,
267 rules: &[Box<dyn Rule>],
268 verbose: bool,
269 flavor: crate::config::MarkdownFlavor,
270 source_file: Option<std::path::PathBuf>,
271 config: Option<&crate::config::Config>,
272) -> LintResult {
273 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, config);
274 result
275}
276
277pub fn build_file_index_only(
285 content: &str,
286 rules: &[Box<dyn Rule>],
287 flavor: crate::config::MarkdownFlavor,
288 source_file: Option<std::path::PathBuf>,
289) -> crate::workspace_index::FileIndex {
290 build_file_index_only_with_config(content, rules, flavor, source_file, &crate::config::Config::default())
291}
292
293pub fn build_file_index_only_with_config(
302 content: &str,
303 rules: &[Box<dyn Rule>],
304 flavor: crate::config::MarkdownFlavor,
305 source_file: Option<std::path::PathBuf>,
306 config: &crate::config::Config,
307) -> crate::workspace_index::FileIndex {
308 let conflicted = crate::merge_conflict::detect_configured(content, config, source_file.as_deref()).is_some();
309 build_index(content, rules, flavor, source_file, conflicted)
310}
311
312pub fn build_file_index_only_for_selection(
317 content: &str,
318 selection: &[Box<dyn Rule>],
319 flavor: crate::config::MarkdownFlavor,
320 source_file: Option<std::path::PathBuf>,
321 config: &crate::config::Config,
322) -> crate::workspace_index::FileIndex {
323 let conflicted =
324 crate::merge_conflict::detect_for_rules(content, selection, config, source_file.as_deref()).is_some();
325 build_index(content, selection, flavor, source_file, conflicted)
326}
327
328fn build_index(
329 content: &str,
330 rules: &[Box<dyn Rule>],
331 flavor: crate::config::MarkdownFlavor,
332 source_file: Option<std::path::PathBuf>,
333 conflicted: bool,
334) -> crate::workspace_index::FileIndex {
335 let content_hash = compute_content_hash(content);
337 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
338
339 if conflicted {
342 return file_index;
343 }
344
345 let content = crate::utils::bom::strip_bom(content);
347
348 if content.is_empty() {
350 return file_index;
351 }
352
353 let lint_ctx = time_function!(
355 "index: parse lint context",
356 crate::lint_context::LintContext::new(content, flavor, source_file)
357 );
358
359 let (file_disabled, persistent_transitions, line_disabled) = lint_ctx.inline_config().export_for_file_index();
363 file_index.file_disabled_rules = file_disabled;
364 file_index.persistent_transitions = persistent_transitions;
365 file_index.line_disabled_rules = line_disabled;
366
367 time_section!("index: contribute cross-file data", {
369 for rule in rules {
370 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
371 rule.contribute_to_index(&lint_ctx, &mut file_index);
372 }
373 }
374 });
375
376 file_index
377}
378
379fn conform_fix_line_endings(content: &str, warnings: &mut [crate::rule::LintWarning]) {
389 if !content.contains('\r') {
390 return;
391 }
392 let mixed = match crate::utils::detect_line_ending_enum(content) {
393 crate::utils::LineEnding::Lf => return,
394 crate::utils::LineEnding::Crlf => false,
395 crate::utils::LineEnding::Mixed => true,
396 };
397 fn conform(content: &str, mixed: bool, fix: &mut crate::rule::Fix) {
398 if fix.replacement.contains('\n')
399 && (!mixed || crate::utils::line_ending_before(content, fix.range.start) == "\r\n")
400 {
401 fix.replacement =
402 crate::utils::normalize_line_ending(&fix.replacement, crate::utils::LineEnding::Crlf).into_owned();
403 }
404 for extra in &mut fix.additional_edits {
405 conform(content, mixed, extra);
406 }
407 }
408 for fix in warnings.iter_mut().filter_map(|warning| warning.fix.as_mut()) {
409 conform(content, mixed, fix);
410 }
411}
412
413pub(crate) fn retain_reportable_warnings(
421 lint_ctx: &crate::lint_context::LintContext,
422 config: Option<&crate::config::Config>,
423 rule_name: &str,
424 rule_warnings: Vec<crate::rule::LintWarning>,
425 mut suppressed: Option<&mut Vec<crate::rule::SuppressedWarning>>,
426) -> Vec<crate::rule::LintWarning> {
427 let inline_config = lint_ctx.inline_config();
428 let mut kept = Vec::with_capacity(rule_warnings.len());
429
430 for mut warning in rule_warnings {
431 if lint_ctx
432 .line_info(warning.line)
433 .is_some_and(|info| info.in_kramdown_extension_block)
434 {
435 continue;
436 }
437
438 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule_name);
440
441 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
443 &rule_name_to_check[..dash_pos]
444 } else {
445 rule_name_to_check
446 };
447
448 let end = if warning.end_line >= warning.line {
454 warning.end_line
455 } else {
456 warning.line
457 };
458 let disabled_at = (warning.line..=end).find_map(|line| {
459 inline_config
460 .disabling_layer(base_rule_name, line)
461 .map(|layer| (line, layer))
462 });
463 if let Some((line, layer)) = disabled_at {
464 if let Some(record) = suppressed.as_deref_mut() {
465 record.push(crate::rule::SuppressedWarning {
466 rule_name: base_rule_name.to_string(),
467 line,
468 layer,
469 });
470 }
471 continue;
472 }
473
474 if let Some(cfg) = config
476 && let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check)
477 {
478 warning.severity = override_severity;
479 }
480
481 kept.push(warning);
482 }
483
484 kept
485}
486
487#[cfg_attr(test, allow(unused_variables))]
498#[allow(clippy::needless_pass_by_value)] pub fn lint_and_index(
500 content: &str,
501 rules: &[Box<dyn Rule>],
502 verbose: bool,
503 flavor: crate::config::MarkdownFlavor,
504 source_file: Option<std::path::PathBuf>,
505 config: Option<&crate::config::Config>,
506) -> (LintResult, crate::workspace_index::FileIndex) {
507 lint_and_index_with_paths(
508 content,
509 rules,
510 verbose,
511 flavor,
512 DocumentPaths::same(source_file.as_deref()),
513 config,
514 )
515}
516
517#[derive(Debug, Clone, Copy, Default)]
519pub struct DocumentPaths<'a> {
520 pub config_path: Option<&'a std::path::Path>,
522 pub source_file: Option<&'a std::path::Path>,
524 pub link_target_policy: Option<&'a crate::lint_context::LinkTargetPolicy>,
526 pub invalid_utf8: Option<&'a [crate::encoding::InvalidSeq]>,
528}
529
530impl<'a> DocumentPaths<'a> {
531 pub fn same(path: Option<&'a std::path::Path>) -> Self {
533 Self {
534 config_path: path,
535 source_file: path,
536 link_target_policy: None,
537 invalid_utf8: None,
538 }
539 }
540}
541
542#[cfg_attr(test, allow(unused_variables))]
549pub fn lint_and_index_with_paths(
550 content: &str,
551 rules: &[Box<dyn Rule>],
552 verbose: bool,
553 flavor: crate::config::MarkdownFlavor,
554 paths: DocumentPaths<'_>,
555 config: Option<&crate::config::Config>,
556) -> (LintResult, crate::workspace_index::FileIndex) {
557 let result = analyze_document(content, rules, verbose, flavor, paths, config, None);
558 (result.warnings, result.file_index)
559}
560
561#[allow(clippy::too_many_arguments)]
562pub(crate) fn analyze_document(
563 content: &str,
564 rules: &[Box<dyn Rule>],
565 verbose: bool,
566 flavor: crate::config::MarkdownFlavor,
567 paths: DocumentPaths<'_>,
568 config: Option<&crate::config::Config>,
569 prepare_fixes: Option<usize>,
570) -> document_run::DocumentFormatResult {
571 analyze_scanned_document(
572 &crate::merge_conflict::ConflictScan::new(content),
573 rules,
574 verbose,
575 flavor,
576 paths,
577 config,
578 prepare_fixes,
579 )
580}
581
582pub(crate) fn analyze_scanned_document(
583 scan: &crate::merge_conflict::ConflictScan<'_>,
584 rules: &[Box<dyn Rule>],
585 verbose: bool,
586 flavor: crate::config::MarkdownFlavor,
587 paths: DocumentPaths<'_>,
588 config: Option<&crate::config::Config>,
589 prepare_fixes: Option<usize>,
590) -> document_run::DocumentFormatResult {
591 use document_run::DocumentFormatResult;
592 let content = scan.content();
593 let content_hash = compute_content_hash(content);
595 let file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
596
597 let conflict = config.map_or_else(
598 || scan.detect_for_rules(rules, &crate::config::Config::default(), paths.config_path),
599 |config| scan.detect_for_rules(rules, config, paths.config_path),
600 );
601 if let Some(conflict) = conflict {
602 return DocumentFormatResult::without_fixes(Ok(vec![conflict]), file_index);
603 }
604
605 let carrier = content;
607 let content = crate::utils::bom::strip_bom(carrier);
608
609 if content.is_empty() {
611 return DocumentFormatResult::without_fixes(Ok(Vec::new()), file_index);
612 }
613
614 let lint_ctx = time_function!(
616 "lint: parse lint context",
617 crate::lint_context::LintContext::new(content, flavor, paths.source_file.map(std::path::Path::to_path_buf))
618 .with_merge_conflicts(scan.markers())
619 );
620 let lint_ctx = match paths.link_target_policy {
621 Some(policy) => lint_ctx.with_link_target_policy(policy.clone()),
622 None => lint_ctx,
623 };
624 let lint_ctx = match paths.invalid_utf8 {
625 Some(invalid) => lint_ctx.with_invalid_utf8(invalid),
626 None => lint_ctx,
627 };
628 let (warnings, file_index, checked_rules) = check_document_context(
629 &lint_ctx,
630 rules,
631 verbose,
632 paths,
633 config,
634 file_index,
635 prepare_fixes.is_some(),
636 Default::default(),
637 );
638 let mut remaining_warnings = None;
639 let fixes = if warnings.as_ref().is_ok_and(|warnings| !warnings.is_empty())
640 && paths.invalid_utf8.is_none()
641 && let (Some(max_iterations), Some(config), Some(checks)) = (prepare_fixes, config, checked_rules)
642 {
643 let mut fixed = content.to_string();
644 let mut on_stable = |ctx: &crate::lint_context::LintContext<'_>,
645 checks: &mut fix_coordinator::RawRuleChecks| {
646 if ctx.content != content {
647 let index = crate::workspace_index::FileIndex::with_hash(compute_content_hash(ctx.content));
648 remaining_warnings = Some(
649 check_document_context(
650 ctx,
651 rules,
652 false,
653 paths,
654 Some(config),
655 index,
656 false,
657 std::mem::take(checks),
658 )
659 .0,
660 );
661 }
662 };
663 let result = fix_coordinator::FixCoordinator::new().apply_fixes_with_analysis(
664 rules,
665 &mut fixed,
666 config,
667 max_iterations,
668 paths,
669 Some((&lint_ctx, &checks)),
670 Some(&mut on_stable),
671 );
672 if crate::utils::bom::has_bom(carrier) {
673 fixed.insert(0, crate::utils::bom::BOM);
674 }
675 Some(Ok((fixed, result)))
676 } else {
677 None
678 };
679 let shift = crate::utils::bom::bom_len(carrier);
682 let mut warnings = warnings;
683 if let Ok(warnings) = &mut warnings {
684 crate::utils::bom::restore_fix_offsets(warnings, shift);
685 }
686 if let Some(Ok(warnings)) = &mut remaining_warnings {
687 crate::utils::bom::restore_fix_offsets(warnings, shift);
688 }
689 DocumentFormatResult {
690 warnings,
691 file_index,
692 fixes,
693 remaining_warnings,
694 }
695}
696
697#[allow(clippy::too_many_arguments)]
701fn check_document_context(
702 lint_ctx: &crate::lint_context::LintContext<'_>,
703 rules: &[Box<dyn Rule>],
704 verbose: bool,
705 paths: DocumentPaths<'_>,
706 config: Option<&crate::config::Config>,
707 mut file_index: crate::workspace_index::FileIndex,
708 collect_fix_checks: bool,
709 mut cached_checks: fix_coordinator::RawRuleChecks,
710) -> (
711 LintResult,
712 crate::workspace_index::FileIndex,
713 Option<fix_coordinator::FixCheckResults>,
714) {
715 let content = lint_ctx.content;
716 let mut warnings = Vec::new();
717 let ignored_for_file = match (config, paths.config_path) {
724 (Some(cfg), Some(path)) => cfg.get_ignored_rules_for_file(path),
725 _ => std::collections::HashSet::new(),
726 };
727 let inline_config = lint_ctx.inline_config();
728
729 let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
731 file_index.file_disabled_rules = file_disabled;
732 file_index.persistent_transitions = persistent_transitions;
733 file_index.line_disabled_rules = line_disabled;
734
735 let characteristics = time_function!(
737 "lint: analyze content characteristics",
738 ContentCharacteristics::analyze(content)
739 );
740
741 let applicable_rules: Vec<_> = rules
743 .iter()
744 .filter(|rule| !ignored_for_file.contains(rule.name()))
745 .filter(|rule| !(rule.skippable_by_category() && characteristics.should_skip_rule(rule.as_ref())))
746 .collect();
747
748 #[cfg(not(test))]
750 let total_rules = rules.len();
751 #[cfg(not(test))]
752 let applicable_count = applicable_rules.len();
753
754 #[cfg(not(target_arch = "wasm32"))]
755 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
756
757 let inline_overrides = inline_config.get_all_rule_configs();
760 let merged_config = if !inline_overrides.is_empty() {
761 config.map(|c| c.merge_with_inline_config(inline_config))
762 } else {
763 None
764 };
765 let effective_config = merged_config.as_ref().or(config);
766
767 let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
769 std::collections::HashMap::new();
770
771 if let Some(cfg) = effective_config {
773 for rule_name in inline_overrides.keys() {
774 if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
775 recreated_rules.insert(rule_name.clone(), recreated);
776 }
777 }
778 }
779
780 let suppression_observers: Vec<_> = applicable_rules
784 .iter()
785 .filter(|rule| rule.observes_suppressions() && !rule.should_skip(lint_ctx))
786 .collect();
787 let mut suppressed = Vec::new();
788 let mut checked_rules = collect_fix_checks.then(std::collections::HashMap::new);
791
792 {
793 let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
794 for rule in &applicable_rules {
795 #[cfg(not(target_arch = "wasm32"))]
796 let rule_start = (profile_rules || verbose).then(Instant::now);
797
798 if rule.should_skip(lint_ctx) {
800 continue;
801 }
802
803 let effective_rule: &dyn crate::rule::Rule = recreated_rules
805 .get(rule.name())
806 .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
807
808 let result = cached_checks
810 .remove(&fix_coordinator::rule_check_key(rule.as_ref()))
811 .map_or_else(|| effective_rule.check(lint_ctx), Ok);
812
813 match result {
814 Ok(rule_warnings) => {
815 if let Some(checks) = &mut checked_rules {
816 checks.insert(
817 fix_coordinator::rule_check_key(rule.as_ref()),
818 fix_coordinator::FixPlan::capture(effective_rule, lint_ctx, &rule_warnings),
819 );
820 }
821 let record = if suppression_observers.is_empty() {
822 None
823 } else {
824 Some(&mut suppressed)
825 };
826 let filtered_warnings =
827 retain_reportable_warnings(lint_ctx, config, rule.name(), rule_warnings, record);
828 warnings.extend(filtered_warnings);
829 }
830 Err(e) => {
831 log::error!("Error checking rule {}: {}", rule.name(), e);
832 return (Err(e), file_index, checked_rules);
833 }
834 }
835
836 #[cfg(not(target_arch = "wasm32"))]
837 {
838 if let Some(rule_start) = rule_start {
839 let rule_duration = rule_start.elapsed();
840 if profile_rules {
841 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
842 }
843
844 #[cfg(not(test))]
845 if verbose && rule_duration.as_millis() > 500 {
846 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
847 }
848 }
849 }
850 }
851 }
852
853 if !suppression_observers.is_empty() {
856 let _timer = profiling::ScopedTimer::new("lint: run suppression rules");
857
858 let report = crate::rule::SuppressionReport {
863 suppressed,
864 judged_rules: rules
865 .iter()
866 .filter(|rule| rule.cross_file_scope() != crate::rule::CrossFileScope::Workspace)
867 .filter(|rule| !ignored_for_file.contains(rule.name()))
868 .map(|rule| rule.name().to_string())
869 .collect(),
870 };
871
872 for rule in &suppression_observers {
873 match rule.check_suppressions(lint_ctx, &report) {
874 Ok(rule_warnings) => {
875 let filtered_warnings =
876 retain_reportable_warnings(lint_ctx, config, rule.name(), rule_warnings, None);
877 warnings.extend(filtered_warnings);
878 }
879 Err(e) => {
880 log::error!("Error checking rule {}: {}", rule.name(), e);
881 return (Err(e), file_index, checked_rules);
882 }
883 }
884 }
885 }
886
887 time_section!("lint: contribute cross-file data", {
895 for rule in rules {
896 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
897 rule.contribute_to_index(lint_ctx, &mut file_index);
898 }
899 }
900 });
901
902 #[cfg(not(test))]
903 if verbose {
904 let skipped_rules = total_rules - applicable_count;
905 if skipped_rules > 0 {
906 log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
907 }
908 }
909
910 if paths.invalid_utf8.is_some() {
911 crate::encoding::settle_lossy_warnings(&mut warnings);
912 }
913
914 conform_fix_line_endings(content, &mut warnings);
915
916 (Ok(warnings), file_index, checked_rules)
917}
918
919pub fn run_cross_file_checks(
932 file_path: &std::path::Path,
933 file_index: &crate::workspace_index::FileIndex,
934 rules: &[Box<dyn Rule>],
935 workspace_index: &crate::workspace_index::WorkspaceIndex,
936 config: Option<&crate::config::Config>,
937) -> LintResult {
938 use crate::rule::CrossFileScope;
939
940 let mut warnings = Vec::new();
941
942 let ignored_rules_for_file = config.map(|cfg| cfg.get_ignored_rules_for_file(file_path));
948
949 for rule in rules {
951 if rule.cross_file_scope() != CrossFileScope::Workspace {
952 continue;
953 }
954
955 if ignored_rules_for_file
956 .as_ref()
957 .is_some_and(|ignored| ignored.contains(rule.name()))
958 {
959 continue;
960 }
961
962 match time_function!(
963 "workspace: cross-file rule check",
964 rule.cross_file_check(file_path, file_index, workspace_index)
965 ) {
966 Ok(rule_warnings) => {
967 let filtered: Vec<_> = rule_warnings
969 .into_iter()
970 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
971 .map(|mut warning| {
972 if let Some(cfg) = config
974 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
975 {
976 warning.severity = override_severity;
977 }
978 warning
979 })
980 .collect();
981 warnings.extend(filtered);
982 }
983 Err(e) => {
984 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
985 return Err(e);
986 }
987 }
988 }
989
990 Ok(warnings)
991}
992
993pub fn get_profiling_report() -> String {
995 profiling::get_report()
996}
997
998pub fn reset_profiling() {
1000 profiling::reset()
1001}
1002
1003pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
1005 crate::utils::regex_cache::get_cache_stats()
1006}
1007
1008#[cfg(test)]
1009mod tests {
1010 use super::*;
1011 use crate::rule::Rule;
1012 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
1013
1014 #[test]
1015 fn test_content_characteristics_analyze() {
1016 let chars = ContentCharacteristics::analyze("");
1018 assert!(!chars.has_headings);
1019 assert!(!chars.has_lists);
1020 assert!(!chars.has_links);
1021 assert!(!chars.has_code);
1022 assert!(!chars.has_emphasis);
1023 assert!(!chars.has_html);
1024 assert!(!chars.has_tables);
1025 assert!(!chars.has_blockquotes);
1026 assert!(!chars.has_images);
1027
1028 let chars = ContentCharacteristics::analyze("# Heading");
1030 assert!(chars.has_headings);
1031
1032 let chars = ContentCharacteristics::analyze("Heading\n=======");
1034 assert!(chars.has_headings);
1035
1036 let chars = ContentCharacteristics::analyze("> ## Alpha\n>\n> ## Alpha");
1039 assert!(chars.has_headings, "blockquoted ATX heading must set has_headings");
1040 let chars = ContentCharacteristics::analyze(">> # Nested");
1041 assert!(
1042 chars.has_headings,
1043 "nested-blockquote ATX heading must set has_headings"
1044 );
1045 let chars = ContentCharacteristics::analyze(">\t## Tabbed");
1048 assert!(
1049 chars.has_headings,
1050 "tab-separated blockquote ATX heading must set has_headings"
1051 );
1052
1053 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
1055 assert!(chars.has_lists);
1056
1057 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
1059 assert!(chars.has_lists);
1060
1061 let chars = ContentCharacteristics::analyze("[link](url)");
1063 assert!(chars.has_links);
1064
1065 let chars = ContentCharacteristics::analyze("Visit https://example.com");
1067 assert!(chars.has_links);
1068
1069 let chars = ContentCharacteristics::analyze("");
1071 assert!(chars.has_images);
1072
1073 let chars = ContentCharacteristics::analyze("`inline code`");
1075 assert!(chars.has_code);
1076
1077 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
1078 assert!(chars.has_code);
1079
1080 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
1082 assert!(chars.has_code);
1083
1084 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
1086 assert!(chars.has_code);
1087
1088 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
1090 assert!(chars.has_code);
1091
1092 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
1094 assert!(chars.has_code);
1095
1096 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
1098 assert!(chars.has_emphasis);
1099
1100 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
1102 assert!(chars.has_html);
1103
1104 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
1106 assert!(chars.has_tables);
1107
1108 let chars = ContentCharacteristics::analyze("> Quote");
1110 assert!(chars.has_blockquotes);
1111
1112 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
1114 let chars = ContentCharacteristics::analyze(content);
1115 assert!(chars.has_headings);
1116 assert!(chars.has_lists);
1117 assert!(chars.has_links);
1118 assert!(chars.has_code);
1119 assert!(chars.has_emphasis);
1120 assert!(chars.has_html);
1121 assert!(chars.has_tables);
1122 assert!(chars.has_blockquotes);
1123 assert!(chars.has_images);
1124 }
1125
1126 #[test]
1127 fn test_content_characteristics_parenthesized_ordered_list() {
1128 assert!(ContentCharacteristics::analyze("1) first\n2) second").has_lists);
1129 assert!(ContentCharacteristics::analyze(" 1) indented first\n 2) second").has_lists);
1130 assert!(ContentCharacteristics::analyze("> 1) quoted item").has_lists);
1131 }
1132
1133 #[test]
1134 fn test_content_characteristics_should_skip_rule() {
1135 let chars = ContentCharacteristics {
1136 has_headings: true,
1137 has_lists: false,
1138 has_links: true,
1139 has_code: false,
1140 has_emphasis: true,
1141 has_html: false,
1142 has_tables: true,
1143 has_blockquotes: false,
1144 has_images: false,
1145 };
1146
1147 let heading_rule = MD001HeadingIncrement::default();
1149 assert!(!chars.should_skip_rule(&heading_rule));
1150
1151 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
1152 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
1156 has_headings: false,
1157 ..Default::default()
1158 };
1159 assert!(chars_no_headings.should_skip_rule(&heading_rule));
1160 }
1161
1162 #[test]
1163 fn test_lint_empty_content() {
1164 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1165
1166 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
1167 assert!(result.is_ok());
1168 assert!(result.unwrap().is_empty());
1169 }
1170
1171 #[test]
1172 fn test_lint_with_violations() {
1173 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1175
1176 let result = lint(
1177 content,
1178 &rules,
1179 false,
1180 crate::config::MarkdownFlavor::Standard,
1181 None,
1182 None,
1183 );
1184 assert!(result.is_ok());
1185 let warnings = result.unwrap();
1186 assert!(!warnings.is_empty());
1187 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
1189 }
1190
1191 #[test]
1192 fn test_lint_with_inline_disable() {
1193 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
1194 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1195
1196 let result = lint(
1197 content,
1198 &rules,
1199 false,
1200 crate::config::MarkdownFlavor::Standard,
1201 None,
1202 None,
1203 );
1204 assert!(result.is_ok());
1205 let warnings = result.unwrap();
1206 assert!(warnings.is_empty()); }
1208
1209 #[test]
1210 fn test_lint_checks_setext_headings_the_content_prefilter_must_keep() {
1211 let rules: Vec<Box<dyn Rule>> = vec![Box::new(crate::rules::MD080HeadingAnchorCollision::new())];
1215 for content in [
1216 "Title\n-\n\ntitle\n-\n",
1217 "Title\n=\n\ntitle\n=\n",
1218 "> Title\n> ===\n\n> title\n> ===\n",
1219 "> Title\n> -\n\n> title\n> -\n",
1220 ] {
1221 let warnings = lint(
1222 content,
1223 &rules,
1224 false,
1225 crate::config::MarkdownFlavor::Standard,
1226 None,
1227 None,
1228 )
1229 .unwrap();
1230 let lines: Vec<_> = warnings.iter().map(|warning| warning.line).collect();
1231 assert_eq!(lines, [4], "{content:?}");
1232 }
1233 }
1234
1235 #[test]
1236 fn test_lint_rule_filtering() {
1237 let content = "# Heading\nJust text";
1239 let rules: Vec<Box<dyn Rule>> = vec![
1240 Box::new(MD001HeadingIncrement::default()),
1241 ];
1243
1244 let result = lint(
1245 content,
1246 &rules,
1247 false,
1248 crate::config::MarkdownFlavor::Standard,
1249 None,
1250 None,
1251 );
1252 assert!(result.is_ok());
1253 }
1254
1255 #[test]
1256 fn test_get_profiling_report() {
1257 let report = get_profiling_report();
1259 assert!(!report.is_empty());
1260 assert!(report.contains("Profiling"));
1261 }
1262
1263 #[test]
1264 fn test_reset_profiling() {
1265 reset_profiling();
1267
1268 let report = get_profiling_report();
1270 assert!(report.contains("disabled") || report.contains("no measurements"));
1271 }
1272
1273 #[test]
1274 fn test_get_regex_cache_stats() {
1275 let stats = get_regex_cache_stats();
1276 assert!(stats.is_empty() || !stats.is_empty());
1278
1279 for count in stats.values() {
1281 assert!(*count > 0);
1282 }
1283 }
1284
1285 #[test]
1286 fn test_content_characteristics_edge_cases() {
1287 for content in [
1290 "Title\n-",
1291 "Title\n=",
1292 "Title\n--",
1293 "> Title\n> ===",
1294 ">\tTitle\n>\t-",
1295 ">> Title\n>>-",
1296 ] {
1297 assert!(ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1298 }
1299 for content in ["- ## Title", "1. # Title", "- - # Title", "> - ## Title", "10) # Title"] {
1301 assert!(ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1302 }
1303 for content in ["> Prose\n>", "Prose\n> text", "Prose\n"] {
1304 assert!(!ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1305 }
1306
1307 let chars = ContentCharacteristics::analyze("*emphasis*"); assert!(chars.has_lists); let chars = ContentCharacteristics::analyze("1.Item"); assert!(chars.has_lists); let chars = ContentCharacteristics::analyze("text > not a quote");
1317 assert!(!chars.has_blockquotes);
1318 }
1319
1320 const LINE_INSERTING_FIXES: &str = "---\ntitle: x\n---\n# Heading\ntext\n## Sub\n- item\ntext\n```sh\n$ ls\n```\ntext\n| a | b |\n|---|---|\n| 1 | 2 |\ntext";
1326
1327 fn fix_replacements(content: &str) -> Vec<(String, String)> {
1329 let config = crate::config::Config::default();
1330 let rules = crate::rules::all_rules(&config);
1331 let warnings = lint(
1332 content,
1333 &rules,
1334 false,
1335 crate::config::MarkdownFlavor::Standard,
1336 None,
1337 Some(&config),
1338 )
1339 .unwrap();
1340 let mut out = Vec::new();
1341 for warning in warnings {
1342 let Some(fix) = warning.fix else { continue };
1343 let rule = warning.rule_name.clone().unwrap_or_default();
1344 let mut stack = vec![fix];
1345 while let Some(fix) = stack.pop() {
1346 out.push((rule.clone(), fix.replacement.clone()));
1347 stack.extend(fix.additional_edits);
1348 }
1349 }
1350 out
1351 }
1352
1353 fn has_bare_lf(text: &str) -> bool {
1354 let bytes = text.as_bytes();
1355 bytes
1356 .iter()
1357 .enumerate()
1358 .any(|(i, b)| *b == b'\n' && (i == 0 || bytes[i - 1] != b'\r'))
1359 }
1360
1361 #[test]
1362 fn fix_replacements_use_the_documents_crlf_line_ending() {
1363 let crlf = LINE_INSERTING_FIXES.replace('\n', "\r\n");
1364 let replacements = fix_replacements(&crlf);
1365
1366 let bare: Vec<_> = replacements.iter().filter(|(_, r)| has_bare_lf(r)).collect();
1367 assert!(bare.is_empty(), "bare LF in a fix for a CRLF document: {bare:?}");
1368
1369 let mut crlf_rules: Vec<_> = replacements
1372 .iter()
1373 .filter(|(_, r)| r.contains("\r\n"))
1374 .map(|(rule, _)| rule.as_str())
1375 .collect();
1376 crlf_rules.sort_unstable();
1377 crlf_rules.dedup();
1378 for rule in ["MD014", "MD022", "MD031", "MD032", "MD047", "MD058", "MD071"] {
1379 assert!(
1380 crlf_rules.contains(&rule),
1381 "{rule} inserted no CRLF line ending; got {crlf_rules:?}"
1382 );
1383 }
1384 }
1385
1386 #[test]
1387 fn fix_replacements_stay_lf_for_lf_documents() {
1388 let lf = fix_replacements(LINE_INSERTING_FIXES);
1390 assert!(lf.iter().any(|(_, r)| has_bare_lf(r)));
1391 assert!(!lf.iter().any(|(_, r)| r.contains('\r')));
1392 }
1393
1394 #[test]
1395 fn fix_replacements_in_a_mixed_document_take_the_ending_of_the_line_they_follow() {
1396 let mixed: String = LINE_INSERTING_FIXES
1398 .split_inclusive('\n')
1399 .enumerate()
1400 .map(|(i, line)| {
1401 if i % 2 == 0 {
1402 line.replace('\n', "\r\n")
1403 } else {
1404 line.to_string()
1405 }
1406 })
1407 .collect();
1408 assert_eq!(
1409 crate::utils::detect_line_ending_enum(&mixed),
1410 crate::utils::LineEnding::Mixed
1411 );
1412
1413 let ending_before = |offset: usize| {
1415 let target = offset.saturating_sub(1);
1416 let mut start = 0;
1417 let mut last_ending = "\n";
1418 for line in mixed.split_inclusive('\n') {
1419 let ending = if line.ends_with("\r\n") {
1420 "\r\n"
1421 } else if line.ends_with('\n') {
1422 "\n"
1423 } else {
1424 last_ending
1425 };
1426 if target < start + line.len() {
1427 return ending;
1428 }
1429 last_ending = ending;
1430 start += line.len();
1431 }
1432 last_ending
1433 };
1434
1435 let config = crate::config::Config::default();
1436 let rules = crate::rules::all_rules(&config);
1437 let warnings = lint(
1438 &mixed,
1439 &rules,
1440 false,
1441 crate::config::MarkdownFlavor::Standard,
1442 None,
1443 Some(&config),
1444 )
1445 .unwrap();
1446 let mut seen = [false, false];
1447 let mut stack: Vec<_> = warnings.into_iter().filter_map(|warning| warning.fix).collect();
1448 while let Some(fix) = stack.pop() {
1449 if fix.replacement.contains('\n') {
1450 let crlf = ending_before(fix.range.start) == "\r\n";
1451 seen[usize::from(crlf)] = true;
1452 assert_eq!(
1453 has_bare_lf(&fix.replacement),
1454 !crlf,
1455 "replacement {:?} at {} in {mixed:?}",
1456 fix.replacement,
1457 fix.range.start
1458 );
1459 }
1460 stack.extend(fix.additional_edits);
1461 }
1462 assert_eq!(seen, [true, true], "fixture should insert lines after both endings");
1463 }
1464}
1465
1466#[doc(hidden)]
1467pub mod format_proof;