1pub mod config;
2pub mod exit_codes;
3pub mod inline_config;
4pub mod lint_context;
5pub mod lsp;
6pub mod markdownlint_config;
7pub mod output;
8pub mod parallel;
9pub mod performance;
10pub mod profiling;
11pub mod rule;
12pub mod vscode;
13#[macro_use]
14pub mod rule_config;
15#[macro_use]
16pub mod rule_config_serde;
17pub mod rules;
18pub mod utils;
19
20#[cfg(feature = "python")]
21pub mod python;
22
23pub use rules::heading_utils::{Heading, HeadingStyle};
24pub use rules::*;
25
26pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
27use crate::rule::{LintResult, Rule, RuleCategory};
28use crate::utils::document_structure::DocumentStructure;
29use std::time::Instant;
30
31#[derive(Debug, Default)]
33struct ContentCharacteristics {
34 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, }
44
45impl ContentCharacteristics {
46 fn analyze(content: &str) -> Self {
47 let mut chars = Self { ..Default::default() };
48
49 let mut has_atx_heading = false;
51 let mut has_setext_heading = false;
52
53 for line in content.lines() {
54 let trimmed = line.trim();
55
56 if !has_atx_heading && trimmed.starts_with('#') {
58 has_atx_heading = true;
59 }
60 if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
61 has_setext_heading = true;
62 }
63
64 if !chars.has_lists && (line.contains("* ") || line.contains("- ") || line.contains("+ ")) {
66 chars.has_lists = true;
67 }
68 if !chars.has_lists && line.chars().next().is_some_and(|c| c.is_ascii_digit()) && line.contains(". ") {
69 chars.has_lists = true;
70 }
71 if !chars.has_links
72 && (line.contains('[')
73 || line.contains("http://")
74 || line.contains("https://")
75 || line.contains("ftp://"))
76 {
77 chars.has_links = true;
78 }
79 if !chars.has_images && line.contains("![") {
80 chars.has_images = true;
81 }
82 if !chars.has_code && (line.contains('`') || line.contains("~~~")) {
83 chars.has_code = true;
84 }
85 if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
86 chars.has_emphasis = true;
87 }
88 if !chars.has_html && line.contains('<') {
89 chars.has_html = true;
90 }
91 if !chars.has_tables && line.contains('|') {
92 chars.has_tables = true;
93 }
94 if !chars.has_blockquotes && line.starts_with('>') {
95 chars.has_blockquotes = true;
96 }
97 }
98
99 chars.has_headings = has_atx_heading || has_setext_heading;
100 chars
101 }
102
103 fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
105 match rule.category() {
106 RuleCategory::Heading => !self.has_headings,
107 RuleCategory::List => !self.has_lists,
108 RuleCategory::Link => !self.has_links && !self.has_images,
109 RuleCategory::Image => !self.has_images,
110 RuleCategory::CodeBlock => !self.has_code,
111 RuleCategory::Html => !self.has_html,
112 RuleCategory::Emphasis => !self.has_emphasis,
113 RuleCategory::Blockquote => !self.has_blockquotes,
114 RuleCategory::Table => !self.has_tables,
115 RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
117 }
118 }
119}
120
121pub fn lint(
125 content: &str,
126 rules: &[Box<dyn Rule>],
127 _verbose: bool,
128 flavor: crate::config::MarkdownFlavor,
129) -> LintResult {
130 let mut warnings = Vec::new();
131 let _overall_start = Instant::now();
132
133 if content.is_empty() {
135 return Ok(warnings);
136 }
137
138 let inline_config = crate::inline_config::InlineConfig::from_content(content);
140
141 let characteristics = ContentCharacteristics::analyze(content);
143
144 let applicable_rules: Vec<_> = rules
146 .iter()
147 .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
148 .collect();
149
150 let _total_rules = rules.len();
152 let _applicable_count = applicable_rules.len();
153
154 let structure = DocumentStructure::new(content);
156
157 let ast_rules_count = applicable_rules.iter().filter(|rule| rule.uses_ast()).count();
159 let ast = if ast_rules_count > 0 {
160 Some(crate::utils::ast_utils::get_cached_ast(content))
161 } else {
162 None
163 };
164
165 let lint_ctx = crate::lint_context::LintContext::new(content, flavor);
167
168 for rule in applicable_rules {
169 let _rule_start = Instant::now();
170
171 let result = if rule.uses_ast() {
173 if let Some(ref ast_ref) = ast {
174 rule.as_maybe_ast()
176 .and_then(|ext| ext.check_with_ast_opt(&lint_ctx, ast_ref))
177 .unwrap_or_else(|| rule.check_with_ast(&lint_ctx, ast_ref))
178 } else {
179 rule.as_maybe_document_structure()
181 .and_then(|ext| ext.check_with_structure_opt(&lint_ctx, &structure))
182 .unwrap_or_else(|| rule.check(&lint_ctx))
183 }
184 } else {
185 rule.as_maybe_document_structure()
187 .and_then(|ext| ext.check_with_structure_opt(&lint_ctx, &structure))
188 .unwrap_or_else(|| rule.check(&lint_ctx))
189 };
190
191 match result {
192 Ok(rule_warnings) => {
193 let filtered_warnings: Vec<_> = rule_warnings
195 .into_iter()
196 .filter(|warning| {
197 let rule_name_to_check = warning.rule_name.unwrap_or(rule.name());
199
200 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
202 &rule_name_to_check[..dash_pos]
203 } else {
204 rule_name_to_check
205 };
206
207 !inline_config.is_rule_disabled(
208 base_rule_name,
209 warning.line, )
211 })
212 .collect();
213 warnings.extend(filtered_warnings);
214 }
215 Err(e) => {
216 log::error!("Error checking rule {}: {}", rule.name(), e);
217 return Err(e);
218 }
219 }
220
221 #[cfg(not(test))]
222 if _verbose {
223 let rule_duration = _rule_start.elapsed();
224 if rule_duration.as_millis() > 500 {
225 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
226 }
227 }
228 }
229
230 #[cfg(not(test))]
231 if _verbose {
232 let skipped_rules = _total_rules - _applicable_count;
233 if skipped_rules > 0 {
234 log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
235 }
236 if ast.is_some() {
237 log::debug!("Used shared AST for {ast_rules_count} rules");
238 }
239 }
240
241 Ok(warnings)
242}
243
244pub fn get_profiling_report() -> String {
246 profiling::get_report()
247}
248
249pub fn reset_profiling() {
251 profiling::reset()
252}
253
254pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
256 crate::utils::regex_cache::get_cache_stats()
257}
258
259pub fn get_ast_cache_stats() -> std::collections::HashMap<u64, u64> {
261 crate::utils::ast_utils::get_ast_cache_stats()
262}
263
264pub fn clear_all_caches() {
266 crate::utils::ast_utils::clear_ast_cache();
267 }
269
270pub fn get_cache_performance_report() -> String {
272 let regex_stats = get_regex_cache_stats();
273 let ast_stats = get_ast_cache_stats();
274
275 let mut report = String::new();
276
277 report.push_str("=== Cache Performance Report ===\n\n");
278
279 report.push_str("Regex Cache:\n");
281 if regex_stats.is_empty() {
282 report.push_str(" No regex patterns cached\n");
283 } else {
284 let total_usage: u64 = regex_stats.values().sum();
285 report.push_str(&format!(" Total patterns: {}\n", regex_stats.len()));
286 report.push_str(&format!(" Total usage: {total_usage}\n"));
287
288 let mut sorted_patterns: Vec<_> = regex_stats.iter().collect();
290 sorted_patterns.sort_by(|a, b| b.1.cmp(a.1));
291
292 report.push_str(" Top patterns by usage:\n");
293 for (pattern, count) in sorted_patterns.iter().take(5) {
294 let truncated_pattern = if pattern.len() > 50 {
295 format!("{}...", &pattern[..47])
296 } else {
297 pattern.to_string()
298 };
299 report.push_str(&format!(
300 " {} ({}x): {}\n",
301 count,
302 pattern.len().min(50),
303 truncated_pattern
304 ));
305 }
306 }
307
308 report.push('\n');
309
310 report.push_str("AST Cache:\n");
312 if ast_stats.is_empty() {
313 report.push_str(" No AST nodes cached\n");
314 } else {
315 let total_usage: u64 = ast_stats.values().sum();
316 report.push_str(&format!(" Total ASTs: {}\n", ast_stats.len()));
317 report.push_str(&format!(" Total usage: {total_usage}\n"));
318
319 if total_usage > ast_stats.len() as u64 {
320 let cache_hit_rate = ((total_usage - ast_stats.len() as u64) as f64 / total_usage as f64) * 100.0;
321 report.push_str(&format!(" Cache hit rate: {cache_hit_rate:.1}%\n"));
322 }
323 }
324
325 report
326}
327
328#[cfg(test)]
329mod tests {
330 use super::*;
331 use crate::rule::Rule;
332 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces, MD012NoMultipleBlanks};
333
334 #[test]
335 fn test_content_characteristics_analyze() {
336 let chars = ContentCharacteristics::analyze("");
338 assert!(!chars.has_headings);
339 assert!(!chars.has_lists);
340 assert!(!chars.has_links);
341 assert!(!chars.has_code);
342 assert!(!chars.has_emphasis);
343 assert!(!chars.has_html);
344 assert!(!chars.has_tables);
345 assert!(!chars.has_blockquotes);
346 assert!(!chars.has_images);
347
348 let chars = ContentCharacteristics::analyze("# Heading");
350 assert!(chars.has_headings);
351
352 let chars = ContentCharacteristics::analyze("Heading\n=======");
354 assert!(chars.has_headings);
355
356 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
358 assert!(chars.has_lists);
359
360 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
362 assert!(chars.has_lists);
363
364 let chars = ContentCharacteristics::analyze("[link](url)");
366 assert!(chars.has_links);
367
368 let chars = ContentCharacteristics::analyze("Visit https://example.com");
370 assert!(chars.has_links);
371
372 let chars = ContentCharacteristics::analyze("");
374 assert!(chars.has_images);
375
376 let chars = ContentCharacteristics::analyze("`inline code`");
378 assert!(chars.has_code);
379
380 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
381 assert!(chars.has_code);
382
383 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
385 assert!(chars.has_emphasis);
386
387 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
389 assert!(chars.has_html);
390
391 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
393 assert!(chars.has_tables);
394
395 let chars = ContentCharacteristics::analyze("> Quote");
397 assert!(chars.has_blockquotes);
398
399 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
401 let chars = ContentCharacteristics::analyze(content);
402 assert!(chars.has_headings);
403 assert!(chars.has_lists);
404 assert!(chars.has_links);
405 assert!(chars.has_code);
406 assert!(chars.has_emphasis);
407 assert!(chars.has_html);
408 assert!(chars.has_tables);
409 assert!(chars.has_blockquotes);
410 assert!(chars.has_images);
411 }
412
413 #[test]
414 fn test_content_characteristics_should_skip_rule() {
415 let chars = ContentCharacteristics {
416 has_headings: true,
417 has_lists: false,
418 has_links: true,
419 has_code: false,
420 has_emphasis: true,
421 has_html: false,
422 has_tables: true,
423 has_blockquotes: false,
424 has_images: false,
425 };
426
427 let heading_rule = MD001HeadingIncrement;
429 assert!(!chars.should_skip_rule(&heading_rule));
430
431 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
432 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
436 has_headings: false,
437 ..Default::default()
438 };
439 assert!(chars_no_headings.should_skip_rule(&heading_rule));
440 }
441
442 #[test]
443 fn test_lint_empty_content() {
444 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
445
446 let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard);
447 assert!(result.is_ok());
448 assert!(result.unwrap().is_empty());
449 }
450
451 #[test]
452 fn test_lint_with_violations() {
453 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
455
456 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
457 assert!(result.is_ok());
458 let warnings = result.unwrap();
459 assert!(!warnings.is_empty());
460 assert_eq!(warnings[0].rule_name, Some("MD001"));
462 }
463
464 #[test]
465 fn test_lint_with_inline_disable() {
466 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
467 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
468
469 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
470 assert!(result.is_ok());
471 let warnings = result.unwrap();
472 assert!(warnings.is_empty()); }
474
475 #[test]
476 fn test_lint_rule_filtering() {
477 let content = "# Heading\nJust text";
479 let rules: Vec<Box<dyn Rule>> = vec![
480 Box::new(MD001HeadingIncrement),
481 ];
483
484 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
485 assert!(result.is_ok());
486 }
487
488 #[test]
489 fn test_get_profiling_report() {
490 let report = get_profiling_report();
492 assert!(!report.is_empty());
493 assert!(report.contains("Profiling"));
494 }
495
496 #[test]
497 fn test_reset_profiling() {
498 reset_profiling();
500
501 let report = get_profiling_report();
503 assert!(report.contains("disabled") || report.contains("no measurements"));
504 }
505
506 #[test]
507 fn test_get_regex_cache_stats() {
508 let stats = get_regex_cache_stats();
509 assert!(stats.is_empty() || !stats.is_empty());
511
512 for count in stats.values() {
514 assert!(*count > 0);
515 }
516 }
517
518 #[test]
519 fn test_get_ast_cache_stats() {
520 let stats = get_ast_cache_stats();
521 assert!(stats.is_empty() || !stats.is_empty());
523
524 for count in stats.values() {
526 assert!(*count > 0);
527 }
528 }
529
530 #[test]
531 fn test_clear_all_caches() {
532 clear_all_caches();
534
535 let ast_stats = get_ast_cache_stats();
537 assert!(ast_stats.is_empty());
538 }
539
540 #[test]
541 fn test_get_cache_performance_report() {
542 let report = get_cache_performance_report();
543
544 assert!(report.contains("Cache Performance Report"));
546 assert!(report.contains("Regex Cache:"));
547 assert!(report.contains("AST Cache:"));
548
549 clear_all_caches();
551 let report_empty = get_cache_performance_report();
552 assert!(report_empty.contains("No AST nodes cached"));
553 }
554
555 #[test]
556 fn test_lint_with_ast_rules() {
557 let content = "# Heading\n\nParagraph with **bold** text.";
559 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD012NoMultipleBlanks::new(1))];
560
561 let result = lint(content, &rules, false, crate::config::MarkdownFlavor::Standard);
562 assert!(result.is_ok());
563 }
564
565 #[test]
566 fn test_content_characteristics_edge_cases() {
567 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
570
571 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
573
574 let chars = ContentCharacteristics::analyze("*emphasis*"); assert!(!chars.has_lists);
577
578 let chars = ContentCharacteristics::analyze("1.Item"); assert!(!chars.has_lists);
580
581 let chars = ContentCharacteristics::analyze("text > not a quote");
583 assert!(!chars.has_blockquotes);
584 }
585
586 #[test]
587 fn test_cache_performance_report_formatting() {
588 let report = get_cache_performance_report();
592
593 assert!(!report.is_empty());
597 assert!(report.lines().count() > 3); }
599}