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 doc_comment_lint;
53pub mod embedded_lint;
54pub mod exit_codes;
55pub mod filtered_lines;
56pub mod fix_coordinator;
57pub mod inline_config;
58pub mod linguist_data;
59pub mod lint_context;
60pub mod markdownlint_config;
61pub mod profiling;
62pub mod rule;
63#[cfg(feature = "native")]
64pub mod vscode;
65pub mod workspace_index;
66#[macro_use]
67pub mod rule_config;
68#[macro_use]
69pub mod rule_config_serde;
70pub mod rules;
71pub mod types;
72pub mod utils;
73
74#[cfg(feature = "native")]
76pub mod lsp;
77#[cfg(feature = "native")]
78pub mod output;
79#[cfg(feature = "native")]
80pub mod parallel;
81#[cfg(feature = "native")]
82pub mod performance;
83
84#[cfg(feature = "wasm")]
86pub mod wasm;
87
88pub use rules::heading_utils::HeadingStyle;
89pub use rules::*;
90
91pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
92use crate::rule::{LintResult, Rule, RuleCategory};
93use crate::utils::calculate_indentation_width_default;
94#[cfg(not(target_arch = "wasm32"))]
95use std::time::Instant;
96
97#[derive(Debug, Default)]
99struct ContentCharacteristics {
100 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, }
110
111fn has_potential_indented_code_indent(line: &str) -> bool {
114 calculate_indentation_width_default(line) >= 4
115}
116
117impl ContentCharacteristics {
118 fn analyze(content: &str) -> Self {
119 let mut chars = Self { ..Default::default() };
120
121 let mut has_atx_heading = false;
123 let mut has_setext_heading = false;
124
125 for line in content.lines() {
126 let trimmed = line.trim();
127
128 if !has_atx_heading
135 && (trimmed.starts_with('#') || trimmed.trim_start_matches(['>', ' ', '\t']).starts_with('#'))
136 {
137 has_atx_heading = true;
138 }
139 if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
140 has_setext_heading = true;
141 }
142
143 if !chars.has_lists
146 && (line.contains("* ")
147 || line.contains("- ")
148 || line.contains("+ ")
149 || trimmed.starts_with("* ")
150 || trimmed.starts_with("- ")
151 || trimmed.starts_with("+ ")
152 || trimmed.starts_with('*')
153 || trimmed.starts_with('-')
154 || trimmed.starts_with('+'))
155 {
156 chars.has_lists = true;
157 }
158 if !chars.has_lists
160 && ((line.chars().next().is_some_and(|c| c.is_ascii_digit())
161 && (line.contains(". ") || line.contains('.')))
162 || (trimmed.starts_with('>')
163 && trimmed.chars().any(|c| c.is_ascii_digit())
164 && (trimmed.contains(". ") || trimmed.contains('.'))))
165 {
166 chars.has_lists = true;
167 }
168 if !chars.has_links
169 && (line.contains('[')
170 || line.contains("http://")
171 || line.contains("https://")
172 || line.contains("ftp://")
173 || line.contains("www."))
174 {
175 chars.has_links = true;
176 }
177 if !chars.has_images && line.contains("![") {
178 chars.has_images = true;
179 }
180 if !chars.has_code
181 && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
182 {
183 chars.has_code = true;
184 }
185 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
186 chars.has_emphasis = true;
187 }
188 if !chars.has_html && line.contains('<') {
189 chars.has_html = true;
190 }
191 if !chars.has_tables && line.contains('|') {
192 chars.has_tables = true;
193 }
194 if !chars.has_blockquotes && line.starts_with('>') {
195 chars.has_blockquotes = true;
196 }
197 }
198
199 chars.has_headings = has_atx_heading || has_setext_heading;
200 chars
201 }
202
203 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
205 match rule.category() {
206 RuleCategory::Heading => !self.has_headings,
207 RuleCategory::List => !self.has_lists,
208 RuleCategory::Link => !self.has_links && !self.has_images,
209 RuleCategory::Image => !self.has_images,
210 RuleCategory::CodeBlock => !self.has_code,
211 RuleCategory::Html => !self.has_html,
212 RuleCategory::Emphasis => !self.has_emphasis,
213 RuleCategory::Blockquote => !self.has_blockquotes,
214 RuleCategory::Table => !self.has_tables,
215 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
217 }
218 }
219}
220
221#[cfg(feature = "native")]
226fn compute_content_hash(content: &str) -> String {
227 #[cfg(feature = "profiling")]
228 let start = std::time::Instant::now();
229 let hash = blake3::hash(content.as_bytes()).to_hex().to_string();
230 #[cfg(feature = "profiling")]
231 profiling::record_duration("index: hash content", start.elapsed());
232 hash
233}
234
235#[cfg(not(feature = "native"))]
237fn compute_content_hash(content: &str) -> String {
238 use std::hash::{DefaultHasher, Hash, Hasher};
239 let mut hasher = DefaultHasher::new();
240 content.hash(&mut hasher);
241 format!("{:016x}", hasher.finish())
242}
243
244pub fn lint(
248 content: &str,
249 rules: &[Box<dyn Rule>],
250 verbose: bool,
251 flavor: crate::config::MarkdownFlavor,
252 source_file: Option<std::path::PathBuf>,
253 config: Option<&crate::config::Config>,
254) -> LintResult {
255 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, config);
256 result
257}
258
259pub fn build_file_index_only(
267 content: &str,
268 rules: &[Box<dyn Rule>],
269 flavor: crate::config::MarkdownFlavor,
270 source_file: Option<std::path::PathBuf>,
271) -> crate::workspace_index::FileIndex {
272 let content_hash = compute_content_hash(content);
274 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
275
276 if content.is_empty() {
278 return file_index;
279 }
280
281 let lint_ctx = time_function!(
283 "index: parse lint context",
284 crate::lint_context::LintContext::new(content, flavor, source_file)
285 );
286
287 let (file_disabled, persistent_transitions, line_disabled) = lint_ctx.inline_config().export_for_file_index();
291 file_index.file_disabled_rules = file_disabled;
292 file_index.persistent_transitions = persistent_transitions;
293 file_index.line_disabled_rules = line_disabled;
294
295 time_section!("index: contribute cross-file data", {
297 for rule in rules {
298 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
299 rule.contribute_to_index(&lint_ctx, &mut file_index);
300 }
301 }
302 });
303
304 file_index
305}
306
307#[cfg_attr(test, allow(unused_variables))]
315pub fn lint_and_index(
316 content: &str,
317 rules: &[Box<dyn Rule>],
318 verbose: bool,
319 flavor: crate::config::MarkdownFlavor,
320 source_file: Option<std::path::PathBuf>,
321 config: Option<&crate::config::Config>,
322) -> (LintResult, crate::workspace_index::FileIndex) {
323 let mut warnings = Vec::new();
324 let content_hash = compute_content_hash(content);
326 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
327
328 if content.is_empty() {
330 return (Ok(warnings), file_index);
331 }
332
333 let lint_ctx = time_function!(
335 "lint: parse lint context",
336 crate::lint_context::LintContext::new(content, flavor, source_file)
337 );
338 let inline_config = lint_ctx.inline_config();
339
340 let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
342 file_index.file_disabled_rules = file_disabled;
343 file_index.persistent_transitions = persistent_transitions;
344 file_index.line_disabled_rules = line_disabled;
345
346 let characteristics = time_function!(
348 "lint: analyze content characteristics",
349 ContentCharacteristics::analyze(content)
350 );
351
352 let applicable_rules: Vec<_> = rules
354 .iter()
355 .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
356 .collect();
357
358 #[cfg(not(test))]
360 let total_rules = rules.len();
361 #[cfg(not(test))]
362 let applicable_count = applicable_rules.len();
363
364 #[cfg(not(target_arch = "wasm32"))]
365 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
366
367 let inline_overrides = inline_config.get_all_rule_configs();
370 let merged_config = if !inline_overrides.is_empty() {
371 config.map(|c| c.merge_with_inline_config(inline_config))
372 } else {
373 None
374 };
375 let effective_config = merged_config.as_ref().or(config);
376
377 let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
379 std::collections::HashMap::new();
380
381 if let Some(cfg) = effective_config {
383 for rule_name in inline_overrides.keys() {
384 if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
385 recreated_rules.insert(rule_name.clone(), recreated);
386 }
387 }
388 }
389
390 {
391 let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
392 for rule in &applicable_rules {
393 #[cfg(not(target_arch = "wasm32"))]
394 let rule_start = Instant::now();
395
396 if rule.should_skip(&lint_ctx) {
398 continue;
399 }
400
401 let effective_rule: &dyn crate::rule::Rule = recreated_rules
403 .get(rule.name())
404 .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
405
406 let result = effective_rule.check(&lint_ctx);
408
409 match result {
410 Ok(rule_warnings) => {
411 let filtered_warnings: Vec<_> = rule_warnings
414 .into_iter()
415 .filter(|warning| {
416 if lint_ctx
418 .line_info(warning.line)
419 .is_some_and(|info| info.in_kramdown_extension_block)
420 {
421 return false;
422 }
423
424 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
426
427 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
429 &rule_name_to_check[..dash_pos]
430 } else {
431 rule_name_to_check
432 };
433
434 {
440 let end = if warning.end_line >= warning.line {
441 warning.end_line
442 } else {
443 warning.line
444 };
445 !(warning.line..=end).any(|line| inline_config.is_rule_disabled(base_rule_name, line))
446 }
447 })
448 .map(|mut warning| {
449 if let Some(cfg) = config {
451 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
452 if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
453 warning.severity = override_severity;
454 }
455 }
456 warning
457 })
458 .collect();
459 warnings.extend(filtered_warnings);
460 }
461 Err(e) => {
462 log::error!("Error checking rule {}: {}", rule.name(), e);
463 return (Err(e), file_index);
464 }
465 }
466
467 #[cfg(not(target_arch = "wasm32"))]
468 {
469 let rule_duration = rule_start.elapsed();
470 if profile_rules {
471 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
472 }
473
474 #[cfg(not(test))]
475 if verbose && rule_duration.as_millis() > 500 {
476 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
477 }
478 }
479 }
480 }
481
482 time_section!("lint: contribute cross-file data", {
489 for rule in rules {
490 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
491 rule.contribute_to_index(&lint_ctx, &mut file_index);
492 }
493 }
494 });
495
496 #[cfg(not(test))]
497 if verbose {
498 let skipped_rules = total_rules - applicable_count;
499 if skipped_rules > 0 {
500 log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
501 }
502 }
503
504 (Ok(warnings), file_index)
505}
506
507pub fn run_cross_file_checks(
520 file_path: &std::path::Path,
521 file_index: &crate::workspace_index::FileIndex,
522 rules: &[Box<dyn Rule>],
523 workspace_index: &crate::workspace_index::WorkspaceIndex,
524 config: Option<&crate::config::Config>,
525) -> LintResult {
526 use crate::rule::CrossFileScope;
527
528 let mut warnings = Vec::new();
529
530 let ignored_rules_for_file = config.map(|cfg| cfg.get_ignored_rules_for_file(file_path));
536
537 for rule in rules {
539 if rule.cross_file_scope() != CrossFileScope::Workspace {
540 continue;
541 }
542
543 if ignored_rules_for_file
544 .as_ref()
545 .is_some_and(|ignored| ignored.contains(rule.name()))
546 {
547 continue;
548 }
549
550 match time_function!(
551 "workspace: cross-file rule check",
552 rule.cross_file_check(file_path, file_index, workspace_index)
553 ) {
554 Ok(rule_warnings) => {
555 let filtered: Vec<_> = rule_warnings
557 .into_iter()
558 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
559 .map(|mut warning| {
560 if let Some(cfg) = config
562 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
563 {
564 warning.severity = override_severity;
565 }
566 warning
567 })
568 .collect();
569 warnings.extend(filtered);
570 }
571 Err(e) => {
572 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
573 return Err(e);
574 }
575 }
576 }
577
578 Ok(warnings)
579}
580
581pub fn get_profiling_report() -> String {
583 profiling::get_report()
584}
585
586pub fn reset_profiling() {
588 profiling::reset()
589}
590
591pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
593 crate::utils::regex_cache::get_cache_stats()
594}
595
596#[cfg(test)]
597mod tests {
598 use super::*;
599 use crate::rule::Rule;
600 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
601
602 #[test]
603 fn test_content_characteristics_analyze() {
604 let chars = ContentCharacteristics::analyze("");
606 assert!(!chars.has_headings);
607 assert!(!chars.has_lists);
608 assert!(!chars.has_links);
609 assert!(!chars.has_code);
610 assert!(!chars.has_emphasis);
611 assert!(!chars.has_html);
612 assert!(!chars.has_tables);
613 assert!(!chars.has_blockquotes);
614 assert!(!chars.has_images);
615
616 let chars = ContentCharacteristics::analyze("# Heading");
618 assert!(chars.has_headings);
619
620 let chars = ContentCharacteristics::analyze("Heading\n=======");
622 assert!(chars.has_headings);
623
624 let chars = ContentCharacteristics::analyze("> ## Alpha\n>\n> ## Alpha");
627 assert!(chars.has_headings, "blockquoted ATX heading must set has_headings");
628 let chars = ContentCharacteristics::analyze(">> # Nested");
629 assert!(
630 chars.has_headings,
631 "nested-blockquote ATX heading must set has_headings"
632 );
633 let chars = ContentCharacteristics::analyze(">\t## Tabbed");
636 assert!(
637 chars.has_headings,
638 "tab-separated blockquote ATX heading must set has_headings"
639 );
640
641 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
643 assert!(chars.has_lists);
644
645 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
647 assert!(chars.has_lists);
648
649 let chars = ContentCharacteristics::analyze("[link](url)");
651 assert!(chars.has_links);
652
653 let chars = ContentCharacteristics::analyze("Visit https://example.com");
655 assert!(chars.has_links);
656
657 let chars = ContentCharacteristics::analyze("");
659 assert!(chars.has_images);
660
661 let chars = ContentCharacteristics::analyze("`inline code`");
663 assert!(chars.has_code);
664
665 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
666 assert!(chars.has_code);
667
668 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
670 assert!(chars.has_code);
671
672 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
674 assert!(chars.has_code);
675
676 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
678 assert!(chars.has_code);
679
680 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
682 assert!(chars.has_code);
683
684 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
686 assert!(chars.has_emphasis);
687
688 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
690 assert!(chars.has_html);
691
692 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
694 assert!(chars.has_tables);
695
696 let chars = ContentCharacteristics::analyze("> Quote");
698 assert!(chars.has_blockquotes);
699
700 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
702 let chars = ContentCharacteristics::analyze(content);
703 assert!(chars.has_headings);
704 assert!(chars.has_lists);
705 assert!(chars.has_links);
706 assert!(chars.has_code);
707 assert!(chars.has_emphasis);
708 assert!(chars.has_html);
709 assert!(chars.has_tables);
710 assert!(chars.has_blockquotes);
711 assert!(chars.has_images);
712 }
713
714 #[test]
715 fn test_content_characteristics_should_skip_rule() {
716 let chars = ContentCharacteristics {
717 has_headings: true,
718 has_lists: false,
719 has_links: true,
720 has_code: false,
721 has_emphasis: true,
722 has_html: false,
723 has_tables: true,
724 has_blockquotes: false,
725 has_images: false,
726 };
727
728 let heading_rule = MD001HeadingIncrement::default();
730 assert!(!chars.should_skip_rule(&heading_rule));
731
732 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
733 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
737 has_headings: false,
738 ..Default::default()
739 };
740 assert!(chars_no_headings.should_skip_rule(&heading_rule));
741 }
742
743 #[test]
744 fn test_lint_empty_content() {
745 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
746
747 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
748 assert!(result.is_ok());
749 assert!(result.unwrap().is_empty());
750 }
751
752 #[test]
753 fn test_lint_with_violations() {
754 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
756
757 let result = lint(
758 content,
759 &rules,
760 false,
761 crate::config::MarkdownFlavor::Standard,
762 None,
763 None,
764 );
765 assert!(result.is_ok());
766 let warnings = result.unwrap();
767 assert!(!warnings.is_empty());
768 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
770 }
771
772 #[test]
773 fn test_lint_with_inline_disable() {
774 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
775 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
776
777 let result = lint(
778 content,
779 &rules,
780 false,
781 crate::config::MarkdownFlavor::Standard,
782 None,
783 None,
784 );
785 assert!(result.is_ok());
786 let warnings = result.unwrap();
787 assert!(warnings.is_empty()); }
789
790 #[test]
791 fn test_lint_rule_filtering() {
792 let content = "# Heading\nJust text";
794 let rules: Vec<Box<dyn Rule>> = vec![
795 Box::new(MD001HeadingIncrement::default()),
796 ];
798
799 let result = lint(
800 content,
801 &rules,
802 false,
803 crate::config::MarkdownFlavor::Standard,
804 None,
805 None,
806 );
807 assert!(result.is_ok());
808 }
809
810 #[test]
811 fn test_get_profiling_report() {
812 let report = get_profiling_report();
814 assert!(!report.is_empty());
815 assert!(report.contains("Profiling"));
816 }
817
818 #[test]
819 fn test_reset_profiling() {
820 reset_profiling();
822
823 let report = get_profiling_report();
825 assert!(report.contains("disabled") || report.contains("no measurements"));
826 }
827
828 #[test]
829 fn test_get_regex_cache_stats() {
830 let stats = get_regex_cache_stats();
831 assert!(stats.is_empty() || !stats.is_empty());
833
834 for count in stats.values() {
836 assert!(*count > 0);
837 }
838 }
839
840 #[test]
841 fn test_content_characteristics_edge_cases() {
842 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
845
846 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
848
849 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");
859 assert!(!chars.has_blockquotes);
860 }
861}