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(content: &str, rules: &[Box<dyn Rule>], _verbose: bool) -> LintResult {
125 let mut warnings = Vec::new();
126 let _overall_start = Instant::now();
127
128 if content.is_empty() {
130 return Ok(warnings);
131 }
132
133 let inline_config = crate::inline_config::InlineConfig::from_content(content);
135
136 let characteristics = ContentCharacteristics::analyze(content);
138
139 let applicable_rules: Vec<_> = rules
141 .iter()
142 .filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
143 .collect();
144
145 let _total_rules = rules.len();
147 let _applicable_count = applicable_rules.len();
148
149 let structure = DocumentStructure::new(content);
151
152 let ast_rules_count = applicable_rules.iter().filter(|rule| rule.uses_ast()).count();
154 let ast = if ast_rules_count > 0 {
155 Some(crate::utils::ast_utils::get_cached_ast(content))
156 } else {
157 None
158 };
159
160 let lint_ctx = crate::lint_context::LintContext::new(content);
162
163 for rule in applicable_rules {
164 let _rule_start = Instant::now();
165
166 let result = if rule.uses_ast() {
168 if let Some(ref ast_ref) = ast {
169 rule.as_maybe_ast()
171 .and_then(|ext| ext.check_with_ast_opt(&lint_ctx, ast_ref))
172 .unwrap_or_else(|| rule.check_with_ast(&lint_ctx, ast_ref))
173 } else {
174 rule.as_maybe_document_structure()
176 .and_then(|ext| ext.check_with_structure_opt(&lint_ctx, &structure))
177 .unwrap_or_else(|| rule.check(&lint_ctx))
178 }
179 } else {
180 rule.as_maybe_document_structure()
182 .and_then(|ext| ext.check_with_structure_opt(&lint_ctx, &structure))
183 .unwrap_or_else(|| rule.check(&lint_ctx))
184 };
185
186 match result {
187 Ok(rule_warnings) => {
188 let filtered_warnings: Vec<_> = rule_warnings
190 .into_iter()
191 .filter(|warning| {
192 let rule_name_to_check = warning.rule_name.unwrap_or(rule.name());
194
195 let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
197 &rule_name_to_check[..dash_pos]
198 } else {
199 rule_name_to_check
200 };
201
202 !inline_config.is_rule_disabled(
203 base_rule_name,
204 warning.line, )
206 })
207 .collect();
208 warnings.extend(filtered_warnings);
209 }
210 Err(e) => {
211 log::error!("Error checking rule {}: {}", rule.name(), e);
212 return Err(e);
213 }
214 }
215
216 #[cfg(not(test))]
217 if _verbose {
218 let rule_duration = _rule_start.elapsed();
219 if rule_duration.as_millis() > 500 {
220 log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
221 }
222 }
223 }
224
225 #[cfg(not(test))]
226 if _verbose {
227 let skipped_rules = _total_rules - _applicable_count;
228 if skipped_rules > 0 {
229 log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
230 }
231 if ast.is_some() {
232 log::debug!("Used shared AST for {ast_rules_count} rules");
233 }
234 }
235
236 Ok(warnings)
237}
238
239pub fn get_profiling_report() -> String {
241 profiling::get_report()
242}
243
244pub fn reset_profiling() {
246 profiling::reset()
247}
248
249pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
251 crate::utils::regex_cache::get_cache_stats()
252}
253
254pub fn get_ast_cache_stats() -> std::collections::HashMap<u64, u64> {
256 crate::utils::ast_utils::get_ast_cache_stats()
257}
258
259pub fn clear_all_caches() {
261 crate::utils::ast_utils::clear_ast_cache();
262 }
264
265pub fn get_cache_performance_report() -> String {
267 let regex_stats = get_regex_cache_stats();
268 let ast_stats = get_ast_cache_stats();
269
270 let mut report = String::new();
271
272 report.push_str("=== Cache Performance Report ===\n\n");
273
274 report.push_str("Regex Cache:\n");
276 if regex_stats.is_empty() {
277 report.push_str(" No regex patterns cached\n");
278 } else {
279 let total_usage: u64 = regex_stats.values().sum();
280 report.push_str(&format!(" Total patterns: {}\n", regex_stats.len()));
281 report.push_str(&format!(" Total usage: {total_usage}\n"));
282
283 let mut sorted_patterns: Vec<_> = regex_stats.iter().collect();
285 sorted_patterns.sort_by(|a, b| b.1.cmp(a.1));
286
287 report.push_str(" Top patterns by usage:\n");
288 for (pattern, count) in sorted_patterns.iter().take(5) {
289 let truncated_pattern = if pattern.len() > 50 {
290 format!("{}...", &pattern[..47])
291 } else {
292 pattern.to_string()
293 };
294 report.push_str(&format!(
295 " {} ({}x): {}\n",
296 count,
297 pattern.len().min(50),
298 truncated_pattern
299 ));
300 }
301 }
302
303 report.push('\n');
304
305 report.push_str("AST Cache:\n");
307 if ast_stats.is_empty() {
308 report.push_str(" No AST nodes cached\n");
309 } else {
310 let total_usage: u64 = ast_stats.values().sum();
311 report.push_str(&format!(" Total ASTs: {}\n", ast_stats.len()));
312 report.push_str(&format!(" Total usage: {total_usage}\n"));
313
314 if total_usage > ast_stats.len() as u64 {
315 let cache_hit_rate = ((total_usage - ast_stats.len() as u64) as f64 / total_usage as f64) * 100.0;
316 report.push_str(&format!(" Cache hit rate: {cache_hit_rate:.1}%\n"));
317 }
318 }
319
320 report
321}
322
323#[cfg(test)]
324mod tests {
325 use super::*;
326 use crate::rule::Rule;
327 use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces, MD012NoMultipleBlanks};
328
329 #[test]
330 fn test_content_characteristics_analyze() {
331 let chars = ContentCharacteristics::analyze("");
333 assert!(!chars.has_headings);
334 assert!(!chars.has_lists);
335 assert!(!chars.has_links);
336 assert!(!chars.has_code);
337 assert!(!chars.has_emphasis);
338 assert!(!chars.has_html);
339 assert!(!chars.has_tables);
340 assert!(!chars.has_blockquotes);
341 assert!(!chars.has_images);
342
343 let chars = ContentCharacteristics::analyze("# Heading");
345 assert!(chars.has_headings);
346
347 let chars = ContentCharacteristics::analyze("Heading\n=======");
349 assert!(chars.has_headings);
350
351 let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
353 assert!(chars.has_lists);
354
355 let chars = ContentCharacteristics::analyze("1. First\n2. Second");
357 assert!(chars.has_lists);
358
359 let chars = ContentCharacteristics::analyze("[link](url)");
361 assert!(chars.has_links);
362
363 let chars = ContentCharacteristics::analyze("Visit https://example.com");
365 assert!(chars.has_links);
366
367 let chars = ContentCharacteristics::analyze("");
369 assert!(chars.has_images);
370
371 let chars = ContentCharacteristics::analyze("`inline code`");
373 assert!(chars.has_code);
374
375 let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
376 assert!(chars.has_code);
377
378 let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
380 assert!(chars.has_emphasis);
381
382 let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
384 assert!(chars.has_html);
385
386 let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
388 assert!(chars.has_tables);
389
390 let chars = ContentCharacteristics::analyze("> Quote");
392 assert!(chars.has_blockquotes);
393
394 let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
396 let chars = ContentCharacteristics::analyze(content);
397 assert!(chars.has_headings);
398 assert!(chars.has_lists);
399 assert!(chars.has_links);
400 assert!(chars.has_code);
401 assert!(chars.has_emphasis);
402 assert!(chars.has_html);
403 assert!(chars.has_tables);
404 assert!(chars.has_blockquotes);
405 assert!(chars.has_images);
406 }
407
408 #[test]
409 fn test_content_characteristics_should_skip_rule() {
410 let chars = ContentCharacteristics {
411 has_headings: true,
412 has_lists: false,
413 has_links: true,
414 has_code: false,
415 has_emphasis: true,
416 has_html: false,
417 has_tables: true,
418 has_blockquotes: false,
419 has_images: false,
420 };
421
422 let heading_rule = MD001HeadingIncrement;
424 assert!(!chars.should_skip_rule(&heading_rule));
425
426 let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
427 assert!(!chars.should_skip_rule(&trailing_spaces_rule)); let chars_no_headings = ContentCharacteristics {
431 has_headings: false,
432 ..Default::default()
433 };
434 assert!(chars_no_headings.should_skip_rule(&heading_rule));
435 }
436
437 #[test]
438 fn test_lint_empty_content() {
439 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
440
441 let result = lint("", &rules, false);
442 assert!(result.is_ok());
443 assert!(result.unwrap().is_empty());
444 }
445
446 #[test]
447 fn test_lint_with_violations() {
448 let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
450
451 let result = lint(content, &rules, false);
452 assert!(result.is_ok());
453 let warnings = result.unwrap();
454 assert!(!warnings.is_empty());
455 assert_eq!(warnings[0].rule_name, Some("MD001"));
457 }
458
459 #[test]
460 fn test_lint_with_inline_disable() {
461 let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
462 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement)];
463
464 let result = lint(content, &rules, false);
465 assert!(result.is_ok());
466 let warnings = result.unwrap();
467 assert!(warnings.is_empty()); }
469
470 #[test]
471 fn test_lint_rule_filtering() {
472 let content = "# Heading\nJust text";
474 let rules: Vec<Box<dyn Rule>> = vec![
475 Box::new(MD001HeadingIncrement),
476 ];
478
479 let result = lint(content, &rules, false);
480 assert!(result.is_ok());
481 }
482
483 #[test]
484 fn test_get_profiling_report() {
485 let report = get_profiling_report();
487 assert!(!report.is_empty());
488 assert!(report.contains("Profiling"));
489 }
490
491 #[test]
492 fn test_reset_profiling() {
493 reset_profiling();
495
496 let report = get_profiling_report();
498 assert!(report.contains("disabled") || report.contains("no measurements"));
499 }
500
501 #[test]
502 fn test_get_regex_cache_stats() {
503 let stats = get_regex_cache_stats();
504 assert!(stats.is_empty() || !stats.is_empty());
506
507 for count in stats.values() {
509 assert!(*count > 0);
510 }
511 }
512
513 #[test]
514 fn test_get_ast_cache_stats() {
515 let stats = get_ast_cache_stats();
516 assert!(stats.is_empty() || !stats.is_empty());
518
519 for count in stats.values() {
521 assert!(*count > 0);
522 }
523 }
524
525 #[test]
526 fn test_clear_all_caches() {
527 clear_all_caches();
529
530 let ast_stats = get_ast_cache_stats();
532 assert!(ast_stats.is_empty());
533 }
534
535 #[test]
536 fn test_get_cache_performance_report() {
537 let report = get_cache_performance_report();
538
539 assert!(report.contains("Cache Performance Report"));
541 assert!(report.contains("Regex Cache:"));
542 assert!(report.contains("AST Cache:"));
543
544 clear_all_caches();
546 let report_empty = get_cache_performance_report();
547 assert!(report_empty.contains("No AST nodes cached"));
548 }
549
550 #[test]
551 fn test_lint_with_ast_rules() {
552 let content = "# Heading\n\nParagraph with **bold** text.";
554 let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD012NoMultipleBlanks::new(1))];
555
556 let result = lint(content, &rules, false);
557 assert!(result.is_ok());
558 }
559
560 #[test]
561 fn test_content_characteristics_edge_cases() {
562 let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
565
566 let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
568
569 let chars = ContentCharacteristics::analyze("*emphasis*"); assert!(!chars.has_lists);
572
573 let chars = ContentCharacteristics::analyze("1.Item"); assert!(!chars.has_lists);
575
576 let chars = ContentCharacteristics::analyze("text > not a quote");
578 assert!(!chars.has_blockquotes);
579 }
580
581 #[test]
582 fn test_cache_performance_report_formatting() {
583 let report = get_cache_performance_report();
587
588 assert!(!report.is_empty());
592 assert!(report.lines().count() > 3); }
594}