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 time_section!("index: contribute cross-file data", {
289 for rule in rules {
290 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
291 rule.contribute_to_index(&lint_ctx, &mut file_index);
292 }
293 }
294 });
295
296 file_index
297}
298
299#[cfg_attr(test, allow(unused_variables))]
307pub fn lint_and_index(
308 content: &str,
309 rules: &[Box<dyn Rule>],
310 verbose: bool,
311 flavor: crate::config::MarkdownFlavor,
312 source_file: Option<std::path::PathBuf>,
313 config: Option<&crate::config::Config>,
314) -> (LintResult, crate::workspace_index::FileIndex) {
315 let mut warnings = Vec::new();
316 let content_hash = compute_content_hash(content);
318 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
319
320 if content.is_empty() {
322 return (Ok(warnings), file_index);
323 }
324
325 let lint_ctx = time_function!(
327 "lint: parse lint context",
328 crate::lint_context::LintContext::new(content, flavor, source_file)
329 );
330 let inline_config = lint_ctx.inline_config();
331
332 let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
334 file_index.file_disabled_rules = file_disabled;
335 file_index.persistent_transitions = persistent_transitions;
336 file_index.line_disabled_rules = line_disabled;
337
338 let characteristics = time_function!(
340 "lint: analyze content characteristics",
341 ContentCharacteristics::analyze(content)
342 );
343
344 let applicable_rules: Vec<_> = rules
346 .iter()
347 .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
348 .collect();
349
350 #[cfg(not(test))]
352 let total_rules = rules.len();
353 #[cfg(not(test))]
354 let applicable_count = applicable_rules.len();
355
356 #[cfg(not(target_arch = "wasm32"))]
357 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
358
359 let inline_overrides = inline_config.get_all_rule_configs();
362 let merged_config = if !inline_overrides.is_empty() {
363 config.map(|c| c.merge_with_inline_config(inline_config))
364 } else {
365 None
366 };
367 let effective_config = merged_config.as_ref().or(config);
368
369 let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
371 std::collections::HashMap::new();
372
373 if let Some(cfg) = effective_config {
375 for rule_name in inline_overrides.keys() {
376 if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
377 recreated_rules.insert(rule_name.clone(), recreated);
378 }
379 }
380 }
381
382 {
383 let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
384 for rule in &applicable_rules {
385 #[cfg(not(target_arch = "wasm32"))]
386 let rule_start = Instant::now();
387
388 if rule.should_skip(&lint_ctx) {
390 continue;
391 }
392
393 let effective_rule: &dyn crate::rule::Rule = recreated_rules
395 .get(rule.name())
396 .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
397
398 let result = effective_rule.check(&lint_ctx);
400
401 match result {
402 Ok(rule_warnings) => {
403 let filtered_warnings: Vec<_> = rule_warnings
406 .into_iter()
407 .filter(|warning| {
408 if lint_ctx
410 .line_info(warning.line)
411 .is_some_and(|info| info.in_kramdown_extension_block)
412 {
413 return false;
414 }
415
416 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
418
419 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
421 &rule_name_to_check[..dash_pos]
422 } else {
423 rule_name_to_check
424 };
425
426 {
432 let end = if warning.end_line >= warning.line {
433 warning.end_line
434 } else {
435 warning.line
436 };
437 !(warning.line..=end).any(|line| inline_config.is_rule_disabled(base_rule_name, line))
438 }
439 })
440 .map(|mut warning| {
441 if let Some(cfg) = config {
443 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
444 if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
445 warning.severity = override_severity;
446 }
447 }
448 warning
449 })
450 .collect();
451 warnings.extend(filtered_warnings);
452 }
453 Err(e) => {
454 log::error!("Error checking rule {}: {}", rule.name(), e);
455 return (Err(e), file_index);
456 }
457 }
458
459 #[cfg(not(target_arch = "wasm32"))]
460 {
461 let rule_duration = rule_start.elapsed();
462 if profile_rules {
463 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
464 }
465
466 #[cfg(not(test))]
467 if verbose && rule_duration.as_millis() > 500 {
468 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
469 }
470 }
471 }
472 }
473
474 time_section!("lint: contribute cross-file data", {
481 for rule in rules {
482 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
483 rule.contribute_to_index(&lint_ctx, &mut file_index);
484 }
485 }
486 });
487
488 #[cfg(not(test))]
489 if verbose {
490 let skipped_rules = total_rules - applicable_count;
491 if skipped_rules > 0 {
492 log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
493 }
494 }
495
496 (Ok(warnings), file_index)
497}
498
499pub fn run_cross_file_checks(
512 file_path: &std::path::Path,
513 file_index: &crate::workspace_index::FileIndex,
514 rules: &[Box<dyn Rule>],
515 workspace_index: &crate::workspace_index::WorkspaceIndex,
516 config: Option<&crate::config::Config>,
517) -> LintResult {
518 use crate::rule::CrossFileScope;
519
520 let mut warnings = Vec::new();
521
522 for rule in rules {
524 if rule.cross_file_scope() != CrossFileScope::Workspace {
525 continue;
526 }
527
528 match time_function!(
529 "workspace: cross-file rule check",
530 rule.cross_file_check(file_path, file_index, workspace_index)
531 ) {
532 Ok(rule_warnings) => {
533 let filtered: Vec<_> = rule_warnings
535 .into_iter()
536 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
537 .map(|mut warning| {
538 if let Some(cfg) = config
540 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
541 {
542 warning.severity = override_severity;
543 }
544 warning
545 })
546 .collect();
547 warnings.extend(filtered);
548 }
549 Err(e) => {
550 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
551 return Err(e);
552 }
553 }
554 }
555
556 Ok(warnings)
557}
558
559pub fn get_profiling_report() -> String {
561 profiling::get_report()
562}
563
564pub fn reset_profiling() {
566 profiling::reset()
567}
568
569pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
571 crate::utils::regex_cache::get_cache_stats()
572}
573
574#[cfg(test)]
575mod tests {
576 use super::*;
577 use crate::rule::Rule;
578 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
579
580 #[test]
581 fn test_content_characteristics_analyze() {
582 let chars = ContentCharacteristics::analyze("");
584 assert!(!chars.has_headings);
585 assert!(!chars.has_lists);
586 assert!(!chars.has_links);
587 assert!(!chars.has_code);
588 assert!(!chars.has_emphasis);
589 assert!(!chars.has_html);
590 assert!(!chars.has_tables);
591 assert!(!chars.has_blockquotes);
592 assert!(!chars.has_images);
593
594 let chars = ContentCharacteristics::analyze("# Heading");
596 assert!(chars.has_headings);
597
598 let chars = ContentCharacteristics::analyze("Heading\n=======");
600 assert!(chars.has_headings);
601
602 let chars = ContentCharacteristics::analyze("> ## Alpha\n>\n> ## Alpha");
605 assert!(chars.has_headings, "blockquoted ATX heading must set has_headings");
606 let chars = ContentCharacteristics::analyze(">> # Nested");
607 assert!(
608 chars.has_headings,
609 "nested-blockquote ATX heading must set has_headings"
610 );
611 let chars = ContentCharacteristics::analyze(">\t## Tabbed");
614 assert!(
615 chars.has_headings,
616 "tab-separated blockquote ATX heading must set has_headings"
617 );
618
619 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
621 assert!(chars.has_lists);
622
623 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
625 assert!(chars.has_lists);
626
627 let chars = ContentCharacteristics::analyze("[link](url)");
629 assert!(chars.has_links);
630
631 let chars = ContentCharacteristics::analyze("Visit https://example.com");
633 assert!(chars.has_links);
634
635 let chars = ContentCharacteristics::analyze("");
637 assert!(chars.has_images);
638
639 let chars = ContentCharacteristics::analyze("`inline code`");
641 assert!(chars.has_code);
642
643 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
644 assert!(chars.has_code);
645
646 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
648 assert!(chars.has_code);
649
650 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
652 assert!(chars.has_code);
653
654 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
656 assert!(chars.has_code);
657
658 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
660 assert!(chars.has_code);
661
662 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
664 assert!(chars.has_emphasis);
665
666 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
668 assert!(chars.has_html);
669
670 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
672 assert!(chars.has_tables);
673
674 let chars = ContentCharacteristics::analyze("> Quote");
676 assert!(chars.has_blockquotes);
677
678 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
680 let chars = ContentCharacteristics::analyze(content);
681 assert!(chars.has_headings);
682 assert!(chars.has_lists);
683 assert!(chars.has_links);
684 assert!(chars.has_code);
685 assert!(chars.has_emphasis);
686 assert!(chars.has_html);
687 assert!(chars.has_tables);
688 assert!(chars.has_blockquotes);
689 assert!(chars.has_images);
690 }
691
692 #[test]
693 fn test_content_characteristics_should_skip_rule() {
694 let chars = ContentCharacteristics {
695 has_headings: true,
696 has_lists: false,
697 has_links: true,
698 has_code: false,
699 has_emphasis: true,
700 has_html: false,
701 has_tables: true,
702 has_blockquotes: false,
703 has_images: false,
704 };
705
706 let heading_rule = MD001HeadingIncrement::default();
708 assert!(!chars.should_skip_rule(&heading_rule));
709
710 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
711 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
715 has_headings: false,
716 ..Default::default()
717 };
718 assert!(chars_no_headings.should_skip_rule(&heading_rule));
719 }
720
721 #[test]
722 fn test_lint_empty_content() {
723 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
724
725 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
726 assert!(result.is_ok());
727 assert!(result.unwrap().is_empty());
728 }
729
730 #[test]
731 fn test_lint_with_violations() {
732 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
734
735 let result = lint(
736 content,
737 &rules,
738 false,
739 crate::config::MarkdownFlavor::Standard,
740 None,
741 None,
742 );
743 assert!(result.is_ok());
744 let warnings = result.unwrap();
745 assert!(!warnings.is_empty());
746 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
748 }
749
750 #[test]
751 fn test_lint_with_inline_disable() {
752 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
753 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
754
755 let result = lint(
756 content,
757 &rules,
758 false,
759 crate::config::MarkdownFlavor::Standard,
760 None,
761 None,
762 );
763 assert!(result.is_ok());
764 let warnings = result.unwrap();
765 assert!(warnings.is_empty()); }
767
768 #[test]
769 fn test_lint_rule_filtering() {
770 let content = "# Heading\nJust text";
772 let rules: Vec<Box<dyn Rule>> = vec![
773 Box::new(MD001HeadingIncrement::default()),
774 ];
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 }
787
788 #[test]
789 fn test_get_profiling_report() {
790 let report = get_profiling_report();
792 assert!(!report.is_empty());
793 assert!(report.contains("Profiling"));
794 }
795
796 #[test]
797 fn test_reset_profiling() {
798 reset_profiling();
800
801 let report = get_profiling_report();
803 assert!(report.contains("disabled") || report.contains("no measurements"));
804 }
805
806 #[test]
807 fn test_get_regex_cache_stats() {
808 let stats = get_regex_cache_stats();
809 assert!(stats.is_empty() || !stats.is_empty());
811
812 for count in stats.values() {
814 assert!(*count > 0);
815 }
816 }
817
818 #[test]
819 fn test_content_characteristics_edge_cases() {
820 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
823
824 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
826
827 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");
837 assert!(!chars.has_blockquotes);
838 }
839}