rumdl/utils/
regex_cache.rs

1//!
2//! Cached Regex Patterns and Fast Content Checks for Markdown Linting
3//!
4//! This module provides a centralized collection of pre-compiled, cached regex patterns
5//! for all major Markdown constructs (headings, lists, code blocks, links, images, etc.).
6//! It also includes fast-path utility functions for quickly checking if content
7//! potentially contains certain Markdown elements, allowing rules to skip expensive
8//! processing when unnecessary.
9//!
10//! # Performance
11//!
12//! All regexes are compiled once at startup using `lazy_static`, avoiding repeated
13//! compilation and improving performance across the linter. Use these shared patterns
14//! in rules instead of compiling new regexes.
15//!
16//! # Usage
17//!
18//! - Use the provided statics for common Markdown patterns.
19//! - Use the `regex_lazy!` macro for ad-hoc regexes that are not predefined.
20//! - Use the utility functions for fast content checks before running regexes.
21
22use fancy_regex::Regex as FancyRegex;
23use lazy_static::lazy_static;
24use regex::Regex;
25use std::collections::HashMap;
26use std::sync::{Arc, Mutex};
27
28/// Global regex cache for dynamic patterns
29#[derive(Debug)]
30pub struct RegexCache {
31    cache: HashMap<String, Arc<Regex>>,
32    fancy_cache: HashMap<String, Arc<FancyRegex>>,
33    usage_stats: HashMap<String, u64>,
34}
35
36impl Default for RegexCache {
37    fn default() -> Self {
38        Self::new()
39    }
40}
41
42impl RegexCache {
43    pub fn new() -> Self {
44        Self {
45            cache: HashMap::new(),
46            fancy_cache: HashMap::new(),
47            usage_stats: HashMap::new(),
48        }
49    }
50
51    /// Get or compile a regex pattern
52    pub fn get_regex(&mut self, pattern: &str) -> Result<Arc<Regex>, regex::Error> {
53        if let Some(regex) = self.cache.get(pattern) {
54            *self.usage_stats.entry(pattern.to_string()).or_insert(0) += 1;
55            return Ok(regex.clone());
56        }
57
58        let regex = Arc::new(Regex::new(pattern)?);
59        self.cache.insert(pattern.to_string(), regex.clone());
60        *self.usage_stats.entry(pattern.to_string()).or_insert(0) += 1;
61        Ok(regex)
62    }
63
64    /// Get or compile a fancy regex pattern
65    pub fn get_fancy_regex(&mut self, pattern: &str) -> Result<Arc<FancyRegex>, Box<fancy_regex::Error>> {
66        if let Some(regex) = self.fancy_cache.get(pattern) {
67            *self.usage_stats.entry(pattern.to_string()).or_insert(0) += 1;
68            return Ok(regex.clone());
69        }
70
71        match FancyRegex::new(pattern) {
72            Ok(regex) => {
73                let arc_regex = Arc::new(regex);
74                self.fancy_cache.insert(pattern.to_string(), arc_regex.clone());
75                *self.usage_stats.entry(pattern.to_string()).or_insert(0) += 1;
76                Ok(arc_regex)
77            }
78            Err(e) => Err(Box::new(e)),
79        }
80    }
81
82    /// Get cache statistics
83    pub fn get_stats(&self) -> HashMap<String, u64> {
84        self.usage_stats.clone()
85    }
86
87    /// Clear cache (useful for testing)
88    pub fn clear(&mut self) {
89        self.cache.clear();
90        self.fancy_cache.clear();
91        self.usage_stats.clear();
92    }
93}
94
95lazy_static! {
96    /// Global regex cache instance
97    static ref GLOBAL_REGEX_CACHE: Arc<Mutex<RegexCache>> = Arc::new(Mutex::new(RegexCache::new()));
98}
99
100/// Get a regex from the global cache
101pub fn get_cached_regex(pattern: &str) -> Result<Arc<Regex>, regex::Error> {
102    let mut cache = GLOBAL_REGEX_CACHE.lock().unwrap();
103    cache.get_regex(pattern)
104}
105
106/// Get a fancy regex from the global cache
107pub fn get_cached_fancy_regex(pattern: &str) -> Result<Arc<FancyRegex>, Box<fancy_regex::Error>> {
108    let mut cache = GLOBAL_REGEX_CACHE.lock().unwrap();
109    cache.get_fancy_regex(pattern)
110}
111
112/// Get cache usage statistics
113pub fn get_cache_stats() -> HashMap<String, u64> {
114    let cache = GLOBAL_REGEX_CACHE.lock().unwrap();
115    cache.get_stats()
116}
117
118/// Macro for defining a lazily-initialized, cached regex pattern.
119/// Use this for ad-hoc regexes that are not already defined in this module.
120/// Example:
121/// ```
122/// use rumdl::regex_lazy;
123/// let my_re = regex_lazy!(r"^foo.*bar$");
124/// assert!(my_re.is_match("foobar"));
125/// ```
126#[macro_export]
127macro_rules! regex_lazy {
128    ($pattern:expr) => {{
129        lazy_static::lazy_static! {
130            static ref REGEX: regex::Regex = regex::Regex::new($pattern).unwrap();
131        }
132        &*REGEX
133    }};
134}
135
136/// Macro for getting regex from global cache
137#[macro_export]
138macro_rules! regex_cached {
139    ($pattern:expr) => {{ $crate::utils::regex_cache::get_cached_regex($pattern).expect("Failed to compile regex") }};
140}
141
142/// Macro for getting fancy regex from global cache
143#[macro_export]
144macro_rules! fancy_regex_cached {
145    ($pattern:expr) => {{ $crate::utils::regex_cache::get_cached_fancy_regex($pattern).expect("Failed to compile fancy regex") }};
146}
147
148// Also make the macro available directly from this module
149pub use crate::regex_lazy;
150
151lazy_static! {
152    // URL patterns
153    pub static ref URL_REGEX: Regex = Regex::new(r#"(?:https?|ftp)://[^\s<>\[\]()'"]+[^\s<>\[\]()"'.,]"#).unwrap();
154    pub static ref BARE_URL_REGEX: Regex = Regex::new(r"(?:https?|ftp)://[^\s<>]+[^\s<>.]").unwrap();
155    pub static ref URL_PATTERN: Regex = Regex::new(r"((?:https?|ftp)://[^\s\)<>]+[^\s\)<>.,])").unwrap();
156
157    // Heading patterns
158    pub static ref ATX_HEADING_REGEX: Regex = Regex::new(r"^(\s*)(#{1,6})(\s+|$)").unwrap();
159    pub static ref CLOSED_ATX_HEADING_REGEX: Regex = Regex::new(r"^(\s*)(#{1,6})(\s+)(.*)(\s+)(#+)(\s*)$").unwrap();
160    pub static ref SETEXT_HEADING_REGEX: Regex = Regex::new(r"^(\s*)[^\s]+.*\n(\s*)(=+|-+)\s*$").unwrap();
161    pub static ref TRAILING_PUNCTUATION_REGEX: Regex = Regex::new(r"[.,:;!?]$").unwrap();
162
163    // ATX heading patterns for MD051 and other rules
164    pub static ref ATX_HEADING_WITH_CAPTURE: Regex = Regex::new(r"^(#{1,6})\s+(.+?)(?:\s+#*\s*)?$").unwrap();
165    pub static ref SETEXT_HEADING_WITH_CAPTURE: FancyRegex = FancyRegex::new(r"^([^\n]+)\n([=\-])\2+\s*$").unwrap();
166
167    // List patterns
168    pub static ref UNORDERED_LIST_MARKER_REGEX: Regex = Regex::new(r"^(\s*)([*+-])(\s+)").unwrap();
169    pub static ref ORDERED_LIST_MARKER_REGEX: Regex = Regex::new(r"^(\s*)(\d+)([.)])(\s+)").unwrap();
170    pub static ref LIST_MARKER_ANY_REGEX: Regex = Regex::new(r"^(\s*)(?:([*+-])|(\d+)[.)])(\s+)").unwrap();
171
172    // Code block patterns
173    pub static ref FENCED_CODE_BLOCK_START_REGEX: Regex = Regex::new(r"^(\s*)(```|~~~)(.*)$").unwrap();
174    pub static ref FENCED_CODE_BLOCK_END_REGEX: Regex = Regex::new(r"^(\s*)(```|~~~)(\s*)$").unwrap();
175    pub static ref INDENTED_CODE_BLOCK_REGEX: Regex = Regex::new(r"^(\s{4,})(.*)$").unwrap();
176    pub static ref CODE_FENCE_REGEX: Regex = Regex::new(r"^(`{3,}|~{3,})").unwrap();
177
178    // Emphasis patterns
179    pub static ref EMPHASIS_REGEX: FancyRegex = FancyRegex::new(r"(\s|^)(\*{1,2}|_{1,2})(?=\S)(.+?)(?<=\S)(\2)(\s|$)").unwrap();
180    pub static ref SPACE_IN_EMPHASIS_REGEX: FancyRegex = FancyRegex::new(r"(\*|_)(\s+)(.+?)(\s+)(\1)").unwrap();
181
182    // MD037 specific emphasis patterns - improved to avoid false positives
183    // Only match emphasis with spaces that are actually complete emphasis blocks
184    // Use word boundaries and negative lookbehind/lookahead to avoid matching across emphasis boundaries
185    pub static ref ASTERISK_EMPHASIS: Regex = Regex::new(r"(?:^|[^*])\*(\s+[^*]+\s*|\s*[^*]+\s+)\*(?:[^*]|$)").unwrap();
186    pub static ref UNDERSCORE_EMPHASIS: Regex = Regex::new(r"(?:^|[^_])_(\s+[^_]+\s*|\s*[^_]+\s+)_(?:[^_]|$)").unwrap();
187    pub static ref DOUBLE_UNDERSCORE_EMPHASIS: Regex = Regex::new(r"(?:^|[^_])__(\s+[^_]+\s*|\s*[^_]+\s+)__(?:[^_]|$)").unwrap();
188    pub static ref DOUBLE_ASTERISK_EMPHASIS: FancyRegex = FancyRegex::new(r"\*\*\s+([^*]+?)\s+\*\*").unwrap();
189    pub static ref DOUBLE_ASTERISK_SPACE_START: FancyRegex = FancyRegex::new(r"\*\*\s+([^*]+?)\*\*").unwrap();
190    pub static ref DOUBLE_ASTERISK_SPACE_END: FancyRegex = FancyRegex::new(r"\*\*([^*]+?)\s+\*\*").unwrap();
191
192    // Code block patterns
193    pub static ref FENCED_CODE_BLOCK_START: Regex = Regex::new(r"^(\s*)```(?:[^`\r\n]*)$").unwrap();
194    pub static ref FENCED_CODE_BLOCK_END: Regex = Regex::new(r"^(\s*)```\s*$").unwrap();
195    pub static ref ALTERNATE_FENCED_CODE_BLOCK_START: Regex = Regex::new(r"^(\s*)~~~(?:[^~\r\n]*)$").unwrap();
196    pub static ref ALTERNATE_FENCED_CODE_BLOCK_END: Regex = Regex::new(r"^(\s*)~~~\s*$").unwrap();
197    pub static ref INDENTED_CODE_BLOCK_PATTERN: Regex = Regex::new(r"^(\s{4,})").unwrap();
198
199    // HTML patterns
200    pub static ref HTML_TAG_REGEX: Regex = Regex::new(r"<([a-zA-Z][^>]*)>").unwrap();
201    pub static ref HTML_SELF_CLOSING_TAG_REGEX: Regex = Regex::new(r"<([a-zA-Z][^>]*/)>").unwrap();
202    pub static ref HTML_TAG_FINDER: Regex = Regex::new("(?i)</?[a-zA-Z][^>]*>").unwrap();
203    pub static ref HTML_TAG_QUICK_CHECK: Regex = Regex::new("(?i)</?[a-zA-Z]").unwrap();
204
205    // Link patterns for MD051 and other rules
206    pub static ref LINK_REFERENCE_DEFINITION_REGEX: Regex = Regex::new(r"^\s*\[([^\]]+)\]:\s+(.+)$").unwrap();
207    pub static ref INLINE_LINK_REGEX: Regex = Regex::new(r"\[([^\]]+)\]\(([^)]+)\)").unwrap();
208    pub static ref LINK_TEXT_REGEX: Regex = Regex::new(r"\[([^\]]*)\]").unwrap();
209    pub static ref LINK_REGEX: FancyRegex = FancyRegex::new(r"(?<!\\)\[([^\]]*)\]\(([^)#]*)#([^)]+)\)").unwrap();
210    pub static ref EXTERNAL_URL_REGEX: FancyRegex = FancyRegex::new(r"^(https?://|ftp://|www\.|[^/]+\.[a-z]{2,})").unwrap();
211
212    // Image patterns
213    pub static ref IMAGE_REGEX: Regex = Regex::new(r"!\[([^\]]*)\]\(([^)]+)\)").unwrap();
214
215    // Whitespace patterns
216    pub static ref TRAILING_WHITESPACE_REGEX: Regex = Regex::new(r"\s+$").unwrap();
217    pub static ref MULTIPLE_BLANK_LINES_REGEX: Regex = Regex::new(r"\n{3,}").unwrap();
218
219    // Front matter patterns
220    pub static ref FRONT_MATTER_REGEX: Regex = Regex::new(r"^---\n.*?\n---\n").unwrap();
221
222    // MD051 specific patterns
223    pub static ref INLINE_CODE_REGEX: FancyRegex = FancyRegex::new(r"`[^`]+`").unwrap();
224    pub static ref BOLD_ASTERISK_REGEX: Regex = Regex::new(r"\*\*(.+?)\*\*").unwrap();
225    pub static ref BOLD_UNDERSCORE_REGEX: Regex = Regex::new(r"__(.+?)__").unwrap();
226    pub static ref ITALIC_ASTERISK_REGEX: Regex = Regex::new(r"\*([^*]+?)\*").unwrap();
227    pub static ref ITALIC_UNDERSCORE_REGEX: Regex = Regex::new(r"_([^_]+?)_").unwrap();
228    pub static ref LINK_TEXT_FULL_REGEX: FancyRegex = FancyRegex::new(r"\[([^\]]*)\]\([^)]*\)").unwrap();
229    pub static ref STRIKETHROUGH_REGEX: Regex = Regex::new(r"~~(.+?)~~").unwrap();
230    pub static ref MULTIPLE_HYPHENS: Regex = Regex::new(r"-{2,}").unwrap();
231    pub static ref TOC_SECTION_START: Regex = Regex::new(r"^#+\s*(?:Table of Contents|Contents|TOC)\s*$").unwrap();
232
233    // Blockquote patterns
234    pub static ref BLOCKQUOTE_PREFIX_RE: Regex = Regex::new(r"^(\s*>+\s*)").unwrap();
235
236    // MD013 specific patterns
237    pub static ref IMAGE_REF_PATTERN: Regex = Regex::new(r"^!\[.*?\]\[.*?\]$").unwrap();
238    pub static ref LINK_REF_PATTERN: Regex = Regex::new(r"^\[.*?\]:\s*https?://\S+$").unwrap();
239    pub static ref URL_IN_TEXT: Regex = Regex::new(r"https?://\S+").unwrap();
240    pub static ref SENTENCE_END: Regex = Regex::new(r"[.!?]\s+[A-Z]").unwrap();
241    pub static ref ABBREVIATION: Regex = Regex::new(r"\b(?:Mr|Mrs|Ms|Dr|Prof|Sr|Jr|vs|etc|i\.e|e\.g|Inc|Corp|Ltd|Co|St|Ave|Blvd|Rd|Ph\.D|M\.D|B\.A|M\.A|Ph\.D|U\.S|U\.K|U\.N|N\.Y|L\.A|D\.C)\.\s+[A-Z]").unwrap();
242    pub static ref DECIMAL_NUMBER: Regex = Regex::new(r"\d+\.\s*\d+").unwrap();
243    pub static ref LIST_ITEM: Regex = Regex::new(r"^\s*\d+\.\s+").unwrap();
244    pub static ref REFERENCE_LINK: Regex = Regex::new(r"\[([^\]]*)\]\[([^\]]*)\]").unwrap();
245
246    // Email pattern
247    pub static ref EMAIL_PATTERN: Regex = Regex::new(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}").unwrap();
248}
249
250// Second lazy_static block for additional patterns
251lazy_static! {
252    // HTML comment patterns
253    pub static ref HTML_COMMENT_START: Regex = Regex::new(r"<!--").unwrap();
254    pub static ref HTML_COMMENT_END: Regex = Regex::new(r"-->").unwrap();
255    pub static ref HTML_COMMENT_PATTERN: Regex = Regex::new(r"<!--[\s\S]*?-->").unwrap();
256
257    // HTML heading pattern (matches <h1> through <h6> tags)
258    pub static ref HTML_HEADING_PATTERN: FancyRegex = FancyRegex::new(r"^\s*<h([1-6])(?:\s[^>]*)?>.*</h\1>\s*$").unwrap();
259
260    // Heading quick check pattern
261    pub static ref HEADING_CHECK: Regex = Regex::new(r"(?m)^(?:\s*)#").unwrap();
262
263    // Horizontal rule patterns
264    pub static ref HR_DASH: Regex = Regex::new(r"^\-{3,}\s*$").unwrap();
265    pub static ref HR_ASTERISK: Regex = Regex::new(r"^\*{3,}\s*$").unwrap();
266    pub static ref HR_UNDERSCORE: Regex = Regex::new(r"^_{3,}\s*$").unwrap();
267    pub static ref HR_SPACED_DASH: Regex = Regex::new(r"^(\-\s+){2,}\-\s*$").unwrap();
268    pub static ref HR_SPACED_ASTERISK: Regex = Regex::new(r"^(\*\s+){2,}\*\s*$").unwrap();
269    pub static ref HR_SPACED_UNDERSCORE: Regex = Regex::new(r"^(_\s+){2,}_\s*$").unwrap();
270}
271
272/// Utility functions for quick content checks
273/// Check if content contains any headings (quick check before regex)
274pub fn has_heading_markers(content: &str) -> bool {
275    content.contains('#')
276}
277
278/// Check if content contains any lists (quick check before regex)
279pub fn has_list_markers(content: &str) -> bool {
280    content.contains('*')
281        || content.contains('-')
282        || content.contains('+')
283        || (content.contains('.') && content.contains(|c: char| c.is_ascii_digit()))
284}
285
286/// Check if content contains any code blocks (quick check before regex)
287pub fn has_code_block_markers(content: &str) -> bool {
288    content.contains("```") || content.contains("~~~") || content.contains("\n    ")
289    // Indented code block potential
290}
291
292/// Check if content contains any emphasis markers (quick check before regex)
293pub fn has_emphasis_markers(content: &str) -> bool {
294    content.contains('*') || content.contains('_')
295}
296
297/// Check if content contains any HTML tags (quick check before regex)
298pub fn has_html_tags(content: &str) -> bool {
299    content.contains('<') && (content.contains('>') || content.contains("/>"))
300}
301
302/// Check if content contains any links (quick check before regex)
303pub fn has_link_markers(content: &str) -> bool {
304    (content.contains('[') && content.contains(']'))
305        || content.contains("http://")
306        || content.contains("https://")
307        || content.contains("ftp://")
308}
309
310/// Check if content contains any images (quick check before regex)
311pub fn has_image_markers(content: &str) -> bool {
312    content.contains("![")
313}
314
315/// Optimize URL detection by implementing a character-by-character scanner
316/// that's much faster than regex for cases where we know there's no URL
317pub fn contains_url(content: &str) -> bool {
318    // Fast check - if these substrings aren't present, there's no URL
319    if !content.contains("://") {
320        return false;
321    }
322
323    let chars: Vec<char> = content.chars().collect();
324    let mut i = 0;
325
326    while i < chars.len() {
327        // Look for the start of a URL protocol
328        if i + 2 < chars.len()
329            && ((chars[i] == 'h' && chars[i + 1] == 't' && chars[i + 2] == 't')
330                || (chars[i] == 'f' && chars[i + 1] == 't' && chars[i + 2] == 'p'))
331        {
332            // Scan forward to find "://"
333            let mut j = i;
334            while j + 2 < chars.len() {
335                if chars[j] == ':' && chars[j + 1] == '/' && chars[j + 2] == '/' {
336                    return true;
337                }
338                j += 1;
339
340                // Don't scan too far ahead for the protocol
341                if j > i + 10 {
342                    break;
343                }
344            }
345        }
346        i += 1;
347    }
348
349    false
350}
351
352/// Escapes a string to be used in a regex pattern
353pub fn escape_regex(s: &str) -> String {
354    let special_chars = ['.', '+', '*', '?', '^', '$', '(', ')', '[', ']', '{', '}', '|', '\\'];
355    let mut result = String::with_capacity(s.len() * 2);
356
357    for c in s.chars() {
358        if special_chars.contains(&c) {
359            result.push('\\');
360        }
361        result.push(c);
362    }
363
364    result
365}
366
367#[cfg(test)]
368mod tests {
369    use super::*;
370
371    #[test]
372    fn test_regex_cache_new() {
373        let cache = RegexCache::new();
374        assert!(cache.cache.is_empty());
375        assert!(cache.fancy_cache.is_empty());
376        assert!(cache.usage_stats.is_empty());
377    }
378
379    #[test]
380    fn test_regex_cache_default() {
381        let cache = RegexCache::default();
382        assert!(cache.cache.is_empty());
383        assert!(cache.fancy_cache.is_empty());
384        assert!(cache.usage_stats.is_empty());
385    }
386
387    #[test]
388    fn test_get_regex_compilation() {
389        let mut cache = RegexCache::new();
390
391        // First call compiles and caches
392        let regex1 = cache.get_regex(r"\d+").unwrap();
393        assert_eq!(cache.cache.len(), 1);
394        assert_eq!(cache.usage_stats.get(r"\d+"), Some(&1));
395
396        // Second call returns cached version
397        let regex2 = cache.get_regex(r"\d+").unwrap();
398        assert_eq!(cache.cache.len(), 1);
399        assert_eq!(cache.usage_stats.get(r"\d+"), Some(&2));
400
401        // Both should be the same Arc
402        assert!(Arc::ptr_eq(&regex1, &regex2));
403    }
404
405    #[test]
406    fn test_get_regex_invalid_pattern() {
407        let mut cache = RegexCache::new();
408        let result = cache.get_regex(r"[unterminated");
409        assert!(result.is_err());
410        assert!(cache.cache.is_empty());
411    }
412
413    #[test]
414    fn test_get_fancy_regex_compilation() {
415        let mut cache = RegexCache::new();
416
417        // First call compiles and caches
418        let regex1 = cache.get_fancy_regex(r"(?<=foo)bar").unwrap();
419        assert_eq!(cache.fancy_cache.len(), 1);
420        assert_eq!(cache.usage_stats.get(r"(?<=foo)bar"), Some(&1));
421
422        // Second call returns cached version
423        let regex2 = cache.get_fancy_regex(r"(?<=foo)bar").unwrap();
424        assert_eq!(cache.fancy_cache.len(), 1);
425        assert_eq!(cache.usage_stats.get(r"(?<=foo)bar"), Some(&2));
426
427        // Both should be the same Arc
428        assert!(Arc::ptr_eq(&regex1, &regex2));
429    }
430
431    #[test]
432    fn test_get_fancy_regex_invalid_pattern() {
433        let mut cache = RegexCache::new();
434        let result = cache.get_fancy_regex(r"(?<=invalid");
435        assert!(result.is_err());
436        assert!(cache.fancy_cache.is_empty());
437    }
438
439    #[test]
440    fn test_get_stats() {
441        let mut cache = RegexCache::new();
442
443        // Use some patterns
444        let _ = cache.get_regex(r"\d+").unwrap();
445        let _ = cache.get_regex(r"\d+").unwrap();
446        let _ = cache.get_regex(r"\w+").unwrap();
447        let _ = cache.get_fancy_regex(r"(?<=foo)bar").unwrap();
448
449        let stats = cache.get_stats();
450        assert_eq!(stats.get(r"\d+"), Some(&2));
451        assert_eq!(stats.get(r"\w+"), Some(&1));
452        assert_eq!(stats.get(r"(?<=foo)bar"), Some(&1));
453    }
454
455    #[test]
456    fn test_clear_cache() {
457        let mut cache = RegexCache::new();
458
459        // Add some patterns
460        let _ = cache.get_regex(r"\d+").unwrap();
461        let _ = cache.get_fancy_regex(r"(?<=foo)bar").unwrap();
462
463        assert!(!cache.cache.is_empty());
464        assert!(!cache.fancy_cache.is_empty());
465        assert!(!cache.usage_stats.is_empty());
466
467        // Clear cache
468        cache.clear();
469
470        assert!(cache.cache.is_empty());
471        assert!(cache.fancy_cache.is_empty());
472        assert!(cache.usage_stats.is_empty());
473    }
474
475    #[test]
476    fn test_global_cache_functions() {
477        // Test get_cached_regex
478        let regex1 = get_cached_regex(r"\d{3}").unwrap();
479        let regex2 = get_cached_regex(r"\d{3}").unwrap();
480        assert!(Arc::ptr_eq(&regex1, &regex2));
481
482        // Test get_cached_fancy_regex
483        let fancy1 = get_cached_fancy_regex(r"(?<=test)ing").unwrap();
484        let fancy2 = get_cached_fancy_regex(r"(?<=test)ing").unwrap();
485        assert!(Arc::ptr_eq(&fancy1, &fancy2));
486
487        // Test stats
488        let stats = get_cache_stats();
489        assert!(stats.contains_key(r"\d{3}"));
490        assert!(stats.contains_key(r"(?<=test)ing"));
491    }
492
493    #[test]
494    fn test_regex_lazy_macro() {
495        let re = regex_lazy!(r"^test.*end$");
496        assert!(re.is_match("test something end"));
497        assert!(!re.is_match("test something"));
498
499        // The macro creates a new static for each invocation location,
500        // so we can't test pointer equality across different invocations
501        // But we can test that the regex works correctly
502        let re2 = regex_lazy!(r"^start.*finish$");
503        assert!(re2.is_match("start and finish"));
504        assert!(!re2.is_match("start without end"));
505    }
506
507    #[test]
508    fn test_has_heading_markers() {
509        assert!(has_heading_markers("# Heading"));
510        assert!(has_heading_markers("Text with # symbol"));
511        assert!(!has_heading_markers("Text without heading marker"));
512    }
513
514    #[test]
515    fn test_has_list_markers() {
516        assert!(has_list_markers("* Item"));
517        assert!(has_list_markers("- Item"));
518        assert!(has_list_markers("+ Item"));
519        assert!(has_list_markers("1. Item"));
520        assert!(!has_list_markers("Text without list markers"));
521    }
522
523    #[test]
524    fn test_has_code_block_markers() {
525        assert!(has_code_block_markers("```code```"));
526        assert!(has_code_block_markers("~~~code~~~"));
527        assert!(has_code_block_markers("Text\n    indented code"));
528        assert!(!has_code_block_markers("Text without code blocks"));
529    }
530
531    #[test]
532    fn test_has_emphasis_markers() {
533        assert!(has_emphasis_markers("*emphasis*"));
534        assert!(has_emphasis_markers("_emphasis_"));
535        assert!(has_emphasis_markers("**bold**"));
536        assert!(has_emphasis_markers("__bold__"));
537        assert!(!has_emphasis_markers("no emphasis"));
538    }
539
540    #[test]
541    fn test_has_html_tags() {
542        assert!(has_html_tags("<div>content</div>"));
543        assert!(has_html_tags("<br/>"));
544        assert!(has_html_tags("<img src='test.jpg'>"));
545        assert!(!has_html_tags("no html tags"));
546        assert!(!has_html_tags("less than < but no tag"));
547    }
548
549    #[test]
550    fn test_has_link_markers() {
551        assert!(has_link_markers("[text](url)"));
552        assert!(has_link_markers("[reference][1]"));
553        assert!(has_link_markers("http://example.com"));
554        assert!(has_link_markers("https://example.com"));
555        assert!(has_link_markers("ftp://example.com"));
556        assert!(!has_link_markers("no links here"));
557    }
558
559    #[test]
560    fn test_has_image_markers() {
561        assert!(has_image_markers("![alt text](image.png)"));
562        assert!(has_image_markers("![](image.png)"));
563        assert!(!has_image_markers("[link](url)"));
564        assert!(!has_image_markers("no images"));
565    }
566
567    #[test]
568    fn test_contains_url() {
569        assert!(contains_url("http://example.com"));
570        assert!(contains_url("Text with https://example.com link"));
571        assert!(contains_url("ftp://example.com"));
572        assert!(!contains_url("Text without URL"));
573        assert!(!contains_url("http not followed by ://"));
574
575        // Edge cases
576        assert!(!contains_url("http"));
577        assert!(!contains_url("https"));
578        assert!(!contains_url("://"));
579        assert!(contains_url("Visit http://site.com now"));
580        assert!(contains_url("See https://secure.site.com/path"));
581    }
582
583    #[test]
584    fn test_contains_url_performance() {
585        // Test early exit for strings without "://"
586        let long_text = "a".repeat(10000);
587        assert!(!contains_url(&long_text));
588
589        // Test with URL at the end
590        let text_with_url = format!("{long_text}https://example.com");
591        assert!(contains_url(&text_with_url));
592    }
593
594    #[test]
595    fn test_escape_regex() {
596        assert_eq!(escape_regex("a.b"), "a\\.b");
597        assert_eq!(escape_regex("a+b*c"), "a\\+b\\*c");
598        assert_eq!(escape_regex("(test)"), "\\(test\\)");
599        assert_eq!(escape_regex("[a-z]"), "\\[a-z\\]");
600        assert_eq!(escape_regex("normal text"), "normal text");
601
602        // Test all special characters
603        assert_eq!(escape_regex(".$^{[(|)*+?\\"), "\\.\\$\\^\\{\\[\\(\\|\\)\\*\\+\\?\\\\");
604
605        // Test empty string
606        assert_eq!(escape_regex(""), "");
607
608        // Test mixed content
609        assert_eq!(escape_regex("test.com/path?query=1"), "test\\.com/path\\?query=1");
610    }
611
612    #[test]
613    fn test_static_regex_patterns() {
614        // Test URL patterns
615        assert!(URL_REGEX.is_match("https://example.com"));
616        assert!(URL_REGEX.is_match("http://test.org/path"));
617        assert!(URL_REGEX.is_match("ftp://files.com"));
618        assert!(!URL_REGEX.is_match("not a url"));
619
620        // Test heading patterns
621        assert!(ATX_HEADING_REGEX.is_match("# Heading"));
622        assert!(ATX_HEADING_REGEX.is_match("  ## Indented"));
623        assert!(ATX_HEADING_REGEX.is_match("### "));
624        assert!(!ATX_HEADING_REGEX.is_match("Not a heading"));
625
626        // Test list patterns
627        assert!(UNORDERED_LIST_MARKER_REGEX.is_match("* Item"));
628        assert!(UNORDERED_LIST_MARKER_REGEX.is_match("- Item"));
629        assert!(UNORDERED_LIST_MARKER_REGEX.is_match("+ Item"));
630        assert!(ORDERED_LIST_MARKER_REGEX.is_match("1. Item"));
631        assert!(ORDERED_LIST_MARKER_REGEX.is_match("99. Item"));
632
633        // Test code block patterns
634        assert!(FENCED_CODE_BLOCK_START_REGEX.is_match("```"));
635        assert!(FENCED_CODE_BLOCK_START_REGEX.is_match("```rust"));
636        assert!(FENCED_CODE_BLOCK_START_REGEX.is_match("~~~"));
637        assert!(FENCED_CODE_BLOCK_END_REGEX.is_match("```"));
638        assert!(FENCED_CODE_BLOCK_END_REGEX.is_match("~~~"));
639
640        // Test emphasis patterns
641        assert!(BOLD_ASTERISK_REGEX.is_match("**bold**"));
642        assert!(BOLD_UNDERSCORE_REGEX.is_match("__bold__"));
643        assert!(ITALIC_ASTERISK_REGEX.is_match("*italic*"));
644        assert!(ITALIC_UNDERSCORE_REGEX.is_match("_italic_"));
645
646        // Test HTML patterns
647        assert!(HTML_TAG_REGEX.is_match("<div>"));
648        assert!(HTML_TAG_REGEX.is_match("<span class='test'>"));
649        assert!(HTML_SELF_CLOSING_TAG_REGEX.is_match("<br/>"));
650        assert!(HTML_SELF_CLOSING_TAG_REGEX.is_match("<img src='test'/>"));
651
652        // Test whitespace patterns
653        assert!(TRAILING_WHITESPACE_REGEX.is_match("line with spaces   "));
654        assert!(TRAILING_WHITESPACE_REGEX.is_match("tabs\t\t"));
655        assert!(MULTIPLE_BLANK_LINES_REGEX.is_match("\n\n\n"));
656        assert!(MULTIPLE_BLANK_LINES_REGEX.is_match("\n\n\n\n"));
657
658        // Test blockquote pattern
659        assert!(BLOCKQUOTE_PREFIX_RE.is_match("> Quote"));
660        assert!(BLOCKQUOTE_PREFIX_RE.is_match("  > Indented quote"));
661        assert!(BLOCKQUOTE_PREFIX_RE.is_match(">> Nested"));
662    }
663
664    #[test]
665    fn test_thread_safety() {
666        use std::thread;
667
668        let handles: Vec<_> = (0..10)
669            .map(|i| {
670                thread::spawn(move || {
671                    let pattern = format!(r"\d{{{i}}}");
672                    let regex = get_cached_regex(&pattern).unwrap();
673                    assert!(regex.is_match(&"1".repeat(i)));
674                })
675            })
676            .collect();
677
678        for handle in handles {
679            handle.join().unwrap();
680        }
681    }
682}