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 disabled_at = warning.covered_lines().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(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 pub embedded_rules: Option<&'a [Box<dyn crate::rule::Rule>]>,
531 pub embedded_depth: usize,
533}
534
535impl std::fmt::Debug for DocumentPaths<'_> {
536 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
537 f.debug_struct("DocumentPaths")
538 .field("config_path", &self.config_path)
539 .field("source_file", &self.source_file)
540 .field("link_target_policy", &self.link_target_policy)
541 .field("invalid_utf8", &self.invalid_utf8)
542 .field("embedded_rules", &self.embedded_rules.map(<[_]>::len))
543 .field("embedded_depth", &self.embedded_depth)
544 .finish()
545 }
546}
547
548impl<'a> DocumentPaths<'a> {
549 pub fn same(path: Option<&'a std::path::Path>) -> Self {
551 Self {
552 config_path: path,
553 source_file: path,
554 ..Default::default()
555 }
556 }
557}
558
559#[cfg_attr(test, allow(unused_variables))]
566pub fn lint_and_index_with_paths(
567 content: &str,
568 rules: &[Box<dyn Rule>],
569 verbose: bool,
570 flavor: crate::config::MarkdownFlavor,
571 paths: DocumentPaths<'_>,
572 config: Option<&crate::config::Config>,
573) -> (LintResult, crate::workspace_index::FileIndex) {
574 let result = analyze_document(content, rules, verbose, flavor, paths, config, None);
575 (result.warnings, result.file_index)
576}
577
578#[allow(clippy::too_many_arguments)]
579pub(crate) fn analyze_document(
580 content: &str,
581 rules: &[Box<dyn Rule>],
582 verbose: bool,
583 flavor: crate::config::MarkdownFlavor,
584 paths: DocumentPaths<'_>,
585 config: Option<&crate::config::Config>,
586 prepare_fixes: Option<usize>,
587) -> document_run::DocumentFormatResult {
588 analyze_scanned_document(
589 &crate::merge_conflict::ConflictScan::new(content),
590 rules,
591 verbose,
592 flavor,
593 paths,
594 config,
595 prepare_fixes,
596 )
597}
598
599pub(crate) fn analyze_scanned_document(
600 scan: &crate::merge_conflict::ConflictScan<'_>,
601 rules: &[Box<dyn Rule>],
602 verbose: bool,
603 flavor: crate::config::MarkdownFlavor,
604 paths: DocumentPaths<'_>,
605 config: Option<&crate::config::Config>,
606 prepare_fixes: Option<usize>,
607) -> document_run::DocumentFormatResult {
608 use document_run::DocumentFormatResult;
609 let content = scan.content();
610 let content_hash = compute_content_hash(content);
612 let file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
613
614 let conflict = config.map_or_else(
615 || scan.detect_for_rules(rules, &crate::config::Config::default(), paths.config_path),
616 |config| scan.detect_for_rules(rules, config, paths.config_path),
617 );
618 if let Some(conflict) = conflict {
619 return DocumentFormatResult::without_fixes(Ok(vec![conflict]), file_index);
620 }
621
622 let carrier = content;
624 let content = crate::utils::bom::strip_bom(carrier);
625
626 if content.is_empty() {
628 return DocumentFormatResult::without_fixes(Ok(Vec::new()), file_index);
629 }
630
631 let lint_ctx = time_function!(
633 "lint: parse lint context",
634 crate::lint_context::LintContext::new(content, flavor, paths.source_file.map(std::path::Path::to_path_buf))
635 .with_merge_conflicts(scan.markers())
636 );
637 let lint_ctx = match paths.link_target_policy {
638 Some(policy) => lint_ctx.with_link_target_policy(policy.clone()),
639 None => lint_ctx,
640 };
641 let lint_ctx = match paths.invalid_utf8 {
642 Some(invalid) => lint_ctx.with_invalid_utf8(invalid),
643 None => lint_ctx,
644 };
645 let (warnings, file_index, checked_rules) = check_document_context(
646 &lint_ctx,
647 rules,
648 verbose,
649 paths,
650 config,
651 file_index,
652 prepare_fixes.is_some(),
653 Default::default(),
654 );
655 let mut remaining_warnings = None;
656 let fixes = if warnings.as_ref().is_ok_and(|warnings| !warnings.is_empty())
657 && paths.invalid_utf8.is_none()
658 && let (Some(max_iterations), Some(config), Some(checks)) = (prepare_fixes, config, checked_rules)
659 {
660 let mut fixed = content.to_string();
661 let mut on_stable = |ctx: &crate::lint_context::LintContext<'_>,
662 checks: &mut fix_coordinator::RawRuleChecks| {
663 if ctx.content != content {
664 let index = crate::workspace_index::FileIndex::with_hash(compute_content_hash(ctx.content));
665 remaining_warnings = Some(
666 check_document_context(
667 ctx,
668 rules,
669 false,
670 paths,
671 Some(config),
672 index,
673 false,
674 std::mem::take(checks),
675 )
676 .0,
677 );
678 }
679 };
680 let result = fix_coordinator::FixCoordinator::new().apply_fixes_with_analysis(
681 rules,
682 &mut fixed,
683 config,
684 max_iterations,
685 paths,
686 Some((&lint_ctx, &checks)),
687 Some(&mut on_stable),
688 );
689 if crate::utils::bom::has_bom(carrier) {
690 fixed.insert(0, crate::utils::bom::BOM);
691 }
692 Some(Ok((fixed, result)))
693 } else {
694 None
695 };
696 let shift = crate::utils::bom::bom_len(carrier);
699 let mut warnings = warnings;
700 if let Ok(warnings) = &mut warnings {
701 crate::utils::bom::restore_fix_offsets(warnings, shift);
702 }
703 if let Some(Ok(warnings)) = &mut remaining_warnings {
704 crate::utils::bom::restore_fix_offsets(warnings, shift);
705 }
706 DocumentFormatResult {
707 warnings,
708 file_index,
709 fixes,
710 remaining_warnings,
711 }
712}
713
714#[allow(clippy::too_many_arguments)]
718fn check_document_context(
719 lint_ctx: &crate::lint_context::LintContext<'_>,
720 rules: &[Box<dyn Rule>],
721 verbose: bool,
722 paths: DocumentPaths<'_>,
723 config: Option<&crate::config::Config>,
724 mut file_index: crate::workspace_index::FileIndex,
725 collect_fix_checks: bool,
726 mut cached_checks: fix_coordinator::RawRuleChecks,
727) -> (
728 LintResult,
729 crate::workspace_index::FileIndex,
730 Option<fix_coordinator::FixCheckResults>,
731) {
732 let content = lint_ctx.content;
733 let mut warnings = Vec::new();
734 let ignored_for_file = match (config, paths.config_path) {
741 (Some(cfg), Some(path)) => cfg.get_ignored_rules_for_file(path),
742 _ => std::collections::HashSet::new(),
743 };
744 let inline_config = lint_ctx.inline_config();
745
746 let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
748 file_index.file_disabled_rules = file_disabled;
749 file_index.persistent_transitions = persistent_transitions;
750 file_index.line_disabled_rules = line_disabled;
751
752 let characteristics = time_function!(
754 "lint: analyze content characteristics",
755 ContentCharacteristics::analyze(content)
756 );
757
758 let applicable_rules: Vec<_> = rules
760 .iter()
761 .filter(|rule| !ignored_for_file.contains(rule.name()))
762 .filter(|rule| !(rule.skippable_by_category() && characteristics.should_skip_rule(rule.as_ref())))
763 .collect();
764
765 #[cfg(not(test))]
767 let total_rules = rules.len();
768 #[cfg(not(test))]
769 let applicable_count = applicable_rules.len();
770
771 #[cfg(not(target_arch = "wasm32"))]
772 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
773
774 let inline_overrides = inline_config.get_all_rule_configs();
777 let merged_config = if !inline_overrides.is_empty() {
778 config.map(|c| c.merge_with_inline_config(inline_config))
779 } else {
780 None
781 };
782 let effective_config = merged_config.as_ref().or(config);
783
784 let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
786 std::collections::HashMap::new();
787
788 if let Some(cfg) = effective_config {
790 for rule_name in inline_overrides.keys() {
791 if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
792 recreated_rules.insert(rule_name.clone(), recreated);
793 }
794 }
795 }
796
797 let suppression_observers: Vec<_> = applicable_rules
801 .iter()
802 .filter(|rule| rule.observes_suppressions() && !rule.should_skip(lint_ctx))
803 .collect();
804 let mut suppressed = Vec::new();
805 let mut checked_rules = collect_fix_checks.then(std::collections::HashMap::new);
808
809 {
810 let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
811 for rule in &applicable_rules {
812 #[cfg(not(target_arch = "wasm32"))]
813 let rule_start = (profile_rules || verbose).then(Instant::now);
814
815 let effective_rule: &dyn crate::rule::Rule = recreated_rules
819 .get(rule.name())
820 .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
821 if effective_rule.should_skip(lint_ctx) {
822 continue;
823 }
824
825 let result = cached_checks
827 .remove(&fix_coordinator::rule_check_key(rule.as_ref()))
828 .map_or_else(|| effective_rule.check(lint_ctx), Ok);
829
830 match result {
831 Ok(rule_warnings) => {
832 if let Some(checks) = &mut checked_rules {
833 checks.insert(
834 fix_coordinator::rule_check_key(rule.as_ref()),
835 fix_coordinator::FixPlan::capture(effective_rule, lint_ctx, &rule_warnings),
836 );
837 }
838 let record = if suppression_observers.is_empty() {
839 None
840 } else {
841 Some(&mut suppressed)
842 };
843 let filtered_warnings =
844 retain_reportable_warnings(lint_ctx, config, rule.name(), rule_warnings, record);
845 warnings.extend(filtered_warnings);
846 }
847 Err(e) => {
848 log::error!("Error checking rule {}: {}", rule.name(), e);
849 return (Err(e), file_index, checked_rules);
850 }
851 }
852
853 #[cfg(not(target_arch = "wasm32"))]
854 {
855 if let Some(rule_start) = rule_start {
856 let rule_duration = rule_start.elapsed();
857 if profile_rules {
858 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
859 }
860
861 #[cfg(not(test))]
862 if verbose && rule_duration.as_millis() > 500 {
863 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
864 }
865 }
866 }
867 }
868 }
869
870 if let (Some(embedded_rules), Some(config)) = (paths.embedded_rules, config)
874 && !embedded_rules.is_empty()
875 {
876 let embedded_rules: Vec<_> = embedded_rules
877 .iter()
878 .filter(|rule| !ignored_for_file.contains(rule.name()))
879 .map(|rule| dyn_clone::clone_box(&**rule))
880 .collect();
881 let embedded = crate::embedded_lint::check_embedded_markdown_blocks_raw(
882 content,
883 &embedded_rules,
884 config,
885 paths.embedded_depth,
886 );
887 let record = (!suppression_observers.is_empty()).then_some(&mut suppressed);
888 warnings.extend(retain_reportable_warnings(
889 lint_ctx,
890 Some(config),
891 "embedded-markdown",
892 embedded,
893 record,
894 ));
895 }
896
897 if !suppression_observers.is_empty() {
900 let _timer = profiling::ScopedTimer::new("lint: run suppression rules");
901
902 let report = crate::rule::SuppressionReport {
907 suppressed,
908 judged_rules: rules
909 .iter()
910 .filter(|rule| rule.cross_file_scope() != crate::rule::CrossFileScope::Workspace)
911 .filter(|rule| !ignored_for_file.contains(rule.name()))
912 .map(|rule| rule.name().to_string())
913 .collect(),
914 };
915
916 for rule in &suppression_observers {
917 match rule.check_suppressions(lint_ctx, &report) {
918 Ok(rule_warnings) => {
919 let filtered_warnings =
920 retain_reportable_warnings(lint_ctx, config, rule.name(), rule_warnings, None);
921 warnings.extend(filtered_warnings);
922 }
923 Err(e) => {
924 log::error!("Error checking rule {}: {}", rule.name(), e);
925 return (Err(e), file_index, checked_rules);
926 }
927 }
928 }
929 }
930
931 time_section!("lint: contribute cross-file data", {
939 for rule in rules {
940 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
941 rule.contribute_to_index(lint_ctx, &mut file_index);
942 }
943 }
944 });
945
946 #[cfg(not(test))]
947 if verbose {
948 let skipped_rules = total_rules - applicable_count;
949 if skipped_rules > 0 {
950 log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
951 }
952 }
953
954 if paths.invalid_utf8.is_some() {
955 crate::encoding::settle_lossy_warnings(&mut warnings);
956 }
957
958 conform_fix_line_endings(content, &mut warnings);
959
960 (Ok(warnings), file_index, checked_rules)
961}
962
963pub fn run_cross_file_checks(
976 file_path: &std::path::Path,
977 file_index: &crate::workspace_index::FileIndex,
978 rules: &[Box<dyn Rule>],
979 workspace_index: &crate::workspace_index::WorkspaceIndex,
980 config: Option<&crate::config::Config>,
981) -> LintResult {
982 use crate::rule::CrossFileScope;
983
984 let mut warnings = Vec::new();
985
986 let ignored_rules_for_file = config.map(|cfg| cfg.get_ignored_rules_for_file(file_path));
992
993 for rule in rules {
995 if rule.cross_file_scope() != CrossFileScope::Workspace {
996 continue;
997 }
998
999 if ignored_rules_for_file
1000 .as_ref()
1001 .is_some_and(|ignored| ignored.contains(rule.name()))
1002 {
1003 continue;
1004 }
1005
1006 match time_function!(
1007 "workspace: cross-file rule check",
1008 rule.cross_file_check(file_path, file_index, workspace_index)
1009 ) {
1010 Ok(rule_warnings) => {
1011 let filtered: Vec<_> = rule_warnings
1013 .into_iter()
1014 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
1015 .map(|mut warning| {
1016 if let Some(cfg) = config
1018 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
1019 {
1020 warning.severity = override_severity;
1021 }
1022 warning
1023 })
1024 .collect();
1025 warnings.extend(filtered);
1026 }
1027 Err(e) => {
1028 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
1029 return Err(e);
1030 }
1031 }
1032 }
1033
1034 Ok(warnings)
1035}
1036
1037pub fn get_profiling_report() -> String {
1039 profiling::get_report()
1040}
1041
1042pub fn reset_profiling() {
1044 profiling::reset()
1045}
1046
1047pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
1049 crate::utils::regex_cache::get_cache_stats()
1050}
1051
1052#[cfg(test)]
1053mod tests {
1054 use super::*;
1055 use crate::rule::Rule;
1056 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
1057
1058 #[test]
1059 fn test_content_characteristics_analyze() {
1060 let chars = ContentCharacteristics::analyze("");
1062 assert!(!chars.has_headings);
1063 assert!(!chars.has_lists);
1064 assert!(!chars.has_links);
1065 assert!(!chars.has_code);
1066 assert!(!chars.has_emphasis);
1067 assert!(!chars.has_html);
1068 assert!(!chars.has_tables);
1069 assert!(!chars.has_blockquotes);
1070 assert!(!chars.has_images);
1071
1072 let chars = ContentCharacteristics::analyze("# Heading");
1074 assert!(chars.has_headings);
1075
1076 let chars = ContentCharacteristics::analyze("Heading\n=======");
1078 assert!(chars.has_headings);
1079
1080 let chars = ContentCharacteristics::analyze("> ## Alpha\n>\n> ## Alpha");
1083 assert!(chars.has_headings, "blockquoted ATX heading must set has_headings");
1084 let chars = ContentCharacteristics::analyze(">> # Nested");
1085 assert!(
1086 chars.has_headings,
1087 "nested-blockquote ATX heading must set has_headings"
1088 );
1089 let chars = ContentCharacteristics::analyze(">\t## Tabbed");
1092 assert!(
1093 chars.has_headings,
1094 "tab-separated blockquote ATX heading must set has_headings"
1095 );
1096
1097 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
1099 assert!(chars.has_lists);
1100
1101 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
1103 assert!(chars.has_lists);
1104
1105 let chars = ContentCharacteristics::analyze("[link](url)");
1107 assert!(chars.has_links);
1108
1109 let chars = ContentCharacteristics::analyze("Visit https://example.com");
1111 assert!(chars.has_links);
1112
1113 let chars = ContentCharacteristics::analyze("");
1115 assert!(chars.has_images);
1116
1117 let chars = ContentCharacteristics::analyze("`inline code`");
1119 assert!(chars.has_code);
1120
1121 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
1122 assert!(chars.has_code);
1123
1124 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
1126 assert!(chars.has_code);
1127
1128 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
1130 assert!(chars.has_code);
1131
1132 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
1134 assert!(chars.has_code);
1135
1136 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
1138 assert!(chars.has_code);
1139
1140 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
1142 assert!(chars.has_emphasis);
1143
1144 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
1146 assert!(chars.has_html);
1147
1148 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
1150 assert!(chars.has_tables);
1151
1152 let chars = ContentCharacteristics::analyze("> Quote");
1154 assert!(chars.has_blockquotes);
1155
1156 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
1158 let chars = ContentCharacteristics::analyze(content);
1159 assert!(chars.has_headings);
1160 assert!(chars.has_lists);
1161 assert!(chars.has_links);
1162 assert!(chars.has_code);
1163 assert!(chars.has_emphasis);
1164 assert!(chars.has_html);
1165 assert!(chars.has_tables);
1166 assert!(chars.has_blockquotes);
1167 assert!(chars.has_images);
1168 }
1169
1170 #[test]
1171 fn test_content_characteristics_parenthesized_ordered_list() {
1172 assert!(ContentCharacteristics::analyze("1) first\n2) second").has_lists);
1173 assert!(ContentCharacteristics::analyze(" 1) indented first\n 2) second").has_lists);
1174 assert!(ContentCharacteristics::analyze("> 1) quoted item").has_lists);
1175 }
1176
1177 #[test]
1178 fn test_content_characteristics_should_skip_rule() {
1179 let chars = ContentCharacteristics {
1180 has_headings: true,
1181 has_lists: false,
1182 has_links: true,
1183 has_code: false,
1184 has_emphasis: true,
1185 has_html: false,
1186 has_tables: true,
1187 has_blockquotes: false,
1188 has_images: false,
1189 };
1190
1191 let heading_rule = MD001HeadingIncrement::default();
1193 assert!(!chars.should_skip_rule(&heading_rule));
1194
1195 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
1196 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
1200 has_headings: false,
1201 ..Default::default()
1202 };
1203 assert!(chars_no_headings.should_skip_rule(&heading_rule));
1204 }
1205
1206 #[test]
1207 fn test_lint_empty_content() {
1208 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1209
1210 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
1211 assert!(result.is_ok());
1212 assert!(result.unwrap().is_empty());
1213 }
1214
1215 #[test]
1216 fn test_lint_with_violations() {
1217 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1219
1220 let result = lint(
1221 content,
1222 &rules,
1223 false,
1224 crate::config::MarkdownFlavor::Standard,
1225 None,
1226 None,
1227 );
1228 assert!(result.is_ok());
1229 let warnings = result.unwrap();
1230 assert!(!warnings.is_empty());
1231 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
1233 }
1234
1235 #[test]
1236 fn test_lint_with_inline_disable() {
1237 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
1238 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
1239
1240 let result = lint(
1241 content,
1242 &rules,
1243 false,
1244 crate::config::MarkdownFlavor::Standard,
1245 None,
1246 None,
1247 );
1248 assert!(result.is_ok());
1249 let warnings = result.unwrap();
1250 assert!(warnings.is_empty()); }
1252
1253 #[test]
1254 fn test_lint_checks_setext_headings_the_content_prefilter_must_keep() {
1255 let rules: Vec<Box<dyn Rule>> = vec![Box::new(crate::rules::MD080HeadingAnchorCollision::new())];
1259 for content in [
1260 "Title\n-\n\ntitle\n-\n",
1261 "Title\n=\n\ntitle\n=\n",
1262 "> Title\n> ===\n\n> title\n> ===\n",
1263 "> Title\n> -\n\n> title\n> -\n",
1264 ] {
1265 let warnings = lint(
1266 content,
1267 &rules,
1268 false,
1269 crate::config::MarkdownFlavor::Standard,
1270 None,
1271 None,
1272 )
1273 .unwrap();
1274 let lines: Vec<_> = warnings.iter().map(|warning| warning.line).collect();
1275 assert_eq!(lines, [4], "{content:?}");
1276 }
1277 }
1278
1279 #[test]
1280 fn test_lint_rule_filtering() {
1281 let content = "# Heading\nJust text";
1283 let rules: Vec<Box<dyn Rule>> = vec![
1284 Box::new(MD001HeadingIncrement::default()),
1285 ];
1287
1288 let result = lint(
1289 content,
1290 &rules,
1291 false,
1292 crate::config::MarkdownFlavor::Standard,
1293 None,
1294 None,
1295 );
1296 assert!(result.is_ok());
1297 }
1298
1299 #[test]
1300 fn test_get_profiling_report() {
1301 let report = get_profiling_report();
1303 assert!(!report.is_empty());
1304 assert!(report.contains("Profiling"));
1305 }
1306
1307 #[test]
1308 fn test_reset_profiling() {
1309 reset_profiling();
1311
1312 let report = get_profiling_report();
1314 assert!(report.contains("disabled") || report.contains("no measurements"));
1315 }
1316
1317 #[test]
1318 fn test_get_regex_cache_stats() {
1319 let stats = get_regex_cache_stats();
1320 assert!(stats.is_empty() || !stats.is_empty());
1322
1323 for count in stats.values() {
1325 assert!(*count > 0);
1326 }
1327 }
1328
1329 #[test]
1330 fn test_content_characteristics_edge_cases() {
1331 for content in [
1334 "Title\n-",
1335 "Title\n=",
1336 "Title\n--",
1337 "> Title\n> ===",
1338 ">\tTitle\n>\t-",
1339 ">> Title\n>>-",
1340 ] {
1341 assert!(ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1342 }
1343 for content in ["- ## Title", "1. # Title", "- - # Title", "> - ## Title", "10) # Title"] {
1345 assert!(ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1346 }
1347 for content in ["> Prose\n>", "Prose\n> text", "Prose\n"] {
1348 assert!(!ContentCharacteristics::analyze(content).has_headings, "{content:?}");
1349 }
1350
1351 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");
1361 assert!(!chars.has_blockquotes);
1362 }
1363
1364 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";
1370
1371 fn fix_replacements(content: &str) -> Vec<(String, String)> {
1373 let config = crate::config::Config::default();
1374 let rules = crate::rules::all_rules(&config);
1375 let warnings = lint(
1376 content,
1377 &rules,
1378 false,
1379 crate::config::MarkdownFlavor::Standard,
1380 None,
1381 Some(&config),
1382 )
1383 .unwrap();
1384 let mut out = Vec::new();
1385 for warning in warnings {
1386 let Some(fix) = warning.fix else { continue };
1387 let rule = warning.rule_name.clone().unwrap_or_default();
1388 let mut stack = vec![fix];
1389 while let Some(fix) = stack.pop() {
1390 out.push((rule.clone(), fix.replacement.clone()));
1391 stack.extend(fix.additional_edits);
1392 }
1393 }
1394 out
1395 }
1396
1397 fn has_bare_lf(text: &str) -> bool {
1398 let bytes = text.as_bytes();
1399 bytes
1400 .iter()
1401 .enumerate()
1402 .any(|(i, b)| *b == b'\n' && (i == 0 || bytes[i - 1] != b'\r'))
1403 }
1404
1405 #[test]
1406 fn fix_replacements_use_the_documents_crlf_line_ending() {
1407 let crlf = LINE_INSERTING_FIXES.replace('\n', "\r\n");
1408 let replacements = fix_replacements(&crlf);
1409
1410 let bare: Vec<_> = replacements.iter().filter(|(_, r)| has_bare_lf(r)).collect();
1411 assert!(bare.is_empty(), "bare LF in a fix for a CRLF document: {bare:?}");
1412
1413 let mut crlf_rules: Vec<_> = replacements
1416 .iter()
1417 .filter(|(_, r)| r.contains("\r\n"))
1418 .map(|(rule, _)| rule.as_str())
1419 .collect();
1420 crlf_rules.sort_unstable();
1421 crlf_rules.dedup();
1422 for rule in ["MD014", "MD022", "MD031", "MD032", "MD047", "MD058", "MD071"] {
1423 assert!(
1424 crlf_rules.contains(&rule),
1425 "{rule} inserted no CRLF line ending; got {crlf_rules:?}"
1426 );
1427 }
1428 }
1429
1430 #[test]
1431 fn fix_replacements_stay_lf_for_lf_documents() {
1432 let lf = fix_replacements(LINE_INSERTING_FIXES);
1434 assert!(lf.iter().any(|(_, r)| has_bare_lf(r)));
1435 assert!(!lf.iter().any(|(_, r)| r.contains('\r')));
1436 }
1437
1438 #[test]
1439 fn fix_replacements_in_a_mixed_document_take_the_ending_of_the_line_they_follow() {
1440 let mixed: String = LINE_INSERTING_FIXES
1442 .split_inclusive('\n')
1443 .enumerate()
1444 .map(|(i, line)| {
1445 if i % 2 == 0 {
1446 line.replace('\n', "\r\n")
1447 } else {
1448 line.to_string()
1449 }
1450 })
1451 .collect();
1452 assert_eq!(
1453 crate::utils::detect_line_ending_enum(&mixed),
1454 crate::utils::LineEnding::Mixed
1455 );
1456
1457 let ending_before = |offset: usize| {
1459 let target = offset.saturating_sub(1);
1460 let mut start = 0;
1461 let mut last_ending = "\n";
1462 for line in mixed.split_inclusive('\n') {
1463 let ending = if line.ends_with("\r\n") {
1464 "\r\n"
1465 } else if line.ends_with('\n') {
1466 "\n"
1467 } else {
1468 last_ending
1469 };
1470 if target < start + line.len() {
1471 return ending;
1472 }
1473 last_ending = ending;
1474 start += line.len();
1475 }
1476 last_ending
1477 };
1478
1479 let config = crate::config::Config::default();
1480 let rules = crate::rules::all_rules(&config);
1481 let warnings = lint(
1482 &mixed,
1483 &rules,
1484 false,
1485 crate::config::MarkdownFlavor::Standard,
1486 None,
1487 Some(&config),
1488 )
1489 .unwrap();
1490 let mut seen = [false, false];
1491 let mut stack: Vec<_> = warnings.into_iter().filter_map(|warning| warning.fix).collect();
1492 while let Some(fix) = stack.pop() {
1493 if fix.replacement.contains('\n') {
1494 let crlf = ending_before(fix.range.start) == "\r\n";
1495 seen[usize::from(crlf)] = true;
1496 assert_eq!(
1497 has_bare_lf(&fix.replacement),
1498 !crlf,
1499 "replacement {:?} at {} in {mixed:?}",
1500 fix.replacement,
1501 fix.range.start
1502 );
1503 }
1504 stack.extend(fix.additional_edits);
1505 }
1506 assert_eq!(seen, [true, true], "fixture should insert lines after both endings");
1507 }
1508}
1509
1510#[doc(hidden)]
1511pub mod format_proof;