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
50extern crate alloc;
51
52pub mod code_block_tools;
53pub mod config;
54#[cfg(any(feature = "native", feature = "wasi"))]
55#[doc(hidden)]
56pub mod custom_rules;
57pub mod discovery;
58pub mod doc_comment_lint;
59pub mod document_run;
60pub mod embedded_lint;
61pub mod encoding;
62pub mod exit_codes;
63pub mod filtered_lines;
64pub mod fix_coordinator;
65pub mod inline_config;
66pub mod linguist_data;
67pub mod lint_context;
68pub mod markdownlint_config;
69mod mdx_parser;
70pub mod merge_conflict;
71pub mod profiling;
72pub mod rule;
73pub mod unused_assets;
74#[cfg(feature = "colored")]
75pub mod vscode;
76pub mod workspace_index;
77#[macro_use]
78pub mod rule_config;
79#[macro_use]
80pub mod rule_config_serde;
81pub mod rules;
82#[doc(hidden)]
83pub mod source_paths;
84pub mod types;
85pub mod utils;
86
87#[cfg(feature = "native")]
89pub mod lsp;
90#[cfg(feature = "colored")]
91pub mod output;
92
93#[cfg(feature = "wasm")]
95pub mod wasm;
96
97pub use rules::heading_utils::HeadingStyle;
98pub use rules::*;
99
100pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
101use crate::rule::{LintResult, Rule, RuleCategory};
102use crate::utils::calculate_indentation_width_default;
103#[cfg(not(target_arch = "wasm32"))]
104use std::time::Instant;
105
106#[derive(Debug, Default)]
108struct ContentCharacteristics {
109 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, }
119
120fn has_potential_indented_code_indent(line: &str) -> bool {
123 calculate_indentation_width_default(line) >= 4
124}
125
126impl ContentCharacteristics {
127 fn analyze(content: &str) -> Self {
128 let mut chars = Self { ..Default::default() };
129
130 let mut has_atx_heading = false;
132 let mut has_setext_heading = false;
133
134 for line in content.lines() {
135 let trimmed = line.trim();
136
137 if !has_atx_heading
148 && (trimmed.starts_with('#')
149 || trimmed
150 .trim_start_matches([
151 '>', ' ', '\t', '-', '+', '*', '.', ')', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
152 ])
153 .starts_with('#'))
154 {
155 has_atx_heading = true;
156 }
157 let underline = trimmed.trim_start_matches(['>', ' ', '\t']);
160 if !has_setext_heading && !underline.is_empty() && underline.chars().all(|c| c == '=' || c == '-') {
161 has_setext_heading = true;
162 }
163
164 if !chars.has_lists
167 && (line.contains("* ")
168 || line.contains("- ")
169 || line.contains("+ ")
170 || trimmed.starts_with("* ")
171 || trimmed.starts_with("- ")
172 || trimmed.starts_with("+ ")
173 || trimmed.starts_with('*')
174 || trimmed.starts_with('-')
175 || trimmed.starts_with('+'))
176 {
177 chars.has_lists = true;
178 }
179 if !chars.has_lists
183 && ((trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) && trimmed.contains(['.', ')']))
184 || (trimmed.starts_with('>')
185 && trimmed.chars().any(|c| c.is_ascii_digit())
186 && trimmed.contains(['.', ')'])))
187 {
188 chars.has_lists = true;
189 }
190 if !chars.has_links
191 && (line.contains('[')
192 || line.contains("http://")
193 || line.contains("https://")
194 || line.contains("ftp://")
195 || line.contains("www."))
196 {
197 chars.has_links = true;
198 }
199 if !chars.has_images && line.contains("![") {
200 chars.has_images = true;
201 }
202 if !chars.has_code
203 && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
204 {
205 chars.has_code = true;
206 }
207 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
208 chars.has_emphasis = true;
209 }
210 if !chars.has_html && line.contains('<') {
211 chars.has_html = true;
212 }
213 if !chars.has_tables && line.contains('|') {
214 chars.has_tables = true;
215 }
216 if !chars.has_blockquotes && line.starts_with('>') {
217 chars.has_blockquotes = true;
218 }
219 }
220
221 chars.has_headings = has_atx_heading || has_setext_heading;
222 chars
223 }
224
225 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
227 match rule.category() {
228 RuleCategory::Heading => !self.has_headings,
229 RuleCategory::List => !self.has_lists,
230 RuleCategory::Link => !self.has_links && !self.has_images,
231 RuleCategory::Image => !self.has_images,
232 RuleCategory::CodeBlock => !self.has_code,
233 RuleCategory::Html => !self.has_html,
234 RuleCategory::Emphasis => !self.has_emphasis,
235 RuleCategory::Blockquote => !self.has_blockquotes,
236 RuleCategory::Table => !self.has_tables,
237 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
239 }
240 }
241}
242
243#[cfg(feature = "native")]
248fn compute_content_hash(content: &str) -> String {
249 #[cfg(feature = "profiling")]
250 let start = std::time::Instant::now();
251 let hash = blake3::hash(content.as_bytes()).to_hex().to_string();
252 #[cfg(feature = "profiling")]
253 profiling::record_duration("index: hash content", start.elapsed());
254 hash
255}
256
257#[cfg(not(feature = "native"))]
259fn compute_content_hash(content: &str) -> String {
260 use std::hash::{DefaultHasher, Hash, Hasher};
261 let mut hasher = DefaultHasher::new();
262 content.hash(&mut hasher);
263 format!("{:016x}", hasher.finish())
264}
265
266pub fn lint(
273 content: &str,
274 rules: &[Box<dyn Rule>],
275 verbose: bool,
276 flavor: crate::config::MarkdownFlavor,
277 source_file: Option<std::path::PathBuf>,
278 config: Option<&crate::config::Config>,
279) -> LintResult {
280 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, config);
281 result
282}
283
284pub fn build_file_index_only(
292 content: &str,
293 rules: &[Box<dyn Rule>],
294 flavor: crate::config::MarkdownFlavor,
295 source_file: Option<std::path::PathBuf>,
296) -> crate::workspace_index::FileIndex {
297 build_file_index_only_with_config(content, rules, flavor, source_file, &crate::config::Config::default())
298}
299
300pub fn build_file_index_only_with_config(
309 content: &str,
310 rules: &[Box<dyn Rule>],
311 flavor: crate::config::MarkdownFlavor,
312 source_file: Option<std::path::PathBuf>,
313 config: &crate::config::Config,
314) -> crate::workspace_index::FileIndex {
315 let conflicted = crate::merge_conflict::detect_configured(content, config, source_file.as_deref()).is_some();
316 build_index(content, rules, flavor, source_file, conflicted)
317}
318
319pub fn build_file_index_only_for_selection(
324 content: &str,
325 selection: &[Box<dyn Rule>],
326 flavor: crate::config::MarkdownFlavor,
327 source_file: Option<std::path::PathBuf>,
328 config: &crate::config::Config,
329) -> crate::workspace_index::FileIndex {
330 let conflicted =
331 crate::merge_conflict::detect_for_rules(content, selection, config, source_file.as_deref()).is_some();
332 build_index(content, selection, flavor, source_file, conflicted)
333}
334
335fn build_index(
336 content: &str,
337 rules: &[Box<dyn Rule>],
338 flavor: crate::config::MarkdownFlavor,
339 source_file: Option<std::path::PathBuf>,
340 conflicted: bool,
341) -> crate::workspace_index::FileIndex {
342 let content_hash = compute_content_hash(content);
344 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
345
346 if conflicted {
349 return file_index;
350 }
351
352 let content = crate::utils::bom::strip_bom(content);
354
355 if content.is_empty() {
357 return file_index;
358 }
359
360 let lint_ctx = time_function!(
362 "index: parse lint context",
363 crate::lint_context::LintContext::new(content, flavor, source_file)
364 );
365
366 let (file_disabled, persistent_transitions, line_disabled) = lint_ctx.inline_config().export_for_file_index();
370 file_index.file_disabled_rules = file_disabled;
371 file_index.persistent_transitions = persistent_transitions;
372 file_index.line_disabled_rules = line_disabled;
373
374 time_section!("index: contribute cross-file data", {
376 for rule in rules {
377 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
378 rule.contribute_to_index(&lint_ctx, &mut file_index);
379 }
380 }
381 });
382
383 file_index
384}
385
386fn conform_fix_line_endings(content: &str, warnings: &mut [crate::rule::LintWarning]) {
396 if !content.contains('\r') {
397 return;
398 }
399 let mixed = match crate::utils::detect_line_ending_enum(content) {
400 crate::utils::LineEnding::Lf => return,
401 crate::utils::LineEnding::Crlf => false,
402 crate::utils::LineEnding::Mixed => true,
403 };
404 fn conform(content: &str, mixed: bool, fix: &mut crate::rule::Fix) {
405 if fix.replacement.contains('\n')
406 && (!mixed || crate::utils::line_ending_before(content, fix.range.start) == "\r\n")
407 {
408 fix.replacement =
409 crate::utils::normalize_line_ending(&fix.replacement, crate::utils::LineEnding::Crlf).into_owned();
410 }
411 for extra in &mut fix.additional_edits {
412 conform(content, mixed, extra);
413 }
414 }
415 for fix in warnings.iter_mut().filter_map(|warning| warning.fix.as_mut()) {
416 conform(content, mixed, fix);
417 }
418}
419
420pub(crate) fn retain_reportable_warnings(
428 lint_ctx: &crate::lint_context::LintContext,
429 config: Option<&crate::config::Config>,
430 rule_name: &str,
431 rule_warnings: Vec<crate::rule::LintWarning>,
432 mut suppressed: Option<&mut Vec<crate::rule::SuppressedWarning>>,
433) -> Vec<crate::rule::LintWarning> {
434 let inline_config = lint_ctx.inline_config();
435 let mut kept = Vec::with_capacity(rule_warnings.len());
436
437 for mut warning in rule_warnings {
438 if lint_ctx
439 .line_info(warning.line)
440 .is_some_and(|info| info.in_kramdown_extension_block)
441 {
442 continue;
443 }
444
445 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule_name);
447
448 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
450 &rule_name_to_check[..dash_pos]
451 } else {
452 rule_name_to_check
453 };
454
455 let end = if warning.end_line >= warning.line {
461 warning.end_line
462 } else {
463 warning.line
464 };
465 let disabled_at = (warning.line..=end).find_map(|line| {
466 inline_config
467 .disabling_layer(base_rule_name, line)
468 .map(|layer| (line, layer))
469 });
470 if let Some((line, layer)) = disabled_at {
471 if let Some(record) = suppressed.as_deref_mut() {
472 record.push(crate::rule::SuppressedWarning {
473 rule_name: base_rule_name.to_string(),
474 line,
475 layer,
476 });
477 }
478 continue;
479 }
480
481 if let Some(cfg) = config
483 && let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check)
484 {
485 warning.severity = override_severity;
486 }
487
488 kept.push(warning);
489 }
490
491 kept
492}
493
494#[cfg_attr(test, allow(unused_variables))]
505#[allow(clippy::needless_pass_by_value)] pub fn lint_and_index(
507 content: &str,
508 rules: &[Box<dyn Rule>],
509 verbose: bool,
510 flavor: crate::config::MarkdownFlavor,
511 source_file: Option<std::path::PathBuf>,
512 config: Option<&crate::config::Config>,
513) -> (LintResult, crate::workspace_index::FileIndex) {
514 lint_and_index_with_paths(
515 content,
516 rules,
517 verbose,
518 flavor,
519 DocumentPaths::same(source_file.as_deref()),
520 config,
521 )
522}
523
524#[derive(Debug, Clone, Copy, Default)]
526pub struct DocumentPaths<'a> {
527 pub config_path: Option<&'a std::path::Path>,
529 pub source_file: Option<&'a std::path::Path>,
531 pub link_target_policy: Option<&'a crate::lint_context::LinkTargetPolicy>,
533 pub invalid_utf8: Option<&'a [crate::encoding::InvalidSeq]>,
535}
536
537impl<'a> DocumentPaths<'a> {
538 pub fn same(path: Option<&'a std::path::Path>) -> Self {
540 Self {
541 config_path: path,
542 source_file: path,
543 link_target_policy: None,
544 invalid_utf8: None,
545 }
546 }
547}
548
549#[cfg_attr(test, allow(unused_variables))]
556pub fn lint_and_index_with_paths(
557 content: &str,
558 rules: &[Box<dyn Rule>],
559 verbose: bool,
560 flavor: crate::config::MarkdownFlavor,
561 paths: DocumentPaths<'_>,
562 config: Option<&crate::config::Config>,
563) -> (LintResult, crate::workspace_index::FileIndex) {
564 let result = analyze_document(content, rules, verbose, flavor, paths, config, None);
565 (result.warnings, result.file_index)
566}
567
568#[allow(clippy::too_many_arguments)]
569pub(crate) fn analyze_document(
570 content: &str,
571 rules: &[Box<dyn Rule>],
572 verbose: bool,
573 flavor: crate::config::MarkdownFlavor,
574 paths: DocumentPaths<'_>,
575 config: Option<&crate::config::Config>,
576 prepare_fixes: Option<usize>,
577) -> document_run::DocumentFormatResult {
578 analyze_scanned_document(
579 &crate::merge_conflict::ConflictScan::new(content),
580 rules,
581 verbose,
582 flavor,
583 paths,
584 config,
585 prepare_fixes,
586 )
587}
588
589pub(crate) fn analyze_scanned_document(
590 scan: &crate::merge_conflict::ConflictScan<'_>,
591 rules: &[Box<dyn Rule>],
592 verbose: bool,
593 flavor: crate::config::MarkdownFlavor,
594 paths: DocumentPaths<'_>,
595 config: Option<&crate::config::Config>,
596 prepare_fixes: Option<usize>,
597) -> document_run::DocumentFormatResult {
598 use document_run::DocumentFormatResult;
599 let content = scan.content();
600 let content_hash = compute_content_hash(content);
602 let file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
603
604 let conflict = config.map_or_else(
605 || scan.detect_for_rules(rules, &crate::config::Config::default(), paths.config_path),
606 |config| scan.detect_for_rules(rules, config, paths.config_path),
607 );
608 if let Some(conflict) = conflict {
609 return DocumentFormatResult::without_fixes(Ok(vec![conflict]), file_index);
610 }
611
612 let carrier = content;
614 let content = crate::utils::bom::strip_bom(carrier);
615
616 if content.is_empty() {
618 return DocumentFormatResult::without_fixes(Ok(Vec::new()), file_index);
619 }
620
621 let lint_ctx = time_function!(
623 "lint: parse lint context",
624 crate::lint_context::LintContext::new(content, flavor, paths.source_file.map(std::path::Path::to_path_buf))
625 .with_merge_conflicts(scan.markers())
626 );
627 let lint_ctx = match paths.link_target_policy {
628 Some(policy) => lint_ctx.with_link_target_policy(policy.clone()),
629 None => lint_ctx,
630 };
631 let lint_ctx = match paths.invalid_utf8 {
632 Some(invalid) => lint_ctx.with_invalid_utf8(invalid),
633 None => lint_ctx,
634 };
635 let (warnings, file_index, checked_rules) = check_document_context(
636 &lint_ctx,
637 rules,
638 verbose,
639 paths,
640 config,
641 file_index,
642 prepare_fixes.is_some(),
643 Default::default(),
644 );
645 let mut remaining_warnings = None;
646 let fixes = if warnings.as_ref().is_ok_and(|warnings| !warnings.is_empty())
647 && paths.invalid_utf8.is_none()
648 && let (Some(max_iterations), Some(config), Some(checks)) = (prepare_fixes, config, checked_rules)
649 {
650 let mut fixed = content.to_string();
651 let mut on_stable = |ctx: &crate::lint_context::LintContext<'_>,
652 checks: &mut fix_coordinator::RawRuleChecks| {
653 if ctx.content != content {
654 let index = crate::workspace_index::FileIndex::with_hash(compute_content_hash(ctx.content));
655 remaining_warnings = Some(
656 check_document_context(
657 ctx,
658 rules,
659 false,
660 paths,
661 Some(config),
662 index,
663 false,
664 std::mem::take(checks),
665 )
666 .0,
667 );
668 }
669 };
670 let result = fix_coordinator::FixCoordinator::new().apply_fixes_with_analysis(
671 rules,
672 &mut fixed,
673 config,
674 max_iterations,
675 paths,
676 Some((&lint_ctx, &checks)),
677 Some(&mut on_stable),
678 );
679 if crate::utils::bom::has_bom(carrier) {
680 fixed.insert(0, crate::utils::bom::BOM);
681 }
682 Some(Ok((fixed, result)))
683 } else {
684 None
685 };
686 let shift = crate::utils::bom::bom_len(carrier);
689 let mut warnings = warnings;
690 if let Ok(warnings) = &mut warnings {
691 crate::utils::bom::restore_fix_offsets(warnings, shift);
692 }
693 if let Some(Ok(warnings)) = &mut remaining_warnings {
694 crate::utils::bom::restore_fix_offsets(warnings, shift);
695 }
696 DocumentFormatResult {
697 warnings,
698 file_index,
699 fixes,
700 remaining_warnings,
701 }
702}
703
704#[allow(clippy::too_many_arguments)]
708fn check_document_context(
709 lint_ctx: &crate::lint_context::LintContext<'_>,
710 rules: &[Box<dyn Rule>],
711 verbose: bool,
712 paths: DocumentPaths<'_>,
713 config: Option<&crate::config::Config>,
714 mut file_index: crate::workspace_index::FileIndex,
715 collect_fix_checks: bool,
716 mut cached_checks: fix_coordinator::RawRuleChecks,
717) -> (
718 LintResult,
719 crate::workspace_index::FileIndex,
720 Option<fix_coordinator::FixCheckResults>,
721) {
722 let content = lint_ctx.content;
723 let mut warnings = Vec::new();
724 let ignored_for_file = match (config, paths.config_path) {
731 (Some(cfg), Some(path)) => cfg.get_ignored_rules_for_file(path),
732 _ => std::collections::HashSet::new(),
733 };
734 let inline_config = lint_ctx.inline_config();
735
736 let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
738 file_index.file_disabled_rules = file_disabled;
739 file_index.persistent_transitions = persistent_transitions;
740 file_index.line_disabled_rules = line_disabled;
741
742 let characteristics = time_function!(
744 "lint: analyze content characteristics",
745 ContentCharacteristics::analyze(content)
746 );
747
748 let applicable_rules: Vec<_> = rules
750 .iter()
751 .filter(|rule| !ignored_for_file.contains(rule.name()))
752 .filter(|rule| !(rule.skippable_by_category() && characteristics.should_skip_rule(rule.as_ref())))
753 .collect();
754
755 #[cfg(not(test))]
757 let total_rules = rules.len();
758 #[cfg(not(test))]
759 let applicable_count = applicable_rules.len();
760
761 #[cfg(not(target_arch = "wasm32"))]
762 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
763
764 let inline_overrides = inline_config.get_all_rule_configs();
767 let merged_config = if !inline_overrides.is_empty() {
768 config.map(|c| c.merge_with_inline_config(inline_config))
769 } else {
770 None
771 };
772 let effective_config = merged_config.as_ref().or(config);
773
774 let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
776 std::collections::HashMap::new();
777
778 if let Some(cfg) = effective_config {
780 for rule_name in inline_overrides.keys() {
781 if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
782 recreated_rules.insert(rule_name.clone(), recreated);
783 }
784 }
785 }
786
787 let suppression_observers: Vec<_> = applicable_rules
791 .iter()
792 .filter(|rule| rule.observes_suppressions() && !rule.should_skip(lint_ctx))
793 .collect();
794 let mut suppressed = Vec::new();
795 let mut checked_rules = collect_fix_checks.then(std::collections::HashMap::new);
798
799 {
800 let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
801 for rule in &applicable_rules {
802 #[cfg(not(target_arch = "wasm32"))]
803 let rule_start = (profile_rules || verbose).then(Instant::now);
804
805 if rule.should_skip(lint_ctx) {
807 continue;
808 }
809
810 let effective_rule: &dyn crate::rule::Rule = recreated_rules
812 .get(rule.name())
813 .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
814
815 let result = cached_checks
817 .remove(&fix_coordinator::rule_check_key(rule.as_ref()))
818 .map_or_else(|| effective_rule.check(lint_ctx), Ok);
819
820 match result {
821 Ok(rule_warnings) => {
822 if let Some(checks) = &mut checked_rules {
823 checks.insert(
824 fix_coordinator::rule_check_key(rule.as_ref()),
825 fix_coordinator::FixPlan::capture(effective_rule, lint_ctx, &rule_warnings),
826 );
827 }
828 let record = if suppression_observers.is_empty() {
829 None
830 } else {
831 Some(&mut suppressed)
832 };
833 let filtered_warnings =
834 retain_reportable_warnings(lint_ctx, config, rule.name(), rule_warnings, record);
835 warnings.extend(filtered_warnings);
836 }
837 Err(e) => {
838 log::error!("Error checking rule {}: {}", rule.name(), e);
839 return (Err(e), file_index, checked_rules);
840 }
841 }
842
843 #[cfg(not(target_arch = "wasm32"))]
844 {
845 if let Some(rule_start) = rule_start {
846 let rule_duration = rule_start.elapsed();
847 if profile_rules {
848 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
849 }
850
851 #[cfg(not(test))]
852 if verbose && rule_duration.as_millis() > 500 {
853 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
854 }
855 }
856 }
857 }
858 }
859
860 if !suppression_observers.is_empty() {
863 let _timer = profiling::ScopedTimer::new("lint: run suppression rules");
864
865 let report = crate::rule::SuppressionReport {
870 suppressed,
871 judged_rules: rules
872 .iter()
873 .filter(|rule| rule.cross_file_scope() != crate::rule::CrossFileScope::Workspace)
874 .filter(|rule| !ignored_for_file.contains(rule.name()))
875 .map(|rule| rule.name().to_string())
876 .collect(),
877 };
878
879 for rule in &suppression_observers {
880 match rule.check_suppressions(lint_ctx, &report) {
881 Ok(rule_warnings) => {
882 let filtered_warnings =
883 retain_reportable_warnings(lint_ctx, config, rule.name(), rule_warnings, None);
884 warnings.extend(filtered_warnings);
885 }
886 Err(e) => {
887 log::error!("Error checking rule {}: {}", rule.name(), e);
888 return (Err(e), file_index, checked_rules);
889 }
890 }
891 }
892 }
893
894 time_section!("lint: contribute cross-file data", {
902 for rule in rules {
903 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
904 rule.contribute_to_index(lint_ctx, &mut file_index);
905 }
906 }
907 });
908
909 #[cfg(not(test))]
910 if verbose {
911 let skipped_rules = total_rules - applicable_count;
912 if skipped_rules > 0 {
913 log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
914 }
915 }
916
917 if paths.invalid_utf8.is_some() {
918 crate::encoding::settle_lossy_warnings(&mut warnings);
919 }
920
921 conform_fix_line_endings(content, &mut warnings);
922
923 (Ok(warnings), file_index, checked_rules)
924}
925
926pub fn run_cross_file_checks(
939 file_path: &std::path::Path,
940 file_index: &crate::workspace_index::FileIndex,
941 rules: &[Box<dyn Rule>],
942 workspace_index: &crate::workspace_index::WorkspaceIndex,
943 config: Option<&crate::config::Config>,
944) -> LintResult {
945 use crate::rule::CrossFileScope;
946
947 let mut warnings = Vec::new();
948
949 let ignored_rules_for_file = config.map(|cfg| cfg.get_ignored_rules_for_file(file_path));
955
956 for rule in rules {
958 if rule.cross_file_scope() != CrossFileScope::Workspace {
959 continue;
960 }
961
962 if ignored_rules_for_file
963 .as_ref()
964 .is_some_and(|ignored| ignored.contains(rule.name()))
965 {
966 continue;
967 }
968
969 match time_function!(
970 "workspace: cross-file rule check",
971 rule.cross_file_check(file_path, file_index, workspace_index)
972 ) {
973 Ok(rule_warnings) => {
974 let filtered: Vec<_> = rule_warnings
976 .into_iter()
977 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
978 .map(|mut warning| {
979 if let Some(cfg) = config
981 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
982 {
983 warning.severity = override_severity;
984 }
985 warning
986 })
987 .collect();
988 warnings.extend(filtered);
989 }
990 Err(e) => {
991 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
992 return Err(e);
993 }
994 }
995 }
996
997 Ok(warnings)
998}
999
1000pub fn get_profiling_report() -> String {
1002 profiling::get_report()
1003}
1004
1005pub fn reset_profiling() {
1007 profiling::reset()
1008}
1009
1010pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
1012 crate::utils::regex_cache::get_cache_stats()
1013}
1014
1015#[cfg(test)]
1016mod tests {
1017 use super::*;
1018 use crate::rule::Rule;
1019 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
1020
1021 #[test]
1022 fn test_content_characteristics_analyze() {
1023 let chars = ContentCharacteristics::analyze("");
1025 assert!(!chars.has_headings);
1026 assert!(!chars.has_lists);
1027 assert!(!chars.has_links);
1028 assert!(!chars.has_code);
1029 assert!(!chars.has_emphasis);
1030 assert!(!chars.has_html);
1031 assert!(!chars.has_tables);
1032 assert!(!chars.has_blockquotes);
1033 assert!(!chars.has_images);
1034
1035 let chars = ContentCharacteristics::analyze("# Heading");
1037 assert!(chars.has_headings);
1038
1039 let chars = ContentCharacteristics::analyze("Heading\n=======");
1041 assert!(chars.has_headings);
1042
1043 let chars = ContentCharacteristics::analyze("> ## Alpha\n>\n> ## Alpha");
1046 assert!(chars.has_headings, "blockquoted ATX heading must set has_headings");
1047 let chars = ContentCharacteristics::analyze(">> # Nested");
1048 assert!(
1049 chars.has_headings,
1050 "nested-blockquote ATX heading must set has_headings"
1051 );
1052 let chars = ContentCharacteristics::analyze(">\t## Tabbed");
1055 assert!(
1056 chars.has_headings,
1057 "tab-separated blockquote ATX heading must set has_headings"
1058 );
1059
1060 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
1062 assert!(chars.has_lists);
1063
1064 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
1066 assert!(chars.has_lists);
1067
1068 let chars = ContentCharacteristics::analyze("[link](url)");
1070 assert!(chars.has_links);
1071
1072 let chars = ContentCharacteristics::analyze("Visit https://example.com");
1074 assert!(chars.has_links);
1075
1076 let chars = ContentCharacteristics::analyze("");
1078 assert!(chars.has_images);
1079
1080 let chars = ContentCharacteristics::analyze("`inline code`");
1082 assert!(chars.has_code);
1083
1084 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
1085 assert!(chars.has_code);
1086
1087 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
1089 assert!(chars.has_code);
1090
1091 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
1093 assert!(chars.has_code);
1094
1095 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
1097 assert!(chars.has_code);
1098
1099 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
1101 assert!(chars.has_code);
1102
1103 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
1105 assert!(chars.has_emphasis);
1106
1107 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
1109 assert!(chars.has_html);
1110
1111 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
1113 assert!(chars.has_tables);
1114
1115 let chars = ContentCharacteristics::analyze("> Quote");
1117 assert!(chars.has_blockquotes);
1118
1119 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
1121 let chars = ContentCharacteristics::analyze(content);
1122 assert!(chars.has_headings);
1123 assert!(chars.has_lists);
1124 assert!(chars.has_links);
1125 assert!(chars.has_code);
1126 assert!(chars.has_emphasis);
1127 assert!(chars.has_html);
1128 assert!(chars.has_tables);
1129 assert!(chars.has_blockquotes);
1130 assert!(chars.has_images);
1131 }
1132
1133 #[test]
1134 fn test_content_characteristics_parenthesized_ordered_list() {
1135 assert!(ContentCharacteristics::analyze("1) first\n2) second").has_lists);
1136 assert!(ContentCharacteristics::analyze(" 1) indented first\n 2) second").has_lists);
1137 assert!(ContentCharacteristics::analyze("> 1) quoted item").has_lists);
1138 }
1139
1140 #[test]
1141 fn test_content_characteristics_should_skip_rule() {
1142 let chars = ContentCharacteristics {
1143 has_headings: true,
1144 has_lists: false,
1145 has_links: true,
1146 has_code: false,
1147 has_emphasis: true,
1148 has_html: false,
1149 has_tables: true,
1150 has_blockquotes: false,
1151 has_images: false,
1152 };
1153
1154 let heading_rule = MD001HeadingIncrement::default();
1156 assert!(!chars.should_skip_rule(&heading_rule));
1157
1158 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
1159 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
1163 has_headings: false,
1164 ..Default::default()
1165 };
1166 assert!(chars_no_headings.should_skip_rule(&heading_rule));
1167 }
1168
1169 #[test]
1170 fn test_lint_empty_content() {
1171 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1172
1173 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
1174 assert!(result.is_ok());
1175 assert!(result.unwrap().is_empty());
1176 }
1177
1178 #[test]
1179 fn test_lint_with_violations() {
1180 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1182
1183 let result = lint(
1184 content,
1185 &rules,
1186 false,
1187 crate::config::MarkdownFlavor::Standard,
1188 None,
1189 None,
1190 );
1191 assert!(result.is_ok());
1192 let warnings = result.unwrap();
1193 assert!(!warnings.is_empty());
1194 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
1196 }
1197
1198 #[test]
1199 fn test_lint_with_inline_disable() {
1200 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
1201 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1202
1203 let result = lint(
1204 content,
1205 &rules,
1206 false,
1207 crate::config::MarkdownFlavor::Standard,
1208 None,
1209 None,
1210 );
1211 assert!(result.is_ok());
1212 let warnings = result.unwrap();
1213 assert!(warnings.is_empty()); }
1215
1216 #[test]
1217 fn test_lint_checks_setext_headings_the_content_prefilter_must_keep() {
1218 let rules: Vec<Box<dyn Rule>> = vec![Box::new(crate::rules::MD080HeadingAnchorCollision::new())];
1222 for content in [
1223 "Title\n-\n\ntitle\n-\n",
1224 "Title\n=\n\ntitle\n=\n",
1225 "> Title\n> ===\n\n> title\n> ===\n",
1226 "> Title\n> -\n\n> title\n> -\n",
1227 ] {
1228 let warnings = lint(
1229 content,
1230 &rules,
1231 false,
1232 crate::config::MarkdownFlavor::Standard,
1233 None,
1234 None,
1235 )
1236 .unwrap();
1237 let lines: Vec<_> = warnings.iter().map(|warning| warning.line).collect();
1238 assert_eq!(lines, [4], "{content:?}");
1239 }
1240 }
1241
1242 #[test]
1243 fn test_lint_rule_filtering() {
1244 let content = "# Heading\nJust text";
1246 let rules: Vec<Box<dyn Rule>> = vec![
1247 Box::new(MD001HeadingIncrement::default()),
1248 ];
1250
1251 let result = lint(
1252 content,
1253 &rules,
1254 false,
1255 crate::config::MarkdownFlavor::Standard,
1256 None,
1257 None,
1258 );
1259 assert!(result.is_ok());
1260 }
1261
1262 #[test]
1263 fn test_get_profiling_report() {
1264 let report = get_profiling_report();
1266 assert!(!report.is_empty());
1267 assert!(report.contains("Profiling"));
1268 }
1269
1270 #[test]
1271 fn test_reset_profiling() {
1272 reset_profiling();
1274
1275 let report = get_profiling_report();
1277 assert!(report.contains("disabled") || report.contains("no measurements"));
1278 }
1279
1280 #[test]
1281 fn test_get_regex_cache_stats() {
1282 let stats = get_regex_cache_stats();
1283 assert!(stats.is_empty() || !stats.is_empty());
1285
1286 for count in stats.values() {
1288 assert!(*count > 0);
1289 }
1290 }
1291
1292 #[test]
1293 fn test_content_characteristics_edge_cases() {
1294 for content in [
1297 "Title\n-",
1298 "Title\n=",
1299 "Title\n--",
1300 "> Title\n> ===",
1301 ">\tTitle\n>\t-",
1302 ">> Title\n>>-",
1303 ] {
1304 assert!(ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1305 }
1306 for content in ["- ## Title", "1. # Title", "- - # Title", "> - ## Title", "10) # Title"] {
1308 assert!(ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1309 }
1310 for content in ["> Prose\n>", "Prose\n> text", "Prose\n"] {
1311 assert!(!ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1312 }
1313
1314 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");
1324 assert!(!chars.has_blockquotes);
1325 }
1326
1327 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";
1333
1334 fn fix_replacements(content: &str) -> Vec<(String, String)> {
1336 let config = crate::config::Config::default();
1337 let rules = crate::rules::all_rules(&config);
1338 let warnings = lint(
1339 content,
1340 &rules,
1341 false,
1342 crate::config::MarkdownFlavor::Standard,
1343 None,
1344 Some(&config),
1345 )
1346 .unwrap();
1347 let mut out = Vec::new();
1348 for warning in warnings {
1349 let Some(fix) = warning.fix else { continue };
1350 let rule = warning.rule_name.clone().unwrap_or_default();
1351 let mut stack = vec![fix];
1352 while let Some(fix) = stack.pop() {
1353 out.push((rule.clone(), fix.replacement.clone()));
1354 stack.extend(fix.additional_edits);
1355 }
1356 }
1357 out
1358 }
1359
1360 fn has_bare_lf(text: &str) -> bool {
1361 let bytes = text.as_bytes();
1362 bytes
1363 .iter()
1364 .enumerate()
1365 .any(|(i, b)| *b == b'\n' && (i == 0 || bytes[i - 1] != b'\r'))
1366 }
1367
1368 #[test]
1369 fn fix_replacements_use_the_documents_crlf_line_ending() {
1370 let crlf = LINE_INSERTING_FIXES.replace('\n', "\r\n");
1371 let replacements = fix_replacements(&crlf);
1372
1373 let bare: Vec<_> = replacements.iter().filter(|(_, r)| has_bare_lf(r)).collect();
1374 assert!(bare.is_empty(), "bare LF in a fix for a CRLF document: {bare:?}");
1375
1376 let mut crlf_rules: Vec<_> = replacements
1379 .iter()
1380 .filter(|(_, r)| r.contains("\r\n"))
1381 .map(|(rule, _)| rule.as_str())
1382 .collect();
1383 crlf_rules.sort_unstable();
1384 crlf_rules.dedup();
1385 for rule in ["MD014", "MD022", "MD031", "MD032", "MD047", "MD058", "MD071"] {
1386 assert!(
1387 crlf_rules.contains(&rule),
1388 "{rule} inserted no CRLF line ending; got {crlf_rules:?}"
1389 );
1390 }
1391 }
1392
1393 #[test]
1394 fn fix_replacements_stay_lf_for_lf_documents() {
1395 let lf = fix_replacements(LINE_INSERTING_FIXES);
1397 assert!(lf.iter().any(|(_, r)| has_bare_lf(r)));
1398 assert!(!lf.iter().any(|(_, r)| r.contains('\r')));
1399 }
1400
1401 #[test]
1402 fn fix_replacements_in_a_mixed_document_take_the_ending_of_the_line_they_follow() {
1403 let mixed: String = LINE_INSERTING_FIXES
1405 .split_inclusive('\n')
1406 .enumerate()
1407 .map(|(i, line)| {
1408 if i % 2 == 0 {
1409 line.replace('\n', "\r\n")
1410 } else {
1411 line.to_string()
1412 }
1413 })
1414 .collect();
1415 assert_eq!(
1416 crate::utils::detect_line_ending_enum(&mixed),
1417 crate::utils::LineEnding::Mixed
1418 );
1419
1420 let ending_before = |offset: usize| {
1422 let target = offset.saturating_sub(1);
1423 let mut start = 0;
1424 let mut last_ending = "\n";
1425 for line in mixed.split_inclusive('\n') {
1426 let ending = if line.ends_with("\r\n") {
1427 "\r\n"
1428 } else if line.ends_with('\n') {
1429 "\n"
1430 } else {
1431 last_ending
1432 };
1433 if target < start + line.len() {
1434 return ending;
1435 }
1436 last_ending = ending;
1437 start += line.len();
1438 }
1439 last_ending
1440 };
1441
1442 let config = crate::config::Config::default();
1443 let rules = crate::rules::all_rules(&config);
1444 let warnings = lint(
1445 &mixed,
1446 &rules,
1447 false,
1448 crate::config::MarkdownFlavor::Standard,
1449 None,
1450 Some(&config),
1451 )
1452 .unwrap();
1453 let mut seen = [false, false];
1454 let mut stack: Vec<_> = warnings.into_iter().filter_map(|warning| warning.fix).collect();
1455 while let Some(fix) = stack.pop() {
1456 if fix.replacement.contains('\n') {
1457 let crlf = ending_before(fix.range.start) == "\r\n";
1458 seen[usize::from(crlf)] = true;
1459 assert_eq!(
1460 has_bare_lf(&fix.replacement),
1461 !crlf,
1462 "replacement {:?} at {} in {mixed:?}",
1463 fix.replacement,
1464 fix.range.start
1465 );
1466 }
1467 stack.extend(fix.additional_edits);
1468 }
1469 assert_eq!(seen, [true, true], "fixture should insert lines after both endings");
1470 }
1471}
1472
1473#[doc(hidden)]
1474pub mod format_proof;