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 && trimmed.starts_with('#') {
130 has_atx_heading = true;
131 }
132 if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
133 has_setext_heading = true;
134 }
135
136 if !chars.has_lists
139 && (line.contains("* ")
140 || line.contains("- ")
141 || line.contains("+ ")
142 || trimmed.starts_with("* ")
143 || trimmed.starts_with("- ")
144 || trimmed.starts_with("+ ")
145 || trimmed.starts_with('*')
146 || trimmed.starts_with('-')
147 || trimmed.starts_with('+'))
148 {
149 chars.has_lists = true;
150 }
151 if !chars.has_lists
153 && ((line.chars().next().is_some_and(|c| c.is_ascii_digit())
154 && (line.contains(". ") || line.contains('.')))
155 || (trimmed.starts_with('>')
156 && trimmed.chars().any(|c| c.is_ascii_digit())
157 && (trimmed.contains(". ") || trimmed.contains('.'))))
158 {
159 chars.has_lists = true;
160 }
161 if !chars.has_links
162 && (line.contains('[')
163 || line.contains("http://")
164 || line.contains("https://")
165 || line.contains("ftp://")
166 || line.contains("www."))
167 {
168 chars.has_links = true;
169 }
170 if !chars.has_images && line.contains("![") {
171 chars.has_images = true;
172 }
173 if !chars.has_code
174 && (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
175 {
176 chars.has_code = true;
177 }
178 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
179 chars.has_emphasis = true;
180 }
181 if !chars.has_html && line.contains('<') {
182 chars.has_html = true;
183 }
184 if !chars.has_tables && line.contains('|') {
185 chars.has_tables = true;
186 }
187 if !chars.has_blockquotes && line.starts_with('>') {
188 chars.has_blockquotes = true;
189 }
190 }
191
192 chars.has_headings = has_atx_heading || has_setext_heading;
193 chars
194 }
195
196 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
198 match rule.category() {
199 RuleCategory::Heading => !self.has_headings,
200 RuleCategory::List => !self.has_lists,
201 RuleCategory::Link => !self.has_links && !self.has_images,
202 RuleCategory::Image => !self.has_images,
203 RuleCategory::CodeBlock => !self.has_code,
204 RuleCategory::Html => !self.has_html,
205 RuleCategory::Emphasis => !self.has_emphasis,
206 RuleCategory::Blockquote => !self.has_blockquotes,
207 RuleCategory::Table => !self.has_tables,
208 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
210 }
211 }
212}
213
214#[cfg(feature = "native")]
219fn compute_content_hash(content: &str) -> String {
220 #[cfg(feature = "profiling")]
221 let start = std::time::Instant::now();
222 let hash = blake3::hash(content.as_bytes()).to_hex().to_string();
223 #[cfg(feature = "profiling")]
224 profiling::record_duration("index: hash content", start.elapsed());
225 hash
226}
227
228#[cfg(not(feature = "native"))]
230fn compute_content_hash(content: &str) -> String {
231 use std::hash::{DefaultHasher, Hash, Hasher};
232 let mut hasher = DefaultHasher::new();
233 content.hash(&mut hasher);
234 format!("{:016x}", hasher.finish())
235}
236
237pub fn lint(
241 content: &str,
242 rules: &[Box<dyn Rule>],
243 verbose: bool,
244 flavor: crate::config::MarkdownFlavor,
245 source_file: Option<std::path::PathBuf>,
246 config: Option<&crate::config::Config>,
247) -> LintResult {
248 let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, config);
249 result
250}
251
252pub fn build_file_index_only(
260 content: &str,
261 rules: &[Box<dyn Rule>],
262 flavor: crate::config::MarkdownFlavor,
263 source_file: Option<std::path::PathBuf>,
264) -> crate::workspace_index::FileIndex {
265 let content_hash = compute_content_hash(content);
267 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
268
269 if content.is_empty() {
271 return file_index;
272 }
273
274 let lint_ctx = time_function!(
276 "index: parse lint context",
277 crate::lint_context::LintContext::new(content, flavor, source_file)
278 );
279
280 time_section!("index: contribute cross-file data", {
282 for rule in rules {
283 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
284 rule.contribute_to_index(&lint_ctx, &mut file_index);
285 }
286 }
287 });
288
289 file_index
290}
291
292#[cfg_attr(test, allow(unused_variables))]
300pub fn lint_and_index(
301 content: &str,
302 rules: &[Box<dyn Rule>],
303 verbose: bool,
304 flavor: crate::config::MarkdownFlavor,
305 source_file: Option<std::path::PathBuf>,
306 config: Option<&crate::config::Config>,
307) -> (LintResult, crate::workspace_index::FileIndex) {
308 let mut warnings = Vec::new();
309 let content_hash = compute_content_hash(content);
311 let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
312
313 if content.is_empty() {
315 return (Ok(warnings), file_index);
316 }
317
318 let lint_ctx = time_function!(
320 "lint: parse lint context",
321 crate::lint_context::LintContext::new(content, flavor, source_file)
322 );
323 let inline_config = lint_ctx.inline_config();
324
325 let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
327 file_index.file_disabled_rules = file_disabled;
328 file_index.persistent_transitions = persistent_transitions;
329 file_index.line_disabled_rules = line_disabled;
330
331 let characteristics = time_function!(
333 "lint: analyze content characteristics",
334 ContentCharacteristics::analyze(content)
335 );
336
337 let applicable_rules: Vec<_> = rules
339 .iter()
340 .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
341 .collect();
342
343 #[cfg(not(test))]
345 let total_rules = rules.len();
346 #[cfg(not(test))]
347 let applicable_count = applicable_rules.len();
348
349 #[cfg(not(target_arch = "wasm32"))]
350 let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
351
352 let inline_overrides = inline_config.get_all_rule_configs();
355 let merged_config = if !inline_overrides.is_empty() {
356 config.map(|c| c.merge_with_inline_config(inline_config))
357 } else {
358 None
359 };
360 let effective_config = merged_config.as_ref().or(config);
361
362 let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
364 std::collections::HashMap::new();
365
366 if let Some(cfg) = effective_config {
368 for rule_name in inline_overrides.keys() {
369 if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
370 recreated_rules.insert(rule_name.clone(), recreated);
371 }
372 }
373 }
374
375 {
376 let _timer = profiling::ScopedTimer::new("lint: run single-file rules");
377 for rule in &applicable_rules {
378 #[cfg(not(target_arch = "wasm32"))]
379 let rule_start = Instant::now();
380
381 if rule.should_skip(&lint_ctx) {
383 continue;
384 }
385
386 let effective_rule: &dyn crate::rule::Rule = recreated_rules
388 .get(rule.name())
389 .map_or(rule.as_ref(), std::convert::AsRef::as_ref);
390
391 let result = effective_rule.check(&lint_ctx);
393
394 match result {
395 Ok(rule_warnings) => {
396 let filtered_warnings: Vec<_> = rule_warnings
399 .into_iter()
400 .filter(|warning| {
401 if lint_ctx
403 .line_info(warning.line)
404 .is_some_and(|info| info.in_kramdown_extension_block)
405 {
406 return false;
407 }
408
409 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
411
412 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
414 &rule_name_to_check[..dash_pos]
415 } else {
416 rule_name_to_check
417 };
418
419 {
425 let end = if warning.end_line >= warning.line {
426 warning.end_line
427 } else {
428 warning.line
429 };
430 !(warning.line..=end).any(|line| inline_config.is_rule_disabled(base_rule_name, line))
431 }
432 })
433 .map(|mut warning| {
434 if let Some(cfg) = config {
436 let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
437 if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
438 warning.severity = override_severity;
439 }
440 }
441 warning
442 })
443 .collect();
444 warnings.extend(filtered_warnings);
445 }
446 Err(e) => {
447 log::error!("Error checking rule {}: {}", rule.name(), e);
448 return (Err(e), file_index);
449 }
450 }
451
452 #[cfg(not(target_arch = "wasm32"))]
453 {
454 let rule_duration = rule_start.elapsed();
455 if profile_rules {
456 eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
457 }
458
459 #[cfg(not(test))]
460 if verbose && rule_duration.as_millis() > 500 {
461 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
462 }
463 }
464 }
465 }
466
467 time_section!("lint: contribute cross-file data", {
474 for rule in rules {
475 if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
476 rule.contribute_to_index(&lint_ctx, &mut file_index);
477 }
478 }
479 });
480
481 #[cfg(not(test))]
482 if verbose {
483 let skipped_rules = total_rules - applicable_count;
484 if skipped_rules > 0 {
485 log::debug!("Skipped {skipped_rules} of {total_rules} rules based on content analysis");
486 }
487 }
488
489 (Ok(warnings), file_index)
490}
491
492pub fn run_cross_file_checks(
505 file_path: &std::path::Path,
506 file_index: &crate::workspace_index::FileIndex,
507 rules: &[Box<dyn Rule>],
508 workspace_index: &crate::workspace_index::WorkspaceIndex,
509 config: Option<&crate::config::Config>,
510) -> LintResult {
511 use crate::rule::CrossFileScope;
512
513 let mut warnings = Vec::new();
514
515 for rule in rules {
517 if rule.cross_file_scope() != CrossFileScope::Workspace {
518 continue;
519 }
520
521 match time_function!(
522 "workspace: cross-file rule check",
523 rule.cross_file_check(file_path, file_index, workspace_index)
524 ) {
525 Ok(rule_warnings) => {
526 let filtered: Vec<_> = rule_warnings
528 .into_iter()
529 .filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
530 .map(|mut warning| {
531 if let Some(cfg) = config
533 && let Some(override_severity) = cfg.get_rule_severity(rule.name())
534 {
535 warning.severity = override_severity;
536 }
537 warning
538 })
539 .collect();
540 warnings.extend(filtered);
541 }
542 Err(e) => {
543 log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
544 return Err(e);
545 }
546 }
547 }
548
549 Ok(warnings)
550}
551
552pub fn get_profiling_report() -> String {
554 profiling::get_report()
555}
556
557pub fn reset_profiling() {
559 profiling::reset()
560}
561
562pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
564 crate::utils::regex_cache::get_cache_stats()
565}
566
567#[cfg(test)]
568mod tests {
569 use super::*;
570 use crate::rule::Rule;
571 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
572
573 #[test]
574 fn test_content_characteristics_analyze() {
575 let chars = ContentCharacteristics::analyze("");
577 assert!(!chars.has_headings);
578 assert!(!chars.has_lists);
579 assert!(!chars.has_links);
580 assert!(!chars.has_code);
581 assert!(!chars.has_emphasis);
582 assert!(!chars.has_html);
583 assert!(!chars.has_tables);
584 assert!(!chars.has_blockquotes);
585 assert!(!chars.has_images);
586
587 let chars = ContentCharacteristics::analyze("# Heading");
589 assert!(chars.has_headings);
590
591 let chars = ContentCharacteristics::analyze("Heading\n=======");
593 assert!(chars.has_headings);
594
595 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
597 assert!(chars.has_lists);
598
599 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
601 assert!(chars.has_lists);
602
603 let chars = ContentCharacteristics::analyze("[link](url)");
605 assert!(chars.has_links);
606
607 let chars = ContentCharacteristics::analyze("Visit https://example.com");
609 assert!(chars.has_links);
610
611 let chars = ContentCharacteristics::analyze("");
613 assert!(chars.has_images);
614
615 let chars = ContentCharacteristics::analyze("`inline code`");
617 assert!(chars.has_code);
618
619 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
620 assert!(chars.has_code);
621
622 let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
624 assert!(chars.has_code);
625
626 let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
628 assert!(chars.has_code);
629
630 let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
632 assert!(chars.has_code);
633
634 let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
636 assert!(chars.has_code);
637
638 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
640 assert!(chars.has_emphasis);
641
642 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
644 assert!(chars.has_html);
645
646 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
648 assert!(chars.has_tables);
649
650 let chars = ContentCharacteristics::analyze("> Quote");
652 assert!(chars.has_blockquotes);
653
654 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
656 let chars = ContentCharacteristics::analyze(content);
657 assert!(chars.has_headings);
658 assert!(chars.has_lists);
659 assert!(chars.has_links);
660 assert!(chars.has_code);
661 assert!(chars.has_emphasis);
662 assert!(chars.has_html);
663 assert!(chars.has_tables);
664 assert!(chars.has_blockquotes);
665 assert!(chars.has_images);
666 }
667
668 #[test]
669 fn test_content_characteristics_should_skip_rule() {
670 let chars = ContentCharacteristics {
671 has_headings: true,
672 has_lists: false,
673 has_links: true,
674 has_code: false,
675 has_emphasis: true,
676 has_html: false,
677 has_tables: true,
678 has_blockquotes: false,
679 has_images: false,
680 };
681
682 let heading_rule = MD001HeadingIncrement::default();
684 assert!(!chars.should_skip_rule(&heading_rule));
685
686 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
687 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
691 has_headings: false,
692 ..Default::default()
693 };
694 assert!(chars_no_headings.should_skip_rule(&heading_rule));
695 }
696
697 #[test]
698 fn test_lint_empty_content() {
699 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
700
701 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
702 assert!(result.is_ok());
703 assert!(result.unwrap().is_empty());
704 }
705
706 #[test]
707 fn test_lint_with_violations() {
708 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
710
711 let result = lint(
712 content,
713 &rules,
714 false,
715 crate::config::MarkdownFlavor::Standard,
716 None,
717 None,
718 );
719 assert!(result.is_ok());
720 let warnings = result.unwrap();
721 assert!(!warnings.is_empty());
722 assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
724 }
725
726 #[test]
727 fn test_lint_with_inline_disable() {
728 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
729 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
730
731 let result = lint(
732 content,
733 &rules,
734 false,
735 crate::config::MarkdownFlavor::Standard,
736 None,
737 None,
738 );
739 assert!(result.is_ok());
740 let warnings = result.unwrap();
741 assert!(warnings.is_empty()); }
743
744 #[test]
745 fn test_lint_rule_filtering() {
746 let content = "# Heading\nJust text";
748 let rules: Vec<Box<dyn Rule>> = vec![
749 Box::new(MD001HeadingIncrement::default()),
750 ];
752
753 let result = lint(
754 content,
755 &rules,
756 false,
757 crate::config::MarkdownFlavor::Standard,
758 None,
759 None,
760 );
761 assert!(result.is_ok());
762 }
763
764 #[test]
765 fn test_get_profiling_report() {
766 let report = get_profiling_report();
768 assert!(!report.is_empty());
769 assert!(report.contains("Profiling"));
770 }
771
772 #[test]
773 fn test_reset_profiling() {
774 reset_profiling();
776
777 let report = get_profiling_report();
779 assert!(report.contains("disabled") || report.contains("no measurements"));
780 }
781
782 #[test]
783 fn test_get_regex_cache_stats() {
784 let stats = get_regex_cache_stats();
785 assert!(stats.is_empty() || !stats.is_empty());
787
788 for count in stats.values() {
790 assert!(*count > 0);
791 }
792 }
793
794 #[test]
795 fn test_content_characteristics_edge_cases() {
796 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
799
800 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
802
803 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");
813 assert!(!chars.has_blockquotes);
814 }
815}