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